Merge pull request #3023 from KarinG/CRM-11302
[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 console.log(contactID);
29 var namefields = ['first_name', 'last_name', 'middle_name'];
30 CRM.api('profile', 'get', {'profile_id': profileids, 'contact_id': contactID}, {
31 success: function (result) {
32 $.each(result.values, function (id, value) {
33 $.each(value, function (fieldname, fieldvalue) {
34 $('#' + fieldname).val(fieldvalue);
35 });
36 });
37 }
38 });
39 }
40 )
41 }
42
43 /**
44 * Show or hide the autocomplete and change the text
45 */
46 function showHideAutoComplete(id_field, hidden_text, shown_text, profileids) {
47 $('#crm-contact-toggle-' + id_field).on('click', function(event) {
48 event.preventDefault();
49 $('#' + name_field).toggle();
50 if($('#' + name_field).is(":visible")) {
51 $('#crm-contact-toggle-text-' + id_field).text(shown_text);
52 }
53 else{
54 $('#crm-contact-toggle-text-' + id_field).text(hidden_text);
55 $('#' + id_field + ', #' + name_field).val('');
56 CRM.api('profile', 'get', {'profile_id' : profileids}, {
57 success: function(result) {
58 $.each(result.values, function (id, values){
59 $.each(values, function (fieldname, fieldvalue) {
60 $('#' + fieldname).val(fieldvalue);
61 });
62 });
63 }
64 });
65 }
66 });
67 }
68
69 var autocompletes = CRM.form.autocompletes;
70 $(autocompletes).each(function (index, autocomplete) {
71 assignAutoComplete(autocomplete.id_field, CRM.ids.profile, autocomplete);
72 }
73 );
74
75 });
76