From 8cc4336526e8163888c377f9a41cc5eaf4753507 Mon Sep 17 00:00:00 2001
From: Coleman Watts <coleman@civicrm.org>
Date: Mon, 9 Jan 2017 23:19:44 -0500
Subject: [PATCH] CRM-19769 - Add colorContrast js function

---
 js/Common.js                   | 11 +++++++++++
 templates/CRM/Tag/Form/Tag.tpl |  2 +-
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/js/Common.js b/js/Common.js
index 57ae68ed0238..86f21fb46e73 100644
--- a/js/Common.js
+++ b/js/Common.js
@@ -1673,4 +1673,15 @@ if (!CRM.vars) CRM.vars = {};
   CRM.utils.formatDate = function(input, outputFormat) {
     return input ? $.datepicker.formatDate(outputFormat || CRM.config.dateInputFormat, CRM.utils.makeDate(input)) : '';
   };
+
+  // Used to set appropriate text color for a given background
+  CRM.utils.colorContrast = function (hexcolor) {
+    hexcolor = hexcolor.replace(/[ #]/g, '');
+    var r = parseInt(hexcolor.substr(0, 2), 16),
+     g = parseInt(hexcolor.substr(2, 2), 16),
+     b = parseInt(hexcolor.substr(4, 2), 16),
+     yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
+    return (yiq >= 128) ? 'black' : 'white';
+  };
+
 })(jQuery, _);
diff --git a/templates/CRM/Tag/Form/Tag.tpl b/templates/CRM/Tag/Form/Tag.tpl
index 3ccbb5fdd7fa..817fdddba812 100644
--- a/templates/CRM/Tag/Form/Tag.tpl
+++ b/templates/CRM/Tag/Form/Tag.tpl
@@ -51,7 +51,7 @@
       });
       $('input.crm-contact-tagset').each(function() {
         $.each($(this).select2('data'), function (i, tag) {
-          tags.push('<span class="crm-tag-item" title="' + (tag.description || '') + '"' + (tag.color ? 'style="color: #fff; background-color: ' + tag.color + ';"' : '') + '>' + tag.label + '</span>');
+          tags.push('<span class="crm-tag-item" title="' + (tag.description || '') + '"' + (tag.color ? 'style="color: ' + CRM.utils.colorContrast(tag.color) + '; background-color: ' + tag.color + ';"' : '') + '>' + tag.label + '</span>');
         });
       });
       // contact summary tabs and search forms both listen for this event