Merge branch 'wip-MDL-57234-master' of https://github.com/Beedell/moodle
[moodle.git] / repository / filepicker.js
blob386a6abcd17a2307e23ea09c4fcaa52c8056b3a0
1 // YUI3 File Picker module for moodle
2 // Author: Dongsheng Cai <dongsheng@moodle.com>
4 /**
5  *
6  * File Picker UI
7  * =====
8  * this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered
9  * this.api, stores the URL to make ajax request
10  * this.mainui, YUI Panel
11  * this.selectnode, contains reference to select-file Node
12  * this.selectui, YUI Panel for selecting particular file
13  * this.msg_dlg, YUI Panel for error or info message
14  * this.process_dlg, YUI Panel for processing existing filename
15  * this.treeview, YUI Treeview
16  * this.viewmode, store current view mode
17  * this.pathbar, reference to the Node with path bar
18  * this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template)
19  * this.currentpath, the current path in the repository (or last requested path)
20  *
21  * Filepicker options:
22  * =====
23  * this.options.client_id, the instance id
24  * this.options.contextid
25  * this.options.itemid
26  * this.options.repositories, stores all repositories displayed in file picker
27  * this.options.formcallback
28  *
29  * Active repository options
30  * =====
31  * this.active_repo.id
32  * this.active_repo.nosearch
33  * this.active_repo.norefresh
34  * this.active_repo.nologin
35  * this.active_repo.help
36  * this.active_repo.manage
37  *
38  * Server responses
39  * =====
40  * this.filelist, cached filelist
41  * this.pages
42  * this.page
43  * this.filepath, current path (each element of the array is a part of the breadcrumb)
44  * this.logindata, cached login form
45  */
47 YUI.add('moodle-core_filepicker', function(Y) {
48     /** help function to extract width/height style as a number, not as a string */
49     Y.Node.prototype.getStylePx = function(attr) {
50         var style = this.getStyle(attr);
51         if (''+style == '0' || ''+style == '0px') {
52             return 0;
53         }
54         var matches = style.match(/^([\d\.]+)px$/)
55         if (matches && parseFloat(matches[1])) {
56             return parseFloat(matches[1]);
57         }
58         return null;
59     }
61     /** if condition is met, the class is added to the node, otherwise - removed */
62     Y.Node.prototype.addClassIf = function(className, condition) {
63         if (condition) {
64             this.addClass(className);
65         } else {
66             this.removeClass(className);
67         }
68         return this;
69     }
71     /** sets the width(height) of the node considering existing minWidth(minHeight) */
72     Y.Node.prototype.setStyleAdv = function(stylename, value) {
73         var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
74         this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
75         return this;
76     }
78     /** set image source to src, if there is preview, remember it in lazyloading.
79      *  If there is a preview and it was already loaded, use it. */
80     Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
81         if (realsrc) {
82             if (M.core_filepicker.loadedpreviews[realsrc]) {
83                 this.set('src', realsrc).addClass('realpreview');
84                 return this;
85             } else {
86                 if (!this.get('id')) {
87                     this.generateID();
88                 }
89                 lazyloading[this.get('id')] = realsrc;
90             }
91         }
92         this.set('src', src);
93         return this;
94     }
96     /**
97      * Replaces the image source with preview. If the image is inside the treeview, we need
98      * also to update the html property of corresponding YAHOO.widget.HTMLNode
99      * @param array lazyloading array containing associations of imgnodeid->realsrc
100      */
101     Y.Node.prototype.setImgRealSrc = function(lazyloading) {
102         if (this.get('id') && lazyloading[this.get('id')]) {
103             var newsrc = lazyloading[this.get('id')];
104             M.core_filepicker.loadedpreviews[newsrc] = true;
105             this.set('src', newsrc).addClass('realpreview');
106             delete lazyloading[this.get('id')];
107             var treenode = this.ancestor('.fp-treeview')
108             if (treenode && treenode.get('parentNode').treeview) {
109                 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
110             }
111         }
112         return this;
113     }
115     /** scan TreeView to find which node contains image with id=imgid and replace it's html
116      * with the new image source. */
117     Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
118         if (!regex) {
119             regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
120         }
121         if (this.expanded || this.isLeaf) {
122             var html = this.getContentHtml();
123             if (html && this.setHtml && regex.test(html)) {
124                 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
125                 this.setHtml(newhtml);
126                 return true;
127             }
128             if (!this.isLeaf && this.children) {
129                 for(var c in this.children) {
130                     if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
131                         return true;
132                     }
133                 }
134             }
135         }
136         return false;
137     }
139     /**
140      * Displays a list of files (used by filepicker, filemanager) inside the Node
141      *
142      * @param array options
143      *   viewmode : 1 - icons, 2 - tree, 3 - table
144      *   appendonly : whether fileslist need to be appended instead of replacing the existing content
145      *   filenode : Node element that contains template for displaying one file
146      *   callback : On click callback. The element of the fileslist array will be passed as argument
147      *   rightclickcallback : On right click callback (optional).
148      *   callbackcontext : context where callbacks are executed
149      *   sortable : whether content may be sortable (in table mode)
150      *   dynload : allow dynamic load for tree view
151      *   filepath : for pre-building of tree view - the path to the current directory in filepicker format
152      *   treeview_dynload : callback to function to dynamically load the folder in tree view
153      *   classnamecallback : callback to function that returns the class name for an element
154      * @param array fileslist array of files to show, each array element may have attributes:
155      *   title or fullname : file name
156      *   shorttitle (optional) : display file name
157      *   thumbnail : url of image
158      *   icon : url of icon image
159      *   thumbnail_width : width of thumbnail, default 90
160      *   thumbnail_height : height of thumbnail, default 90
161      *   thumbnail_alt : TODO not needed!
162      *   description or thumbnail_title : alt text
163      * @param array lazyloading : reference to the array with lazy loading images
164      */
165     Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
166         var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
167         var classname = viewmodeclassnames[options.viewmode];
168         var scope = this;
169         /** return whether file is a folder (different attributes in FileManager and FilePicker) */
170         var file_is_folder = function(node) {
171             if (node.children) {return true;}
172             if (node.type && node.type == 'folder') {return true;}
173             return false;
174         };
175         /** return the name of the file (different attributes in FileManager and FilePicker) */
176         var file_get_filename = function(node) {
177             return node.title ? node.title : node.fullname;
178         };
179         /** return display name of the file (different attributes in FileManager and FilePicker) */
180         var file_get_displayname = function(node) {
181             var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node);
182             return Y.Escape.html(displayname);
183         };
184         /** return file description (different attributes in FileManager and FilePicker) */
185         var file_get_description = function(node) {
186             var description = '';
187             if (node.description) {
188                 description = node.description;
189             } else if (node.thumbnail_title) {
190                 description = node.thumbnail_title;
191             } else {
192                 description = file_get_filename(node);
193             }
194             return Y.Escape.html(description);
195         };
196         /** help funciton for tree view */
197         var build_tree = function(node, level) {
198             // prepare file name with icon
199             var el = Y.Node.create('<div/>');
200             el.appendChild(options.filenode.cloneNode(true));
202             el.one('.fp-filename').setContent(file_get_displayname(node));
203             // TODO add tooltip with node.title or node.thumbnail_title
204             var tmpnodedata = {className:options.classnamecallback(node)};
205             el.get('children').addClass(tmpnodedata.className);
206             if (node.icon) {
207                 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
208                 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
209             }
210             // create node
211             tmpnodedata.html = el.getContent();
212             var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false);
213             if (node.dynamicLoadComplete) {
214                 tmpNode.dynamicLoadComplete = true;
215             }
216             tmpNode.fileinfo = node;
217             tmpNode.isLeaf = !file_is_folder(node);
218             if (!tmpNode.isLeaf) {
219                 if(node.expanded) {
220                     tmpNode.expand();
221                 }
222                 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
223                 for(var c in node.children) {
224                     build_tree(node.children[c], tmpNode);
225                 }
226             }
227         };
228         /** initialize tree view */
229         var initialize_tree_view = function() {
230             var parentid = scope.one('.'+classname).get('id');
231             // TODO MDL-32736 use YUI3 gallery TreeView
232             scope.treeview = new Y.YUI2.widget.TreeView(parentid);
233             if (options.dynload) {
234                 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
235             }
236             scope.treeview.singleNodeHighlight = true;
237             if (options.filepath && options.filepath.length) {
238                 // we just jumped from icon/details view, we need to show all parents
239                 // we extract as much information as possible from filepath and filelist
240                 // and send additional requests to retrieve siblings for parent folders
241                 var mytree = {};
242                 var mytreeel = null;
243                 for (var i in options.filepath) {
244                     if (mytreeel == null) {
245                         mytreeel = mytree;
246                     } else {
247                         mytreeel.children = [{}];
248                         mytreeel = mytreeel.children[0];
249                     }
250                     var pathelement = options.filepath[i];
251                     mytreeel.path = pathelement.path;
252                     mytreeel.title = pathelement.name;
253                     mytreeel.icon = pathelement.icon;
254                     mytreeel.dynamicLoadComplete = true; // we will call it manually
255                     mytreeel.expanded = true;
256                 }
257                 mytreeel.children = fileslist;
258                 build_tree(mytree, scope.treeview.getRoot());
259                 // manually call dynload for parent elements in the tree so we can load other siblings
260                 if (options.dynload) {
261                     var root = scope.treeview.getRoot();
262                     while (root && root.children && root.children.length) {
263                         root = root.children[0];
264                         if (root.path == mytreeel.path) {
265                             root.origpath = options.filepath;
266                             root.origlist = fileslist;
267                         } else if (!root.isLeaf && root.expanded) {
268                             Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
269                         }
270                     }
271                 }
272             } else {
273                 // there is no path information, just display all elements as a list, without hierarchy
274                 for(k in fileslist) {
275                     build_tree(fileslist[k], scope.treeview.getRoot());
276                 }
277             }
278             scope.treeview.subscribe('clickEvent', function(e){
279                 e.node.highlight(false);
280                 var callback = options.callback;
281                 if (options.rightclickcallback && e.event.target &&
282                         Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
283                     callback = options.rightclickcallback;
284                 }
285                 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
286                 Y.YUI2.util.Event.stopEvent(e.event)
287             });
288             // TODO MDL-32736 support right click
289             /*if (options.rightclickcallback) {
290                 scope.treeview.subscribe('dblClickEvent', function(e){
291                     e.node.highlight(false);
292                     Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
293                 });
294             }*/
295             scope.treeview.draw();
296         };
297         /** formatting function for table view */
298         var formatValue = function (o){
299             if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
300             else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
301             else if (o.value) {return o.value;}
302             else {return '';}
303         };
304         /** formatting function for table view */
305         var formatTitle = function(o) {
306             var el = Y.Node.create('<div/>');
307             el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
308             el.get('children').addClass(o.data['classname']);
309             el.one('.fp-filename').setContent(o.value);
310             if (o.data['icon']) {
311                 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
312                 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
313             }
314             if (options.rightclickcallback) {
315                 el.get('children').addClass('fp-hascontextmenu');
316             }
317             // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
318             return el.getContent();
319         }
320         /** sorting function for table view */
321         var sortFoldersFirst = function(a, b, desc) {
322             if (a.get('isfolder') && !b.get('isfolder')) {
323                 return -1;
324             }
325             if (!a.get('isfolder') && b.get('isfolder')) {
326                 return 1;
327             }
328             var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
329             return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
330         }
331         /** initialize table view */
332         var initialize_table_view = function() {
333             var cols = [
334                 {key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle,
335                     sortable: true, sortFn: sortFoldersFirst},
336                 {key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue,
337                     sortable: true, sortFn: sortFoldersFirst},
338                 {key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue,
339                     sortable: true, sortFn: sortFoldersFirst},
340                 {key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true,
341                     sortable: true, sortFn: sortFoldersFirst}
342             ];
343             scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
344             scope.tableview.delegate('click', function (e, tableview) {
345                 var record = tableview.getRecord(e.currentTarget.get('id'));
346                 if (record) {
347                     var callback = options.callback;
348                     if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
349                         callback = options.rightclickcallback;
350                     }
351                     Y.bind(callback, this)(e, record.getAttrs());
352                 }
353             }, 'tr', options.callbackcontext, scope.tableview);
354             if (options.rightclickcallback) {
355                 scope.tableview.delegate('contextmenu', function (e, tableview) {
356                     var record = tableview.getRecord(e.currentTarget.get('id'));
357                     if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
358                 }, 'tr', options.callbackcontext, scope.tableview);
359             }
360         }
361         /** append items in table view mode */
362         var append_files_table = function() {
363             if (options.appendonly) {
364                 fileslist.forEach(function(el) {
365                     this.tableview.data.add(el);
366                 },scope);
367             }
368             scope.tableview.render(scope.one('.'+classname));
369             scope.tableview.sortable = options.sortable ? true : false;
370         };
371         /** append items in tree view mode */
372         var append_files_tree = function() {
373             if (options.appendonly) {
374                 var parentnode = scope.treeview.getRoot();
375                 if (scope.treeview.getHighlightedNode()) {
376                     parentnode = scope.treeview.getHighlightedNode();
377                     if (parentnode.isLeaf) {parentnode = parentnode.parent;}
378                 }
379                 for (var k in fileslist) {
380                     build_tree(fileslist[k], parentnode);
381                 }
382                 scope.treeview.draw();
383             } else {
384                 // otherwise files were already added in initialize_tree_view()
385             }
386         }
387         /** append items in icon view mode */
388         var append_files_icons = function() {
389             parent = scope.one('.'+classname);
390             for (var k in fileslist) {
391                 var node = fileslist[k];
392                 var element = options.filenode.cloneNode(true);
393                 parent.appendChild(element);
394                 element.addClass(options.classnamecallback(node));
395                 var filenamediv = element.one('.fp-filename');
396                 filenamediv.setContent(file_get_displayname(node));
397                 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
398                 if (node.thumbnail) {
399                     width = node.thumbnail_width ? node.thumbnail_width : 90;
400                     height = node.thumbnail_height ? node.thumbnail_height : 90;
401                     src = node.thumbnail;
402                 } else {
403                     width = 16;
404                     height = 16;
405                     src = node.icon;
406                 }
407                 filenamediv.setStyleAdv('width', width);
408                 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
409                 var img = Y.Node.create('<img/>').setAttrs({
410                         title: file_get_description(node),
411                         alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
412                     setStyle('maxWidth', ''+width+'px').
413                     setStyle('maxHeight', ''+height+'px');
414                 img.setImgSrc(src, node.realthumbnail, lazyloading);
415                 imgdiv.appendChild(img);
416                 element.on('click', function(e, nd) {
417                     if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
418                         Y.bind(options.rightclickcallback, this)(e, nd);
419                     } else {
420                         Y.bind(options.callback, this)(e, nd);
421                     }
422                 }, options.callbackcontext, node);
423                 if (options.rightclickcallback) {
424                     element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
425                 }
426             }
427         }
429         // If table view, need some additional properties
430         // before passing fileslist to the YUI tableview
431         if (options.viewmode == 3) {
432             fileslist.forEach(function(el) {
433                 el.displayname = file_get_displayname(el);
434                 el.isfolder = file_is_folder(el);
435                 el.classname = options.classnamecallback(el);
436             }, scope);
437         }
439         // initialize files view
440         if (!options.appendonly) {
441             var parent = Y.Node.create('<div/>').addClass(classname);
442             this.setContent('').appendChild(parent);
443             parent.generateID();
444             if (options.viewmode == 2) {
445                 initialize_tree_view();
446             } else if (options.viewmode == 3) {
447                 initialize_table_view();
448             } else {
449                 // nothing to initialize for icon view
450             }
451         }
453         // append files to the list
454         if (options.viewmode == 2) {
455             append_files_tree();
456         } else if (options.viewmode == 3) {
457             append_files_table();
458         } else {
459             append_files_icons();
460         }
462     }
463 }, '@VERSION@', {
464     requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
467 M.core_filepicker = M.core_filepicker || {};
470  * instances of file pickers used on page
471  */
472 M.core_filepicker.instances = M.core_filepicker.instances || {};
473 M.core_filepicker.active_filepicker = null;
476  * HTML Templates to use in FilePicker
477  */
478 M.core_filepicker.templates = M.core_filepicker.templates || {};
481  * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
482  */
483 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
486 * Set selected file info
488 * @param object file info
490 M.core_filepicker.select_file = function(file) {
491     M.core_filepicker.active_filepicker.select_file(file);
495  * Init and show file picker
496  */
497 M.core_filepicker.show = function(Y, options) {
498     if (!M.core_filepicker.instances[options.client_id]) {
499         M.core_filepicker.init(Y, options);
500     }
501     M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
502     M.core_filepicker.instances[options.client_id].show();
505 M.core_filepicker.set_templates = function(Y, templates) {
506     for (var templid in templates) {
507         M.core_filepicker.templates[templid] = templates[templid];
508     }
512  * Add new file picker to current instances
513  */
514 M.core_filepicker.init = function(Y, options) {
515     var FilePickerHelper = function(options) {
516         FilePickerHelper.superclass.constructor.apply(this, arguments);
517     };
519     FilePickerHelper.NAME = "FilePickerHelper";
520     FilePickerHelper.ATTRS = {
521         options: {},
522         lang: {}
523     };
525     Y.extend(FilePickerHelper, Y.Base, {
526         api: M.cfg.wwwroot+'/repository/repository_ajax.php',
527         cached_responses: {},
528         waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
529         initializer: function(options) {
530             this.options = options;
531             if (!this.options.savepath) {
532                 this.options.savepath = '/';
533             }
534         },
536         destructor: function() {
537         },
539         request: function(args, redraw) {
540             var api = (args.api ? args.api : this.api) + '?action='+args.action;
541             var params = {};
542             var scope = args['scope'] ? args['scope'] : this;
543             params['repo_id']=args.repository_id;
544             params['p'] = args.path?args.path:'';
545             params['page'] = args.page?args.page:'';
546             params['env']=this.options.env;
547             // the form element only accept certain file types
548             params['accepted_types']=this.options.accepted_types;
549             params['sesskey'] = M.cfg.sesskey;
550             params['client_id'] = args.client_id;
551             params['itemid'] = this.options.itemid?this.options.itemid:0;
552             params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
553             // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
554             params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
555             if (this.options.context && this.options.context.id) {
556                 params['ctx_id'] = this.options.context.id;
557             }
558             if (args['params']) {
559                 for (i in args['params']) {
560                     params[i] = args['params'][i];
561                 }
562             }
563             if (args.action == 'upload') {
564                 var list = [];
565                 for(var k in params) {
566                     var value = params[k];
567                     if(value instanceof Array) {
568                         for(var i in value) {
569                             list.push(k+'[]='+value[i]);
570                         }
571                     } else {
572                         list.push(k+'='+value);
573                     }
574                 }
575                 params = list.join('&');
576             } else {
577                 params = build_querystring(params);
578             }
579             var cfg = {
580                 method: 'POST',
581                 on: {
582                     complete: function(id,o,p) {
583                         var data = null;
584                         try {
585                             data = Y.JSON.parse(o.responseText);
586                         } catch(e) {
587                             if (o && o.status && o.status > 0) {
588                                 Y.use('moodle-core-notification-exception', function() {
589                                     return new M.core.exception(e);
590                                 });
591                                 return;
592                             }
593                         }
594                         // error checking
595                         if (data && data.error) {
596                             Y.use('moodle-core-notification-ajaxexception', function () {
597                                 return new M.core.ajaxException(data);
598                             });
599                             this.fpnode.one('.fp-content').setContent('');
600                             return;
601                         } else {
602                             if (data.msg) {
603                                 scope.print_msg(data.msg, 'info');
604                             }
605                             // cache result if applicable
606                             if (args.action != 'upload' && data.allowcaching) {
607                                 scope.cached_responses[params] = data;
608                             }
609                             // invoke callback
610                             args.callback(id,data,p);
611                         }
612                     }
613                 },
614                 arguments: {
615                     scope: scope
616                 },
617                 headers: {
618                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
619                 },
620                 data: params,
621                 context: this
622             };
623             if (args.form) {
624                 cfg.form = args.form;
625             }
626             // check if result of the same request has been already cached. If not, request it
627             // (never applicable in case of form submission and/or upload action):
628             if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
629                 args.callback(null, scope.cached_responses[params], {scope: scope})
630             } else {
631                 Y.io(api, cfg);
632                 if (redraw) {
633                     this.wait();
634                 }
635             }
636         },
637         /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
638         process_existing_file: function(data) {
639             var scope = this;
640             var handleOverwrite = function(e) {
641                 // overwrite
642                 e.preventDefault();
643                 var data = this.process_dlg.dialogdata;
644                 var params = {}
645                 params['existingfilename'] = data.existingfile.filename;
646                 params['existingfilepath'] = data.existingfile.filepath;
647                 params['newfilename'] = data.newfile.filename;
648                 params['newfilepath'] = data.newfile.filepath;
649                 this.hide_header();
650                 this.request({
651                     'params': params,
652                     'scope': this,
653                     'action':'overwrite',
654                     'path': '',
655                     'client_id': this.options.client_id,
656                     'repository_id': this.active_repo.id,
657                     'callback': function(id, o, args) {
658                         scope.hide();
659                         if (scope.options.editor_target && scope.options.env == 'editor') {
660                             // editor needs to update url
661                             scope.options.editor_target.value = data.existingfile.url;
662                             scope.options.editor_target.onchange();
663                         }
664                         var fileinfo = {'client_id':scope.options.client_id,
665                                 'url':data.existingfile.url,
666                                 'file':data.existingfile.filename};
667                         var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
668                         scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
669                     }
670                 }, true);
671             }
672             var handleRename = function(e) {
673                 // inserts file with the new name
674                 e.preventDefault();
675                 var scope = this;
676                 var data = this.process_dlg.dialogdata;
677                 if (scope.options.editor_target && scope.options.env == 'editor') {
678                     scope.options.editor_target.value = data.newfile.url;
679                     scope.options.editor_target.onchange();
680                 }
681                 scope.hide();
682                 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
683                 var fileinfo = {'client_id':scope.options.client_id,
684                                 'url':data.newfile.url,
685                                 'file':data.newfile.filename};
686                 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
687             }
688             var handleCancel = function(e) {
689                 // Delete tmp file
690                 e.preventDefault();
691                 var params = {};
692                 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
693                 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
694                 this.request({
695                     'params': params,
696                     'scope': this,
697                     'action':'deletetmpfile',
698                     'path': '',
699                     'client_id': this.options.client_id,
700                     'repository_id': this.active_repo.id,
701                     'callback': function(id, o, args) {
702                         // let it be in background, from user point of view nothing is happenning
703                     }
704                 }, false);
705                 this.process_dlg.hide();
706                 this.selectui.hide();
707             }
708             if (!this.process_dlg) {
709                 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
710                 var node = this.process_dlg_node;
711                 node.generateID();
712                 this.process_dlg = new M.core.dialogue({
713                     draggable    : true,
714                     bodyContent  : node,
715                     headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
716                     centered     : true,
717                     modal        : true,
718                     visible      : false,
719                     zIndex       : this.options.zIndex
720                 });
721                 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
722                 node.one('.fp-dlg-butrename').on('click', handleRename, this);
723                 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
724                 if (this.options.env == 'editor') {
725                     node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
726                 } else {
727                     node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
728                 }
729             }
730             this.selectnode.removeClass('loading');
731             this.process_dlg.dialogdata = data;
732             this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
733             this.process_dlg.show();
734         },
735         /** displays error instead of filepicker contents */
736         display_error: function(errortext, errorcode) {
737             this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
738             this.fpnode.one('.fp-content .fp-error').
739                 addClass(errorcode).
740                 setContent(Y.Escape.html(errortext));
741         },
742         /** displays message in a popup */
743         print_msg: function(msg, type) {
744             var header = M.util.get_string('error', 'moodle');
745             if (type != 'error') {
746                 type = 'info'; // one of only two types excepted
747                 header = M.util.get_string('info', 'moodle');
748             }
749             if (!this.msg_dlg) {
750                 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
751                 this.msg_dlg_node.generateID();
753                 this.msg_dlg = new M.core.dialogue({
754                     draggable    : true,
755                     bodyContent  : this.msg_dlg_node,
756                     centered     : true,
757                     modal        : true,
758                     visible      : false,
759                     zIndex       : this.options.zIndex
760                 });
761                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
762                     e.preventDefault();
763                     this.msg_dlg.hide();
764                 }, this);
765             }
767             this.msg_dlg.set('headerContent', header);
768             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
769             this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
770             this.msg_dlg.show();
771         },
772         view_files: function(appenditems) {
773             this.viewbar_set_enabled(true);
774             this.print_path();
775             /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
776              // TODO do it via classes and adjust for each view mode!
777                 // If there are no items and no next page, just display status message and quit
778                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
779                 return;
780             }*/
781             if (this.viewmode == 2) {
782                 this.view_as_list(appenditems);
783             } else if (this.viewmode == 3) {
784                 this.view_as_table(appenditems);
785             } else {
786                 this.view_as_icons(appenditems);
787             }
788             this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
789             this.fpnode.one('.fp-content').focus();
790             // display/hide the link for requesting next page
791             if (!appenditems && this.active_repo.hasmorepages) {
792                 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
793                     this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
794                 }
795                 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
796                     e.preventDefault();
797                     this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
798                     this.request_next_page();
799                 }, this);
800             }
801             if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
802                 this.fpnode.one('.fp-content .fp-nextpage').remove();
803             }
804             if (this.fpnode.one('.fp-content .fp-nextpage')) {
805                 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
806             }
807             this.content_scrolled();
808         },
809         content_scrolled: function(e) {
810             setTimeout(Y.bind(function() {
811                 if (this.processingimages) {
812                     return;
813                 }
814                 this.processingimages = true;
815                 var scope = this,
816                     fpcontent = this.fpnode.one('.fp-content'),
817                     fpcontenty = fpcontent.getY(),
818                     fpcontentheight = fpcontent.getStylePx('height'),
819                     nextpage = fpcontent.one('.fp-nextpage'),
820                     is_node_visible = function(node) {
821                         var offset = node.getY()-fpcontenty;
822                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
823                             return true;
824                         }
825                         return false;
826                     };
827                 // automatically load next page when 'more' link becomes visible
828                 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
829                     nextpage.one('a,button').simulate('click');
830                 }
831                 // replace src for visible images that need to be lazy-loaded
832                 if (scope.lazyloading) {
833                     fpcontent.all('img').each( function(node) {
834                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
835                             node.setImgRealSrc(scope.lazyloading);
836                         }
837                     });
838                 }
839                 this.processingimages = false;
840             }, this), 200)
841         },
842         treeview_dynload: function(node, cb) {
843             var retrieved_children = {};
844             if (node.children) {
845                 for (var i in node.children) {
846                     retrieved_children[node.children[i].path] = node.children[i];
847                 }
848             }
849             this.request({
850                 action:'list',
851                 client_id: this.options.client_id,
852                 repository_id: this.active_repo.id,
853                 path:node.path?node.path:'',
854                 page:node.page?args.page:'',
855                 scope:this,
856                 callback: function(id, obj, args) {
857                     var list = obj.list;
858                     var scope = args.scope;
859                     // check that user did not leave the view mode before recieving this response
860                     if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
861                         return;
862                     }
863                     if (cb != null) { // (in manual mode do not update current path)
864                         scope.viewbar_set_enabled(true);
865                         scope.parse_repository_options(obj);
866                     }
867                     node.highlight(false);
868                     node.origlist = obj.list ? obj.list : null;
869                     node.origpath = obj.path ? obj.path : null;
870                     node.children = [];
871                     for(k in list) {
872                         if (list[k].children && retrieved_children[list[k].path]) {
873                             // if this child is a folder and has already been retrieved
874                             node.children[node.children.length] = retrieved_children[list[k].path];
875                         } else {
876                             // append new file to the list
877                             scope.view_as_list([list[k]]);
878                         }
879                     }
880                     if (cb == null) {
881                         node.refresh();
882                     } else {
883                         // invoke callback requested by TreeView component
884                         cb();
885                     }
886                     scope.content_scrolled();
887                 }
888             }, false);
889         },
890        classnamecallback : function(node) {
891             var classname = '';
892             if (node.children) {
893                 classname = classname + ' fp-folder';
894             }
895             if (node.isref) {
896                 classname = classname + ' fp-isreference';
897             }
898             if (node.refcount) {
899                 classname = classname + ' fp-hasreferences';
900             }
901             if (node.originalmissing) {
902                 classname = classname + ' fp-originalmissing';
903             }
904             return Y.Lang.trim(classname);
905         },
906         /** displays list of files in tree (list) view mode. If param appenditems is specified,
907          * appends those items to the end of the list. Otherwise (default behaviour)
908          * clears the contents and displays the items from this.filelist */
909         view_as_list: function(appenditems) {
910             var list = (appenditems != null) ? appenditems : this.filelist;
911             this.viewmode = 2;
912             if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
913                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
914                 return;
915             }
917             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
918             var options = {
919                 viewmode : this.viewmode,
920                 appendonly : (appenditems != null),
921                 filenode : element_template,
922                 callbackcontext : this,
923                 callback : function(e, node) {
924                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
925                     if (!node.children) {
926                         if (e.node.parent && e.node.parent.origpath) {
927                             // set the current path
928                             this.filepath = e.node.parent.origpath;
929                             this.filelist = e.node.parent.origlist;
930                             this.print_path();
931                         }
932                         this.select_file(node);
933                     } else {
934                         // save current path and filelist (in case we want to jump to other viewmode)
935                         this.filepath = e.node.origpath;
936                         this.filelist = e.node.origlist;
937                         this.currentpath = e.node.path;
938                         this.print_path();
939                         this.content_scrolled();
940                     }
941                 },
942                 classnamecallback : this.classnamecallback,
943                 dynload : this.active_repo.dynload,
944                 filepath : this.filepath,
945                 treeview_dynload : this.treeview_dynload
946             };
947             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
948         },
949         /** displays list of files in icon view mode. If param appenditems is specified,
950          * appends those items to the end of the list. Otherwise (default behaviour)
951          * clears the contents and displays the items from this.filelist */
952         view_as_icons: function(appenditems) {
953             this.viewmode = 1;
954             var list = (appenditems != null) ? appenditems : this.filelist;
955             var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
956             if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
957                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
958                 return;
959             }
960             var options = {
961                 viewmode : this.viewmode,
962                 appendonly : (appenditems != null),
963                 filenode : element_template,
964                 callbackcontext : this,
965                 callback : function(e, node) {
966                     if (e.preventDefault) {
967                         e.preventDefault();
968                     }
969                     if(node.children) {
970                         if (this.active_repo.dynload) {
971                             this.list({'path':node.path});
972                         } else {
973                             this.filelist = node.children;
974                             this.view_files();
975                         }
976                     } else {
977                         this.select_file(node);
978                     }
979                 },
980                 classnamecallback : this.classnamecallback
981             };
982             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
983         },
984         /** displays list of files in table view mode. If param appenditems is specified,
985          * appends those items to the end of the list. Otherwise (default behaviour)
986          * clears the contents and displays the items from this.filelist */
987         view_as_table: function(appenditems) {
988             this.viewmode = 3;
989             var list = (appenditems != null) ? appenditems : this.filelist;
990             if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
991                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
992                 return;
993             }
994             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
995             var options = {
996                 viewmode : this.viewmode,
997                 appendonly : (appenditems != null),
998                 filenode : element_template,
999                 callbackcontext : this,
1000                 sortable : !this.active_repo.hasmorepages,
1001                 callback : function(e, node) {
1002                     if (e.preventDefault) {e.preventDefault();}
1003                     if (node.children) {
1004                         if (this.active_repo.dynload) {
1005                             this.list({'path':node.path});
1006                         } else {
1007                             this.filelist = node.children;
1008                             this.view_files();
1009                         }
1010                     } else {
1011                         this.select_file(node);
1012                     }
1013                 },
1014                 classnamecallback : this.classnamecallback
1015             };
1016             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1017         },
1018         /** If more than one page available, requests and displays the files from the next page */
1019         request_next_page: function() {
1020             if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1021                 // nothing to load
1022                 return;
1023             }
1024             this.active_repo.nextpagerequested = true;
1025             var nextpage = this.active_repo.page+1;
1026             var args = {
1027                 page: nextpage,
1028                 repo_id: this.active_repo.id
1029             };
1030             var action = this.active_repo.issearchresult ? 'search' : 'list';
1031             this.request({
1032                 path: this.currentpath,
1033                 scope: this,
1034                 action: action,
1035                 client_id: this.options.client_id,
1036                 repository_id: args.repo_id,
1037                 params: args,
1038                 callback: function(id, obj, args) {
1039                     var scope = args.scope;
1040                     // Check that we are still in the same repository and are expecting this page. We have no way
1041                     // to compare the requested page and the one returned, so we assume that if the last chunk
1042                     // of the breadcrumb is similar, then we probably are on the same page.
1043                     var samepage = true;
1044                     if (obj.path && scope.filepath) {
1045                         var pathbefore = scope.filepath[scope.filepath.length-1];
1046                         var pathafter = obj.path[obj.path.length-1];
1047                         if (pathbefore.path != pathafter.path) {
1048                             samepage = false;
1049                         }
1050                     }
1051                     if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1052                             obj.repo_id == scope.active_repo.id &&
1053                             obj.page == scope.active_repo.page+1 && samepage) {
1054                         scope.parse_repository_options(obj, true);
1055                         scope.view_files(obj.list)
1056                     }
1057                 }
1058             }, false);
1059         },
1060         select_file: function(args) {
1061             var argstitle = args.title;
1062             // Limit the string length so it fits nicely on mobile devices
1063             var titlelength = 30;
1064             if (argstitle.length > titlelength) {
1065                 argstitle = argstitle.substring(0, titlelength) + '...';
1066             }
1067             Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle));
1068             this.selectui.show();
1069             Y.one('#'+this.selectnode.get('id')).focus();
1070             var client_id = this.options.client_id;
1071             var selectnode = this.selectnode;
1072             var return_types = this.options.repositories[this.active_repo.id].return_types;
1073             selectnode.removeClass('loading');
1074             selectnode.one('.fp-saveas input').set('value', args.title);
1076             var imgnode = Y.Node.create('<img/>').
1077                 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1078                 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1079                 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1080             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1082             // filelink is the array of file-link-types available for this repository in this env
1083             var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
1084             var filelink = {}, firstfilelink = null, filelinkcount = 0;
1085             for (var i in filelinktypes) {
1086                 var allowed = (return_types & filelinktypes[i]) &&
1087                     (this.options.return_types & filelinktypes[i]);
1088                 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1089                     // special configuration setting 'repositoryallowexternallinks' may prevent
1090                     // using external links in editor environment
1091                     allowed = false;
1092                 }
1093                 filelink[filelinktypes[i]] = allowed;
1094                 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1095                 filelinkcount += allowed ? 1 : 0;
1096             }
1097             // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1098             // check the first available file-link-type option
1099             for (var linktype in filelink) {
1100                 var el = selectnode.one('.fp-linktype-'+linktype);
1101                 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1102                 el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change');
1103             }
1105             // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1106             selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1107             this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1108             selectnode.one('form #filesource-'+client_id).set('value', args.source);
1110             // display static information about a file (when known)
1111             var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1112             for (var i in attrs) {
1113                 if (selectnode.one('.fp-'+attrs[i])) {
1114                     var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1115                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1116                         .one('.fp-value').setContent(Y.Escape.html(value));
1117                 }
1118             }
1119         },
1120         setup_select_file: function() {
1121             var client_id = this.options.client_id;
1122             var selectnode = this.selectnode;
1123             var getfile = selectnode.one('.fp-select-confirm');
1124             // bind labels with corresponding inputs
1125             selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
1126                 node.all('label').set('for', node.one('input,select').generateID());
1127             });
1128             selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1129             selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1130             selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1131             var changelinktype = function(e) {
1132                 if (e.currentTarget.get('checked')) {
1133                     var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1134                     selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1135                         node.addClassIf('uneditable', !allowinputs);
1136                         node.all('input,select').set('disabled', allowinputs?'':'disabled');
1137                     });
1138                 }
1139             };
1140             selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1141                 node.one('input').on('change', changelinktype, this);
1142             });
1143             this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1144             // register event on clicking submit button
1145             getfile.on('click', function(e) {
1146                 e.preventDefault();
1147                 var client_id = this.options.client_id;
1148                 var scope = this;
1149                 var repository_id = this.active_repo.id;
1150                 var title = selectnode.one('.fp-saveas input').get('value');
1151                 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1152                 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1153                 var license = selectnode.one('.fp-setlicense select');
1154                 if (license) {
1155                     params['license'] = license.get('value');
1156                     var origlicense = selectnode.one('.fp-license .fp-value');
1157                     if (origlicense) {
1158                         origlicense = origlicense.getContent();
1159                     }
1160                     this.set_preference('recentlicense', license.get('value'));
1161                 }
1162                 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1164                 var return_types = this.options.repositories[this.active_repo.id].return_types;
1165                 if (this.options.env == 'editor') {
1166                     // in editor, images are stored in '/' only
1167                     params.savepath = '/';
1168                 }
1169                 if ((this.options.externallink || this.options.env != 'editor') &&
1170                             (return_types & 1/*FILE_EXTERNAL*/) &&
1171                             (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1172                             selectnode.one('.fp-linktype-1 input').get('checked')) {
1173                     params['linkexternal'] = 'yes';
1174                 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1175                         (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1176                         selectnode.one('.fp-linktype-4 input').get('checked')) {
1177                     params['usefilereference'] = '1';
1178                 }
1180                 selectnode.addClass('loading');
1181                 this.request({
1182                     action:'download',
1183                     client_id: client_id,
1184                     repository_id: repository_id,
1185                     'params': params,
1186                     onerror: function(id, obj, args) {
1187                         selectnode.removeClass('loading');
1188                         scope.selectui.hide();
1189                     },
1190                     callback: function(id, obj, args) {
1191                         selectnode.removeClass('loading');
1192                         if (obj.event == 'fileexists') {
1193                             scope.process_existing_file(obj);
1194                             return;
1195                         }
1196                         if (scope.options.editor_target && scope.options.env=='editor') {
1197                             scope.options.editor_target.value=obj.url;
1198                             scope.options.editor_target.onchange();
1199                         }
1200                         scope.hide();
1201                         obj.client_id = client_id;
1202                         var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1203                         scope.options.formcallback.apply(formcallback_scope, [obj]);
1204                     }
1205                 }, false);
1206             }, this);
1207             var elform = selectnode.one('form');
1208             elform.appendChild(Y.Node.create('<input/>').
1209                 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1210             elform.on('keydown', function(e) {
1211                 if (e.keyCode == 13) {
1212                     getfile.simulate('click');
1213                     e.preventDefault();
1214                 }
1215             }, this);
1216             var cancel = selectnode.one('.fp-select-cancel');
1217             cancel.on('click', function(e) {
1218                 e.preventDefault();
1219                 this.selectui.hide();
1220             }, this);
1221         },
1222         wait: function() {
1223             // First check there isn't already an interval in play, and if there is kill it now.
1224             if (this.waitinterval != null) {
1225                 clearInterval(this.waitinterval);
1226             }
1227             // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1228             var root = this.fpnode.one('.fp-content');
1229             var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1230             var count = 0;
1231             // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1232             // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1233             // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1234             // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1235             // Count 16 - The interval will be cancelled.
1236             var interval = setInterval(function(){
1237                 if (!content || !root.contains(content) || count >= 15) {
1238                     clearInterval(interval);
1239                     return true;
1240                 }
1241                 if (count == 5) {
1242                     content.removeClass('fp-content-hidden');
1243                 } else if (count > 5) {
1244                     var opacity = parseFloat(content.getStyle('opacity'));
1245                     content.setStyle('opacity', opacity + 0.1);
1246                 }
1247                 count++;
1248                 return false;
1249             }, 100);
1250             // Store the wait interval so that we can check it in the future.
1251             this.waitinterval = interval;
1252             // Set the content to the loading template.
1253             root.setContent(content);
1254         },
1255         viewbar_set_enabled: function(mode) {
1256             var viewbar = this.fpnode.one('.fp-viewbar')
1257             if (viewbar) {
1258                 if (mode) {
1259                     viewbar.addClass('enabled').removeClass('disabled');
1260                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1261                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
1262                 } else {
1263                     viewbar.removeClass('enabled').addClass('disabled');
1264                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1265                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
1266                 }
1267             }
1268             this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
1269             var modes = {1:'icons', 2:'tree', 3:'details'};
1270             this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1271         },
1272         viewbar_clicked: function(e) {
1273             e.preventDefault();
1274             var viewbar = this.fpnode.one('.fp-viewbar')
1275             if (!viewbar || !viewbar.hasClass('disabled')) {
1276                 if (e.currentTarget.hasClass('fp-vb-tree')) {
1277                     this.viewmode = 2;
1278                 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1279                     this.viewmode = 3;
1280                 } else {
1281                     this.viewmode = 1;
1282                 }
1283                 this.viewbar_set_enabled(true)
1284                 this.view_files();
1285                 this.set_preference('recentviewmode', this.viewmode);
1286             }
1287         },
1288         render: function() {
1289             var client_id = this.options.client_id;
1290             var fpid = "filepicker-"+ client_id;
1291             var labelid = 'fp-dialog-label_'+ client_id;
1292             var width = 873;
1293             var draggable = true;
1294             this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1295                 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1297             if (this.in_iframe()) {
1298                 width = Math.floor(window.innerWidth * 0.95);
1299                 draggable = false;
1300             }
1302             this.mainui = new M.core.dialogue({
1303                 extraClasses : ['filepicker'],
1304                 draggable    : draggable,
1305                 bodyContent  : this.fpnode,
1306                 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
1307                 centered     : true,
1308                 modal        : true,
1309                 visible      : false,
1310                 width        : width+'px',
1311                 responsiveWidth : 768,
1312                 height       : '558px',
1313                 zIndex       : this.options.zIndex
1314             });
1316             // create panel for selecting a file (initially hidden)
1317             this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1318                 set('id', 'filepicker-select-'+client_id).
1319                 set('aria-live', 'assertive').
1320                 set('role', 'dialog');
1322             var fplabel = 'fp-file_label_'+ client_id;
1323             this.selectui = new M.core.dialogue({
1324                 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1325                 draggable    : true,
1326                 width        : '450px',
1327                 bodyContent  : this.selectnode,
1328                 centered     : true,
1329                 modal        : true,
1330                 visible      : false,
1331                 zIndex       : this.options.zIndex
1332             });
1333             Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1334             // event handler for lazy loading of thumbnails and next page
1335             this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1336             // save template for one path element and location of path bar
1337             if (this.fpnode.one('.fp-path-folder')) {
1338                 this.pathnode = this.fpnode.one('.fp-path-folder');
1339                 this.pathbar = this.pathnode.get('parentNode');
1340                 this.pathbar.removeChild(this.pathnode);
1341             }
1342             // assign callbacks for view mode switch buttons
1343             this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1344             this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1345             this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1347             // assign callbacks for toolbar links
1348             this.setup_toolbar();
1349             this.setup_select_file();
1350             this.hide_header();
1352             // processing repository listing
1353             // Resort the repositories by sortorder
1354             var sorted_repositories = [];
1355             for (var i in this.options.repositories) {
1356                 sorted_repositories[i] = this.options.repositories[i];
1357             }
1358             sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1359             // extract one repository template and repeat it for all repositories available,
1360             // set name and icon and assign callbacks
1361             var reponode = this.fpnode.one('.fp-repo');
1362             if (reponode) {
1363                 var list = reponode.get('parentNode');
1364                 list.removeChild(reponode);
1365                 for (i in sorted_repositories) {
1366                     var repository = sorted_repositories[i];
1367                     var node = reponode.cloneNode(true);
1368                     list.appendChild(node);
1369                     node.
1370                         set('id', 'fp-repo-'+client_id+'-'+repository.id).
1371                         on('click', function(e, repository_id) {
1372                             e.preventDefault();
1373                             this.set_preference('recentrepository', repository_id);
1374                             this.hide_header();
1375                             this.list({'repo_id':repository_id});
1376                         }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1377                     node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1378                     node.one('.fp-repo-icon').set('src', repository.icon);
1379                     if (i==0) {
1380                         node.addClass('first');
1381                     }
1382                     if (i==sorted_repositories.length-1) {
1383                         node.addClass('last');
1384                     }
1385                     if (i%2) {
1386                         node.addClass('even');
1387                     } else {
1388                         node.addClass('odd');
1389                     }
1390                 }
1391             }
1392             // display error if no repositories found
1393             if (sorted_repositories.length==0) {
1394                 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1395             }
1396             // display repository that was used last time
1397             this.mainui.show();
1398             this.show_recent_repository();
1399         },
1400         parse_repository_options: function(data, appendtolist) {
1401             if (appendtolist) {
1402                 if (data.list) {
1403                     if (!this.filelist) {
1404                         this.filelist = [];
1405                     }
1406                     for (var i in data.list) {
1407                         this.filelist[this.filelist.length] = data.list[i];
1408                     }
1409                 }
1410             } else {
1411                 this.filelist = data.list?data.list:null;
1412                 this.lazyloading = {};
1413             }
1414             this.filepath = data.path?data.path:null;
1415             this.objecttag = data.object?data.object:null;
1416             this.active_repo = {};
1417             this.active_repo.issearchresult = data.issearchresult ? true : false;
1418             this.active_repo.dynload = data.dynload?data.dynload:false;
1419             this.active_repo.pages = Number(data.pages?data.pages:null);
1420             this.active_repo.page = Number(data.page?data.page:null);
1421             this.active_repo.hasmorepages = (this.active_repo.pages && this.active_repo.page && (this.active_repo.page < this.active_repo.pages || this.active_repo.pages == -1))
1422             this.active_repo.id = data.repo_id?data.repo_id:null;
1423             this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1424             this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1425             this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1426             this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1427             this.active_repo.logouturl = (data.logouturl || '');
1428             this.active_repo.message = (data.message || '');
1429             this.active_repo.help = data.help?data.help:null;
1430             this.active_repo.manage = data.manage?data.manage:null;
1431             this.print_header();
1432         },
1433         print_login: function(data) {
1434             this.parse_repository_options(data);
1435             var client_id = this.options.client_id;
1436             var repository_id = data.repo_id;
1437             var l = this.logindata = data.login;
1438             var loginurl = '';
1439             var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1440             var form_id = 'fp-form-'+client_id;
1442             var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1443             loginform_node.one('form').set('id', form_id);
1444             this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1445             var templates = {
1446                 'popup' : loginform_node.one('.fp-login-popup'),
1447                 'textarea' : loginform_node.one('.fp-login-textarea'),
1448                 'select' : loginform_node.one('.fp-login-select'),
1449                 'text' : loginform_node.one('.fp-login-text'),
1450                 'radio' : loginform_node.one('.fp-login-radiogroup'),
1451                 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1452                 'input' : loginform_node.one('.fp-login-input')
1453             };
1454             var container;
1455             for (var i in templates) {
1456                 if (templates[i]) {
1457                     container = templates[i].get('parentNode');
1458                     container.removeChild(templates[i]);
1459                 }
1460             }
1462             for(var k in l) {
1463                 if (templates[l[k].type]) {
1464                     var node = templates[l[k].type].cloneNode(true);
1465                 } else {
1466                     node = templates['input'].cloneNode(true);
1467                 }
1468                 if (l[k].type == 'popup') {
1469                     // submit button
1470                     loginurl = l[k].url;
1471                     var popupbutton = node.one('button');
1472                     popupbutton.on('click', function(e){
1473                         M.core_filepicker.active_filepicker = this;
1474                         window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1475                         e.preventDefault();
1476                     }, this);
1477                     loginform_node.one('form').on('keydown', function(e) {
1478                         if (e.keyCode == 13) {
1479                             popupbutton.simulate('click');
1480                             e.preventDefault();
1481                         }
1482                     }, this);
1483                     loginform_node.all('.fp-login-submit').remove();
1484                     action = 'popup';
1485                 } else if(l[k].type=='textarea') {
1486                     // textarea element
1487                     if (node.one('label')) {
1488                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1489                     }
1490                     node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1491                 } else if(l[k].type=='select') {
1492                     // select element
1493                     if (node.one('label')) {
1494                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1495                     }
1496                     node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1497                     for (i in l[k].options) {
1498                         node.one('select').appendChild(
1499                             Y.Node.create('<option/>').
1500                                 set('value', l[k].options[i].value).
1501                                 setContent(l[k].options[i].label));
1502                     }
1503                 } else if(l[k].type=='radio') {
1504                     // radio input element
1505                     node.all('label').setContent(l[k].label);
1506                     var list = l[k].value.split('|');
1507                     var labels = l[k].value_label.split('|');
1508                     var radionode = null;
1509                     for(var item in list) {
1510                         if (radionode == null) {
1511                             radionode = node.one('.fp-login-radio');
1512                             radionode.one('input').set('checked', 'checked');
1513                         } else {
1514                             var x = radionode.cloneNode(true);
1515                             radionode.insert(x, 'after');
1516                             radionode = x;
1517                             radionode.one('input').set('checked', '');
1518                         }
1519                         radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1520                             type:l[k].type, value:list[item]});
1521                         radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1522                     }
1523                     if (radionode == null) {
1524                         node.one('.fp-login-radio').remove();
1525                     }
1526                 } else {
1527                     // input element
1528                     if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1529                     node.one('input').
1530                         set('type', l[k].type).
1531                         set('id', l[k].id).
1532                         set('name', l[k].name).
1533                         set('value', l[k].value?l[k].value:'')
1534                 }
1535                 container.appendChild(node);
1536             }
1537             // custom label text for submit button
1538             if (data['login_btn_label']) {
1539                 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1540             }
1541             // register button action for login and search
1542             if (action == 'login' || action == 'search') {
1543                 loginform_node.one('.fp-login-submit').on('click', function(e){
1544                     e.preventDefault();
1545                     this.hide_header();
1546                     this.request({
1547                         'scope': this,
1548                         'action':(action == 'search') ? 'search' : 'signin',
1549                         'path': '',
1550                         'client_id': client_id,
1551                         'repository_id': repository_id,
1552                         'form': {id:form_id, upload:false, useDisabled:true},
1553                         'callback': this.display_response
1554                     }, true);
1555                 }, this);
1556             }
1557             // if 'Enter' is pressed in the form, simulate the button click
1558             if (loginform_node.one('.fp-login-submit')) {
1559                 loginform_node.one('form').on('keydown', function(e) {
1560                     if (e.keyCode == 13) {
1561                         loginform_node.one('.fp-login-submit').simulate('click')
1562                         e.preventDefault();
1563                     }
1564                 }, this);
1565             }
1566         },
1567         display_response: function(id, obj, args) {
1568             var scope = args.scope;
1569             // highlight the current repository in repositories list
1570             scope.fpnode.all('.fp-repo.active').removeClass('active');
1571             scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1572             // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1573             for (var i in scope.options.repositories) {
1574                 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1575             }
1576             if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1577                 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1578             }
1579             Y.one('.file-picker .fp-repo-items').focus();
1581             // display response
1582             if (obj.login) {
1583                 scope.viewbar_set_enabled(false);
1584                 scope.print_login(obj);
1585             } else if (obj.upload) {
1586                 scope.viewbar_set_enabled(false);
1587                 scope.parse_repository_options(obj);
1588                 scope.create_upload_form(obj);
1589             } else if (obj.object) {
1590                 M.core_filepicker.active_filepicker = scope;
1591                 scope.viewbar_set_enabled(false);
1592                 scope.parse_repository_options(obj);
1593                 scope.create_object_container(obj.object);
1594             } else if (obj.list) {
1595                 scope.viewbar_set_enabled(true);
1596                 scope.parse_repository_options(obj);
1597                 scope.view_files();
1598             }
1599         },
1600         list: function(args) {
1601             if (!args) {
1602                 args = {};
1603             }
1604             if (!args.repo_id) {
1605                 args.repo_id = this.active_repo.id;
1606             }
1607             if (!args.path) {
1608                 args.path = '';
1609             }
1610             this.currentpath = args.path;
1611             this.request({
1612                 action: 'list',
1613                 client_id: this.options.client_id,
1614                 repository_id: args.repo_id,
1615                 path: args.path,
1616                 page: args.page,
1617                 scope: this,
1618                 callback: this.display_response
1619             }, true);
1620         },
1621         populate_licenses_select: function(node) {
1622             if (!node) {
1623                 return;
1624             }
1625             node.setContent('');
1626             var licenses = this.options.licenses;
1627             var recentlicense = this.get_preference('recentlicense');
1628             if (recentlicense) {
1629                 this.options.defaultlicense=recentlicense;
1630             }
1631             for (var i in licenses) {
1632                 var option = Y.Node.create('<option/>').
1633                     set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1634                     set('value', licenses[i].shortname).
1635                     setContent(Y.Escape.html(licenses[i].fullname));
1636                 node.appendChild(option)
1637             }
1638         },
1639         set_selected_license: function(node, value) {
1640             var licenseset = false;
1641             node.all('option').each(function(el) {
1642                 if (el.get('value')==value || el.getContent()==value) {
1643                     el.set('selected', true);
1644                     licenseset = true;
1645                 }
1646             });
1647             if (!licenseset) {
1648                 // we did not find the value in the list
1649                 var recentlicense = this.get_preference('recentlicense');
1650                 node.all('option[selected]').set('selected', false);
1651                 node.all('option[value='+recentlicense+']').set('selected', true);
1652             }
1653         },
1654         create_object_container: function(data) {
1655             var content = this.fpnode.one('.fp-content');
1656             content.setContent('');
1657             //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1658             var container = Y.Node.create('<object/>').
1659                 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1660                 addClass('fp-object-container');
1661             content.setContent('').appendChild(container);
1662         },
1663         create_upload_form: function(data) {
1664             var client_id = this.options.client_id;
1665             var id = data.upload.id+'_'+client_id;
1666             var content = this.fpnode.one('.fp-content');
1667             var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1668             var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1669             content.setContent(template);
1671             content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1672                 node.all('label').set('for', node.one('input,select').generateID());
1673             });
1674             content.one('form').set('id', id);
1675             content.one('.fp-file input').set('name', 'repo_upload_file');
1676             if (data.upload.label && content.one('.fp-file label')) {
1677                 content.one('.fp-file label').setContent(data.upload.label);
1678             }
1679             content.one('.fp-saveas input').set('name', 'title');
1680             content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1681             content.one('.fp-setlicense select').set('name', 'license');
1682             this.populate_licenses_select(content.one('.fp-setlicense select'))
1683             // append hidden inputs to the upload form
1684             content.one('form').appendChild(Y.Node.create('<input/>').
1685                 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1686             var types = this.options.accepted_types;
1687             for (var i in types) {
1688                 content.one('form').appendChild(Y.Node.create('<input/>').
1689                     setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1690             }
1692             var scope = this;
1693             content.one('.fp-upload-btn').on('click', function(e) {
1694                 e.preventDefault();
1695                 var license = content.one('.fp-setlicense select');
1697                 this.set_preference('recentlicense', license.get('value'));
1698                 if (!content.one('.fp-file input').get('value')) {
1699                     scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1700                     return false;
1701                 }
1702                 this.hide_header();
1703                 scope.request({
1704                         scope: scope,
1705                         action:'upload',
1706                         client_id: client_id,
1707                         params: {'savepath':scope.options.savepath},
1708                         repository_id: scope.active_repo.id,
1709                         form: {id: id, upload:true},
1710                         onerror: function(id, o, args) {
1711                             scope.create_upload_form(data);
1712                         },
1713                         callback: function(id, o, args) {
1714                             if (o.event == 'fileexists') {
1715                                 scope.create_upload_form(data);
1716                                 scope.process_existing_file(o);
1717                                 return;
1718                             }
1719                             if (scope.options.editor_target&&scope.options.env=='editor') {
1720                                 scope.options.editor_target.value=o.url;
1721                                 scope.options.editor_target.onchange();
1722                             }
1723                             scope.hide();
1724                             o.client_id = client_id;
1725                             var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1726                             scope.options.formcallback.apply(formcallback_scope, [o]);
1727                         }
1728                 }, true);
1729             }, this);
1730         },
1731         /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1732         setup_toolbar: function() {
1733             var client_id = this.options.client_id;
1734             var toolbar = this.fpnode.one('.fp-toolbar');
1735             toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1736                 e.preventDefault();
1737                 if (!this.active_repo.nologin) {
1738                     this.hide_header();
1739                     this.request({
1740                         action:'logout',
1741                         client_id: this.options.client_id,
1742                         repository_id: this.active_repo.id,
1743                         path:'',
1744                         callback: this.display_response
1745                     }, true);
1746                 }
1747                 if (this.active_repo.logouturl) {
1748                     window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1749                 }
1750             }, this);
1751             toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1752                 e.preventDefault();
1753                 if (!this.active_repo.norefresh) {
1754                     this.list({ path: this.currentpath });
1755                 }
1756             }, this);
1757             toolbar.one('.fp-tb-search form').
1758                 set('method', 'POST').
1759                 set('id', 'fp-tb-search-'+client_id).
1760                 on('submit', function(e) {
1761                     e.preventDefault();
1762                     if (!this.active_repo.nosearch) {
1763                         this.request({
1764                             scope: this,
1765                             action:'search',
1766                             client_id: this.options.client_id,
1767                             repository_id: this.active_repo.id,
1768                             form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1769                             callback: this.display_response
1770                         }, true);
1771                     }
1772             }, this);
1774             // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1775             // element and use it to open url on click event
1776             var managelnk = Y.Node.create('<a/>').
1777                 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1778                 setStyle('display', 'none');
1779             toolbar.append(managelnk);
1780             toolbar.one('.fp-tb-manage').one('a,button').
1781                 on('click', function(e) {
1782                     e.preventDefault();
1783                     managelnk.simulate('click')
1784                 });
1786             // same with .fp-tb-help
1787             var helplnk = Y.Node.create('<a/>').
1788                 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1789                 setStyle('display', 'none');
1790             toolbar.append(helplnk);
1791             toolbar.one('.fp-tb-help').one('a,button').
1792                 on('click', function(e) {
1793                     e.preventDefault();
1794                     helplnk.simulate('click')
1795                 });
1796         },
1797         hide_header: function() {
1798             if (this.fpnode.one('.fp-toolbar')) {
1799                 this.fpnode.one('.fp-toolbar').addClass('empty');
1800             }
1801             if (this.pathbar) {
1802                 this.pathbar.setContent('').addClass('empty');
1803             }
1804         },
1805         print_header: function() {
1806             var r = this.active_repo;
1807             var scope = this;
1808             var client_id = this.options.client_id;
1809             this.hide_header();
1810             this.print_path();
1811             var toolbar = this.fpnode.one('.fp-toolbar');
1812             if (!toolbar) { return; }
1814             var enable_tb_control = function(node, enabled) {
1815                 if (!node) { return; }
1816                 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1817                 if (enabled) {
1818                     toolbar.removeClass('empty');
1819                 }
1820             }
1822             // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1823             enable_tb_control(toolbar.one('.fp-tb-back'), false);
1825             // search form
1826             enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1827             if(!r.nosearch) {
1828                 var searchform = toolbar.one('.fp-tb-search form');
1829                 searchform.setContent('');
1830                 this.request({
1831                     scope: this,
1832                     action:'searchform',
1833                     repository_id: this.active_repo.id,
1834                     callback: function(id, obj, args) {
1835                         if (obj.repo_id == scope.active_repo.id && obj.form) {
1836                             // if we did not jump to another repository meanwhile
1837                             searchform.setContent(obj.form);
1838                             // Highlight search text when user click for search.
1839                             var searchnode = searchform.one('input[name="s"]');
1840                             if (searchnode) {
1841                                 searchnode.once('click', function(e) {
1842                                     e.preventDefault();
1843                                     this.select();
1844                                 });
1845                             }
1846                         }
1847                     }
1848                 }, false);
1849             }
1851             // refresh button
1852             // weather we use cache for this instance, this button will reload listing anyway
1853             enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1855             // login button
1856             enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1858             // manage url
1859             enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1860             Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1862             // help url
1863             enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1864             Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1866             // message
1867             enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1868             toolbar.one('.fp-tb-message').setContent(r.message);
1869         },
1870         print_path: function() {
1871             if (!this.pathbar) {
1872                 return;
1873             }
1874             this.pathbar.setContent('').addClass('empty');
1875             var p = this.filepath;
1876             if (p && p.length!=0 && this.viewmode != 2) {
1877                 for(var i = 0; i < p.length; i++) {
1878                     var el = this.pathnode.cloneNode(true);
1879                     this.pathbar.appendChild(el);
1880                     if (i == 0) {
1881                         el.addClass('first');
1882                     }
1883                     if (i == p.length-1) {
1884                         el.addClass('last');
1885                     }
1886                     if (i%2) {
1887                         el.addClass('even');
1888                     } else {
1889                         el.addClass('odd');
1890                     }
1891                     el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
1892                     el.on('click',
1893                             function(e, path) {
1894                                 e.preventDefault();
1895                                 this.list({'path':path});
1896                             },
1897                         this, p[i].path);
1898                 }
1899                 this.pathbar.removeClass('empty');
1900             }
1901         },
1902         hide: function() {
1903             this.selectui.hide();
1904             if (this.process_dlg) {
1905                 this.process_dlg.hide();
1906             }
1907             if (this.msg_dlg) {
1908                 this.msg_dlg.hide();
1909             }
1910             this.mainui.hide();
1911         },
1912         show: function() {
1913             if (this.fpnode) {
1914                 this.hide();
1915                 this.mainui.show();
1916                 this.show_recent_repository();
1917             } else {
1918                 this.launch();
1919             }
1920         },
1921         launch: function() {
1922             this.render();
1923         },
1924         show_recent_repository: function() {
1925             this.hide_header();
1926             this.viewbar_set_enabled(false);
1927             var repository_id = this.get_preference('recentrepository');
1928             this.viewmode = this.get_preference('recentviewmode');
1929             if (this.viewmode != 2 && this.viewmode != 3) {
1930                 this.viewmode = 1;
1931             }
1932             if (this.options.repositories[repository_id]) {
1933                 this.list({'repo_id':repository_id});
1934             }
1935         },
1936         get_preference: function (name) {
1937             if (this.options.userprefs[name]) {
1938                 return this.options.userprefs[name];
1939             } else {
1940                 return false;
1941             }
1942         },
1943         set_preference: function(name, value) {
1944             if (this.options.userprefs[name] != value) {
1945                 M.util.set_user_preference('filepicker_' + name, value);
1946                 this.options.userprefs[name] = value;
1947             }
1948         },
1949         in_iframe: function () {
1950             // If we're not the top window then we're in an iFrame
1951             return window.self !== window.top;
1952         }
1953     });
1954     var loading = Y.one('#filepicker-loading-'+options.client_id);
1955     if (loading) {
1956         loading.setStyle('display', 'none');
1957     }
1958     M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);