PageSourceSearch

https://www.bolderscience.com/etc.clientlibs/bms-commercial-shared…lderscience-exploretrials/clientlibs.min.js

js bolderscience.com collected 2026-10-06 13:46:32 UTC 58,032 bytes, 1,215 lines download raw bytes

1$(document).ready(function() {
2    var urlParams = new URLSearchParams(window.location.search);
3    var searchText = urlParams.get('searchText');
4    var searchType = urlParams.get('searchType');
5    var searchLocation = urlParams.get('searchlocation');
6    var latitude = urlParams.get('latitude');
7    var longitude = urlParams.get('longitude');
8    var radius = urlParams.get('radius');
9	var userId = getGigyaSessionUserId();
10	var selCollection = '';
11    var fulltrialPagePath = $('#fulltrialpage-path').data('path') || '';
12    var synonymFilePath = $('#synonymdam-path').data('path') || '';
13    var synonymsDataJson = {};
14
15
16    const filterParams = {};
17
18    function csvToJson(csv) {
19        const rows = csv.split("\n").map(row => row.trim()).filter(row => row);
20        const jsonArray = rows.slice(1).map(row => {
21            const values = row.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g) || [];
22            return {
23                standardname: values[0].trim(),
24                synonyms: values[1].replace(/"/g, "").split(",").map(syn => syn.trim())
25            };
26        });
27
28        return jsonArray;
29    }
30
31    async function fetchCSV(url,callback) {
32        try {
33            const response = await fetch(url);
34            const csvData = await response.text();
35            synonymsDataJson = csvToJson(csvData);
36			if (typeof callback === "function") {
37				callback(true);
38			}
39        } catch (error) {
40            console.error('Error fetching CSV:', error);
41        }
42    }
43    
44    if(synonymFilePath){
45         fetchCSV(synonymFilePath, function(synonymsJson) {
46            if (synonymsJson) {
47                fetchOnload();
48            }
49		});
50    }
51
52    function replaceSynonym(inputText) {
53        if(synonymsDataJson.length > 0){
54            for (const item of synonymsDataJson) {
55                if (item.synonyms.includes(inputText)) {
56                    return item.standardname;
57                }
58            }
59        }
60        return inputText;
61    }
62
63    for (const [paramKey, value] of urlParams.entries()) {
64        if (paramKey.startsWith('f_')) {
65            const mainKey = paramKey.split('_')[1];
66            let childKey;
67            if (mainKey.includes('-')) {
68                [parentKey, childKey] = mainKey.split('-'); 
69                if (!filterParams[parentKey]) {
70                    filterParams[parentKey] = {};
71                }
72
73                if ($("#filterForm [name='" + mainKey + "']").is("button")) {
74                    if(childKey == 'multiselect'){
75                        filterParams[parentKey][childKey] = value.includes(',') ? value.split(',') : [value];
76                    } else filterParams[parentKey][childKey] = value.includes(',') ? value.split(',') : [value];
77                } else {
78                    filterParams[parentKey][childKey] = value;
79                }
80            } else {
81                if ($("#filterForm [name='" + mainKey + "']").is("button")) {
82                    if(mainKey === 'acceptsHealthyVolunteers'){
83                        filterParams[mainKey] = true;
84                    } else {
85                        filterParams[mainKey] = value.includes(',') ? value.split(',') : [value];
86                    }                           
87                } else {
88                    filterParams[mainKey] = value;
89                }
90            }
91        }
92    }
93
94    var paginationsize = $('#inpagepagination').data('page-size') || 50;
95    var interventionLabel = $('#interventionLabel').data('intervention-label') || "Intervention";
96    var conditionLabel = $('#conditionLabel').data('condition-label') || "Condition";
97    var eligibilityLabel = $('#eligibilityLabel').data('eligibility-label') || "Eligibility";
98    var viewlabel = $('.viewtrialLabel').attr('data-viewtriallabel-label');
99
100    var currentFrom = 0;
101    var sortBy = "";
102    var defaultRadius = radius || "50";
103
104    let savedNctIds = [];
105
106    setSelectedSearchValues();
107
108    $(".trial-container__sort-dropdown").on("change", function() {
109		let trialType = $(this).closest('.trial-container__tab-content').attr('data-trial');
110		if(trialType == 'all' || trialType == 'preferred') {
111	        sortBy = $(this).val();
112	        $("#"+trialType+"-trials .trial-container__result-container").empty();
113	        currentFrom = 0;
114	        $("#"+trialType+"-trials .event-resources").hide();
115	        $("#"+trialType+"-trials .loader").show();
116	        fetchTrials(trialType);
117		}
118    });
119
120    function toGetLocationValues() {
121        if (latitude && longitude) {
122            return {
123                latlon: {
124                    lat: parseFloat(latitude) || "",
125                    lon: parseFloat(longitude) || "",
126                    miles: defaultRadius+'mi'
127                }
128            }
129        }
130        var searchCountry1 = "";
131        if (searchLocation) {
132            searchLocation = decodeURIComponent(searchLocation);
133            if (searchLocation.includes(',')) {
134                searchLocation = searchLocation.split(',');
135                searchCountry1 = searchLocation[1].trim();
136            } else {
137                searchCountry1 = searchLocation;
138            }
139            return {
140                country: searchCountry1
141            }
142        }
143    }
144
145
146    // Hide the "Load More" button initially
147    $(".event-resources").hide();
148
149    function fetchTrials(trialType) {
150        if(synonymFilePath){
151            searchText = replaceSynonym(searchText);
152        }
153        var payload = {
154            searchType: 'search',
155            searchCat: searchType ? searchType : "",
156            searchText: searchText === "null" || !searchText ? "" : decodeURIComponent(searchText),
157            pagination: {
158                from: currentFrom,
159                size: paginationsize
160            }
161        };
162		if(trialType && trialType == 'preferred') {
163			payload.userPreference = true;
164			payload.UID = userId ? userId : '';
165		}
166
167        if (sortBy) {
168            payload.sortBy = sortBy;
169        }
170        if (Object.keys(filterParams).length > 0) {
171            payload.filter = filterParams;
172        }
173        if (searchLocation) {
174            if (!payload.filter) {
175                payload.filter = {}
176
177            }
178            payload.filter.location = toGetLocationValues()
179        }
180
181        $("#"+trialType+"-trials .loader").show();
182
183        return $.ajax({
184            url: '/bin/buildeasy/bolderscience/search',
185            method: 'POST',
186            contentType: 'application/json',
187            data: JSON.stringify(payload),
188            success: function(response) {
189                console.log('Response from backend:', response);
190				if(response.hits){
191                    const trialsToRender = response.hits;
192                    renderTrials(trialsToRender, trialType);
193                    if (!userId) {
194                        $(".trial-container__interaction").hide();
195                    }
196                    var trailCount = response.trailCount || 0;
197                    var viewingTrialsLabel = `${trailCount.toLocaleString()} trials`;
198                    $("#"+trialType+"-trials #viewing-trials-label").text(`Viewing ${viewingTrialsLabel}`);
199
200                    // Show the "No trials found" message if no trials are found
201                    if (trialsToRender.length === 0) {
202                        $("#"+trialType+"-trials #viewing-trials-label").text("Viewing 0 trials");
203                        $("#"+trialType+"-trials .no-trials-message").show();
204                    } else {
205                        $("#"+trialType+"-trials .no-trials-message").hide();
206                    }
207
208                    // Show the "Load More" button after trials are loaded
209                    if (response.hits.length >= paginationsize) {
210                        $("#"+trialType+"-trials .event-resources").show();
211                    } else {
212                        $("#"+trialType+"-trials .event-resources").hide();
213                    }
214			    } else if (response.status !=200 || response.message === "No data found") {
215                    $("#"+trialType+"-trials #viewing-trials-label").text("Viewing 0 trials");
216                    $("#"+trialType+"-trials .no-trials-message").show();
217                }
218
219                $("#"+trialType+"-trials .loader").hide();
220                if(trialType == 'preferred') {
221                    if(response.hits)
222                        $("#" + trialType + "-trials").attr('data-result', 'true');
223                    else
224                        $("#" + trialType + "-trials").attr('data-result', 'false');
225                }
226            },
227            error: function(error) {
228                console.error("Error fetching search results:", error);
229                $("#"+trialType+"-trials .loader").hide();
230                if (userId) {
231                    alert("Failed to fetch search results. Please try again later.");
232                }
233                $("#"+trialType+"-trials .event-resources").show();
234            }
235        });
236    }
237
238    function toRenderAgeEligibility(ageEligibleData) {
239		let ageHtml = '';
240		if(ageEligibleData?.minimumAge)
241			ageHtml += ageEligibleData.minimumAge;
242		if(ageEligibleData?.maximumAge) 
243			ageHtml += ' to ' + ageEligibleData.maximumAge + ' ';
244		else
245			ageHtml += ' and Older ';
246		if(ageEligibleData.stdAges && ageEligibleData.stdAges.length > 0) {
247			let stdAges = ageEligibleData.stdAges.map(item => capitalizeEachWord(item));
248			ageHtml += '('+stdAges.toString()+')';
249		}
250		return ageHtml;
251	}
252		
253	function capitalizeEachWord(str) {
254	    if (!str) return ""; 
255	    return str.replace(/_/g, " ").toLowerCase().replace(/\b\w/g, function(char) {
256	        return char.toUpperCase();
257	    });
258	}
259
260    function renderTrials(trials, trialType) {
261        const container = $("#" + trialType + "-trials .trial-container__result-container");
262        //container.empty();
263
264        trials.forEach(trial => {
265			collections.forEach(function(collection){
266                if(collection.ntcIds && collection.ntcIds.indexOf(trial.nct_id)!==-1){
267                    trial.collectionName = collection.CollectionName
268                }
269			})
270			trial.status = trial.status.replace(/_/g, " "); 
271            const isSaved = savedNctIds.includes(trial.nct_id); // Check if trial is saved
272            const savedIcon = isSaved ? `
273                <svg width="10" height="13" viewBox="0 0 10 13" fill="none" xmlns="http://www.w3.org/2000/svg">
274                    <path d="M4.99998 11.0961L2.02306 12.374C1.57115 12.5673 1.14183 12.5302 0.735106 12.2629C0.328368 11.9956 0.125 11.6197 0.125 11.1351V1.98078C0.125 1.60193 0.25625 1.28125 0.51875 1.01875C0.78125 0.75625 1.10192 0.625 1.48077 0.625H8.51919C8.89804 0.625 9.21871 0.75625 9.48121 1.01875C9.74371 1.28125 9.87496 1.60193 9.87496 1.98078V11.1351C9.87496 11.6197 9.67159 11.9956 9.26486 12.2629C8.85813 12.5302 8.42881 12.5673 7.9769 12.374L4.99998 11.0961Z" fill="#173C58"/>
275                </svg>
276            ` : `
277                <svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" viewBox="0 0 10 12" fill="none">
278                    <path d="M5.12498 10.4711L2.14806 11.749C1.69615 11.9423 1.26683 11.9052 0.860106 11.6379C0.453368 11.3706 0.25 10.9947 0.25 10.5101V1.35578C0.25 0.976926 0.38125 0.65625 0.64375 0.39375C0.90625 0.13125 1.22692 0 1.60577 0H8.64419C9.02304 0 9.34371 0.13125 9.60621 0.39375C9.86871 0.65625 9.99996 0.976926 9.99996 1.35578V10.5101C9.99996 10.9947 9.79659 11.3706 9.38986 11.6379C8.98313 11.9052 8.55381 11.9423 8.1019 11.749L5.12498 10.4711ZM5.12498 9.22498L8.55044 10.7005C8.62736 10.7341 8.70069 10.7269 8.77041 10.6788C8.84012 10.6307 8.87498 10.5658 8.87498 10.4841V1.35578C8.87498 1.29808 8.85094 1.24518 8.80287 1.19709C8.75478 1.14902 8.70189 1.12498 8.64419 1.12498H1.60577C1.54807 1.12498 1.49518 1.14902 1.44709 1.19709C1.39902 1.24518 1.37498 1.29808 1.37498 1.35578V10.4841C1.37498 10.5658 1.40984 10.6307 1.47955 10.6788C1.54927 10.7269 1.6226 10.7341 1.69952 10.7005L5.12498 9.22498Z" fill="#123045"/>
279                </svg>
280            `;
281            const phase = trial.phase ? (Array.isArray(trial.phase) ? trial.phase.join(", ") : trial.phase) : "NA";
282
283            const trialHtml = `
284                <div class="trial-container__box">
285                    <div class="trial-container__head">
286                         <a aria-label="button" href="${fulltrialPagePath}?nctid=${trial.nct_id}" class="trial-container__title">${trial.title}</a>
287                        <button aria-label="button" type="button" class="trial-container__interaction" data-collection="${trial.collectionName}">
288                            ${savedIcon}
289                        </button>
290                    </div>
291                    <div class="trial-container__horizontal-labels">
292                        <div class="trial-container__horizontal-label trial-container__label-1">${trial.status}</div>
293                        <div class="trial-container__horizontal-label trial-container__label-2">${phase}</div>
294                        <div class="trial-container__horizontal-label trial-container__label-3">${trial.nct_id}</div>
295                    </div>
296                    <div class="trial-container__vertical-section">
297                        <div class="trial-container__vertical-item">
298                            <div class="trial-container__vertical-label">Intervention</div>
299                            <div class="trial-container__vertical-value">${Array.isArray(trial.intervention) ? trial.intervention.join(", ") : trial.intervention}</div>
300                        </div>
301                        <div class="trial-container__vertical-item">
302                            <div class="trial-container__vertical-label">Condition</div>
303                            <div class="trial-container__vertical-value">${Array.isArray(trial.condition) ? trial.condition.join(", ") : trial.condition}</div>
304                        </div>
305                        <div class="trial-container__vertical-item">
306                            <div class="trial-container__vertical-label">Eligibility</div>
307                             <div class="trial-container__vertical-value"> ${toRenderAgeEligibility(trial.ages)}, Sexes: ${trial.sexes}, Accepting Healthy Volunteers: ${trial.accepts_healthy_volunteers}</div>
308                        </div>
309                    </div>
310                    <a aria-label="button" href="${fulltrialPagePath}?nctid=${trial.nct_id}" class="trial-container__view-trial-btn">
311                        <span>View Details</span>
312                        <svg xmlns="http://www.w3.org/2000/svg" width="19" height="18" viewBox="0 0 19 18" fill="none">
313                            <path fill-rule="evenodd" clip-rule="evenodd" d="M6.14732 3.14547C5.95205 3.34073 5.95205 3.65731 6.14732 3.85258L11.2949 9.00018L6.14732 14.1478C5.95205 14.3431 5.95205 14.6596 6.14732 14.8549C6.34258 15.0502 6.65916 15.0502 6.85442 14.8549L12.002 9.70729C12.3926 9.31677 12.3926 8.6836 12.002 8.29308L6.85442 3.14547C6.65916 2.95021 6.34258 2.95021 6.14732 3.14547Z" fill="#595454"/>
314                        </svg>
315                    </a>
316                </div>
317            `;
318
319            container.append(trialHtml);
320        });
321    }
322
323    let selectedNctId = null;
324    let selectedCollectionName = {};
325    let collections = [];
326    let savedTrials = [];
327    let allCollections = [];
328
329  $(document).on("click", ".trial-container__interaction", function (e) {
330        e.stopPropagation();
331
332        const trialBox = $(this).closest(".trial-container__box");
333        const svgHtml = $(this).html().trim();
334
335        selectedNctId = trialBox.find(".trial-container__label-3").text().trim();
336	    selCollection = $(this).data('collection') || '';
337        console.log("Selected NCT ID:", selectedNctId);
338
339        if (svgHtml.includes('fill="#173C58"')) {
340            $("#unsaveModal").show();
341        } else {
342            const popover = $("#savedTrialsPopover");
343            populateCollectionsList(collections);
344            if($("#collectionsList li .check-icon:not(.hidden)").length){
345                $('#doneButton').removeAttr('disabled')
346            } else {
347				$('#doneButton').attr('disabled','disabled')
348			}
349            const buttonRect = this.getBoundingClientRect();
350			const parentRect = $('.bolderscience-exploretrials').offset().left;
351
352            const isMobile = window.innerWidth < 768;
353
354            if (isMobile) {
355              popover.css({
356                position: "absolute",
357                top: buttonRect.bottom + window.scrollY - 145,
358                left: "57%",
359                transform: "translateX(-50%)",
360              });
361            } else {
362              popover.css({
363                position: "absolute",
364                top: buttonRect.bottom + window.scrollY - 140,
365                left:buttonRect.left- parentRect -250 ,
366              });
367            }
368
369            popover.addClass("visible");
370
371
372        }
373  });
374
375    $("#unsaveButton").on("click", function () {
376		$("#unsaveModal").hide();
377		$("#saved-trials-content").empty();
378        const payload = {
379            MethodName: "update",
380            UID: userId,
381            eventCategory: "collection",
382            Operation: "idsToRemove",
383            collections: [{
384                ntcIds: [selectedNctId],
385                CollectionName: selectedCollectionName[selectedNctId] || selCollection,
386            }],
387        };
388
389        $('.loader').show();
390
391        $.ajax({
392            url: "/bin/buildeasy/bolderscience/collections",
393            method: "POST",
394            contentType: "application/json",
395            data: JSON.stringify(payload),
396            success: function(response) {
397                console.log("Collection updated successfully:", response);
398
399				const trialBox = $(`.trial-container__label-3:contains('${selectedNctId}')`).closest(".trial-container__box");
400                    trialBox.find(".trial-container__interaction").html(`
401                      <svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" viewBox="0 0 10 12" fill="none">
402                        <path d="M5.12498 10.4711L2.14806 11.749C1.69615 11.9423 1.26683 11.9052 0.860106 11.6379C0.453368 11.3706 0.25 10.9947 0.25 10.5101V1.35578C0.25 0.976926 0.38125 0.65625 0.64375 0.39375C0.90625 0.13125 1.22692 0 1.60577 0H8.64419C9.02304 0 9.34371 0.13125 9.60621 0.39375C9.86871 0.65625 9.99996 0.976926 9.99996 1.35578V10.5101C9.99996 10.9947 9.79659 11.3706 9.38986 11.6379C8.98313 11.9052 8.55381 11.9423 8.1019 11.749L5.12498 10.4711ZM5.12498 9.22498L8.55044 10.7005C8.62736 10.7341 8.70069 10.7269 8.77041 10.6788C8.84012 10.6307 8.87498 10.5658 8.87498 10.4841V1.35578C8.87498 1.29808 8.85094 1.24518 8.80287 1.19709C8.75478 1.14902 8.70189 1.12498 8.64419 1.12498H1.60577C1.54807 1.12498 1.49518 1.14902 1.44709 1.19709C1.39902 1.24518 1.37498 1.29808 1.37498 1.35578V10.4841C1.37498 10.5658 1.40984 10.6307 1.47955 10.6788C1.54927 10.7269 1.6226 10.7341 1.69952 10.7005L5.12498 9.22498Z" fill="#123045"/>
403                      </svg>
404                    `);
405
406                fetchSavedTrials('saved');
407				showUnsaveSuccessModal();
408                $('.loader').hide();
409
410
411
412            },
413            error: function(xhr, status, error) {
414                console.error("Error updating collection:", error);
415                $('.loader').hide();
416                alert("Failed to update collection. Please try again.");
417            }
418        });
419    });
420
421    $("#cancelButton").on("click", function () {
422        $("#unsaveModal").hide();
423    });
424
425    $(document).on("click", "#doneButton", function() {
426        const selectedCollection = $("#collectionsList li .check-icon:not(.hidden)").parent().find("span").text();
427         $("#savedTrialsPopover").removeClass("visible");
428
429        if (selectedCollection) {
430            const payload = {
431                MethodName: "update",
432                UID: userId,
433                eventCategory: "collection",
434                collections: [{
435                    ntcIds: [selectedNctId],
436                    CollectionName: selectedCollection,
437                }],
438            };
439
440            $('.loader').show();
441
442            $.ajax({
443                url: "/bin/buildeasy/bolderscience/collections",
444                method: "POST",
445                contentType: "application/json",
446                data: JSON.stringify(payload),
447                success: function(response) {
448                    console.log("Collection updated successfully:", response);
449
450                    showSuccessModal(selectedCollection);
451
452                    const trialBox = $(`.trial-container__label-3:contains('${selectedNctId}')`).closest(".trial-container__box");
453                    trialBox.find(".trial-container__interaction").html(`
454                      <svg width="10" height="13" viewBox="0 0 10 13" fill="none" xmlns="http://www.w3.org/2000/svg">
455                        <path d="M4.99998 11.0961L2.02306 12.374C1.57115 12.5673 1.14183 12.5302 0.735106 12.2629C0.328368 11.9956 0.125 11.6197 0.125 11.1351V1.98078C0.125 1.60193 0.25625 1.28125 0.51875 1.01875C0.78125 0.75625 1.10192 0.625 1.48077 0.625H8.51919C8.89804 0.625 9.21871 0.75625 9.48121 1.01875C9.74371 1.28125 9.87496 1.60193 9.87496 1.98078V11.1351C9.87496 11.6197 9.67159 11.9956 9.26486 12.2629C8.85813 12.5302 8.42881 12.5673 7.9769 12.374L4.99998 11.0961Z" fill="#173C58"/>
456                      </svg>
457                    `);
458
459                    $('.loader').hide();
460
461                    $("#savedTrialsPopover").removeClass("visible");
462
463                    selectedCollectionName[selectedNctId] = selectedCollection;
464                    selectedNctId = null;
465
466                    fetchCollections().then(() => {
467                        populateCollectionsList(collections);
468						$("#saved-trials-content").empty();
469					    fetchSavedTrials('saved');
470                    });
471                },
472                error: function(xhr, status, error) {
473                    console.error("Error updating collection:", error);
474                    $('.loader').hide();
475                    alert("Failed to update collection. Please try again.");
476                }
477            });
478        } else {
479            const payload = {
480                MethodName: "update",
481                UID: userId,
482                eventCategory: "collection",
483                Operation: "idsToRemove",
484                collections: [
485                    {
486                        ntcIds: [selectedNctId],
487                        CollectionName: selectedCollectionName[selectedNctId],
488                    },
489                ],
490            };
491
492            $('.loader').show();
493
494            $.ajax({
495                url: "/bin/buildeasy/bolderscience/collections",
496                method: "POST",
497                contentType: "application/json",
498                data: JSON.stringify(payload),
499                success: function(response) {
500                    console.log("Collection updated successfully:", response);
501
502                    const trialBox = $(`.trial-container__label-3:contains('${selectedNctId}')`).closest(".trial-container__box");
503                    trialBox.find(".trial-container__interaction").html(`
504                      <svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" viewBox="0 0 10 12" fill="none">
505                        <path d="M5.12498 10.4711L2.14806 11.749C1.69615 11.9423 1.26683 11.9052 0.860106 11.6379C0.453368 11.3706 0.25 10.9947 0.25 10.5101V1.35578C0.25 0.976926 0.38125 0.65625 0.64375 0.39375C0.90625 0.13125 1.22692 0 1.60577 0H8.64419C9.02304 0 9.34371 0.13125 9.60621 0.39375C9.86871 0.65625 9.99996 0.976926 9.99996 1.35578V10.5101C9.99996 10.9947 9.79659 11.3706 9.38986 11.6379C8.98313 11.9052 8.55381 11.9423 8.1019 11.749L5.12498 10.4711ZM5.12498 9.22498L8.55044 10.7005C8.62736 10.7341 8.70069 10.7269 8.77041 10.6788C8.84012 10.6307 8.87498 10.5658 8.87498 10.4841V1.35578C8.87498 1.29808 8.85094 1.24518 8.80287 1.19709C8.75478 1.14902 8.70189 1.12498 8.64419 1.12498H1.60577C1.54807 1.12498 1.49518 1.14902 1.44709 1.19709C1.39902 1.24518 1.37498 1.29808 1.37498 1.35578V10.4841C1.37498 10.5658 1.40984 10.6307 1.47955 10.6788C1.54927 10.7269 1.6226 10.7341 1.69952 10.7005L5.12498 9.22498Z" fill="#123045"/>
506                      </svg>
507                    `);
508
509                    $('.loader').hide();
510
511                    $("#savedTrialsPopover").removeClass("visible");
512
513                    delete selectedCollectionName[selectedNctId];
514                    selectedNctId = null;
515
516                    fetchCollections().then(() => {
517                        populateCollectionsList(collections);
518						$("#saved-trials-content").empty();
519					    fetchSavedTrials('saved');
520                    });
521                },
522                error: function(xhr, status, error) {
523                    console.error("Error updating collection:", error);
524                    $('.loader').hide();
525                    alert("Failed to update collection. Please try again.");
526                }
527            });
528        }
529    });
530
531    function showSuccessModal(collectionName) {
532        $("#collectionNameDisplay").text(collectionName);
533
534        $("#successModal").removeClass("hidden");
535		setTimeout(function(){
536			$("#successModal").addClass("hidden");
537		},1000)
538    }
539
540    $(document).on("click", ".close-modal", function() {
541        $("#successModal").addClass("hidden");
542    });
543
544    $("#saveCollectionButton").on("click", function() {
545        const collectionName = $("#collectionName").val();
546        if (!collectionName) {
547            alert("Please enter a collection name.");
548            return;
549        }
550
551$("#savedTrialsPopover").removeClass("visible");
552        const payload = {
553            MethodName: "create",
554            UID: userId,
555            eventCategory: "collection",
556            collections: [{
557                ntcIds: [selectedNctId],
558                CollectionName: collectionName,
559            }],
560        };
561
562        $.ajax({
563            url: "/bin/buildeasy/bolderscience/collections",
564            method: "POST",
565            contentType: "application/json",
566            data: JSON.stringify(payload),
567            success: function(response) {
568                console.log("Collection saved successfully:", response);
569
570                showSuccessModal(collectionName);
571
572	            const trialBox = $(`.trial-container__label-3:contains('${selectedNctId}')`).closest(".trial-container__box");
573                trialBox.find(".trial-container__interaction").html(`
574                  <svg width="10" height="13" viewBox="0 0 10 13" fill="none" xmlns="http://www.w3.org/2000/svg">
575                    <path d="M4.99998 11.0961L2.02306 12.374C1.57115 12.5673 1.14183 12.5302 0.735106 12.2629C0.328368 11.9956 0.125 11.6197 0.125 11.1351V1.98078C0.125 1.60193 0.25625 1.28125 0.51875 1.01875C0.78125 0.75625 1.10192 0.625 1.48077 0.625H8.51919C8.89804 0.625 9.21871 0.75625 9.48121 1.01875C9.74371 1.28125 9.87496 1.60193 9.87496 1.98078V11.1351C9.87496 11.6197 9.67159 11.9956 9.26486 12.2629C8.85813 12.5302 8.42881 12.5673 7.9769 12.374L4.99998 11.0961Z" fill="#173C58"/>
576                  </svg>
577                `);
578
579                $("#newCollectionInput").addClass("hidden");
580                $("#newCollectionButton").removeClass("hidden");
581                $("#doneButton").removeClass("hidden");
582                $("#collectionName").val("");
583
584                // Refresh the collections list and set the new collection as selected
585                fetchCollections().then(() => {
586                    selectedCollectionName[selectedNctId] = collectionName;
587                    populateCollectionsList(collections);
588					$("#saved-trials-content").empty();
589					    fetchSavedTrials('saved');
590                });
591            },
592            error: function(xhr, status, error) {
593                console.error("Error saving collection:", error);
594                console.error("Status:", status);
595                console.error("Response:", xhr.responseText);
596                alert("Failed to save trial to collection. Please try again.");
597            },
598        });
599    });
600
601    function showSuccessModal(collectionName) {
602        $("#collectionNameDisplay").text(collectionName);
603
604        $("#successModal").removeClass("hidden");
605        setTimeout(function() {
606            $("#successModal").addClass("hidden");
607        }, 2000);
608    }
609
610    $(document).on("click", ".close-modal", function() {
611        $("#successModal").addClass("hidden");
612    });
613
614    $("#newCollectionButton").on("click", function() {
615        $("#newCollectionInput").removeClass("hidden");
616        $("#doneButton").addClass("hidden");
617        $(this).addClass("hidden");
618    });
619
620    $("#cancelCollectionButton").on("click", function() {
621        $("#newCollectionInput").addClass("hidden");
622        $("#newCollectionButton").removeClass("hidden");
623        $("#doneButton").removeClass("hidden");
624        $("#collectionName").val("");
625    });
626
627
628
629
630    function fetchCollections() {
631        const payload = {
632            MethodName: "get",
633            UID: userId,
634            eventCategory: "savedTrialsDetails",
635            pagination: {
636                from: 0,
637                size: 20
638            }
639        };
640
641        $("#savedTrialsPopover .loader").show();
642
643        return $.ajax({
644            url: '/bin/buildeasy/bolderscience/collections',
645            method: 'POST',
646            contentType: 'application/json',
647            data: JSON.stringify(payload),
648            success: function(response) {
649                console.log('Collections Response:', response);
650                if(response && response.Data){
651                    collections = response.Data.collections;
652                    allCollections = response.Data.collections;
653                    response.Data.collections.forEach(collection => {
654                        savedNctIds = savedNctIds.concat(collection.ntcIds);
655                    });
656                    savedNctIds = [...new Set(savedNctIds)];
657                }
658                $("#savedTrialsPopover .loader").hide();
659            },
660            error: function(error) {
661                console.error("Error fetching collections:", error);
662                $("#savedTrialsPopover .loader").hide();
663                if (userId) {
664                    alert("Failed to fetch collections. Please try again later.");
665                }
666            }
667        });
668    }
669
670
671    function populateCollectionsList(collections) {
672        const collectionsList = $("#collectionsList");
673        collectionsList.empty();
674
675        allCollections.forEach(collection => {
676            const isSelected = collection.CollectionName === selectedCollectionName[selectedNctId];
677            const collectionHtml = `
678        <li>
679          <span>${collection.CollectionName}</span>
680          <svg class="check-icon ${isSelected ? '' : 'hidden'}" width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
681            <path d="M7.34881 11.3718L13.7051 5.01553C13.8551 4.86553 14.0332 4.79053 14.2394 4.79053C14.4457 4.79053 14.6238 4.86553 14.7738 5.01553C14.9238 5.16553 14.9988 5.34365 14.9988 5.5499C14.9988 5.75615 14.9238 5.93428 14.7738 6.08428L7.87381 12.9843C7.72381 13.1343 7.54881 13.2093 7.34881 13.2093C7.14881 13.2093 6.97381 13.1343 6.82381 12.9843L3.59881 9.75928C3.44881 9.60928 3.37694 9.43115 3.38319 9.2249C3.38944 9.01865 3.46756 8.84053 3.61756 8.69053C3.76756 8.54053 3.94569 8.46553 4.15194 8.46553C4.35819 8.46553 4.53631 8.54053 4.68631 8.69053L7.34881 11.3718Z" fill="#173C58"/>
682          </svg>
683        </li>
684      `;
685            collectionsList.append(collectionHtml);
686        });
687    }
688
689    $(".event-resources").on("click", function() {
690        $(this).hide();
691		let trialType = $(this).closest('.trial-container__tab-content').attr('data-trial');
692        $("#"+trialType+"-trials .loader").show();
693        currentFrom += paginationsize;
694        fetchTrials(trialType).then(() => {
695			$("#" + trialType + "-trials .loader").hide();
696            $("#" + trialType+"-trials .event-resources").show();
697        });
698    });
699
700    $(document).on("click", function(e) {
701        if (
702            !$(e.target).closest(".trial-container__interaction, #savedTrialsPopover").length ||
703            $(e.target).hasClass("close-popover")
704        ) {
705            $("#savedTrialsPopover").removeClass("visible");
706        }
707    });
708
709    $(document).on("click", "#collectionsList li", function() {
710        const checkIcon = $(this).find(".check-icon");
711        if (checkIcon.hasClass("hidden")) {
712            $("#collectionsList .check-icon").addClass("hidden");
713            checkIcon.removeClass("hidden");
714        } else {
715            checkIcon.addClass("hidden");
716        }
717        if($("#collectionsList li .check-icon:not(.hidden)").length){
718            $('#doneButton').removeAttr('disabled')
719        } else {
720            $('#doneButton').attr('disabled','disabled')
721        }
722    });
723
724    $("#newCollectionButton").on("click", function() {
725        $("#newCollectionInput").removeClass("hidden");
726        $("#doneButton").addClass("hidden");
727        $(this).addClass("hidden");
728    });
729
730    $("#cancelCollectionButton").on("click", function() {
731        $("#newCollectionInput").addClass("hidden");
732        $("#newCollectionButton").removeClass("hidden");
733        $("#doneButton").removeClass("hidden");
734        $("#collectionName").val("");
735    });
736
737	$(".trial-container__search-box .trial-container__tab-content-container .trial-container__tab-content").hide();
738    $("#all-trials").show();
739    $(".trial-container__search-box #filters").show();
740
741
742
743    function showLoginRequiredModal() {
744        $("#overlay").addClass("visible");
745        $("#loginRequiredModal").addClass("visible").css("display", "block");
746    }
747
748    function hideLoginRequiredModal() {
749        $("#overlay").removeClass("visible");
750        $("#loginRequiredModal").removeClass("visible").css("display", "none");
751    }
752
753	$(".close-login-modal").on("click", function(e) {
754        e.preventDefault();
755        e.stopPropagation();
756        hideLoginRequiredModal();
757    });
758
759	$(document).on("click", function(e) {
760        if ($(e.target).closest("#loginRequiredModal").length === 0) {
761            hideLoginRequiredModal();
762        }
763    });
764
765    function fetchSavedTrials(trialType, sortBy = "relevance", filterBy = {}) {
766        const payload = {
767            MethodName: "get",
768            UID: userId,
769            eventCategory: "savedTrialsDetails",
770            sortBy: sortBy,
771            filterBy: filterBy,
772            pagination: { from: 0, size: 20 }
773        };
774
775        $('.loader').show();
776
777        $.ajax({
778            url: '/bin/buildeasy/bolderscience/collections',
779            method: 'POST',
780            contentType: 'application/json',
781            data: JSON.stringify(payload),
782            success: function (response) {
783                console.log("API Response:", response);
784                savedTrials = response.hits || [];
785				if(response.Data && response.Data.collections){
786					collections = response.Data.collections;
787	                if (Object.keys(filterBy).length === 0) {
788	                    allCollections = response.Data.collections || [];
789	                }
790				}
791
792                const savedTrialsCount = Number(response.Count) || 0;
793                $("#saved-trials-content").empty();
794                renderSavedTrials("saved", savedTrials, savedTrialsCount, allCollections, currentSortBy, currentFilterBy.CollectionName);
795                $('.loader').hide();
796
797                // Set the collection dropdown to the selected collection name or "All Saved Trials"
798                $(".trial-container__collection-dropdown").val(filterBy.CollectionName || "");
799            },
800            error: function (error) {
801                console.error("Error fetching saved trials:", error);
802                $('.loader').hide();
803                if (userId) {
804                    alert("Failed to fetch search results. Please try again later.");
805                }
806            }
807        });
808    }
809
810    if (!userId) {
811        $(".trial-container__tab--preferred").addClass("disabled").attr("aria-disabled", "true").on("click", function(e) {
812            e.preventDefault();
813            e.stopPropagation();
814            showLoginRequiredModal();
815        });
816        $(".trial-container__tab--saved").addClass("disabled").attr("aria-disabled", "true").on("click", function(e) {
817            e.preventDefault();
818            e.stopPropagation();
819            showLoginRequiredModal();
820        });
821        $(".trial-container__interaction").hide();
822    }
823
824    function fetchOnload(){
825        if (userId) {
826            fetchCollections().then(() => {
827                fetchTrials('all').then(() => {
828                fetchTrials('preferred');
829                $("#saved-trials-content").empty();
830                fetchSavedTrials('saved');
831            });
832        });
833        } else {
834            fetchTrials('all');
835        }
836    }
837    if(!synonymFilePath){
838        fetchOnload();
839    }
840
841     $(document).on("click", ".trial-container .trial-container__tab", function () {
842        var tabsContainer = $(this).closest(".trial-container__tabs-container");
843        tabsContainer.find(".trial-container__tab").removeClass("active").attr("aria-selected", "false");
844        $(this).addClass("active").attr("aria-selected", "true");
845        const selectedTab = $(this).data("tab");
846        tabsContainer.find(".trial-container__tab-content").hide();
847        tabsContainer.find("#" + selectedTab).show();
848    });
849
850    $(document).on("keydown", ".trial-container__radio-input span", function (e) {
851        if (e.key === "Enter" || e.key === " ") {
852            e.preventDefault();
853            $(this).click();
854        }
855    });
856
857    $(document).on("click", ".trial-container__accordion-head", function (e) {
858        $(this).parent().find('.trial-container__accordion-body').toggle();
859    });
860
861    $(document).on("keydown", ".trial-container__accordion-head", function (e) {
862        if (e.key === "Enter" || e.key === " ") {
863            e.preventDefault();
864            $(this).click();
865        }
866    });
867
868    $(document).on("keydown", ".trial-container__tab", function (e) {
869        if (e.key === "Enter" || e.key === " ") {
870            e.preventDefault();
871            $(this).click();
872        }
873    });
874
875    const labels = {
876        intervention: $('#interventionLabel').data('intervention-label') || "Intervention",
877        condition: $('#conditionLabel').data('condition-label') || "Condition",
878        eligibility: $('#eligibilityLabel').data('eligibility-label') || "Eligibility",
879        view: $('.viewtrialLabel').attr('data-viewtriallabel-label') || "View Trial Details"
880    };
881
882    let currentSortBy = "relevance";
883    let currentFilterBy = {};
884
885    function isMobile() {
886        return window.matchMedia("(max-width: 767px)").matches;
887    }
888
889    function getGigyaSessionUserId() {
890        if ($.cookie("apex__gigyaSession")) {
891            var gigyaSessionData = JSON.parse($.cookie("apex__gigyaSession"));
892            if (gigyaSessionData.UID) {
893                return gigyaSessionData.UID;
894            }
895        }
896        return "";
897    }
898
899    var userId = getGigyaSessionUserId();
900
901    function renderSavedTrials(trialType, trials, savedTrialsCount, allCollections, sortBy, selectedCollectionName) {
902        const container = $("#saved-trials-content");
903        container.empty();
904
905        const buttonText = selectedCollectionName || "All Saved Trials";
906
907        const sortAndViewHtml = `
908            <div class="trial-container__sort">
909                ${isMobile() ? `
910                    <div class="trial-container__collection-dropdown-box">
911                        <button class="trial-container__collection-button">
912                            ${buttonText}
913                            <svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
914                                <path d="M1 4.96555L4.66884 8.64492C4.86422 8.84086 5.18158 8.84086 5.37696 8.64492L13 1" stroke="#000" stroke-width="1.5" stroke-linecap="round"/>
915                            </svg>
916                        </button>
917                    </div>
918                    <div class="trial-container__sort-and-view">
919                        <span id="viewing-trials-label">Viewing ${savedTrialsCount} trials</span>
920                        <div class="trial-container__sort-dropdown-box">
921                            <select class="trial-container__sort-dropdown">
922                                <option value="" disabled="">SortBy</option>
923                                <option selected="" value="relevance"> Relevance </option>
924                                <option value="date">Date</option>
925                            </select>
926                            <div class="sortsvg show-mobile">
927                                <svg width="12" height="16" viewBox="0 0 12 16" fill="none" xmlns="http://www.w3.org/2000/svg">
928                                    <path d="M3.64024 8.64524C3.48794 8.64524 3.3589 8.59332 3.25314 8.48951C3.14737 8.3857 3.09449 8.25706 3.09449 8.10359V2.43209L1.0592 4.46738C0.946492 4.58276 0.818333 4.64044 0.674721 4.64044C0.531124 4.64044 0.403951 4.58066 0.2932 4.46111C0.177812 4.34919 0.120117 4.2221 0.120117 4.07984C0.120117 3.93756 0.177812 3.80873 0.2932 3.69336L3.16339 0.823172C3.23304 0.759075 3.30663 0.710998 3.38416 0.678942C3.46169 0.646887 3.54476 0.630859 3.63337 0.630859C3.72196 0.630859 3.80628 0.647005 3.8863 0.679297C3.96632 0.711603 4.03784 0.759561 4.10087 0.823172L6.97105 3.69336C7.0811 3.8034 7.13879 3.92626 7.14414 4.06194C7.14947 4.19762 7.09445 4.32705 6.97908 4.45023C6.8637 4.56315 6.7347 4.61828 6.59208 4.61561C6.44945 4.61294 6.32044 4.55392 6.20505 4.43853L4.17778 2.43209V8.11161C4.17778 8.2628 4.12627 8.38954 4.02324 8.49182C3.92021 8.5941 3.79255 8.64524 3.64024 8.64524ZM8.36645 15.2446C8.27785 15.2446 8.19354 15.2284 8.11351 15.1962C8.0335 15.1639 7.96198 15.1159 7.89895 15.0523L5.02876 12.1821C4.91872 12.0733 4.8645 11.9473 4.8661 11.804C4.86771 11.6608 4.9262 11.5276 5.04158 11.4044C5.15695 11.2915 5.28595 11.2363 5.42858 11.239C5.5712 11.2417 5.70021 11.3007 5.8156 11.4161L7.82203 13.4434V7.76386C7.82203 7.61267 7.87355 7.48592 7.97658 7.38363C8.0796 7.28135 8.20727 7.23021 8.35958 7.23021C8.51188 7.23021 8.64092 7.28212 8.74668 7.38594C8.85244 7.48976 8.90533 7.6184 8.90533 7.77186V13.4434L10.9406 11.4081C11.0533 11.2927 11.1815 11.235 11.3251 11.235C11.4687 11.235 11.5959 11.2948 11.7066 11.4144C11.822 11.5263 11.8797 11.6534 11.8797 11.7956C11.8797 11.9379 11.822 12.0667 11.7066 12.1821L8.83643 15.0523C8.76678 15.1164 8.69319 15.1645 8.61566 15.1965C8.53813 15.2286 8.45506 15.2446 8.36645 15.2446Z" fill="#595454"/></path>
929                                </svg>
930                            </div>
931                        </div>
932                    </div>
933                ` : `
934                    <span id="viewing-trials-label">Viewing ${savedTrialsCount} trials</span>
935					<div class="sort-container">
936                    <div class="trial-container__sort-dropdown-box">
937                        <select class="trial-container__sort-dropdown">
938                            <option value="" disabled="">SortBy</option>
939                            <option selected="" value="relevance"> Relevance </option>
940                            <option value="date">Date</option>
941                        </select>
942                        <div class="sortsvg show-desktop">
943                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
944                                <path fill-rule="evenodd" clip-rule="evenodd" d="M3.14429 6.00212C3.33944 5.80674 3.65602 5.80656 3.8514 6.00171L9.00006 11.1445L14.1487 6.00171C14.344 5.80656 14.6606 5.80674 14.8558 6.00212C15.0509 6.19749 15.0507 6.51407 14.8554 6.70922L9.70676 11.852C9.31633 12.242 8.68379 12.242 8.29336 11.852L3.1447 6.70923C2.94932 6.51408 2.94914 6.19749 3.14429 6.00212Z" fill="#595454"></path>
945                            </svg>
946                        </div>
947                    </div>
948                    <div class="trial-container__collection-dropdown-box">
949                        <select class="trial-container__collection-dropdown">
950                            <option value="">All Saved Trials</option>
951                            ${allCollections.map(collection => `
952                                <option value="${collection.CollectionName}" ${collection.CollectionName === selectedCollectionName ? 'selected' : ''}>
953                                    ${collection.CollectionName}
954                                </option>
955                            `).join('')}
956                        </select>
957						<div class="sortsvg show-desktop">
958                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
959                                <path fill-rule="evenodd" clip-rule="evenodd" d="M3.14429 6.00212C3.33944 5.80674 3.65602 5.80656 3.8514 6.00171L9.00006 11.1445L14.1487 6.00171C14.344 5.80656 14.6606 5.80674 14.8558 6.00212C15.0509 6.19749 15.0507 6.51407 14.8554 6.70922L9.70676 11.852C9.31633 12.242 8.68379 12.242 8.29336 11.852L3.1447 6.70923C2.94932 6.51408 2.94914 6.19749 3.14429 6.00212Z" fill="#595454"></path>
960                            </svg>
961                        </div>
962                    </div>
963					</div>
964                `}
965            </div>
966        `;
967
968        container.append(sortAndViewHtml);
969
970        $("#" + trialType + "-trials .trial-container__sort-dropdown").val(sortBy);
971
972	    if (trials.length === 0) {
973	        container.append('<p class="no-trials-message">No trials found in this collection.</p>');
974	    } else {
975	        trials.forEach(trial => {
976				allCollections.forEach(function(collection){
977					if(collection.ntcIds && collection.ntcIds.indexOf(trial.nct_id)!==-1){
978						trial.collectionName = collection.CollectionName
979					}
980				})
981	            const trialHtml = buildTrialHtml(trial);
982	            container.append(trialHtml);
983	        });
984	    }
985
986	    container.removeClass("hidden");
987
988
989		$(".trial-container__sort-dropdown").on("change", function () {
990		    let trialType = $(this).closest('.trial-container__tab-content').attr('data-trial');
991		    if (trialType === 'saved') {
992                        currentSortBy = $(this).val();
993		        $('.loader').show();
994		        $("#saved-trials-content").empty();
995           	         fetchSavedTrials(trialType, currentSortBy, currentFilterBy);
996		    }
997		})
998
999        if (isMobile()) {
1000            $(".trial-container__collection-button").on("click", function () {
1001                openCollectionsModal(allCollections, selectedCollectionName);
1002            });
1003        } else {
1004            $(".trial-container__collection-dropdown").on("change", function () {
1005			    const selectedCollectionName = $(this).val();
1006			    currentFilterBy = selectedCollectionName ? { CollectionName: selectedCollectionName } : {};
1007
1008			    console.log("Fetching trials for collection:", selectedCollectionName);
1009
1010			    $('.loader').show();
1011			    $("#saved-trials-content").empty();
1012
1013			    fetchSavedTrials("saved", currentSortBy, currentFilterBy);
1014			});
1015
1016        }
1017    }
1018
1019    function openCollectionsModal(collections, selectedCollectionName) {
1020        const isAllSelected = !selectedCollectionName; // True if no specific collection is selected
1021        const modalHtml = `
1022            <div class="collections-modal">
1023                <div class="collections-modal__content">
1024                    <div class="collections-modal__header">
1025                        <div class="drag-handle">
1026                            <svg width="32" height="4" viewBox="0 0 32 4" fill="none" xmlns="http://www.w3.org/2000/svg">
1027                            <rect opacity="0.4" width="32" height="4" rx="2" fill="#595454"></rect>
1028                            </svg>
1029                        </div>
1030                        <div class="collection-title">All Saved Trials</div>
1031                    </div>
1032                    <div class="collections-modal__body">
1033                        <ul class="collections-list">
1034                            <li class="collection-item ${isAllSelected ? 'selected' : ''}" data-collection-name="">
1035                                All Saved Trials
1036                                ${isAllSelected ? `
1037                                    <svg width="14" height="10" viewB
1037ox="0 0 14 10" fill="none" xmlns="http://www.w3.org/2000/svg">
1038                                        <path d="M1 4.96555L4.66884 8.64492C4.86422 8.84086 5.18158 8.84086 5.37696 8.64492L13 1" stroke="#FFFFFE" stroke-width="1.5" stroke-linecap="round"/>
1039                                    </svg>
1040                                ` : ''}
1041                            </li>
1042                            ${collections.map(collection => `
1043                                <li class="collection-item ${collection.CollectionName === selectedCollectionName ? 'selected' : ''}"
1044                                    data-collection-name="${collection.CollectionName}">
1045                                    ${collection.CollectionName}
1046                                    ${collection.CollectionName === selectedCollectionName ? `
1047                                        <svg width="14" height="10" viewBox="0 0 14 10" fill="none" xmlns="http://www.w3.org/2000/svg">
1048                                            <path d="M1 4.96555L4.66884 8.64492C4.86422 8.84086 5.18158 8.84086 5.37696 8.64492L13 1" stroke="#FFFFFE" stroke-width="1.5" stroke-linecap="round"/>
1049                                        </svg>
1050                                    ` : ''}
1051                                </li>
1052                            `).join('')}
1053                        </ul>
1054                    </div>
1055                </div>
1056            </div>
1057        `;
1058
1059        $("body").append(modalHtml);
1060
1061        $(".collection-item").on("click", function () {
1062            const selectedCollectionName = $(this).data("collection-name");
1063            currentFilterBy = selectedCollectionName ? { CollectionName: selectedCollectionName } : {};
1064
1065            $(".collection-item").removeClass("selected").find("svg").remove();
1066            $(this).addClass("selected").append(`
1067                <svg width="14" height="10" viewBox="0 0 14 10" fill="none" xmlns="http://www.w3.org/2000/svg">
1068                    <path d="M1 4.96555L4.66884 8.64492C4.86422 8.84086 5.18158 8.84086 5.37696 8.64492L13 1" stroke="#FFFFFE" stroke-width="1.5" stroke-linecap="round"/>
1069                </svg>
1070            `);
1071
1072            setTimeout(() => {
1073                fetchSavedTrials('saved', currentSortBy, currentFilterBy);
1074                closeCollectionsModal();
1075            }, 1000);
1076        });
1077
1078        $(".drag-handle").on("click", closeCollectionsModal);
1079    }
1080
1081    function closeCollectionsModal() {
1082        $(".collections-modal").remove();
1083    }
1084
1085    function buildTrialHtml(trial) {
1086	    const status = trial.status.replace(/_/g, " ");
1087		const intervention = Array.isArray(trial.intervention) ? trial.intervention.join(", ") : trial.intervention || "Not Available";
1088        const phase = Array.isArray(trial.phase) && trial.phase.length ? trial.phase.join(", ") : "Not Available";
1089        const condition = trial.condition.join(", ");
1090        const eligibility = trial.ages;
1091        const healthyVolunteers = trial.accepts_healthy_volunteers === "Yes" ? "Yes" : "No";
1092
1093        return `
1094            <div class="trial-container__box">
1095                <div class="trial-container__head">
1096                     <a aria-label="button" href="${fulltrialPagePath}?nctid=${trial.nct_id}" class="trial-container__title">${trial.title}</a>
1097                    <button aria-label="button" type="button" class="trial-container__interaction" data-collection="${trial.collectionName}">
1098                    <svg width="10" height="13" viewBox="0 0 10 13" fill="none" xmlns="http://www.w3.org/2000/svg">
1099                        <path d="M4.99998 11.0961L2.02306 12.374C1.57115 12.5673 1.14183 12.5302 0.735106 12.2629C0.328368 11.9956 0.125 11.6197 0.125 11.1351V1.98078C0.125 1.60193 0.25625 1.28125 0.51875 1.01875C0.78125 0.75625 1.10192 0.625 1.48077 0.625H8.51919C8.89804 0.625 9.21871 0.75625 9.48121 1.01875C9.74371 1.28125 9.87496 1.60193 9.87496 1.98078V11.1351C9.87496 11.6197 9.67159 11.9956 9.26486 12.2629C8.85813 12.5302 8.42881 12.5673 7.9769 12.374L4.99998 11.0961Z" fill="#173C58"/>
1100                    </svg>
1101                    </button>
1102                </div>
1103
1104                <div class="trial-container__horizontal-labels">
1105                    <div class="trial-container__horizontal-label trial-container__label-1">${status}</div>
1106                    <div class="trial-container__horizontal-label trial-container__label-2">${phase}</div>
1107                    <div class="trial-container__horizontal-label trial-container__label-3">${trial.nct_id}</div>
1108                </div>
1109
1110                <div class="trial-container__vertical-section">
1111                    <div class="trial-container__vertical-item">
1112                        <div class="trial-container__vertical-label">${labels.intervention}</div>
1113                        <div class="trial-container__vertical-value">${intervention}</div>
1114                    </div>
1115                    <div class="trial-container__vertical-item">
1116                        <div class="trial-container__vertical-label">${labels.condition}</div>
1117                        <div class="trial-container__vertical-value">${condition}</div>
1118                    </div>
1119                    <div class="trial-container__vertical-item">
1120                        <div class="trial-container__vertical-label">${labels.eligibility}</div>
1121                        <div class="trial-container__vertical-value">
1122                            ${toRenderAgeEligibility(eligibility)}, Sexes: ${trial.sexes}, Accepting Healthy Volunteers: ${healthyVolunteers}
1123                        </div>
1124                    </div>
1125                </div>
1126
1127                <a aria-label="button" href="${fulltrialPagePath}?nctid=${trial.nct_id}" class="trial-container__view-trial-btn">
1128                    <span>${labels.view}</span>
1129                    <svg xmlns="http://www.w3.org/2000/svg" width="19" height="18" viewBox="0 0 19 18" fill="none">
1130                            <path fill-rule="evenodd" clip-rule="evenodd" d="M6.14732 3.14547C5.95205 3.34073 5.95205 3.65731 6.14732 3.85258L11.2949 9.00018L6.14732 14.1478C5.95205 14.3431 5.95205 14.6596 6.14732 14.8549C6.34258 15.0502 6.65916 15.0502 6.85442 14.8549L12.002 9.70729C12.3926 9.31677 12.3926 8.6836 12.002 8.29308L6.85442 3.14547C6.65916 2.95021 6.34258 2.95021 6.14732 3.14547Z" fill="#595454"/>
1131                        </svg>
1132                </a>
1133            </div>
1134        `;
1135    }
1136
1137    $(document).on("click", ".trial-container__interaction", function (e) {
1138        e.stopPropagation();
1139
1140        const trialBox = $(this).closest(".trial-container__box");
1141        const svgHtml = $(this).html().trim();
1142
1143        selectedNctId = trialBox.find(".trial-container__label-3").text().trim();
1144		selCollection = $(this).data('collection') || '';
1145        console.log("Selected NCT ID:", selectedNctId);
1146
1147        if (svgHtml.includes('fill="#173C58"')) {
1148            $("#unsaveModal").show();
1149        } else {
1150            // ...existing code for opening popover...
1151        }
1152    });
1153
1154    $("#cancelButton").on("click", function () {
1155        $("#unsaveModal").hide();
1156    });
1157
1158    function setSelectedSearchValues() {
1159        var urlParams = new URLSearchParams(window.location.search);
1160        var searchText = urlParams.get('searchText') || '';
1161        var searchType = urlParams.get('searchType') || '';
1162        var searchLocation1 = urlParams.get('searchlocation') || '';
1163        var latitude = urlParams.get('latitude') || '';
1164        var longitude = urlParams.get('longitude') || '';
1165        var radius = urlParams.get('radius') || '';
1166        var zipcode = urlParams.get('zipcode') || '';
1167        var searchCountry1 = "";
1168        var searchCity1 = "";
1169        if (searchText) {
1170          $('.bssearch-wrapper #search-text').val(searchText);
1171        }
1172        if (!searchType) {
1173          if (searchLocation1) {
1174            searchLocation1 = decodeURIComponent(searchLocation1);
1175            if (searchLocation1.includes(',')) {
1176              searchLocation1 = searchLocation1.split(',');
1177              searchCity1 = searchLocation1[0].trim();
1178              searchCountry1 = searchLocation1[1].trim();
1179              if ($('.bssearch-wrapper #country-dropdown').find('option[value="' + searchCountry1 + '"]').length > 0)
1180                $('.bssearch-wrapper #country-dropdown').val(searchCountry1).trigger('change');
1181              if ($('.bssearch-wrapper #city-dropdown').find('option[value="' + searchCity1 + '"]').length > 0) {
1182                $('.bssearch-wrapper #city-dropdown').val(searchCity1).trigger('change');
1183              }
1184              if (zipcode) {
1185                $('.bssearch-wrapper #zip-input').val(zipcode).trigger('change');
1186              }
1187              if (radius) {
1188                $('.bssearch-wrapper #radius-dropdown').val(radius).trigger('change');
1189              }
1190            } else {
1191              searchCountry1 = searchLocation1;
1192              $('.bssearch-wrapper #country-dropdown').val(searchCountry1).trigger('change');
1193              if (zipcode) {
1194                $('.bssearch-wrapper #zip-input').val(zipcode).trigger('change');
1195              }
1196              if (radius) {
1197                $('.bssearch-wrapper #radius-dropdown').val(radius).trigger('change');
1198              }
1199            }
1200          }
1201        }
1202      }
1203	function showUnsaveSuccessModal() {
1204        $("#unsaveSuccessModal").removeClass("hidden");
1205        setTimeout(function () {
1206            $("#unsaveSuccessModal").addClass("hidden");
1207        }, 2000);
1208    }
1209
1210    $(document).on("click", ".close-modal", function () {
1211        $("#unsaveSuccessModal").addClass("hidden");
1212    });
1213});
1214
1215

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.