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