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(); } } if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } 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++) { if (arr[i] == deleteValue) { arr.splice(i, 1); i--; } } return arr; }; // Keep it DRY ;) var wrongKey = function(event) { return (event.type === 'keydown' && (event.keyCode !== 32 && event.keyCode !== 13)); } /** * Simply notifier * Arguments: * @param message The text message to show. * @param timeout The timeout in seconds before the notification disappears. Default 10. * @param timeouthandler A function to run on timeout. * @param clickhandler A function to run on click. If a timeouthandler is given it will be cancelled on click. * @param data An object that will be passed as argument to the timeouthandler and clickhandler functions. * @param 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'); if(!self.notifier.length) { $('#content').prepend('
'); self.notifier = $('#notification'); } } 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(); return; } self.notifier.text(params.message); self.notifier.fadeIn(); self.notifier.on('click', function() { $(this).fadeOut();}); var timer = setTimeout(function() { /*if(!self || !self.notifier) { var self = OC.Contacts; self.notifier = $('#notification'); }*/ 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() { /*if(!self || !self.notifier) { var self = OC.Contacts; self.notifier = $(this); }*/ clearTimeout(timer); self.notifier.off('click'); params.clickhandler(self.notifier.data(dataid)); self.notifier.removeData(dataid); }); } } var GroupList = function(groupList, listItemTmpl) { this.$groupList = groupList; var self = this; var numtypes = ['category', 'fav', 'all']; this.$groupList.on('click', 'h3', function(event) { $('.tipsy').remove(); if(wrongKey(event)) { return; } console.log($(event.target)); if($(event.target).is('.action.delete')) { var id = $(event.target).parents('h3').first().data('id'); self.deleteGroup(id, function(response) { if(response.status !== 'success') { OC.notify({message:response.data.message}); } }) } else { self.selectGroup({element:$(this)}); } }); this.$groupListItemTemplate = listItemTmpl; this.categories = []; } GroupList.prototype.nameById = function(id) { return this.findById(id).contents().filter(function(){ return(this.nodeType == 3); }).text().trim() } GroupList.prototype.findById = function(id) { return this.$groupList.find('h3[data-id="' + id + '"]'); } GroupList.prototype.isFavorite = function(contactid) { return this.inGroup(contactid, 'fav'); } GroupList.prototype.selectGroup = function(params) { var id, $elem; if(typeof params.id !== 'undefined') { id = params.id; $elem = this.findById(id); } else if(typeof params.element !== 'undefined') { id = params.element.data('id'); $elem = params.element; } if(!$elem) { self.selectGroup('all'); return; } console.log('selectGroup', id, $elem); this.$groupList.find('h3').removeClass('active'); $elem.addClass('active'); if(id === 'new') { return; } this.lastgroup = id; $(document).trigger('status.group.selected', { id: this.lastgroup, type: $elem.data('type'), contacts: $elem.data('contacts'), }); } GroupList.prototype.inGroup = function(contactid, groupid) { var $groupelem = this.findById(groupid); var contacts = $groupelem.data('contacts'); return (contacts.indexOf(contactid) !== -1); } GroupList.prototype.setAsFavorite = function(contactid, state, cb) { contactid = parseInt(contactid); var $groupelem = this.findById('fav'); var contacts = $groupelem.data('contacts'); if(state) { OCCategories.addToFavorites(contactid, 'contact', function(jsondata) { if(jsondata.status === 'success') { contacts.push(contactid); $groupelem.data('contacts', contacts); $groupelem.find('.numcontacts').text(contacts.length); if(contacts.length > 0 && $groupelem.is(':hidden')) { $groupelem.show(); } } if(typeof cb === 'function') { cb(jsondata); } else if(jsondata.status !== 'success') { OC.notify({message:t('contacts', jsondata.data.message)}); } }); } else { OCCategories.removeFromFavorites(contactid, 'contact', function(jsondata) { if(jsondata.status === 'success') { contacts.splice(contacts.indexOf(contactid), 1); //console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); $groupelem.data('contacts', contacts); $groupelem.find('.numcontacts').text(contacts.length); if(contacts.length === 0 && $groupelem.is(':visible')) { $groupelem.hide(); } } if(typeof cb === 'function') { cb(jsondata); } else if(jsondata.status !== 'success') { OC.notify({message:t('contacts', jsondata.data.message)}); } }); } } /** * Add one or more contact ids to a group * @param contactid An integer id or an array of integer ids. * @param groupid The integer id of the group * @param cb Optional call-back function */ GroupList.prototype.addTo = function(contactid, groupid, cb) { console.log('GroupList.addTo', contactid, groupid); var $groupelem = this.findById(groupid); var contacts = $groupelem.data('contacts'); var ids = []; if(!contacts) { console.log('Contacts not found, adding list!!!'); contacts = []; } var self = this; var doPost = false; if(typeof contactid === 'number') { if(contacts.indexOf(contactid) === -1) { ids.push(contactid); doPost = true; } else { if(typeof cb == 'function') { cb({status:'error', message:t('contacts', 'Contact is already in this group.')}); } } } else if(utils.isArray(contactid)) { $.each(contactid, function(i, id) { if(contacts.indexOf(id) === -1) { ids.push(id); } }); if(ids.length > 0) { doPost = true; } else { if(typeof cb == 'function') { cb({status:'error', message:t('contacts', 'Contacts are already in this group.')}); } } } if(doPost) { $.post(OC.filePath('contacts', 'ajax', 'categories/addto.php'), {contactids: ids, categoryid: groupid},function(jsondata) { if(!jsondata) { if(typeof cb === 'function') { cb({status:'error', message:'Network or server error. Please inform administrator.'}); } return; } if(jsondata.status === 'success') { contacts = contacts.concat(ids).sort(); $groupelem.data('contacts', contacts); var $numelem = $groupelem.find('.numcontacts'); $numelem.text(contacts.length).switchClass('', 'active', 200); setTimeout(function() { $numelem.switchClass('active', '', 1000); }, 2000); if(typeof cb === 'function') { cb({status:'success', ids:ids}); } else { $(document).trigger('status.group.contactadded', { contactid: contactid, groupid: groupid, groupname: self.nameById(groupid), }); } } else { if(typeof cb == 'function') { cb({status:'error', message:jsondata.data.message}); } } }); } } GroupList.prototype.removeFrom = function(contactid, groupid, cb) { console.log('GroupList.removeFrom', contactid, groupid); var $groupelem = this.findById(groupid); var contacts = $groupelem.data('contacts'); var ids = []; // If it's the 'all' group simply decrement the number if(groupid === 'all') { var $numelem = $groupelem.find('.numcontacts'); $numelem.text(parseInt($numelem.text()-1)).switchClass('', 'active', 200); setTimeout(function() { $numelem.switchClass('active', '', 1000); }, 2000); if(typeof cb === 'function') { cb({status:'success', ids:[id]}); } } // If the contact is in the category remove it from internal list. if(!contacts) { if(typeof cb === 'function') { cb({status:'error', message:t('contacts', 'Couldn\'t get contact list.')}); } return; } var doPost = false; if(typeof contactid === 'number') { if(contacts.indexOf(contactid) !== -1) { ids.push(contactid); doPost = true; } else { if(typeof cb == 'function') { cb({status:'error', message:t('contacts', 'Contact is not in this group.')}); } } } else if(utils.isArray(contactid)) { $.each(contactid, function(i, id) { if(contacts.indexOf(id) !== -1) { ids.push(id); } }); if(ids.length > 0) { doPost = true; } else { console.log(contactid, 'not in', contacts); if(typeof cb == 'function') { cb({status:'error', message:t('contacts', 'Contacts are not in this group.')}); } } } if(doPost) { $.post(OC.filePath('contacts', 'ajax', 'categories/removefrom.php'), {contactids: ids, categoryid: groupid},function(jsondata) { if(!jsondata) { if(typeof cb === 'function') { cb({status:'error', message:'Network or server error. Please inform administrator.'}); } return; } if(jsondata.status === 'success') { $.each(ids, function(idx, id) { contacts.splice(contacts.indexOf(id), 1); }); //console.log('contacts', contacts, contacts.indexOf(id), contacts.indexOf(String(id))); $groupelem.data('contacts', contacts); var $numelem = $groupelem.find('.numcontacts'); $numelem.text(contacts.length).switchClass('', 'active', 200); setTimeout(function() { $numelem.switchClass('active', '', 1000); }, 2000); if(typeof cb === 'function') { cb({status:'success', ids:ids}); } } else { if(typeof cb == 'function') { cb({status:'error', message:jsondata.data.message}); } } }); } } GroupList.prototype.removeFromAll = function(contactid, alsospecial) { var self = this; var selector = alsospecial ? 'h3' : 'h3[data-type="category"]'; $.each(this.$groupList.find(selector), function(i, group) { self.removeFrom(contactid, $(this).data('id')); }); } GroupList.prototype.categoriesChanged = function(newcategories) { console.log('GroupList.categoriesChanged, I should do something'); } GroupList.prototype.contactDropped = function(event, ui) { var dragitem = ui.draggable, droptarget = $(this); console.log('dropped', dragitem); if(dragitem.is('tr')) { console.log('tr dropped', dragitem.data('id'), 'on', $(this).data('id')); if($(this).data('type') === 'fav') { $(this).data('obj').setAsFavorite(dragitem.data('id'), true); } else { $(this).data('obj').addTo(dragitem.data('id'), $(this).data('id')); } } } GroupList.prototype.deleteGroup = function(groupid, cb) { var $elem = this.findById(groupid); var $newelem = $elem.prev('h3'); var name = this.nameById(groupid); var contacts = $elem.data('contacts'); var self = this; console.log('delete group', groupid, contacts); $.post(OC.filePath('contacts', 'ajax', 'categories/delete.php'), {categories: name}, function(jsondata) { if (jsondata && jsondata.status == 'success') { $(document).trigger('status.group.groupremoved', { groupid: groupid, newgroupid: parseInt($newelem.data('id')), groupname: self.nameById(groupid), contacts: contacts, }); $elem.remove(); self.selectGroup({element:$newelem}); } else { // } if(typeof cb === 'function') { cb(jsondata); } }); } GroupList.prototype.editGroup = function(id) { var self = this; // NOTE: Currently this only works for adding, not renaming var saveChanges = function($elem, $input) { console.log('saveChanges', $input.val()); var name = $input.val().trim(); if(name.length === 0) { return false; } $input.prop('disabled', true); $elem.data('name', ''); self.addGroup({name:name, element:$elem}, function(response) { if(response.status === 'success') { $elem.prepend(name).removeClass('editing').attr('data-id', response.id); $input.next('.checked').remove() $input.remove() } else { $input.prop('disabled', false); OC.notify({message:response.message}); } }); } if(typeof id === 'undefined') { // Add new group var tmpl = this.$groupListItemTemplate; var $elem = (tmpl).octemplate({ id: 'new', type: 'category', num: 0, name: '', }); var $input = $(''); $elem.prepend($input).addClass('editing'); $elem.data('contacts', []); this.$groupList.find('h3.group[data-type="category"]').first().before($elem); this.selectGroup({element:$elem}); $input.on('input', function(event) { if($(this).val().length > 0) { $(this).next('.checked').removeClass('disabled'); } else { $(this).next('.checked').addClass('disabled'); } }); $input.on('keyup', function(event) { var keyCode = Math.max(event.keyCode, event.which); if(keyCode === 13) { saveChanges($elem, $(this)); } else if(keyCode === 27) { $elem.remove(); } }); $input.next('.checked').on('click keydown', function(event) { console.log('clicked', event); if(wrongKey(event)) { return; } saveChanges($elem, $input); }); $input.focus(); } else if(utils.isUInt(id)) { var $elem = this.findById(id); var $text = $elem.contents().filter(function(){ return(this.nodeType == 3); }); var name = $text.text(); console.log('Group name', $text, name); $text.remove(); var $input = $(' 0) { $(this).before($elem); added = true; return false; } }); if(!added) { $elem.insertAfter(self.$groupList.find('h3.group[data-type="category"]').last()); } self.selectGroup({element:$elem}); $elem.tipsy({trigger:'manual', gravity:'w', fallback: t('contacts', 'You can drag groups to\narrange them as you like.')}); $elem.tipsy('show'); if(typeof cb === 'function') { cb({status:'success', id:parseInt(jsondata.data.id), name:name}); } } else { if(typeof cb === 'function') { cb({status:'error', message:jsondata.data.message}); } } }); } GroupList.prototype.loadGroups = function(numcontacts, cb) { var self = this; var acceptdrop = 'tr.contact'; var $groupList = this.$groupList; var tmpl = this.$groupListItemTemplate; tmpl.octemplate({id: 'all', type: 'all', num: numcontacts, name: t('contacts', 'All')}).appendTo($groupList); $.getJSON(OC.filePath('contacts', 'ajax', 'categories/list.php'), {}, function(jsondata) { if (jsondata && jsondata.status == 'success') { self.lastgroup = jsondata.data.lastgroup; self.sortorder = jsondata.data.sortorder.length > 0 ? $.map(jsondata.data.sortorder.split(','), function(c) {return parseInt(c)}) : []; console.log('sortorder', self.sortorder); // Favorites var contacts = $.map(jsondata.data.favorites, function(c) {return parseInt(c)}); var $elem = tmpl.octemplate({ id: 'fav', type: 'fav', num: contacts.length, name: t('contacts', 'Favorites') }).appendTo($groupList); $elem.data('obj', self); $elem.data('contacts', contacts).find('.numcontacts').before(''); $elem.droppable({ drop: self.contactDropped, activeClass: 'ui-state-active', hoverClass: 'ui-state-hover', accept: acceptdrop }); if(contacts.length === 0) { $elem.hide(); } console.log('favorites', $elem.data('contacts')); // Normal groups $.each(jsondata.data.categories, function(c, category) { var contacts = $.map(category.contacts, function(c) {return parseInt(c)}); var $elem = (tmpl).octemplate({ id: category.id, type: 'category', num: contacts.length, name: category.name, }); self.categories.push({id: category.id, name: category.name}); $elem.data('obj', self); $elem.data('contacts', contacts); $elem.data('name', category.name); $elem.data('id', category.id); $elem.droppable({ drop: self.contactDropped, activeClass: 'ui-state-hover', accept: acceptdrop }); $elem.appendTo($groupList); }); var elems = $groupList.find('h3[data-type="category"]').get(); elems.sort(function(a, b) { return self.sortorder.indexOf(parseInt($(a).data('id'))) > self.sortorder.indexOf(parseInt($(b).data('id'))); }); $.each(elems, function(index, elem) { $groupList.append(elem); }); // Shared addressbook $.each(jsondata.data.shared, function(c, shared) { var sharedindicator = '' var $elem = (tmpl).octemplate({ id: shared.id, type: 'shared', num: '', //jsondata.data.shared.length, name: shared.displayname, }); $elem.find('.numcontacts').after(sharedindicator); $elem.data('obj', self); $elem.data('name', shared.displayname); $elem.data('id', shared.id); $elem.appendTo($groupList); }); $groupList.sortable({ items: 'h3[data-type="category"]', stop: function() { console.log('stop sorting', $(this)); var ids = []; $.each($(this).children('h3[data-type="category"]'), function(i, elem) { ids.push($(elem).data('id')) }) self.sortorder = ids; $(document).trigger('status.groups.sorted', { sortorder: self.sortorder.join(','), }); }, }); var $elem = self.findById(self.lastgroup); $elem.addClass('active'); $(document).trigger('status.group.selected', { id: self.lastgroup, type: $elem.data('type'), contacts: $elem.data('contacts'), }); } // TODO: else if(typeof cb === 'function') { cb(); } }); } OC.Contacts = OC.Contacts || { init:function(id) { if(oc_debug === true) { $(document).ajaxError(function(e, xhr, settings, exception) { // Don't try to get translation because it's likely a network error. OC.notify({ message: 'error in: ' + settings.url + ', '+'error: ' + xhr.responseText, }); }); } //if(id) { this.currentid = parseInt(id); console.log('init, id:', id); //} // Holds an array of {id,name} maps this.scrollTimeoutMiliSecs = 100; this.isScrolling = false; this.cacheElements(); this.contacts = new OC.Contacts.ContactList( this.$contactList, this.$contactListItemTemplate, this.$contactFullTemplate, this.detailTemplates ); this.groups = new GroupList(this.$groupList, this.$groupListItemTemplate); OCCategories.changed = this.groups.categoriesChanged; OCCategories.app = 'contacts'; OCCategories.type = 'contact'; this.bindEvents(); this.$toggleAll.show(); this.showActions(['add']); // Wait 2 mins then check if contacts are indexed. setTimeout(function() { if(!is_indexed) { OC.notify({message:t('contacts', 'Indexing contacts'), timeout:20}); $.post(OC.filePath('contacts', 'ajax', 'indexproperties.php')); } else { console.log('contacts are indexed.'); } }, 10000); }, 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.$headeractions.children('.'+act.join(',.')).show(); } }, showAction:function(act, show) { this.$headeractions.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) { if(node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'DIV') { var $tmpl = $(node.innerHTML); self.detailTemplates[$tmpl.data('element')] = $(node.outerHTML); } }); this.$groupListItemTemplate = $('#groupListItemTemplate'); this.$contactListItemTemplate = $('#contactListItemTemplate'); this.$contactFullTemplate = $('#contactFullTemplate'); this.$contactDetailsTemplate = $('#contactDetailsTemplate'); this.$rightContent = $('#rightcontent'); this.$header = $('#contactsheader'); this.$headeractions = this.$header.find('div.actions'); this.$groupList = $('#grouplist'); this.$contactList = $('#contactlist'); this.$contactListHeader = $('#contactlistheader'); this.$toggleAll = $('#toggle_all'); this.$groups = this.$headeractions.find('.groups'); this.$ninjahelp = $('#ninjahelp'); this.$firstRun = $('#firstrun'); this.$settings = $('#contacts-settings'); this.$importFileInput = $('#import_fileupload'); this.$importIntoSelect = $('#import_into'); }, // 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.contacts[this.currentid]; 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 += ''; } else { addopts += ''; } }); if(addopts.length) { $(addopts).appendTo(this.$groups) .wrapAll(''); } if(rmopts.length) { $(rmopts).appendTo(this.$groups) .wrapAll(''); } } 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) { rmopts += ''; addopts += ''; }); $(addopts).appendTo(this.$groups) .wrapAll(''); $(rmopts).appendTo(this.$groups) .wrapAll(''); } else { // 3rd option: No contact open, none checked, just show "Add group..." this.$groups.find('optgroup,option:not([value="-1"])').remove(); } $('').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'); }); // App specific events $(document).bind('status.contact.deleted', function(e, data) { var id = parseInt(data.id); console.log('contact', data.id, 'deleted'); // update counts on group lists self.groups.removeFromAll(data.id, true) }); $(document).bind('status.contact.added', function(e, data) { self.currentid = parseInt(data.id); self.buildGroupSelect(); self.hideActions(); }); $(document).bind('status.contact.error', function(e, data) { OC.notify({message:data.message}); }); $(document).bind('status.contact.enabled', function(e, enabled) { console.log('status.contact.enabled', enabled) /*if(enabled) { self.showActions(['back', 'download', 'delete', 'groups']); } else { self.showActions(['back']); }*/ }); $(document).bind('status.contacts.loaded', function(e, result) { console.log('status.contacts.loaded', result); if(result.status !== true) { alert('Error loading contacts!'); } else { self.numcontacts = result.numcontacts; self.loading(self.$rightContent, false); self.groups.loadGroups(self.numcontacts, function() { self.loading($('#leftcontent'), false); console.log('Groups loaded, currentid', self.currentid); if(self.currentid) { self.openContact(self.currentid); } }); } }); $(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); } self.currentlistid = result.id }); $(document).bind('status.nomorecontacts', function(e, result) { console.log('status.nomorecontacts', result); self.$contactList.hide(); self.$firstRun.show(); // TODO: Show a first-run page. }); $(document).bind('status.visiblecontacts', function(e, result) { console.log('status.visiblecontacts', result); // TODO: To be decided. }); // 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); } }); $(document).bind('request.contact.setasfavorite', function(e, data) { console.log('contact', data.id, 'request.contact.setasfavorite'); self.groups.setAsFavorite(data.id, data.state); }); $(document).bind('request.contact.addtogroup', function(e, data) { console.log('contact', data.id, 'request.contact.addtogroup'); self.groups.addTo(data.id, data.groupid); }); $(document).bind('request.contact.export', function(e, data) { var id = parseInt(data.id); console.log('contact', data.id, 'request.contact.export'); document.location.href = OC.linkTo('contacts', 'export.php') + '?contactid=' + self.currentid; }); $(document).bind('request.contact.close', function(e, data) { var id = parseInt(data.id); console.log('contact', data.id, 'request.contact.close'); self.closeContact(id); }); $(document).bind('request.contact.delete', function(e, data) { var id = parseInt(data.id); console.log('contact', data.id, 'request.contact.delete'); self.contacts.delayedDelete(id); self.$contactList.removeClass('dim'); self.showActions(['add']); }); $(document).bind('request.select.contactphoto.fromlocal', function(e, result) { console.log('request.select.contactphoto.fromlocal', result); $('#contactphoto_fileupload').trigger('click'); }); $(document).bind('request.select.contactphoto.fromcloud', function(e, result) { console.log('request.select.contactphoto.fromcloud', result); OC.dialogs.filepicker(t('contacts', 'Select photo'), function(path) { self.cloudPhotoSelected(self.currentid, path); }, false, 'image', true); }); $(document).bind('request.edit.contactphoto', function(e, result) { console.log('request.edit.contactphoto', result); self.editCurrentPhoto(result.id); }); $(document).bind('request.addressbook.activate', function(e, result) { console.log('request.addressbook.activate', result); self.contacts.showFromAddressbook(result.id, result.activate); }); $(document).bind('status.contact.removedfromgroup', function(e, result) { console.log('status.contact.removedfromgroup', result); if(self.currentgroup == result.groupid) { self.contacts.hideContact(result.contactid); self.closeContact(result.contactid); } }); $(document).bind('status.group.groupremoved', function(e, result) { console.log('status.group.groupremoved', result); if(parseInt(result.groupid) === parseInt(self.currentgroup)) { console.time('hiding'); self.contacts.showContacts([]); console.timeEnd('hiding'); self.currentgroup = 'all'; } $.each(result.contacts, function(idx, contactid) { var contact = self.contacts.findById(contactid); console.log('contactid', contactid, contact); self.contacts.findById(contactid).removeFromGroup(result.groupname); }); }); $(document).bind('status.group.contactadded', function(e, result) { console.log('status.group.contactadded', result); self.contacts.contacts[parseInt(result.contactid)].addToGroup(result.groupname); }); // Group sorted, save the sort order $(document).bind('status.groups.sorted', function(e, result) { console.log('status.groups.sorted', result); $.post(OC.filePath('contacts', 'ajax', 'setpreference.php'), {'key':'groupsort', 'value':result.sortorder}, function(jsondata) { if(jsondata.status !== 'success') { OC.notify({message: jsondata ? jsondata.data.message : t('contacts', 'Network or server error. Please inform administrator.')}); } }); }); // 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); } self.$contactList.show(); self.$toggleAll.show(); self.showActions(['add']); 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 { self.contacts.showContacts(self.currentgroup); } $.post(OC.filePath('contacts', 'ajax', 'setpreference.php'), {'key':'lastgroup', 'value':self.currentgroup}, function(jsondata) { if(!jsondata || jsondata.status !== 'success') { OC.notify({message: (jsondata && jsondata.data) ? jsondata.data.message : t('contacts', 'Network or server error. Please inform administrator.')}); } }); 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()); } });*/ this.$settings.find('.settings').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); } }); $('#contactphoto_fileupload').on('change', function() { self.uploadPhoto(this.files); }); $('#groupactions > .addgroup').on('click keydown',function(event) { if(wrongKey(event)) { return; } self.groups.editGroup(); //self.addGroup(); }); this.$ninjahelp.find('.close').on('click keydown',function(event) { if(wrongKey(event)) { return; } self.$ninjahelp.hide(); }); this.$toggleAll.on('change', function() { var isChecked = $(this).is(':checked'); self.setAllChecked(isChecked); if(self.$groups.find('option').length === 1) { self.buildGroupSelect(); } if(isChecked) { self.showActions(['add', 'download', 'groups', 'delete', 'favorite']); } else { self.showActions(['add']); } }); this.$contactList.on('change', 'input:checkbox', function(event) { if($(this).is(':checked')) { if(self.$groups.find('option').length === 1) { self.buildGroupSelect(); } self.showActions(['add', 'download', 'groups', 'delete', 'favorite']); } else if(self.contacts.getSelectedContacts().length === 0) { self.showActions(['add']); } }); // Add to/remove from group multiple contacts. // FIXME: Refactor this to be usable for favoriting also. this.$groups.on('change', function() { var $opt = $(this).find('option:selected'); var action = $opt.parent().data('action'); var ids, groupName, groupId, buildnow = false; // If a contact is open the action is only applied to that, // otherwise on all selected items. if(self.currentid) { ids = [self.currentid,]; buildnow = true } else { ids = self.contacts.getSelectedContacts(); } self.setAllChecked(false); self.$toggleAll.prop('checked', false); if(!self.currentid) { self.showActions(['add']); } if($opt.val() === 'add') { // Add new group action = 'add'; console.log('add group...'); self.$groups.val(-1); self.addGroup(function(response) { if(response.status === 'success') { groupId = response.id; groupName = response.name; self.groups.addTo(ids, groupId, function(result) { if(result.status === 'success') { $.each(ids, function(idx, id) { // Delay each contact to not trigger too many ajax calls // at a time. setTimeout(function() { self.contacts.contacts[id].addToGroup(groupName); // I don't think this is used... if(buildnow) { self.buildGroupSelect(); } $(document).trigger('status.contact.addedtogroup', { contactid: id, groupid: groupId, groupname: groupName, }); }, 1000); }); } else { // TODO: Use message returned from groups object. OC.notify({message:t('contacts', t('contacts', 'Error adding to group.'))}); } }); } else { OC.notify({message: response.message}); } }); return; } groupName = $opt.text(), groupId = $opt.val(); console.log('trut', groupName, groupId); if(action === 'add') { self.groups.addTo(ids, $opt.val(), function(result) { console.log('after add', result); if(result.status === 'success') { $.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); self.contacts.contacts[id].addToGroup(groupName); // I don't think this is used... if(buildnow) { self.buildGroupSelect(); } $(document).trigger('status.contact.addedtogroup', { contactid: id, groupid: groupId, groupname: groupName, }); }, 1000); }); } else { var msg = result.message ? result.message : t('contacts', 'Error adding to group.'); OC.notify({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(), function(result) { console.log('after remove', result); if(result.status === 'success') { var groupname = $opt.text(), groupid = $opt.val(); $.each(result.ids, function(idx, id) { self.contacts.contacts[id].removeFromGroup(groupname); if(buildnow) { self.buildGroupSelect(); } // If a group is selected the contact has to be removed from the list $(document).trigger('status.contact.removedfromgroup', { contactid: id, groupid: groupId, groupname: groupName, }); }); } else { var msg = result.message ? result.message : t('contacts', 'Error removing from group.'); OC.notify({message:msg}); } }); if(!buildnow) { self.$groups.val(-1).hide().find('optgroup,option:not([value="-1"])').remove(); } } // else something's wrong ;) self.setAllChecked(false); }); // Contact list. Either open a contact or perform an action (mailto etc.) this.$contactList.on('click', 'tr', function(event) { if($(event.target).is('input')) { return; } if(event.ctrlKey || event.metaKey) { event.stopPropagation(); event.preventDefault(); console.log('select', event); self.dontScroll = true; self.contacts.select($(this).data('id'), true); return; } if($(event.target).is('a.mailto')) { var mailto = 'mailto:' + $(this).find('.email').text().trim(); console.log('mailto', mailto); try { window.location.href=mailto; } catch(e) { alert(t('contacts', 'There was an error opening a mail composer.')); } return; } self.openContact($(this).data('id')); }); this.$settings.find('h3').on('click keydown', function(event) { if(wrongKey(event)) { return; } if($(this).next('ul').is(':visible')) { $(this).next('ul').slideUp(); return; } console.log('settings'); var $list = $(this).next('ul'); if($(this).data('id') === 'addressbooks') { console.log('addressbooks'); if(!self.$addressbookTmpl) { self.$addressbookTmpl = $('#addressbookTemplate'); } $list.empty(); $.each(self.contacts.addressbooks, function(id, book) { var $li = self.$addressbookTmpl.octemplate({ id: id, permissions: book.permissions, displayname: book.displayname, }); $list.append($li); }); $list.find('a.action').tipsy({gravity: 'w'}); $list.find('a.action.delete').on('click keypress', function() { $('.tipsy').remove(); var id = parseInt($(this).parents('li').first().data('id')); console.log('delete', id); var $li = $(this).parents('li').first(); $.ajax({ type:'POST', url:OC.filePath('contacts', 'ajax', 'addressbook/delete.php'), data:{ id: id }, success:function(jsondata) { console.log(jsondata); if(jsondata.status == 'success') { self.contacts.unsetAddressbook(id); $li.remove(); OC.notify({ message:t('contacts','Deleting done. Click here to cancel reloading.'), timeout:5, timeouthandler:function() { console.log('reloading'); window.location.href = OC.linkTo('contacts', 'index.php'); }, clickhandler:function() { console.log('reloading cancelled'); OC.notify({cancel:true}); } }); } else { OC.notify({message:jsondata.data.message}); } }, error:function(jqXHR, textStatus, errorThrown) { OC.notify({message:textStatus + ': ' + errorThrown}); id = false; }, }); }); $list.find('a.action.globe').on('click keypress', function() { var id = parseInt($(this).parents('li').first().data('id')); var book = self.contacts.addressbooks[id]; var uri = (book.owner === oc_current_user ) ? book.uri : book.uri + '_shared_by_' + book.owner; var link = totalurl+'/'+encodeURIComponent(oc_current_user)+'/'+encodeURIComponent(uri); var $dropdown = $(''); $dropdown.appendTo($(this).parents('li').first()); var $input = $dropdown.find('input'); $input.focus().get(0).select(); $input.on('blur', function() { $dropdown.hide('blind', function() { $dropdown.remove(); }); }); }); if(typeof OC.Share !== 'undefined') { OC.Share.loadIcons('addressbook'); } else { $list.find('a.action.share').css('display', 'none'); } } else if($(this).data('id') === 'import') { console.log('import'); $('.import-upload').show(); $('.import-select').hide(); var addAddressbookCallback = function(select, name) { var id; $.ajax({ type:'POST', async:false, url:OC.filePath('contacts', 'ajax', 'addressbook/add.php'), data:{ name: name }, success:function(jsondata) { console.log(jsondata); if(jsondata.status == 'success') { self.contacts.setAddressbook(jsondata.data.addressbook); id = jsondata.data.addressbook.id } else { OC.notify({message:jsondata.data.message}); } }, error:function(jqXHR, textStatus, errorThrown) { OC.notify({message:textStatus + ': ' + errorThrown}); id = false; }, }); return id; } self.$importIntoSelect.empty(); $.each(self.contacts.addressbooks, function(id, book) { self.$importIntoSelect.append(''); }); self.$importIntoSelect.multiSelect({ createCallback:addAddressbookCallback, singleSelect: true, createText:String(t('contacts', 'Add address book')), minWidth: 120, }); } $(this).parents('ul').first().find('ul:visible').slideUp(); $list.toggle('slow'); }); this.$header.on('click keydown', '.add', function(event) { if(wrongKey(event)) { return; } console.log('add'); self.$toggleAll.hide(); $(this).hide(); 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.tmpcontact = self.contacts.addContact(groupprops); self.$rightContent.prepend(self.tmpcontact); self.hideActions(); }); this.$header.on('click keydown', '.delete', function(event) { if(wrongKey(event)) { return; } console.log('delete'); if(self.currentid) { console.assert(utils.isUInt(self.currentid), 'self.currentid is not an integer'); self.contacts.delayedDelete(self.currentid); } else { self.contacts.delayedDelete(self.contacts.getSelectedContacts()); } self.showActions(['add']); }); this.$header.on('click keydown', '.download', function(event) { if(wrongKey(event)) { return; } console.log('download'); document.location.href = OC.linkTo('contacts', 'export.php') + '?selectedids=' + self.contacts.getSelectedContacts().join(','); }); this.$header.on('click keydown', '.favorite', function(event) { if(wrongKey(event)) { return; } if(!utils.isUInt(self.currentid)) { return; } // FIXME: This should only apply for contacts list. var state = self.groups.isFavorite(self.currentid); console.log('Favorite?', this, state); self.groups.setAsFavorite(self.currentid, !state, function(jsondata) { if(jsondata.status === 'success') { if(state) { self.$header.find('.favorite').switchClass('active', ''); } else { self.$header.find('.favorite').switchClass('', 'active'); } } else { OC.notify({message:t('contacts', jsondata.data.message)}); } }); }); this.$contactList.on('mouseenter', 'td.email', function(event) { if($(this).text().trim().length > 3) { $(this).find('.mailto').css('display', 'inline-block'); //.fadeIn(100); } }); this.$contactList.on('mouseleave', 'td.email', function(event) { $(this).find('.mailto').fadeOut(100); }); // Import using jquery.fileupload $(function() { var uploadingFiles = {}, numfiles = 0, uploadedfiles = 0, retries = 0; var aid, importError = false; var $progressbar = $('#import-progress'); var $status = $('#import-status-text'); var waitForImport = function() { if(numfiles == 0 && uploadedfiles == 0) { $progressbar.progressbar('value',100); if(!importError) { OC.notify({ message:t('contacts','Import done. Click here to cancel reloading.'), timeout:5, timeouthandler:function() { console.log('reloading'); window.location.href = OC.linkTo('contacts', 'index.php'); }, clickhandler:function() { console.log('reloading cancelled'); OC.notify({cancel:true}); } }); } retries = aid = 0; $progressbar.fadeOut(); setTimeout(function() { $status.fadeOut('slow'); $('.import-upload').show(); }, 3000); } else { setTimeout(function() { waitForImport(); }, 1000); } }; var doImport = function(file, aid, cb) { $.post(OC.filePath('contacts', '', 'import.php'), { id: aid, file: file, fstype: 'OC_FilesystemView' }, function(jsondata) { if(jsondata.status != 'success') { importError = true; OC.notify({message:jsondata.data.message}); } if(typeof cb == 'function') { cb(jsondata); } }); return false; }; var importFiles = function(aid, uploadingFiles) { console.log('importFiles', aid, uploadingFiles); if(numfiles != uploadedfiles) { OC.notify({message:t('contacts', 'Not all files uploaded. Retrying...')}); retries += 1; if(retries > 3) { numfiles = uploadedfiles = retries = aid = 0; uploadingFiles = {}; $progressbar.fadeOut(); OC.dialogs.alert(t('contacts', 'Something went wrong with the upload, please retry.'), t('contacts', 'Error')); return; } setTimeout(function() { // Just to let any uploads finish importFiles(aid, uploadingFiles); }, 1000); } $progressbar.progressbar('value', 50); var todo = uploadedfiles; $.each(uploadingFiles, function(fileName, data) { $status.text(t('contacts', 'Importing from {filename}...', {filename:fileName})).fadeIn(); doImport(fileName, aid, function(response) { if(response.status === 'success') { $status.text(t('contacts', '{success} imported, {failed} failed.', {success:response.data.imported, failed:response.data.failed})).fadeIn(); } delete uploadingFiles[fileName]; numfiles -= 1; uploadedfiles -= 1; $progressbar.progressbar('value',50+(50/(todo-uploadedfiles))); }); }) //$status.text(t('contacts', 'Importing...')).fadeIn(); waitForImport(); }; // Start the actual import. $('.doImport').on('click keypress', function(event) { if(wrongKey(event)) { return; } aid = $(this).prev('select').val(); $('.import-select').hide(); importFiles(aid, uploadingFiles); }); $('#import_fileupload').fileupload({ acceptFileTypes: /^text\/(directory|vcard|x-vcard)$/i, add: function(e, data) { var files = data.files; var totalSize=0; if(files) { numfiles += files.length; uploadedfiles = 0; for(var i=0;i