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