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