var CFSSmartSearch = {
"timer": null,
"activeElement": null,
"results": [],
"history": null,
"showHistory": true,
"searchOptions": "",
"searchType": "",
"cookiePrefix": "",
"page" : "",
"init": function (showHistoryOnInit = false, showHistory = true) {
if (!showHistory) CFSSmartSearch.showHistory = false;
const url = window.location.toString()
this.page = url.match(/\/([^\/]+\.aspx)/)[1]
if (url.toLowerCase().includes('portal/crm/')) {
this.searchType = "accounts"
this.cookiePrefix = "a_"
}
else if (url.toLowerCase().includes('portal/claims/')) {
this.searchType = "claims"
this.cookiePrefix = "c_"
}
else this.searchType = ""
$(".smart-search").each(function () {
var smartSearch = this;
$(smartSearch).addClass("noterm");
CFSSmartSearch.searchOptions = $(smartSearch).attr("data-search-options");
$("input, select", smartSearch).keyup(function (event) {
//clearTimeout(CFSSmartSearch.timer);
CFSSmartSearch.activeElement = smartSearch;
//CFSSmartSearch.timer = setTimeout("CFSSmartSearch.get_lookup_count()", 500);
if (event.which == 13) {
CFSSmartSearch.get_lookup_count();
event.preventDefault();
}
}).focus(function () {
CFSSmartSearch.activeElement = smartSearch;
CFSSmartSearch.show_history();
$(smartSearch).addClass("expanded");
}).ready(function () {
if (showHistoryOnInit) {
CFSSmartSearch.activeElement = smartSearch;
CFSSmartSearch.show_history();
}
});
});
$(window).resize(function () {
$("#smartSearch .suggestions").css("max-height", $(window).height() - 150);
CFSSmartSearch.size_search_holder();
});
$("#smartSearch .suggestions").css("max-height", $(window).height() - 150);
CFSSmartSearch.size_search_holder();
},
"size_search_holder": function () {
if (this.page === "Search.aspx" && this.searchType === "accounts") return
var baseWidth = $("header.md-header").width() - 40 - 282;
$(".md-header .not-logged-in-broker-logo, .md-desktop-user #toolbar-options-menu i").each(function () {
baseWidth -= $(this).width();
});
$(".smart-search").css("max-width", baseWidth);
},
"selected_search_option": function () {
if (CFSSmartSearch.searchOptions == "") {
return "";
} else {
return $("select", CFSSmartSearch.activeElement).val();
}
},
"change_search_option": function (newOption) {
$("select", CFSSmartSearch.activeElement).val(newOption);
CFSSmartSearch.get_lookup_count();
},
"get_lookup_count": function () {
$("input", CFSSmartSearch.activeElement).focus();
var term = $("input", CFSSmartSearch.activeElement).val().trim();
$("input", CFSSmartSearch.activeElement).val(term);
if (term == "") {
$(CFSSmartSearch.activeElement).addClass("noterm");
}
else {
operationLoadBegin();
$(CFSSmartSearch.activeElement).addClass("searching");
var countFunc = $(CFSSmartSearch.activeElement).attr("data-search-count");
const searchType = $(CFSSmartSearch.activeElement).find('select.search-opt option:selected').text();
switch (countFunc) {
case "durell.cfs.admin.searchGetCount":
durell.cfs.admin.searchGetCount(term, CFSSmartSearch.selected_search_option(), CFSSmartSearch.get_lookup_count_callback);
break;
case "durell.cfs.crm.client.searchGetCount":
const searchParameters = durell.cfs.crm.client.generateSearchParameters(CFSSmartSearch.selected_search_option(), $("input", CFSSmartSearch.activeElement).val())
searchParameters['IsOrStatement'] = searchType == "Policy Search" ? false : true;
searchParameters['IsExact'] = false
durell.cfs.crm.client.searchGetCount(searchParameters, CFSSmartSearch.get_lookup_count_callback);
break;
case "durell.cfs.claims.searchCount":
const keys = {
'Policy Search': 'PolicyReference',
'Claim Search': 'ClaimReference',
}
const parameters = {}
parameters[keys[searchType]] = [$("input", CFSSmartSearch.activeElement).val()]
parameters['IsOrStatement'] = false;
parameters['IsExact'] = true;
durell.cfs.claims.searchCount(parameters, CFSSmartSearch.get_lookup_count_callback);
break;
case "data_search_count":
data_search_count(term, CFSSmartSearch.get_lookup_count_callback);
break;
case "message_search_count":
message_search_count(term, CFSSmartSearch.get_lookup_count_callback);
break;
}
}
},
"get_lookup_data": function () {
$(CFSSmartSearch.activeElement).addClass("searching");
var getDataFunc = $(CFSSmartSearch.activeElement).attr("data-search-data");
const searchType = $(CFSSmartSearch.activeElement).find('select.search-opt option:selected').text();
switch (getDataFunc) {
case "durell.cfs.admin.search":
durell.cfs.admin.search($("input", CFSSmartSearch.activeElement).val(), CFSSmartSearch.selected_search_option(), CFSSmartSearch.get_lookup_data_callback);
break;
case "durell.cfs.crm.client.search":
const searchParameters = durell.cfs.crm.client.generateSearchParameters(CFSSmartSearch.selected_search_option(), $("input", CFSSmartSearch.activeElement).val())
searchParameters['IsOrStatement'] = searchType == "Policy Search" ? false : true;
searchParameters['IsExact'] = false
searchParameters['PageSize'] = 1000
durell.cfs.crm.client.search(searchParameters, CFSSmartSearch.get_lookup_data_callback)
break
case "durell.cfs.claims.search":
const keys = {
'Policy Search': 'PolicyReference',
'Claim Search': 'ClaimReference',
}
const parameters = {
}
parameters[keys[searchType]] = [$("input", CFSSmartSearch.activeElement).val()]
parameters['IsOrStatement'] = false;
parameters['IsExact'] = true;
durell.cfs.claims.search(parameters, (data) => CFSSmartSearch.get_lookup_data_callback(data, false, 'claims'));
break;
case "data_search_getItems":
data_search_getItems($("input", CFSSmartSearch.activeElement).val(), CFSSmartSearch.get_lookup_data_callback);
break;
case "message_search":
message_search($("input", CFSSmartSearch.activeElement).val(), CFSSmartSearch.get_lookup_data_callback);
break;
}
},
"get_lookup_count_callback": function (count) {
// If the item count is less than 25 the system will automatically call get_lookup_data,
// otherwise a placeholder is shown showing how many results are in the set.
const suggestions = document.querySelector('.suggestions');
const divider = document.querySelector('.divider');
if (suggestions) suggestions.classList.add('result')
if (divider) divider.classList.add('result')
if (count == 0) {
var selectedSearchOption = CFSSmartSearch.selected_search_option();
if (selectedSearchOption == "") {
$(".suggestions ul", CFSSmartSearch.activeElement).html("
Nothing found.
");
} else {
var otherOpts = "";
if (selectedSearchOption != "All" && selectedSearchOption != "All (every search term)") {
$(CFSSmartSearch.searchOptions.split("|")).each(function () {
var opt = this;
if (opt != selectedSearchOption) {
if (otherOpts != "") {
otherOpts += " or "
}
otherOpts += "" + opt + "";
}
});
if (otherOpts != "") {
otherOpts = "
Search for " + otherOpts + " instead?";
}
$(".suggestions ul", CFSSmartSearch.activeElement).html("Nothing found under that " + selectedSearchOption + "." + otherOpts + "
");
}
else {
$(".suggestions ul", CFSSmartSearch.activeElement).html("Nothing found.
");
}
}
$(CFSSmartSearch.activeElement).removeClass("noterm").removeClass("searching").addClass("expanded");
operationLoadComplete();
}
else if (count <= 25) {
CFSSmartSearch.get_lookup_data();
}
else {
$(".suggestions ul", CFSSmartSearch.activeElement).html("" + count + (count == 999 ? "+" : "") + " matching items, please refine search or View all
");
$(CFSSmartSearch.activeElement).removeClass("noterm").removeClass("searching").addClass("expanded");
operationLoadComplete();
}
},
/*
* Data should be an array of objects with the following syntax:
* {
* icon : [Optional] mdi icon name to display to the left of the row
* mainText: [Required] the main body of text to display as the result (plain text only, will be formatted by search term)
* subText: [Optional] secondary result text to display to the right of the main text (plain text only, will be formatted by search term)
* subTextIcon: [Optional] if using subText can contain an mdi icon to display before the text
* date: [Required] date of item (results are sorted by this vector with newest being at the top)
* action: [Required] callback when an item is clicked
* }
*/
"get_lookup_data_callback": function (data, isHistory, searchType) {
if (searchType === "accounts") {
const suggestions = document.querySelector('.suggestions');
const divider = document.querySelector('.divider');
if (suggestions) suggestions.classList.remove('result')
if (divider) divider.classList.remove('result')
if (!isHistory) {
/* Sort items by their date to ensure the latest items are at the top */
data.sort(function (a, b) {
return (a.CreatedDate > b.CreatedDate) ? -1 : ((b.CreatedDate > a.CreatedDate) ? 1 : 0);
});
}
CFSSmartSearch.results = data;
/* Render items */
var listItems = "";
var term = (isHistory ? "history$items$used$no$highlight" : $("input", CFSSmartSearch.activeElement).val()); // ?
$(CFSSmartSearch.results).each(function (idx) {
listItems += "";
//var clientType = durell.cfs.crm.getClientTypeAsString(this.Category.ClientType);
var addSet = durell.cfs.options.addSetTypeLabels[this.Category.AddSet] ?? '';
let searchTerm = ""
switch (CFSSmartSearch.selected_search_option().toLowerCase()) {
case "phone":
searchTerm = this.PrimaryInfo.PhoneNumber
break
case "id":
searchTerm = "#" + this.Id
break
case "quick search":
const keys = [
{ label: "Id", val: this.Id.toString(), matchExact: true },
{ label: "Initials", val: this.Initials },
{ label: "Search name", val: this.Name },
{ label: "Email", val: this.PrimaryInfo.Email },
{ label: "Phone number", val: this.PrimaryInfo.PhoneNumber },
{ label: "Mobile phone", val: this.PrimaryInfo.MobilePhoneNumber },
{ label: "Work phone", val: this.PrimaryInfo.WorkPhoneNumber },
{ label: "Postal name", val: this.PrimaryInfo.Address?.Line1 },
{ label: "Primary address line 1", val: this.PrimaryInfo.Address?.Line2 },
{ label: "Primary address line 2", val: this.PrimaryInfo.Address?.Line3 },
{ label: "Primary town", val: this.PrimaryInfo.Address?.Line4 },
{ label: "Primary county", val: this.PrimaryInfo.Address?.Line5 },
{ label: "Primary country", val: this.PrimaryInfo.Address?.Line6 },
{ label: "Primary postcode", val: this.PrimaryInfo.Address?.Postcode },
{ label: "Other phone 1", val: this.OtherPhone1 },
{ label: "Other phone 2", val: this.OtherPhone2 },
{ label: "Secondary postal name", val: this.SecondaryInfo.Address?.Line1 },
{ label: "Secondary address line 1", val: this.SecondaryInfo.Address?.Line2 },
{ label: "Secondary address line 2", val: this.SecondaryInfo.Address?.Line3 },
{ label: "Secondary town", val: this.SecondaryInfo.Address?.Line4 },
{ label: "Secondary county", val: this.SecondaryInfo.Address?.Line5 },
{ label: "Secondary country", val: this.SecondaryInfo.Address?.Line6 },
{ label: "Secondary postcode", val: this.SecondaryInfo.Address?.Postcode },
];
keys.forEach(key => {
valLowercase = key.val?.toLowerCase() ?? "";
key.val = key.val ?? "";
if (valLowercase === term || (!key.matchExact && valLowercase.indexOf(term.toLowerCase()) !== -1)) {
searchTerm = `${key.label}: ${durell.cfs.mdfields.util.highlightString(key.val, term, "strong")}`;
return;
}
});
if (searchTerm === "") {
searchTerm = `Matched: ${term}`;
}
break;
default:
searchTerm = this.PrimaryInfo.Email
break
}
const historyIcon = "";
// 1. So if has gravatar, use that
// 2. If not, check initials
// 3. If no intials use gravatar?
const gravatarSrc = durell.cfs.crm.loadGravatar(this.PrimaryInfo.Email, (durell.cfs.isEmpty(this.Name) ? "mysteryman" : "empty"))
const initials = durell.cfs.crm.getInitials(this.Name)
//const gravatar = ``;
// I've made it a span because for absoltuely no reason having it as a p breaks to html structure
const gravatar = `${initials}
`
listItems +=
`
${isHistory ? historyIcon : gravatar}
${this.Name}
${isHistory ? "" : searchTerm}
${addSet}
`
});
}
else if (searchType == 'claims') {
CFSSmartSearch.results = data;
const val = $("input", CFSSmartSearch.activeElement).val()
const type = CFSSmartSearch.selected_search_option().toLowerCase()
var listItems = data.map((i, index) => {
const claimRef = type == 'claim search' ? durell.cfs.mdfields.util.highlightString(i.ClaimReference, val, 'strong') : i.ClaimReference;
const policyRef = type == 'policy search' ? durell.cfs.mdfields.util.highlightString(i.PolicyRef, val, 'strong') : i.PolicyRef;
const gravatar = `${durell.cfs.crm.getInitials(i.ClientName)}
`
return `${gravatar}${claimRef}
${i.Stage}${policyRef}
${i.IntimatedDate != null ? `${durell.cfs.formatDateTime(i.IntimatedDate)}` : ''}`
}).join('');
}
else {
if (!isHistory) {
/* Sort items by their date to ensure the latest items are at the top */
data.sort(function (a, b) {
return (a.date > b.date) ? -1 : ((b.date > a.date) ? 1 : 0);
});
}
CFSSmartSearch.results = data;
/* Render items */
var listItems = "";
var term = (isHistory ? "history$items$used$no$highlight" : $("input", CFSSmartSearch.activeElement).val());
$(CFSSmartSearch.results).each(function (idx) {
listItems += "";
if (this.icon || isHistory) listItems += "";
listItems += "" + (this.mainText + "").replace(new RegExp("(" + term + ")", 'gi'), "$1");
listItems += "";
if (this.subText && this.subText != "undefined") {
listItems += " " + this.subText.replace(new RegExp("(" + term + ")", 'gi'), "$1") + "";
}
listItems += durell.cfs.formatDateTime(this.date) + "";
if (this.inlineSubText && this.inlineSubText != "undefined" && this.inlineSubText != "") {
listItems += "
" + this.inlineSubText.replace(new RegExp("(" + term + ")", 'gi'), "$1") + "";
}
listItems += "
";
});
}
/* Ensure the suggestions box is displayed and output the generated HTML */
$(".suggestions ul", CFSSmartSearch.activeElement).html(listItems);
$(CFSSmartSearch.activeElement).removeClass("noterm").removeClass("searching").addClass("expanded");
const suggestions = document.querySelector('.suggestions');
const divider = document.querySelector('.divider');
if (suggestions && !isHistory) suggestions.classList.add('result');
if (divider && !isHistory) divider.classList.add('result');
// Render MD3 tooltips
durell.cfs.mdfields?.tooltip?.initAll();
operationLoadComplete();
},
"select_item": function (index, isHistory, crm) {
var item = CFSSmartSearch.results[index];
if (!isHistory) {
/* Reset the search element back to an empty state and remove the last term */
$(CFSSmartSearch.activeElement).addClass("noresults").addClass("noterm").removeClass("historic");
$("input", CFSSmartSearch.activeElement).val("");
/* Add the clicked item to the top of the history array */
CFSSmartSearch.history.splice(0, 0, item);
/* Limit the number of items in the history to 5 */
if (CFSSmartSearch.history.length > 5) CFSSmartSearch.history.length = 5;
/* Output the current history to a cookie */
var cookie = "";
const existingIds = [];
$(CFSSmartSearch.history).each(function () {
if (CFSSmartSearch.searchType == "accounts") {
if (!existingIds.includes(this.Id)) {
cookie += this.PrimaryInfo.Email + ";;;" + this.PrimaryInfo.Salutation + ";;;" + this.Name + ";;;" + this.Category.MainType + ";;;" + this.Otp + ";;;" + this.Id + ";;;" + this.Category.SubType + ";;;" + this.PrimaryInfo.PhoneNumber + "|||"
existingIds.push(this.Id)
}
} else if (CFSSmartSearch.searchType == "claims") {
if (!existingIds.includes(this.ClaimId)) {
cookie += this.ClaimId + ";;;" + this.ClaimReference + ";;;" + this.PolicyRef + ";;;" + this.ClientId + ";;;" + this.ClientTOTP + ";;;" + this.ClientName + ";;;" + this.ClientGravatar + ";;;" + this.IntimatedDate + "|||"
existingIds.push(this.ClaimID)
}
}
else {
cookie += this.icon + ";;;" + this.mainText + ";;;" + this.subText + ";;;" + this.subTextIcon + ";;;" + this.date + ";;;" + this.action + "|||";
}
});
cfs_setCookie("_cfs_s_" + this.cookiePrefix + $(CFSSmartSearch.activeElement).attr("data-search-data"), cookie, 7);
}
/* Callback to the original action from the search element */
if (this.searchType == "accounts") {
durell.cfs.crm.loadNewAccountPage(item.Id, item.Otp)
}
else if (this.searchType == "claims") {
operationLoadBegin(`/Portal/Claims/Item.aspx?id=${item.ClaimId}`)
}
else {
eval(item.action);
}
},
"show_history": function (smartSearch) {
if (CFSSmartSearch.history == null) {
CFSSmartSearch.history = [];
const self = this;
var cHistory = cfs_getCookie("_cfs_s_" + this.cookiePrefix + $(CFSSmartSearch.activeElement).attr("data-search-data"));
if (cHistory && cHistory != "" && CFSSmartSearch.showHistory === true) {
$(cHistory.split("|||")).each(function () {
if (this && this != "") {
var px = ("" + this).split(";;;");
if (self.searchType == "accounts")
CFSSmartSearch.history.push({ PrimaryInfo: { Email: px[0], Salutation: px[1], PhoneNumber: px[7] }, Name: px[2], Category: { MainType: px[3], SubType: px[6] }, Otp: px[4], Id: px[5] });
else if (self.searchType == "claims") // this.ClaimId + ";;;" + this.ClaimReference + ";;;" + this.PolicyRef + ";;;" + this.ClientId + ";;;" + this.ClientTOTP + ";;;" + this.ClientName + ";;;" + this.ClientGravatar + ";;;" + this.IntimatedDate + "|||"
CFSSmartSearch.history.push({ ClaimId: px[0], ClaimReference: px[1], PolicyRef: px[2], ClientId: px[3], ClientTOTP: px[4], ClientName: px[5], ClientGravatar: px[6], IntimatedDate: px[7] });
else
CFSSmartSearch.history.push({ icon: "clock", mainText: px[1], subText: px[2], subTextIcon: px[3], date: new Date(px[4]), action: px[5] });
}
});
}
}
if ($("input", CFSSmartSearch.activeElement).val() == "" && CFSSmartSearch.history.length > 0) {
// Show some history instead
CFSSmartSearch.get_lookup_data_callback(CFSSmartSearch.history, true, this.searchType);
//var output = "";
//$(CFSSmartSearch.history).each(function () {
// output += "" + this.html + "";
//});
//$(".suggestions ul", smartSearch).html(output);
//smartSearch.removeClass("noresults").removeClass("noterm").addClass("historic");
}
}
};
$(document).ready(function () {
CFSSmartSearch.init();
});