Blame view

sources/apps/contacts/js/app.js 54.1 KB
d1bafeea1   Kload   [fix] Upgrade to ...
1
2
3
4
5
6
7
8
9
10
  Modernizr.load({
  	test: Modernizr.input.placeholder,
  	nope: [
  			OC.filePath('contacts', 'css', 'placeholder_polyfill.min.css'),
  			OC.filePath('contacts', 'js', 'placeholder_polyfill.jquery.min.combo.js')
  		]
  });
  
  (function($) {
  	$.QueryString = (function(a) {
6d9380f96   Cédric Dupont   Update sources OC...
11
  		if (a === '') {return {};}
d1bafeea1   Kload   [fix] Upgrade to ...
12
13
14
15
  		var b = {};
  		for (var i = 0; i < a.length; ++i)
  		{
  			var p=a[i].split('=');
6d9380f96   Cédric Dupont   Update sources OC...
16
17
18
19
  			if (p.length !== 2) {
  				continue;
  			}
  			b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, ' '));
d1bafeea1   Kload   [fix] Upgrade to ...
20
21
  		}
  		return b;
6d9380f96   Cédric Dupont   Update sources OC...
22
  	})(window.location.search.substr(1).split('&'));
d1bafeea1   Kload   [fix] Upgrade to ...
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
  })(jQuery);
  
  var utils = {};
  
  /**
   * utils.isArray
   *
   * Best guess if object is an array.
   */
  utils.isArray = function(obj) {
       // do an instanceof check first
       if (obj instanceof Array) {
           return true;
       }
       // then check for obvious falses
       if (typeof obj !== 'object') {
           return false;
       }
       if (utils.type(obj) === 'array') {
           return true;
       }
       return false;
  };
  
  utils.isInt = function(s) {
    return typeof s === 'number' && (s.toString().search(/^-?[0-9]+$/) === 0);
  };
  
  utils.isUInt = function(s) {
    return typeof s === 'number' && (s.toString().search(/^[0-9]+$/) === 0);
  };
  
  /**
   * utils.type
   *
   * Attempt to ascertain actual object type.
   */
  utils.type = function(obj) {
      if (obj === null || typeof obj === 'undefined') {
          return String (obj);
      }
      return Object.prototype.toString.call(obj)
          .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
  };
  
  utils.moveCursorToEnd = function(el) {
  	if (typeof el.selectionStart === 'number') {
  		el.selectionStart = el.selectionEnd = el.value.length;
  	} else if (typeof el.createTextRange !== 'undefined') {
  		el.focus();
  		var range = el.createTextRange();
  		range.collapse(false);
  		range.select();
  	}
  };
  
  Array.prototype.clone = function() {
    return this.slice(0);
  };
  
  Array.prototype.clean = function(deleteValue) {
  	var arr = this.clone();
  	for (var i = 0; i < arr.length; i++) {
6d9380f96   Cédric Dupont   Update sources OC...
86
  		if (arr[i] === deleteValue) {
d1bafeea1   Kload   [fix] Upgrade to ...
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  			arr.splice(i, 1);
  			i--;
  		}
  	}
  	return arr;
  };
  
  // Keep it DRY ;)
  var wrongKey = function(event) {
  	return ((event.type === 'keydown' || event.type === 'keypress') 
  		&& (event.keyCode !== 32 && event.keyCode !== 13));
  };
  
  /**
   * Simply notifier
   * Arguments:
   * @param string message - The text message to show.
   * @param int timeout - The timeout in seconds before the notification disappears. Default 10.
   * @param function timeouthandler - A function to run on timeout.
   * @param function clickhandler - A function to run on click. If a timeouthandler is given it will be cancelled on click.
   * @param object data - An object that will be passed as argument to the timeouthandler and clickhandler functions.
   * @param bool cancel - If set cancel all ongoing timer events and hide the notification.
   */
  OC.notify = function(params) {
  	var self = this;
  	if(!self.notifier) {
  		self.notifier = $('#notification');
  		self.notifier.on('click', function() { $(this).fadeOut();});
  	}
  	if(params.cancel) {
  		self.notifier.off('click');
  		for(var id in self.notifier.data()) {
  			if($.isNumeric(id)) {
  				clearTimeout(parseInt(id));
  			}
  		}
  		self.notifier.text('').fadeOut().removeData();
  	}
  	if(params.message) {
  		self.notifier.text(params.message).fadeIn().css('display', 'inline');
  	}
  
  	var timer = setTimeout(function() {
  		self.notifier.fadeOut();
  		if(params.timeouthandler && $.isFunction(params.timeouthandler)) {
  			params.timeouthandler(self.notifier.data(dataid));
  			self.notifier.off('click');
  			self.notifier.removeData(dataid);
  		}
  	}, params.timeout && $.isNumeric(params.timeout) ? parseInt(params.timeout)*1000 : 10000);
  	var dataid = timer.toString();
  	if(params.data) {
  		self.notifier.data(dataid, params.data);
  	}
  	if(params.clickhandler && $.isFunction(params.clickhandler)) {
  		self.notifier.on('click', function() {
  			clearTimeout(timer);
  			self.notifier.off('click');
  			params.clickhandler(self.notifier.data(dataid));
  			self.notifier.removeData(dataid);
  		});
  	}
  };
6d9380f96   Cédric Dupont   Update sources OC...
150
151
  (function(window, $, OC) {
  	'use strict';
d1bafeea1   Kload   [fix] Upgrade to ...
152

6d9380f96   Cédric Dupont   Update sources OC...
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
  	OC.Contacts = OC.Contacts || {
  		init:function() {
  			if(oc_debug === true) {
  				$.error = console.error;
  			}
  			var self = this;
  
  			this.lastSelectedContacts = [];
  			this.scrollTimeoutMiliSecs = 100;
  			this.isScrolling = false;
  			this.cacheElements();
  			this.storage = new OC.Contacts.Storage();
  			this.addressBooks = new OC.Contacts.AddressBookList(
  				this.storage,
  				$('#app-settings-content'),
  				$('#addressBookTemplate')
  			);
  			this.otherBackendConfig = new OC.Contacts.OtherBackendConfig(
  				this.storage,
  				this.addressBooks,
  				$('#addressBookConfigTemplate')
  			);
  			this.contacts = new OC.Contacts.ContactList(
  				this.storage,
  				this.addressBooks,
  				this.$contactList,
  				this.$contactListItemTemplate,
  				this.$contactDragItemTemplate,
  				this.$contactFullTemplate,
  				this.detailTemplates
  			);
  			this.groups = new OC.Contacts.GroupList(
  				this.storage,
  				this.$groupList,
  				this.$groupListItemTemplate
  			);
  			self.groups.loadGroups(function() {
  				self.loading(self.$navigation, false);
  			});
  			// Hide the list while populating it.
  			this.$contactList.hide();
  			$.when(this.addressBooks.loadAddressBooks()).then(function(addressBooks) {
  				var deferreds = $(addressBooks).map(function(/*i, elem*/) {
  					return self.contacts.loadContacts(this.getBackend(), this.getId(), this.isActive());
  				});
  				// This little beauty is from http://stackoverflow.com/a/6162959/373007 ;)
  				$.when.apply(null, deferreds.get()).then(function() {
  					self.contacts.setSortOrder(contacts_sortby);
  					self.$contactList.show();
  					$(document).trigger('status.contacts.loaded', {
  						numcontacts: self.contacts.length
  					});
  					self.loading(self.$rightContent, false);
  					// TODO: Move this to event handler
  					self.groups.selectGroup({id:contacts_lastgroup});
  					var id = $.QueryString.id; // Keep for backwards compatible links.
  					if(!id) {
  						id = window.location.hash.substr(1);
  					}
  					console.log('Groups loaded, id from url:', id);
  					if(id) {
  						self.openContact(id);
  					}
  					if(!contacts_properties_indexed) {
  						// Wait a couple of mins then check if contacts are indexed.
  						setTimeout(function() {
  								$.when($.post(OC.generateUrl('apps/contacts/indexproperties/{user}/')))
  									.then(function(response) {
  										if(!response.isIndexed) {
  											OC.notify({message:t('contacts', 'Indexing contacts'), timeout:20});
  										}
  									});
  						}, 10000);
  					} else {
  						console.log('contacts are indexed.');
  					}
  				}).fail(function(response) {
  					console.warn(response);
  					self.$rightContent.removeClass('loading');
  					var message = t('contacts', 'Unrecoverable error loading address books: {msg}', {msg:response.message});
  					OC.dialogs.alert(message, t('contacts', 'Error.'));
d1bafeea1   Kload   [fix] Upgrade to ...
234
  				});
6d9380f96   Cédric Dupont   Update sources OC...
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
  			}).fail(function(response) {
  				console.log(response.message);
  				$(document).trigger('status.contacts.error', response);
  			});
  			$(OC.Tags).on('change', this.groups.categoriesChanged);
  			this.bindEvents();
  			this.$toggleAll.show();
  			this.hideActions();
  			$('.hidden-on-load').removeClass('hidden-on-load');
  		},
  		loading:function(obj, state) {
  			$(obj).toggleClass('loading', state);
  		},
  		/**
  		* Show/hide elements in the header
  		* @param act An array of actions to show based on class name e.g ['add', 'delete']
  		*/
  		hideActions:function() {
  			this.showActions(false);
  		},
  		showActions:function(act) {
  			console.log('showActions', act);
  			//console.trace();
  			this.$headeractions.children().hide();
  			if(act && act.length > 0) {
  				this.$contactList.addClass('multiselect');
  				this.$contactListHeader.find('.actions').css('display', '');
  				this.$contactListHeader.find('.action').css('display', 'none');
  				this.$contactListHeader.find('.name').attr('colspan', '5');
  				this.$contactListHeader.find('.info').css('display', 'none');
  				this.$contactListHeader.find('.'+act.join(',.')).css('display', '');
  			} else {
  				this.$contactListHeader.find('.actions').css('display', 'none');
  				this.$contactListHeader.find('.name').attr('colspan', '1');
  				this.$contactListHeader.find('.info').css('display', '');
  				this.$contactList.removeClass('multiselect');
  			}
  		},
  		showAction:function(act, show) {
  			this.$contactListHeader.find('.' + act).toggle(show);
  		},
  		cacheElements: function() {
  			var self = this;
  			this.detailTemplates = {};
  			// Load templates for contact details.
  			// The weird double loading is because jquery apparently doesn't
  			// create a searchable object from a script element.
  			$.each($($('#contactDetailsTemplate').html()), function(idx, node) {
  				var $node = $(node);
  				if($node.is('div')) {
  					var $tmpl = $(node.innerHTML);
  					self.detailTemplates[$tmpl.data('element')] = $node;
d1bafeea1   Kload   [fix] Upgrade to ...
287
  				}
6d9380f96   Cédric Dupont   Update sources OC...
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
  			});
  			this.$groupListItemTemplate = $('#groupListItemTemplate');
  			this.$contactListItemTemplate = $('#contactListItemTemplate');
  			this.$contactDragItemTemplate = $('#contactDragItemTemplate');
  			this.$contactFullTemplate = $('#contactFullTemplate');
  			this.$contactDetailsTemplate = $('#contactDetailsTemplate');
  			this.$rightContent = $('#app-content');
  			this.$navigation = $('#app-navigation');
  			//this.$header = $('#contactsheader');
  			this.$groupList = $('#grouplist');
  			this.$contactList = $('#contactlist');
  			this.$contactListHeader = $('#contactsHeader');
  			this.$sortOrder = this.$contactListHeader.find('.action.sort');
  			this.$sortOrder.val(contacts_sortby||'fn');
  			this.$headeractions = this.$groupList.find('.contact-actions');
  			this.$toggleAll = this.$contactListHeader.find('.toggle');
  			this.$groups = this.$contactListHeader.find('.groups');
  			this.$ninjahelp = $('#ninjahelp');
  			this.$firstRun = $('#firstrun');
  			this.$settings = $('#app-settings');
  		},
  		// Build the select to add/remove from groups.
  		buildGroupSelect: function() {
  			// If a contact is open we know which categories it's in
  			if(this.currentid) {
  				var contact = this.contacts.findById(this.currentid);
  				if(contact === null) {
  					return false;
d1bafeea1   Kload   [fix] Upgrade to ...
316
  				}
6d9380f96   Cédric Dupont   Update sources OC...
317
318
319
320
321
322
323
324
325
326
327
328
  				this.$groups.find('optgroup,option:not([value="-1"])').remove();
  				var addopts = '', rmopts = '';
  				$.each(this.groups.categories, function(i, category) {
  					if(contact.inGroup(category.name)) {
  						rmopts += '<option value="' + category.id + '">' + category.name + '</option>';
  					} else {
  						addopts += '<option value="' + category.id + '">' + category.name + '</option>';
  					}
  				});
  				if(addopts.length) {
  					$(addopts).appendTo(this.$groups)
  					.wrapAll('<optgroup data-action="add" label="' + t('contacts', 'Add to...') + '"/>');
d1bafeea1   Kload   [fix] Upgrade to ...
329
  				}
6d9380f96   Cédric Dupont   Update sources OC...
330
331
332
333
334
335
336
337
  				if(rmopts.length) {
  					$(rmopts).appendTo(this.$groups)
  					.wrapAll('<optgroup data-action="remove" label="' + t('contacts', 'Remove from...') + '"/>');
  				}
  			} else if(this.contacts.getSelectedContacts().length > 0) { // Otherwise add all categories to both add and remove
  				this.$groups.find('optgroup,option:not([value="-1"])').remove();
  				var addopts = '', rmopts = '';
  				$.each(this.groups.categories, function(i, category) {
d1bafeea1   Kload   [fix] Upgrade to ...
338
  					rmopts += '<option value="' + category.id + '">' + category.name + '</option>';
d1bafeea1   Kload   [fix] Upgrade to ...
339
  					addopts += '<option value="' + category.id + '">' + category.name + '</option>';
6d9380f96   Cédric Dupont   Update sources OC...
340
  				});
d1bafeea1   Kload   [fix] Upgrade to ...
341
  				$(addopts).appendTo(this.$groups)
6d9380f96   Cédric Dupont   Update sources OC...
342
  					.wrapAll('<optgroup data-action="add" label="' + t('contacts', 'Add to...') + '"/>');
d1bafeea1   Kload   [fix] Upgrade to ...
343
  				$(rmopts).appendTo(this.$groups)
6d9380f96   Cédric Dupont   Update sources OC...
344
345
346
347
  					.wrapAll('<optgroup data-action="remove" label="' + t('contacts', 'Remove from...') + '"/>');
  			} else {
  				// 3rd option: No contact open, none checked, just show "Add group..."
  				this.$groups.find('optgroup,option:not([value="-1"])').remove();
d1bafeea1   Kload   [fix] Upgrade to ...
348
  			}
6d9380f96   Cédric Dupont   Update sources OC...
349
350
351
352
353
354
355
356
357
358
  			$('<option value="add">' + t('contacts', 'Add group...') + '</option>').appendTo(this.$groups);
  			this.$groups.val(-1);
  		},
  		bindEvents: function() {
  			var self = this;
  
  			// Should fix Opera check for delayed delete.
  			$(window).unload(function (){
  				$(window).trigger('beforeunload');
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
359

6d9380f96   Cédric Dupont   Update sources OC...
360
361
362
363
364
365
366
367
368
  			this.hashChange = function() {
  				console.log('hashchange', window.location.hash);
  				var id = String(window.location.hash.substr(1));
  				if(id && id !== self.currentid && self.contacts.findById(id) !== null) {
  					self.openContact(id);
  				} else if(!id && self.currentid) {
  					self.closeContact(self.currentid);
  				}
  			};
d1bafeea1   Kload   [fix] Upgrade to ...
369

6d9380f96   Cédric Dupont   Update sources OC...
370
371
372
  			// This apparently get's called on some weird occasions.
  			//$(window).bind('popstate', this.hashChange);
  			$(window).bind('hashchange', this.hashChange);
d1bafeea1   Kload   [fix] Upgrade to ...
373

6d9380f96   Cédric Dupont   Update sources OC...
374
375
376
377
378
379
380
381
382
383
  			// App specific events
  			$(document).bind('status.contact.deleted', function(e, data) {
  				var id = String(data.id);
  				if(id === self.currentid) {
  					delete self.currentid;
  				}
  				console.log('contact', data.id, 'deleted');
  				// update counts on group lists
  				self.groups.removeFromAll(data.id, true, true);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
384

6d9380f96   Cédric Dupont   Update sources OC...
385
386
387
388
389
  			$(document).bind('status.contact.added', function(e, data) {
  				self.currentid = String(data.id);
  				self.buildGroupSelect();
  				self.hideActions();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
390

6d9380f96   Cédric Dupont   Update sources OC...
391
392
393
394
395
396
397
  			// Keep error messaging at one place to be able to replace it.
  			$(document).bind('status.contacts.error', function(e, data) {
  				var message = data.message;
  				console.warn(message);
  				//console.trace();
  				OC.notify({message:message});
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
398

6d9380f96   Cédric Dupont   Update sources OC...
399
400
401
402
  			$(document).bind('status.contact.enabled', function(e, enabled) {
  				console.log('status.contact.enabled', enabled);
  				/*if(enabled) {
  					self.showActions(['back', 'download', 'delete', 'groups']);
d1bafeea1   Kload   [fix] Upgrade to ...
403
  				} else {
6d9380f96   Cédric Dupont   Update sources OC...
404
405
406
407
408
409
410
  					self.showActions(['back']);
  				}*/
  			});
  
  			$(document).bind('status.contacts.count', function(e, response) {
  				console.log('Num contacts:', response.count);
  				if(response.count > 0) {
d1bafeea1   Kload   [fix] Upgrade to ...
411
412
  					self.$contactList.show();
  					self.$firstRun.hide();
d1bafeea1   Kload   [fix] Upgrade to ...
413
  				}
6d9380f96   Cédric Dupont   Update sources OC...
414
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
415

6d9380f96   Cédric Dupont   Update sources OC...
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
  			$(document).bind('status.contacts.loaded status.contacts.deleted', function(e, response) {
  				console.log('status.contacts.loaded', response);
  				if(response.error) {
  					$(document).trigger('status.contacts.error', response);
  					console.log('Error loading contacts!');
  				} else {
  					if(response.numcontacts === 0) {
  						self.$contactList.hide();
  						self.$firstRun.show();
  					} else {
  						self.$contactList.show();
  						self.$firstRun.hide();
  					$.each(self.addressBooks.addressBooks, function(idx, addressBook) {
  						console.log('addressBook', addressBook);
  						if(!addressBook.isActive()) {
  							self.contacts.showFromAddressbook(addressBook.getId(), false);
  						}
  					});
  					}
d1bafeea1   Kload   [fix] Upgrade to ...
435
  				}
6d9380f96   Cédric Dupont   Update sources OC...
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
  			});
  
  			$(document).bind('status.contact.currentlistitem', function(e, result) {
  				//console.log('status.contact.currentlistitem', result, self.$rightContent.height());
  				if(self.dontScroll !== true) {
  					if(result.pos > self.$rightContent.height()) {
  						self.$rightContent.scrollTop(result.pos - self.$rightContent.height() + result.height);
  					}
  					else if(result.pos < self.$rightContent.offset().top) {
  						self.$rightContent.scrollTop(result.pos);
  					}
  				} else {
  					setTimeout(function() {
  						self.dontScroll = false;
  					}, 100);
d1bafeea1   Kload   [fix] Upgrade to ...
451
  				}
6d9380f96   Cédric Dupont   Update sources OC...
452
453
  				self.currentlistid = result.id;
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
454

6d9380f96   Cédric Dupont   Update sources OC...
455
456
457
458
459
  			$(document).bind('status.nomorecontacts', function(e, result) {
  				console.log('status.nomorecontacts', result);
  				self.$contactList.hide();
  				self.$firstRun.show();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
460

6d9380f96   Cédric Dupont   Update sources OC...
461
462
463
464
  			$(document).bind('status.visiblecontacts', function(e, result) {
  				console.log('status.visiblecontacts', result);
  				// TODO: To be decided.
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
465

6d9380f96   Cédric Dupont   Update sources OC...
466
467
468
469
470
471
472
473
474
475
476
477
478
  			$(document).bind('request.openurl', function(e, data) {
  				switch(data.type) {
  					case 'url':
  						var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!-\/]))?/;
  						//if(new RegExp("[a-zA-Z0-9]+://([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(data.url)) {
  						if(regexp.test(data.url)) {
  							var newWindow = window.open(data.url,'_blank');
  							newWindow.focus();
  						} else {
  							$(document).trigger('status.contacts.error', {
  								error: true,
  								message: t('contacts', 'Invalid URL: "{url}"', {url:data.url})
  							});
d1bafeea1   Kload   [fix] Upgrade to ...
479
  						}
6d9380f96   Cédric Dupont   Update sources OC...
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
  						break;
  					case 'email':
  						var regexp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  						if(regexp.test(data.url)) {
  							console.log('success');
  							var url = 'mailto:' + data.url;
  							try {
  								var mailer = window.open(url, 'Mailer');
  							} catch(e) {
  								console.log('There was an error opening a mail composer.', e);
  							}
  							setTimeout(function(){
  								try {
  									if(mailer.location.href === url || mailer.location.href.substr(0, 6) === 'about:') {
  										mailer.close();
  									}
  								} catch(e) {
  									console.log('There was an error opening a mail composer.', e);
  								}
  								}, 1000);
  						} else {
  							$(document).trigger('status.contacts.error', {
  								error: true,
  								message: t('contacts', 'Invalid email: "{url}"', {url:data.url})
  							});
  						}
  						break;
  					case 'adr':
  						var address = data.url.filter(function(n) {
  							return n;
d1bafeea1   Kload   [fix] Upgrade to ...
510
  						});
6d9380f96   Cédric Dupont   Update sources OC...
511
512
513
514
515
  						var newWindow = window.open('http://open.mapquest.com/?q='+address, '_blank');
  						newWindow.focus();
  						break;
  				}
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
516

6d9380f96   Cédric Dupont   Update sources OC...
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
  			// A contact id was in the request
  			$(document).bind('request.loadcontact', function(e, result) {
  				console.log('request.loadcontact', result);
  				if(self.numcontacts) {
  					self.openContact(result.id);
  				} else {
  					// Contacts are not loaded yet, try again.
  					console.log('waiting for contacts to load');
  					setTimeout(function() {
  						$(document).trigger('request.loadcontact', {
  							id: result.id
  						});
  					}, 1000);
  				}
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
532

6d9380f96   Cédric Dupont   Update sources OC...
533
534
535
536
  			$(document).bind('request.contact.move', function(e, data) {
  				console.log('contact', data, 'request.contact.move');
  				self.addressBooks.moveContact(data.contact, data.from, data.target);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
537

6d9380f96   Cédric Dupont   Update sources OC...
538
539
540
541
  			$(document).bind('request.contact.setasfavorite', function(e, data) {
  				console.log('contact', data.id, 'request.contact.setasfavorite');
  				self.groups.setAsFavorite(data.id, data.state);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
542

6d9380f96   Cédric Dupont   Update sources OC...
543
544
545
546
  			$(document).bind('request.contact.addtogroup', function(e, data) {
  				self.groups.addTo(data.id, data.groupid, function(response) {
  					console.log('contact', data.id, 'request.contact.addtogroup', response);
  				});
d1bafeea1   Kload   [fix] Upgrade to ...
547
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
548

6d9380f96   Cédric Dupont   Update sources OC...
549
550
551
552
  			$(document).bind('request.contact.removefromgroup', function(e, data) {
  				console.log('contact', data.id, 'request.contact.removefromgroup');
  				self.groups.removeFrom(data.id, data.groupid);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
553

6d9380f96   Cédric Dupont   Update sources OC...
554
555
556
557
  			$(document).bind('request.contact.export', function(e, data) {
  				console.log('request.contact.export', data);
  				document.location.href = OC.generateUrl('apps/contacts/addressbook/{backend}/{addressBookId}/contact/{contactId}/export', data);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
558

6d9380f96   Cédric Dupont   Update sources OC...
559
560
561
562
563
  			$(document).bind('request.contact.close', function(e, data) {
  				var id = String(data.id);
  				console.log('contact', data.id, 'request.contact.close');
  				self.closeContact(id);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
564

6d9380f96   Cédric Dupont   Update sources OC...
565
566
567
568
569
  			$(document).bind('request.contact.open', function(e, data) {
  				var id = String(data.id);
  				console.log('contact', data.id, 'request.contact.open');
  				self.openContact(id);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
570

6d9380f96   Cédric Dupont   Update sources OC...
571
572
573
574
575
576
577
578
  			$(document).bind('request.contact.delete', function(e, data) {
  				var id = String(data.contactId);
  				console.log('contact', data, 'request.contact.delete');
  				self.closeContact(id);
  				self.contacts.delayedDelete(data);
  				self.$contactList.removeClass('dim');
  				self.hideActions();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
579

6d9380f96   Cédric Dupont   Update sources OC...
580
581
582
583
584
585
586
587
588
  			$(document).bind('request.contact.merge', function(e, data) {
  				console.log('contact','request.contact.merge', data);
  				var merger = self.contacts.findById(data.merger);
  				var mergees = [];
  				if(!merger) {
  					$(document).trigger('status.contacts.error', {
  						message: t('contacts', 'Merge failed. Cannot find contact: {id}', {id:data.merger})
  					});
  					return;
d1bafeea1   Kload   [fix] Upgrade to ...
589
  				}
6d9380f96   Cédric Dupont   Update sources OC...
590
591
592
593
594
595
  				$.each(data.mergees, function(idx, id) {
  					var contact = self.contacts.findById(id);
  					if(!contact) {
  						console.warn('cannot find', id, 'by id');
  					}
  					mergees.push(contact);
d1bafeea1   Kload   [fix] Upgrade to ...
596
  				});
6d9380f96   Cédric Dupont   Update sources OC...
597
  				if(!merger.merge(mergees)) {
d1bafeea1   Kload   [fix] Upgrade to ...
598
  					$(document).trigger('status.contacts.error', {
6d9380f96   Cédric Dupont   Update sources OC...
599
  						message: t('contacts', 'Merge failed.')
d1bafeea1   Kload   [fix] Upgrade to ...
600
601
  					});
  					return;
d1bafeea1   Kload   [fix] Upgrade to ...
602
  				}
6d9380f96   Cédric Dupont   Update sources OC...
603
604
605
606
607
608
609
610
611
612
613
614
615
616
  				merger.saveAll(function(response) {
  					if(response.error) {
  						$(document).trigger('status.contacts.error', {
  							message: t('contacts', 'Merge failed. Error saving contact.')
  						});
  						return;
  					} else {
  						if(data.deleteOther) {
  							self.contacts.delayedDelete(mergees);
  						}
  						console.log('merger', merger);
  						self.openContact(merger.getId());
  					}
  				});
d1bafeea1   Kload   [fix] Upgrade to ...
617
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
618

6d9380f96   Cédric Dupont   Update sources OC...
619
620
621
622
  			$(document).bind('request.select.contactphoto.fromlocal', function(e, contact) {
  				console.log('request.select.contactphoto.fromlocal', contact);
  				$('#contactphoto_fileupload').trigger('click', contact);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
623

6d9380f96   Cédric Dupont   Update sources OC...
624
625
626
627
628
629
  			$(document).bind('request.select.contactphoto.fromcloud', function(e, metadata) {
  				console.log('request.select.contactphoto.fromcloud', metadata);
  				OC.dialogs.filepicker(t('contacts', 'Select photo'), function(path) {
  					self.cloudPhotoSelected(metadata, path);
  				}, false, 'image', true);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
630

6d9380f96   Cédric Dupont   Update sources OC...
631
632
633
634
  			$(document).bind('request.edit.contactphoto', function(e, metadata) {
  				console.log('request.edit.contactphoto', metadata);
  				self.editCurrentPhoto(metadata);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
635

6d9380f96   Cédric Dupont   Update sources OC...
636
637
638
639
640
  			$(document).bind('request.groups.reload', function(e, result) {
  				console.log('request.groups.reload', result);
  				self.groups.loadGroups(function() {
  					self.groups.triggerLastGroup();
  				});
d1bafeea1   Kload   [fix] Upgrade to ...
641
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
642

6d9380f96   Cédric Dupont   Update sources OC...
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
  			$(document).bind('status.group.groupremoved', function(e, result) {
  				console.log('status.group.groupremoved', result);
  				if(parseInt(result.groupid) === parseInt(self.currentgroup)) {
  					self.contacts.showContacts([]);
  					self.currentgroup = 'all';
  				}
  				$.each(result.contacts, function(idx, contactid) {
  					var contact = self.contacts.findById(contactid);
  
  					// Test if valid because there could be stale ids in the tag index.
  					if(contact) {
  						contact.removeFromGroup(result.groupname);
  					}
  				});
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
658

6d9380f96   Cédric Dupont   Update sources OC...
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
  			$(document).bind('status.group.grouprenamed', function(e, result) {
  				console.log('status.group.grouprenamed', result);
  				$.each(result.contacts, function(idx, contactid) {
  					var contact = self.contacts.findById(contactid);
  					if(!contact) {
  						console.warn('Couldn\'t find contact', contactid);
  						return true; // continue
  					}
  					contact.renameGroup(result.from, result.to);
  				});
  			});
  
  			$(document).bind('status.group.contactremoved', function(e, result) {
  				console.log('status.group.contactremoved', result, self.currentgroup, result.groupid);
  				var contact = self.contacts.findById(result.contactid);
d1bafeea1   Kload   [fix] Upgrade to ...
674
  				if(contact) {
6d9380f96   Cédric Dupont   Update sources OC...
675
676
677
678
679
680
681
  					if(contact.inGroup(result.groupname)) {
  						contact.removeFromGroup(result.groupname);
  					}
  					if(parseInt(self.currentgroup) === parseInt(result.groupid)) {
  						console.log('Hiding', contact.getId());
  						contact.hide();
  					}
d1bafeea1   Kload   [fix] Upgrade to ...
682
683
  				}
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
684

6d9380f96   Cédric Dupont   Update sources OC...
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
  			$(document).bind('status.group.contactadded', function(e, result) {
  				console.log('status.group.contactadded', result);
  				var contact = self.contacts.findById(result.contactid);
  				if(contact) {
  					if(!contact.inGroup(result.groupname)) {
  						contact.addToGroup(result.groupname);
  					}
  					if(parseInt(self.currentgroup) === parseInt(result.groupid)) {
  						console.log('Showing', contact.getId());
  						contact.show();
  					}
  					if(self.currentgroup === 'uncategorized') {
  						console.log('Hiding', contact.getId());
  						contact.hide();
  					}
d1bafeea1   Kload   [fix] Upgrade to ...
700
  				}
d1bafeea1   Kload   [fix] Upgrade to ...
701
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
702

6d9380f96   Cédric Dupont   Update sources OC...
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
  			// Group sorted, save the sort order
  			$(document).bind('status.groups.sorted', function(e, result) {
  				console.log('status.groups.sorted', result);
  				$.when(self.storage.setPreference('groupsort', result.sortorder)).then(function(response) {
  					if(response.error) {
  						$(document).trigger('status.contacts.error', {
  							message: response ? response.message : t('contacts', 'Network or server error. Please inform administrator.')
  						});
  					}
  				})
  				.fail(function(response) {
  					console.log(response.message);
  					$(document).trigger('status.contacts.error', response);
  					done = true;
  				});
  			});
  			// Group selected, only show contacts from that group
  			$(document).bind('status.group.selected', function(e, result) {
  				console.log('status.group.selected', result);
  				self.currentgroup = result.id;
  				// Close any open contact.
  				if(self.currentid) {
  					var id = self.currentid;
  					self.closeContact(id);
  					self.jumpToContact(id);
d1bafeea1   Kload   [fix] Upgrade to ...
728
  				}
6d9380f96   Cédric Dupont   Update sources OC...
729
730
731
732
733
734
735
736
737
738
  				self.$toggleAll.show();
  				self.hideActions();
  				if(result.type === 'category' ||  result.type === 'fav') {
  					self.contacts.showContacts(result.contacts);
  				} else if(result.type === 'shared') {
  					self.contacts.showFromAddressbook(self.currentgroup, true, true);
  				} else if(result.type === 'uncategorized') {
  					self.contacts.showUncategorized();
  				} else {
  					self.contacts.showContacts(self.currentgroup);
d1bafeea1   Kload   [fix] Upgrade to ...
739
  				}
6d9380f96   Cédric Dupont   Update sources OC...
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
  				$.when(self.storage.setPreference('lastgroup', self.currentgroup)).then(function(response) {
  					if(response.error) {
  						$(document).trigger('status.contacts.error', response);
  					}
  				})
  				.fail(function(response) {
  					console.log(response.message);
  					$(document).trigger('status.contacts.error', response);
  					done = true;
  				});
  				self.$rightContent.scrollTop(0);
  			});
  			// mark items whose title was hid under the top edge as read
  			/*this.$rightContent.scroll(function() {
  				// prevent too many scroll requests;
  				if(!self.isScrolling) {
  					self.isScrolling = true;
  					var num = self.$contactList.find('tr').length;
  					//console.log('num', num);
  					var offset = self.$contactList.find('tr:eq(' + (num-20) + ')').offset().top;
  					if(offset < self.$rightContent.height()) {
  						console.log('load more');
  						self.contacts.loadContacts(num, function() {
  							self.isScrolling = false;
  						});
  					} else {
  						setTimeout(function() {
  							self.isScrolling = false;
  						}, self.scrollTimeoutMiliSecs);
  					}
  					//console.log('scroll, unseen:', offset, self.$rightContent.height());
d1bafeea1   Kload   [fix] Upgrade to ...
771
  				}
6d9380f96   Cédric Dupont   Update sources OC...
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
  			});*/
  			$('#contactphoto_fileupload').on('click', function(event, contact) {
  				console.log('contact', contact);
  				var metaData = contact.metaData();
  				var url = OC.generateUrl(
  					'apps/contacts/addressbook/{backend}/{addressBookId}/contact/{contactId}/photo',
  					{backend: metaData.backend, addressBookId: metaData.addressBookId, contactId: metaData.contactId}
  				);
  				$(this).fileupload('option', 'url', url);
  			}).fileupload({
  				singleFileUploads: true,
  				multipart: false,
  				dataType: 'json',
  				type: 'PUT',
  				dropZone: null, pasteZone: null,
  				acceptFileTypes: /^image\//,
  				add: function(e, data) {
  					var file = data.files[0];
  					if (file.type.substr(0, 6) !== 'image/') {
  						$(document).trigger('status.contacts.error', {
  							error: true,
  							message: t('contacts', 'Only images can be used as contact photos')
  						});
  						return;
  					}
  					if (file.size > parseInt($(this).siblings('[name="MAX_FILE_SIZE"]').val())) {
  						$(document).trigger('status.contacts.error', {
  							error: true,
  							message: t(
  								'contacts',
  								'The size of "{filename}" exceeds the maximum allowed {size}',
  								{filename: file.name, size: $(this).siblings('[name="max_human_file_size"]').val()}
  							)
  						});
  						return;
  					}
  					data.submit();
  				},
  				start: function(e, data) {
  					console.log('fileupload.start',data);
  				},
  				done: function (e, data) {
  					console.log('Upload done:', data);
  					self.editPhoto(
  						data.result.metadata,
  						data.result.tmp
  					);
  				},
  				fail: function(e, data) {
  					console.log('fail', data);
  					var response = self.storage.formatResponse(data.jqXHR);
  					$(document).trigger('status.contacts.error', response);
d1bafeea1   Kload   [fix] Upgrade to ...
824
  				}
6d9380f96   Cédric Dupont   Update sources OC...
825
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
826

6d9380f96   Cédric Dupont   Update sources OC...
827
828
829
830
831
832
833
  			this.$rightContent.bind('drop dragover', function (e) {
  				e.preventDefault();
  			});
  
  			this.$ninjahelp.find('.close').on('click keydown',function(event) {
  				if(wrongKey(event)) {
  					return;
d1bafeea1   Kload   [fix] Upgrade to ...
834
  				}
6d9380f96   Cédric Dupont   Update sources OC...
835
  				self.$ninjahelp.hide();
d1bafeea1   Kload   [fix] Upgrade to ...
836
  			});
6d9380f96   Cédric Dupont   Update sources OC...
837
838
839
840
841
842
843
844
  
  			this.$toggleAll.on('change', function(event) {
  				event.stopPropagation();
  				event.preventDefault();
  				var isChecked = $(this).is(':checked');
  				self.setAllChecked(isChecked);
  				if(self.$groups.find('option').length === 1) {
  					self.buildGroupSelect();
d1bafeea1   Kload   [fix] Upgrade to ...
845
  				}
6d9380f96   Cédric Dupont   Update sources OC...
846
847
  				if(isChecked) {
  					self.showActions(['toggle', 'add', 'download', 'groups', 'delete', 'favorite', 'merge']);
d1bafeea1   Kload   [fix] Upgrade to ...
848
  				} else {
6d9380f96   Cédric Dupont   Update sources OC...
849
  					self.hideActions();
d1bafeea1   Kload   [fix] Upgrade to ...
850
  				}
6d9380f96   Cédric Dupont   Update sources OC...
851
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
852

6d9380f96   Cédric Dupont   Update sources OC...
853
854
855
856
857
858
859
  			this.$contactList.on('change', 'input:checkbox', function(/*event*/) {
  				var selected = self.contacts.getSelectedContacts();
  				var id = String($(this).val());
  				// Save list of last selected contact to be able to select range
  				$(this).is(':checked') && self.lastSelectedContacts.indexOf(id) === -1
  					? self.lastSelectedContacts.push(id)
  					: self.lastSelectedContacts.splice(self.lastSelectedContacts.indexOf(id), 1);
d1bafeea1   Kload   [fix] Upgrade to ...
860

6d9380f96   Cédric Dupont   Update sources OC...
861
862
863
864
865
866
867
868
869
870
871
  				if(selected.length > 0 && self.$groups.find('option').length === 1) {
  					self.buildGroupSelect();
  				}
  				if(selected.length === 0) {
  					self.hideActions();
  				} else if(selected.length === 1) {
  					self.showActions(['toggle', 'add', 'download', 'groups', 'delete', 'favorite']);
  				} else {
  					self.showActions(['toggle', 'add', 'download', 'groups', 'delete', 'favorite', 'merge']);
  				}
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
872

6d9380f96   Cédric Dupont   Update sources OC...
873
874
875
876
877
878
  			this.$contactList.on('click', 'label:not([for=select_all])', function(/*event*/) {
  				var $input = $(this).prev('input');
  				$input.prop('checked', !$input.prop('checked'));
  				$input.trigger('change');
  				return false; // Prevent opening contact
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
879

6d9380f96   Cédric Dupont   Update sources OC...
880
881
882
  			// Add title to names that would elliptisized (is that a word?)
  			this.$contactList.on('mouseenter', '.nametext', function() {
  				var $this = $(this);
d1bafeea1   Kload   [fix] Upgrade to ...
883

6d9380f96   Cédric Dupont   Update sources OC...
884
885
886
887
  				if($this.width() > $this.parent().width() && !$this.attr('title')) {
  					$this.attr('title', $this.text());
  				}
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
888

6d9380f96   Cédric Dupont   Update sources OC...
889
890
891
892
893
894
895
  			this.$sortOrder.on('change', function() {
  				$(this).blur().addClass('loading');
  				contacts_sortby = $(this).val();
  				self.contacts.setSortOrder();
  				$(this).removeClass('loading');
  				self.storage.setPreference('sortby', contacts_sortby);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
896

6d9380f96   Cédric Dupont   Update sources OC...
897
898
899
900
901
  			// Add to/remove from group multiple contacts.
  			this.$groups.on('change', function() {
  				var $opt = $(this).find('option:selected');
  				var action = $opt.parent().data('action');
  				var groupName, groupId, buildnow = false;
d1bafeea1   Kload   [fix] Upgrade to ...
902

6d9380f96   Cédric Dupont   Update sources OC...
903
904
  				var contacts = self.contacts.getSelectedContacts();
  				var ids = $.map(contacts, function(c) {return c.getId();});
d1bafeea1   Kload   [fix] Upgrade to ...
905

6d9380f96   Cédric Dupont   Update sources OC...
906
907
908
909
910
  				self.setAllChecked(false);
  				self.$toggleAll.prop('checked', false);
  				if(!self.currentid) {
  					self.hideActions();
  				}
d1bafeea1   Kload   [fix] Upgrade to ...
911

6d9380f96   Cédric Dupont   Update sources OC...
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
  				if($opt.val() === 'add') { // Add new group
  					action = 'add';
  					console.log('add group...');
  					self.$groups.val(-1);
  					self.addGroup(function(response) {
  						if(!response.error) {
  							groupId = response.id;
  							groupName = response.name;
  							self.groups.addTo(ids, groupId, function(result) {
  								if(!result.error) {
  									$.each(ids, function(idx, id) {
  										// Delay each contact to not trigger too many ajax calls
  										// at a time.
  										setTimeout(function() {
  											var contact = self.contacts.findById(id);
  											if(contact === null) {
  												return true;
  											}
  											contact.addToGroup(groupName);
  											// I don't think this is used...
  											if(buildnow) {
  												self.buildGroupSelect();
  											}
  										}, 1000);
  									});
  								} else {
  									$(document).trigger('status.contacts.error', result);
  								}
  							});
  						} else {
  							$(document).trigger('status.contacts.error', response);
  						}
  					});
  					return;
  				}
d1bafeea1   Kload   [fix] Upgrade to ...
947

6d9380f96   Cédric Dupont   Update sources OC...
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
  				groupName = $opt.text(), groupId = $opt.val();
  
  				if(action === 'add') {
  					self.groups.addTo(ids, $opt.val(), function(result) {
  						console.log('after add', result);
  						if(!result.error) {
  							$.each(result.ids, function(idx, id) {
  								// Delay each contact to not trigger too many ajax calls
  								// at a time.
  								setTimeout(function() {
  									console.log('adding', id, 'to', groupName);
  									var contact = self.contacts.findById(id);
  									if(contact === null) {
  										return true;
  									}
  									contact.addToGroup(groupName);
  									// I don't think this is used...
  									if(buildnow) {
  										self.buildGroupSelect();
  									}
  								}, 1000);
  							});
  						} else {
  							var msg = result.message ? result.message : t('contacts', 'Error adding to group.');
  							$(document).trigger('status.contacts.error', {message:msg});
  						}
  					});
  					if(!buildnow) {
  						self.$groups.val(-1).hide().find('optgroup,option:not([value="-1"])').remove();
  					}
  				} else if(action === 'remove') {
  					self.groups.removeFrom(ids, $opt.val(), false, function(result) {
  						console.log('after remove', result);
  						if(!result.error) {
  							var groupname = $opt.text(), groupid = $opt.val();
  							$.each(result.ids, function(idx, id) {
d1bafeea1   Kload   [fix] Upgrade to ...
984
985
986
987
  								var contact = self.contacts.findById(id);
  								if(contact === null) {
  									return true;
  								}
6d9380f96   Cédric Dupont   Update sources OC...
988
  								contact.removeFromGroup(groupname);
d1bafeea1   Kload   [fix] Upgrade to ...
989
990
991
  								if(buildnow) {
  									self.buildGroupSelect();
  								}
6d9380f96   Cédric Dupont   Update sources OC...
992
993
994
995
996
997
998
999
  							});
  						} else {
  							var msg = result.message ? result.message : t('contacts', 'Error removing from group.');
  							$(document).trigger('status.contacts.error', {message:msg});
  						}
  					});
  					if(!buildnow) {
  						self.$groups.val(-1).hide().find('optgroup,option:not([value="-1"])').remove();
d1bafeea1   Kload   [fix] Upgrade to ...
1000
  					}
6d9380f96   Cédric Dupont   Update sources OC...
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
  				} // else something's wrong ;)
  				self.setAllChecked(false);
  			});
  
  			this.$contactList.on('mouseenter', 'tr.contact', function(event) {
  				if ($(this).data('obj').hasPermission(OC.PERMISSION_DELETE)) {
  					var $td = $(this).find('td').filter(':visible').last();
  					$('<a />').addClass('icon-delete svg delete action').appendTo($td);
  				}
  			});
  
  			this.$contactList.on('mouseleave', 'tr.contact', function(event) {
  				$(this).find('a.delete').remove();
  			});
  
  			// Prevent Firefox from selecting the table-cell
  			this.$contactList.mousedown(function (event) {
  				if (event.ctrlKey || event.metaKey || event.shiftKey) {
  					event.preventDefault();
  				}
  			});
  
  			$(window).on('click', function(event) {
  				if(!$(event.target).is('a[href^="mailto"]')) {
  					return;
  				}
  				console.log('mailto clicked', $(event.target));
  
  				$(document).trigger('request.openurl', {
  					type: 'email',
  					url: $(event.target).attr('href').substr(7)
d1bafeea1   Kload   [fix] Upgrade to ...
1032
  				});
6d9380f96   Cédric Dupont   Update sources OC...
1033
1034
1035
1036
1037
1038
1039
1040
1041
  
  				event.stopPropagation();
  				event.preventDefault();
  			});
  
  			// Contact list. Either open a contact or perform an action (mailto etc.)
  			this.$contactList.on('click', 'tr.contact', function(event) {
  				if($(event.target).is('input') || $(event.target).is('a[href^="mailto"]')) {
  					return;
d1bafeea1   Kload   [fix] Upgrade to ...
1042
  				}
6d9380f96   Cédric Dupont   Update sources OC...
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
  				// Select a single contact or a range of contacts.
  				if(event.ctrlKey || event.metaKey || event.shiftKey) {
  					event.stopPropagation();
  					event.preventDefault();
  					self.dontScroll = true;
  					var $input = $(this).find('input:checkbox');
  					var index = self.$contactList.find('tr.contact:visible').index($(this));
  					if(event.shiftKey && self.lastSelectedContacts.length > 0) {
  						self.contacts.selectRange(
  							$(this).data('id'),
  							self.lastSelectedContacts[self.lastSelectedContacts.length-1]
  						);
d1bafeea1   Kload   [fix] Upgrade to ...
1055
  					} else {
6d9380f96   Cédric Dupont   Update sources OC...
1056
  						self.contacts.setSelected($(this).data('id'), !$input.prop('checked'));
d1bafeea1   Kload   [fix] Upgrade to ...
1057
  					}
6d9380f96   Cédric Dupont   Update sources OC...
1058
  					return;
d1bafeea1   Kload   [fix] Upgrade to ...
1059
  				}
6d9380f96   Cédric Dupont   Update sources OC...
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
  				if($(event.target).is('a.mailto')) {
  					$(document).trigger('request.openurl', {
  						type: 'email',
  						url: $.trim($(this).find('.email').text())
  					});
  					return;
  				}
  				if($(event.target).is('a.delete')) {
  					$(document).trigger('request.contact.delete', {
  						contactId: $(this).data('id')
  					});
  					return;
  				}
  				self.openContact(String($(this).data('id')));
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1075

6d9380f96   Cédric Dupont   Update sources OC...
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
  			this.$settings.find('#app-settings-header').on('click keydown',function(event) {
  				if(wrongKey(event)) {
  					return;
  				}
  				var bodyListener = function(e) {
  					if(self.$settings.find($(e.target)).length === 0) {
  						self.$settings.switchClass('open', '');
  					}
  				};
  				if(self.$settings.hasClass('open')) {
  					self.$settings.switchClass('open', '');
  					$('body').unbind('click', bodyListener);
  				} else {
  					self.$settings.switchClass('', 'open');
  					$('body').bind('click', bodyListener);
  				}
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1093

6d9380f96   Cédric Dupont   Update sources OC...
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
  			var addContact = function() {
  				console.log('add');
  				if(self.currentid) {
  					if(self.currentid === 'new') {
  						return;
  					} else {
  						var contact = self.contacts.findById(self.currentid);
  						if(contact) {
  							contact.close(true);
  						}
  					}
  				}
  				self.currentid = 'new';
  				// Properties that the contact doesn't know
  				console.log('addContact, groupid', self.currentgroup);
  				var groupprops = {
  					favorite: false,
  					groups: self.groups.categories,
  					currentgroup: {id:self.currentgroup, name:self.groups.nameById(self.currentgroup)}
  				};
  				self.$firstRun.hide();
  				self.$contactList.show();
  				self.tmpcontact = self.contacts.addContact(groupprops);
  				self.tmpcontact.prependTo(self.$contactList.find('tbody')).show().find('.fullname').focus();
  				self.$rightContent.scrollTop(0);
  				self.hideActions();
  			};
d1bafeea1   Kload   [fix] Upgrade to ...
1121

6d9380f96   Cédric Dupont   Update sources OC...
1122
  			this.$firstRun.on('click keydown', '.import', function(event) {
d1bafeea1   Kload   [fix] Upgrade to ...
1123
  				event.preventDefault();
d1bafeea1   Kload   [fix] Upgrade to ...
1124
  				event.stopPropagation();
6d9380f96   Cédric Dupont   Update sources OC...
1125
1126
1127
1128
1129
1130
  				self.$settings.find('.settings').click();
  			});
  
  			this.$firstRun.on('click keydown', '.add-contact', function(event) {
  				if(wrongKey(event)) {
  					return;
d1bafeea1   Kload   [fix] Upgrade to ...
1131
  				}
6d9380f96   Cédric Dupont   Update sources OC...
1132
1133
  				addContact();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1134

6d9380f96   Cédric Dupont   Update sources OC...
1135
1136
1137
  			this.$groupList.on('click keydown', '.add-contact', function(event) {
  				if(wrongKey(event)) {
  					return;
d1bafeea1   Kload   [fix] Upgrade to ...
1138
  				}
6d9380f96   Cédric Dupont   Update sources OC...
1139
1140
  				addContact();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1141

6d9380f96   Cédric Dupont   Update sources OC...
1142
1143
  			this.$contactListHeader.on('click keydown', '.delete', function(event) {
  				if(wrongKey(event)) {
d1bafeea1   Kload   [fix] Upgrade to ...
1144
  					return;
6d9380f96   Cédric Dupont   Update sources OC...
1145
1146
1147
1148
1149
1150
  				}
  				console.log('delete');
  				if(self.currentid) {
  					console.assert(typeof self.currentid === 'string', 'self.currentid is not a string');
  					contactInfo = self.contacts[self.currentid].metaData();
  					self.contacts.delayedDelete(contactInfo);
d1bafeea1   Kload   [fix] Upgrade to ...
1151
  				} else {
6d9380f96   Cédric Dupont   Update sources OC...
1152
  					self.contacts.delayedDelete(self.contacts.getSelectedContacts());
d1bafeea1   Kload   [fix] Upgrade to ...
1153
  				}
6d9380f96   Cédric Dupont   Update sources OC...
1154
1155
  				self.hideActions();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1156

6d9380f96   Cédric Dupont   Update sources OC...
1157
1158
1159
1160
  			this.$contactListHeader.on('click keydown', '.download', function(event) {
  				if(wrongKey(event)) {
  					return;
  				}
d1bafeea1   Kload   [fix] Upgrade to ...
1161

6d9380f96   Cédric Dupont   Update sources OC...
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
  				var doDownload = function(contacts) {
  					// Only get backend, addressbookid and contactid
  					contacts = $.map(contacts, function(c) {return c.metaData();});
  					var targets = {};
  					// Try to shorten request URI
  					$.each(contacts, function(idx, contact) {
  						if(!targets[contact.backend]) {
  							targets[contact.backend] = {};
  						}
  						if(!targets[contact.backend][contact.addressBookId]) {
  							targets[contact.backend][contact.addressBookId] = [];
  						}
  						targets[contact.backend][contact.addressBookId].push(contact.contactId);
  					});
  					var url = OC.generateUrl('exportSelected', {t:targets});
  					//console.log('export url', url);
  					document.location.href = url;
  				};
  				var contacts = self.contacts.getSelectedContacts();
  				console.log('download', contacts.length);
  
  				// The 300 is just based on my little testing with Apache2
  				// Other web servers may fail before.
  				if(contacts.length > 300) {
  					OC.notify({
  						message:t('contacts', 'You have selected over 300 contacts.
  This will most likely fail! Click here to try anyway.'),
  						timeout:5,
  						clickhandler:function() {
  							doDownload(contacts);
  						}
  					});
  				} else {
  					doDownload(contacts);
  				}
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1198

6d9380f96   Cédric Dupont   Update sources OC...
1199
1200
1201
1202
1203
1204
1205
  			this.$contactListHeader.on('click keydown', '.merge', function(event) {
  				if(wrongKey(event)) {
  					return;
  				}
  				console.log('merge');
  				self.mergeSelectedContacts();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1206

6d9380f96   Cédric Dupont   Update sources OC...
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
  			this.$contactListHeader.on('click keydown', '.favorite', function(event) {
  				if(wrongKey(event)) {
  					return;
  				}
  
  				var contacts = self.contacts.getSelectedContacts();
  
  				self.setAllChecked(false);
  				self.$toggleAll.prop('checked', false);
  				if(!self.currentid) {
  					self.hideActions();
  				}
d1bafeea1   Kload   [fix] Upgrade to ...
1219

d1bafeea1   Kload   [fix] Upgrade to ...
1220
  				$.each(contacts, function(idx, contact) {
6d9380f96   Cédric Dupont   Update sources OC...
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
  					if(!self.groups.isFavorite(contact.getId())) {
  						self.groups.setAsFavorite(contact.getId(), true, function(result) {
  							if(result.status !== 'success') {
  								$(document).trigger('status.contacts.error', {message:
  									t('contacts',
  										'Error setting {name} as favorite.',
  										{name:contact.getDisplayName()})
  								});
  							}
  						});
d1bafeea1   Kload   [fix] Upgrade to ...
1231
1232
  					}
  				});
d1bafeea1   Kload   [fix] Upgrade to ...
1233

d1bafeea1   Kload   [fix] Upgrade to ...
1234
  				self.hideActions();
6d9380f96   Cédric Dupont   Update sources OC...
1235
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1236

6d9380f96   Cédric Dupont   Update sources OC...
1237
1238
1239
  			this.$contactList.on('mouseenter', 'td.email', function(event) {
  				if($.trim($(this).text()).length > 3) {
  					$(this).find('.mailto').css('display', 'inline-block'); //.fadeIn(100);
d1bafeea1   Kload   [fix] Upgrade to ...
1240
1241
  				}
  			});
6d9380f96   Cédric Dupont   Update sources OC...
1242
1243
1244
  			this.$contactList.on('mouseleave', 'td.email', function(event) {
  				$(this).find('.mailto').fadeOut(100);
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1245

6d9380f96   Cédric Dupont   Update sources OC...
1246
1247
1248
  			$('body').on('touchmove', function(event) {
  				event.preventDefault();
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1249

6d9380f96   Cédric Dupont   Update sources OC...
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
  			$(document).on('keyup', function(event) {
  				if(!$(event.target).is('body') || event.isPropagationStopped()) {
  					return;
  				}
  				var keyCode = Math.max(event.keyCode, event.which);
  				// TODO: This should go in separate method
  				console.log(event, keyCode + ' ' + event.target.nodeName);
  				/**
  				* To add:
  				* Shift-a: add addressbook
  				* u (85): hide/show leftcontent
  				* f (70): add field
  				*/
  				switch(keyCode) {
  					case 13: // Enter?
  						console.log('Enter?');
  						if(!self.currentid && self.currentlistid) {
  							self.openContact(self.currentlistid);
  						}
d1bafeea1   Kload   [fix] Upgrade to ...
1269
  						break;
6d9380f96   Cédric Dupont   Update sources OC...
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
  					case 27: // Esc
  						if(self.$ninjahelp.is(':visible')) {
  							self.$ninjahelp.hide();
  						} else if(self.currentid) {
  							self.closeContact(self.currentid);
  						}
  						break;
  					case 46: // Delete
  						if(event.shiftKey) {
  							self.contacts.delayedDelete(self.currentid);
  						}
  						break;
  					case 40: // down
  					case 74: // j
  						console.log('next');
  						if(!self.currentid && self.currentlistid) {
  							self.contacts.contacts[self.currentlistid].next();
  						}
  						break;
  					case 65: // a
  						if(event.shiftKey) {
  							console.log('add group?');
  							break;
  						}
  						addContact();
  						break;
  					case 38: // up
  					case 75: // k
  						console.log('previous');
  						if(!self.currentid && self.currentlistid) {
  							self.contacts.contacts[self.currentlistid].prev();
  						}
  						break;
  					case 34: // PageDown
  					case 78: // n
  						console.log('page down');
  						break;
  					case 79: // o
  						console.log('open contact?');
  						break;
  					case 33: // PageUp
  					case 80: // p
  						// prev addressbook
  						//OC.contacts.contacts.previousAddressbook();
  						break;
  					case 82: // r
  						console.log('refresh - what?');
  						break;
  					case 63: // ? German.
  						if(event.shiftKey) {
  							self.$ninjahelp.toggle('fast');
  						}
  						break;
  					case 171: // ? Danish
  					case 191: // ? Standard qwerty
  						self.$ninjahelp.toggle('fast').position({my: 'center', at: 'center', of: '#content'});
  						break;
  				}
d1bafeea1   Kload   [fix] Upgrade to ...
1328

6d9380f96   Cédric Dupont   Update sources OC...
1329
  			});
d1bafeea1   Kload   [fix] Upgrade to ...
1330

6d9380f96   Cédric Dupont   Update sources OC...
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
  			// find all with a title attribute and tipsy them
  			$('.tooltipped.downwards:not(.onfocus)').tipsy({gravity: 'n'});
  			$('.tooltipped.upwards:not(.onfocus)').tipsy({gravity: 's'});
  			$('.tooltipped.rightwards:not(.onfocus)').tipsy({gravity: 'w'});
  			$('.tooltipped.leftwards:not(.onfocus)').tipsy({gravity: 'e'});
  			$('.tooltipped.downwards.onfocus').tipsy({trigger: 'focus', gravity: 'n'});
  			$('.tooltipped.rightwards.onfocus').tipsy({trigger: 'focus', gravity: 'w'});
  		},
  		mergeSelectedContacts: function() {
  			var contacts = this.contacts.getSelectedContacts();
  			this.$rightContent.append('<div id="merge_contacts_dialog"></div>');
  			if(!this.$mergeContactsTmpl) {
  				this.$mergeContactsTmpl = $('#mergeContactsTemplate');
d1bafeea1   Kload   [fix] Upgrade to ...
1344
  			}
6d9380f96   Cédric Dupont   Update sources OC...
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
  			var $dlg = this.$mergeContactsTmpl.octemplate();
  			var $liTmpl = $dlg.find('li').detach();
  			var $mergeList = $dlg.find('.mergelist');
  			$.each(contacts, function(idx, contact) {
  				var $li = $liTmpl
  					.octemplate({idx: idx, id: contact.getId(), displayname: contact.getDisplayName()});
  				if(!contact.data.thumbnail) {
  					$li.addClass('thumbnail');
  				} else {
  					$li.css('background-image', 'url(data:image/png;base64,' + contact.data.thumbnail + ')');
  				}
  				if(idx === 0) {
  					$li.find('input:radio').prop('checked', true);
  				}
  				$mergeList.append($li);
  			});
  			$('#merge_contacts_dialog').html($dlg).ocdialog({
  				modal: true,
  				closeOnEscape: true,
  				title:  t('contacts', 'Merge contacts'),
  				height: 'auto', width: 'auto',
  				buttons: [
  					{
  						text: t('contacts', 'Merge contacts'),
  						click:function() {
  							// Do the merging, use $(this) to get dialog
  							var contactid = $(this).find('input:radio:checked').val();
  							var others = [];
  							var deleteOther = $(this).find('#delete_other').prop('checked');
  							console.log('Selected contact', contactid, 'Delete others', deleteOther);
  							$.each($(this).find('input:radio:not(:checked)'), function(idx, item) {
  								others.push($(item).val());
  							});
  							console.log('others', others);
  							$(document).trigger('request.contact.merge', {
  								merger: contactid,
  								mergees: others,
  								deleteOther: deleteOther
  							});
d1bafeea1   Kload   [fix] Upgrade to ...
1384

6d9380f96   Cédric Dupont   Update sources OC...
1385
1386
1387
  							$(this).ocdialog('close');
  						},
  						defaultButton: true
d1bafeea1   Kload   [fix] Upgrade to ...
1388
  					},
6d9380f96   Cédric Dupont   Update sources OC...
1389
1390
1391
1392
  					{
  						text: t('contacts', 'Cancel'),
  						click:function() {
  							$(this).ocdialog('close');
d1bafeea1   Kload   [fix] Upgrade to ...
1393
1394
  							return false;
  						}
d1bafeea1   Kload   [fix] Upgrade to ...
1395
  					}
6d9380f96   Cédric Dupont   Update sources OC...
1396
1397
1398
1399
1400
1401
1402
  				],
  				close: function(/*event, ui*/) {
  					$(this).ocdialog('destroy').remove();
  					$('#merge_contacts_dialog').remove();
  				},
  				open: function(/*event, ui*/) {
  					$dlg.find('input').focus();
d1bafeea1   Kload   [fix] Upgrade to ...
1403
  				}
6d9380f96   Cédric Dupont   Update sources OC...
1404
1405
1406
1407
1408
1409
1410
  			});
  		},
  		addGroup: function(cb) {
  			var self = this;
  			this.$rightContent.append('<div id="add_group_dialog"></div>');
  			if(!this.$addGroupTmpl) {
  				this.$addGroupTmpl = $('#addGroupTemplate');
d1bafeea1   Kload   [fix] Upgrade to ...
1411
  			}
6d9380f96   Cédric Dupont   Update sources OC...
1412
1413
1414
  			this.$contactList.addClass('dim');
  			var $dlg = this.$addGroupTmpl.octemplate();
  			$('#add_group_dialog').html($dlg).ocdialog({
d1bafeea1   Kload   [fix] Upgrade to ...
1415
1416
  				modal: true,
  				closeOnEscape: true,
6d9380f96   Cédric Dupont   Update sources OC...
1417
1418
  				title:  t('contacts', 'Add group'),
  				height: 'auto', width: 'auto',
d1bafeea1   Kload   [fix] Upgrade to ...
1419
1420
  				buttons: [
  					{
6d9380f96   Cédric Dupont   Update sources OC...
1421
  						text: t('contacts', 'OK'),
d1bafeea1   Kload   [fix] Upgrade to ...
1422
  						click:function() {
6d9380f96   Cédric Dupont   Update sources OC...
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
  							var name = $(this).find('input').val();
  							if(name.trim() === '') {
  								return false;
  							}
  							self.groups.addGroup(
  								{name:$dlg.find('input:text').val()},
  								function(response) {
  									if(typeof cb === 'function') {
  										cb(response);
  									} else {
  										if(response.error) {
  											$(document).trigger('status.contacts.error', response);
  										}
  									}
  								});
  							$(this).ocdialog('close');
d1bafeea1   Kload   [fix] Upgrade to ...
1439
1440
  						},
  						defaultButton: true
6d9380f96   Cédric Dupont   Update sources OC...
1441
1442
1443
1444
1445
1446
1447
  					},
  					{
  						text: t('contacts', 'Cancel'),
  						click:function() {
  							$(this).ocdialog('close');
  							return false;
  						}
d1bafeea1   Kload   [fix] Upgrade to ...
1448
1449
  					}
  				],
6d9380f96   Cédric Dupont   Update sources OC...
1450
  				close: function(/*event, ui*/) {
d1bafeea1   Kload   [fix] Upgrade to ...
1451
  					$(this).ocdialog('destroy').remove();
6d9380f96   Cédric Dupont   Update sources OC...
1452
1453
  					$('#add_group_dialog').remove();
  					self.$contactList.removeClass('dim');
d1bafeea1   Kload   [fix] Upgrade to ...
1454
  				},
6d9380f96   Cédric Dupont   Update sources OC...
1455
1456
  				open: function(/*event, ui*/) {
  					$dlg.find('input').focus();
d1bafeea1   Kload   [fix] Upgrade to ...
1457
1458
  				}
  			});
6d9380f96   Cédric Dupont   Update sources OC...
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
  		},
  		setAllChecked: function(checked) {
  			var selector = checked ? 'input:checkbox:visible:not(checked)' : 'input:checkbox:visible:checked';
  			$.each(this.$contactList.find(selector), function() {
  				$(this).prop('checked', checked);
  			});
  			this.lastSelectedContacts = [];
  		},
  		jumpToContact: function(id) {
  			this.$rightContent.scrollTop(this.contacts.contactPos(id));
  		},
  		closeContact: function(id) {
  			$(window).unbind('hashchange', this.hashChange);
  			if(this.currentid === 'new') {
  				this.tmpcontact.slideUp().remove();
  				this.$contactList.show();
  			} else {
  				var contact = this.contacts.findById(id);
  				if(contact) {
  					// Only show the list element if contact is in current group
  					var showListElement = contact.inGroup(this.groups.nameById(this.currentgroup))
  						|| ['all', 'fav', 'uncategorized'].indexOf(this.currentgroup) !== -1
  						|| (this.currentgroup === 'uncategorized' && contact.groups().length === 0);
  					contact.close(showListElement);
  				}
  			}
  			delete this.currentid;
  			this.hideActions();
  			this.$groups.find('optgroup,option:not([value="-1"])').remove();
  			if(this.contacts.length === 0) {
  				$(document).trigger('status.nomorecontacts');
  			}
  			window.location.hash = '';
  			$(window).bind('hashchange', this.hashChange);
  		},
  		openContact: function(id) {
  			var self = this, contact;
  			if(typeof id === 'undefined' || id === 'undefined') {
  				console.warn('id is undefined!');
  				console.trace();
  			}
  			console.log('Contacts.openContact', id, typeof id);
  			if(this.currentid && this.currentid !== id) {
  				this.closeContact(this.currentid);
  			}
  			contact = this.contacts.findById(id);
  			if (!contact) {
  				console.warn('Contact', id, 'not found. Possibly deleted');
  				return;
  			}
  			this.currentid = id;
  			this.hideActions();
  			// If opened from search we can't be sure the contact is in currentgroup
  			if(!contact.inGroup(this.groups.nameById(this.currentgroup))
  				&& ['all', 'fav', 'uncategorized'].indexOf(this.currentgroup) === -1
  			) {
  				this.groups.selectGroup({id:'all'});
  			}
  			$(window).unbind('hashchange', this.hashChange);
  			console.assert(typeof this.currentid === 'string', 'Current ID not string:' + this.currentid);
  			// Properties that the contact doesn't know
  			var groupprops = {
  				favorite: this.groups.isFavorite(this.currentid),
  				groups: this.groups.categories,
  				currentgroup: {id:this.currentgroup, name:this.groups.nameById(this.currentgroup)}
  			};
  			if(!contact) {
  				console.warn('Error opening', this.currentid);
  				$(document).trigger('status.contacts.error', {
  					message: t('contacts', 'Could not find contact: {id}', {id:this.currentid})
  				});
  				this.currentid = null;
  				return;
  			}
  			var $contactelem = contact.renderContact(groupprops);
  			var $listElement = contact.getListItemElement();
  			console.log('selected element', $listElement);
  			window.location.hash = this.currentid;
  			$contactelem.insertAfter($listElement).show().find('.fullname').focus();
  			// Remove once IE8 is finally obsoleted in oC.
  			if (!OC.Util.hasSVGSupport()) {
  				OC.Util.replaceSVG($contactelem);
  			}
  			self.jumpToContact(self.currentid);
  			$listElement.hide();
  			setTimeout(function() {
  				$(window).bind('hashchange', self.hashChange);
  			}, 500);
  		},
  		update: function() {
  			console.log('update');
  		},
  		cloudPhotoSelected:function(metadata, path) {
  			var self = this;
  			console.log('cloudPhotoSelected', metadata);
  			var url = OC.generateUrl(
  				'apps/contacts/addressbook/{backend}/{addressBookId}/contact/{contactId}/photo/cacheFS',
  				{backend: metadata.backend, addressBookId: metadata.addressBookId, contactId: metadata.contactId}
  			);
  			var jqXHR = $.getJSON(url, {path: path}, function(response) {
  				console.log('response', response);
  				response = self.storage.formatResponse(jqXHR);
  				if(!response.error) {
  					self.editPhoto(metadata, response.data.tmp);
  				} else {
  					$(document).trigger('status.contacts.error', response);
  				}
  			}).fail(function(response) {
  				response = self.storage.formatResponse(jqXHR);
  				console.warn('response', response);
  				$(document).trigger('status.contacts.error', response);
  			});
  		},
  		editCurrentPhoto:function(metadata) {
  			var self = this;
  			var url = OC.generateUrl(
  				'apps/contacts/addressbook/{backend}/{addressBookId}/contact/{contactId}/photo/cacheCurrent',
  				{backend: metadata.backend, addressBookId: metadata.addressBookId, contactId: metadata.contactId}
  			);
  			console.log('url', url);
  			var jqXHR = $.getJSON(url, function(response) {
  				response = self.storage.formatResponse(jqXHR);
  				if(!response.error) {
  					self.editPhoto(metadata, response.data.tmp);
  				} else {
  					$(document).trigger('status.contacts.error', response);
  				}
  			}).fail(function(response) {
  				response = self.storage.formatResponse(jqXHR);
  				console.warn('response', response);
  				$(document).trigger('status.contacts.error', response);
  			});
  		},
  		editPhoto:function(metadata, tmpkey) {
  			console.log('editPhoto', metadata, tmpkey);
  			$('.tipsy').remove();
  			// Simple event handler, called from onChange and onSelect
  			// event handlers, as per the Jcrop invocation below
  			var showCoords = function(c) {
  				$('#x').val(c.x);
  				$('#y').val(c.y);
  				$('#w').val(c.w);
  				$('#h').val(c.h);
  			};
  
  			var clearCoords = function() {
  				$('#coords input').val('');
  			};
  
  			var self = this;
  			if(!this.$cropBoxTmpl) {
  				this.$cropBoxTmpl = $('#cropBoxTemplate');
  			}
  			var $container = $('<div />').appendTo($('#content'));
  			var $dlg = this.$cropBoxTmpl.octemplate().prependTo($container);
  
  			$.when(this.storage.getTempContactPhoto(
  				metadata.backend,
  				metadata.addressBookId,
  				metadata.contactId,
  				tmpkey
  			))
  			.then(function(image) {
  				var x = 5, y = 5, w = Math.min(image.width, image.height), h = w;
  				//$dlg.css({'min-width': w, 'min-height': h});
  				console.log(x,y,w,h);
  				$(image).attr('id', 'cropbox').prependTo($dlg).show()
  				.Jcrop({
  					onChange:	showCoords,
  					onSelect:	showCoords,
  					onRelease:	clearCoords,
  					//maxSize:	[w, h],
  					bgColor:	'black',
  					bgOpacity:	.4,
  					boxWidth:	400,
  					boxHeight:	400,
  					setSelect:	[ x, y, w-10, h-10 ],
  					aspectRatio: 1
  				});
  				$container.ocdialog({
  					modal: true,
  					closeOnEscape: true,
  					title:  t('contacts', 'Edit profile picture'),
  					height: image.height+100, width: image.width+20,
  					buttons: [
  						{
  							text: t('contacts', 'Crop photo'),
  							click:function() {
  								self.savePhoto($(this), metadata, tmpkey, function() {
  									$container.ocdialog('close');
  								});
  							},
  							defaultButton: true
  						}
  					],
  					close: function(/*event, ui*/) {
  						$(this).ocdialog('destroy').remove();
  						$container.remove();
  					},
  					open: function(/*event, ui*/) {
  						showCoords({x:x,y:y,w:w-10,h:h-10});
  					}
  				});
  			})
  			.fail(function() {
  				console.warn('Error getting temporary photo');
  			});
  		},
  		savePhoto:function($dlg, metaData, key, cb) {
  			var coords = {};
  			$.each($dlg.find('#coords').serializeArray(), function(idx, coord) {
  				coords[coord.name] = coord.value;
  			});
  
  			$.when(this.storage.cropContactPhoto(
  				metaData.backend, metaData.addressBookId, metaData.contactId, key, coords
  			))
  			.then(function(response) {
d1bafeea1   Kload   [fix] Upgrade to ...
1677
1678
1679
1680
  				$(document).trigger('status.contact.photoupdated', {
  					id: response.data.id,
  					thumbnail: response.data.thumbnail
  				});
6d9380f96   Cédric Dupont   Update sources OC...
1681
1682
1683
1684
  			})
  			.fail(function(response) {
  				console.log('response', response);
  				if(!response || !response.message) {
d1bafeea1   Kload   [fix] Upgrade to ...
1685
1686
1687
1688
1689
1690
  					$(document).trigger('status.contacts.error', {
  						message:t('contacts', 'Network or server error. Please inform administrator.')
  					});
  				} else {
  					$(document).trigger('status.contacts.error', response);
  				}
6d9380f96   Cédric Dupont   Update sources OC...
1691
1692
1693
1694
1695
1696
1697
  			})
  			.always(function() {
  				cb();
  			});
  		}
  	};
  })(window, jQuery, OC);
d1bafeea1   Kload   [fix] Upgrade to ...
1698
1699
  
  $(document).ready(function() {
6d9380f96   Cédric Dupont   Update sources OC...
1700
1701
1702
1703
1704
1705
  	$.getScript(OC.generateUrl('apps/contacts/ajax/config.js'))
  	.done(function() {
  		OC.Contacts.init();
  	})
  	.fail(function(jqxhr, settings, exception) {
  		console.log('Failed loading settings.', jqxhr, settings, exception);
d1bafeea1   Kload   [fix] Upgrade to ...
1706
1707
1708
  	});
  
  });