7a1237e02688cb92c13a836bffca2b72edb04212
[civicrm-core.git] / js / AutoComplete.js
1 CRM.$(function($) {
2 'use strict';
3
4 // Behind the scenes method deals with browser for setting cursor position
5 $.caretTo = function (el, index) {
6 if (el.createTextRange) {
7 var range = el.createTextRange();
8 range.move("character", index);
9 range.select();
10 }
11 else if (el.selectionStart != null) {
12 el.focus();
13 el.setSelectionRange(index, index);
14 }
15 };
16
17 /**
18 * Display a personalized message containing the contact's name
19 * and a variable from the server
20 */
21 function assignAutoComplete( id_field, profileids, autocomplete) {
22 if(profileids === undefined) {profileids = [];}
23
24 var customIdObj = $('#' + id_field);
25
26 customIdObj.on('change', function (event, data) {
27 var contactID = $(this).val();
28 var namefields = ['first_name', 'last_name', 'middle_name'];
29 CRM.api('profile', 'get', {'profile_id': profileids, 'contact_id': contactID}, {
30 success: function (result) {
31 $.each(result.values, function (id, value) {
32 $.each(value, function (fieldname, fieldvalue) {
33 $('#' + fieldname).val(fieldvalue);
34 });
35 });
36 }
37 });
38 }
39 )
40 }
41
42 /**
43 * Show or hide the autocomplete and change the text
44 */
45 function showHideAutoComplete(id_field, hidden_text, shown_text, profileids) {
46 $('#crm-contact-toggle-' + id_field).on('click', function(event) {
47 event.preventDefault();
48 $('#' + name_field).toggle();
49 if($('#' + name_field).is(":visible")) {
50 $('#crm-contact-toggle-text-' + id_field).text(shown_text);
51 }
52 else{
53 $('#crm-contact-toggle-text-' + id_field).text(hidden_text);
54 $('#' + id_field + ', #' + name_field).val('');
55 CRM.api('profile', 'get', {'profile_id' : profileids}, {
56 success: function(result) {
57 $.each(result.values, function (id, values){
58 $.each(values, function (fieldname, fieldvalue) {
59 $('#' + fieldname).val(fieldvalue);
60 });
61 });
62 }
63 });
64 }
65 });
66 }
67
68 var autocompletes = CRM.form.autocompletes;
69 $(autocompletes).each(function (index, autocomplete) {
70 assignAutoComplete(autocomplete.id_field, CRM.ids.profile, autocomplete);
71 }
72 );
73
74 });
75