';
$(this).append(breadcrumbHtml);
}
jQuery.fn.removeLastBreadcrumb = function() {
$(this).find('li:last').remove();
}
// JSON response from ajax call comes here
function parseJSONresponse(json, replacedom, supressMessage)
{
supressMessage = (undefined == supressMessage) ? false : supressMessage;
if( json != null )
{
if( ( json['status'] == -1 || json['status'] == 1 ) && json.hasOwnProperty('location') )
{
// -1 == bail out
document.location.href = json['location'];
return false;
}
if (json['status'] == 1 && json.hasOwnProperty('new_window'))
{
window.open(json['new_window'],'_blank');
return;
}
// process any JSON and 'message' values
if(!supressMessage) {
if (json.hasOwnProperty('status') && json.hasOwnProperty('message')) {
jsonResponseMessage(json);
} else if (json.hasOwnProperty('status') &&
json.status == 0 &&
(json.hasOwnProperty('modal_message') || json.hasOwnProperty('lg_modal_message'))) {
let modalSize = (json.hasOwnProperty('lg_modal_message')) ? 'lg' : null;
renderErrorModal(json, modalSize);
}
}
if( json.hasOwnProperty('endpoint') )
{
var endpoint = json['endpoint'];
if (endpoint === '/logout_attempt/')
{
if (json['status'] == 1)
{
document.location.href = document.location.origin;
}
}
let callbackProcessed = callbackProcessor({
endpoint: endpoint,
json: json,
replacedom: replacedom
});
if (!callbackProcessed.executed) {
if (endpoint === '/home/') {
if (json.hasOwnProperty('menu')) {
var jMenu = json['menu'];
var menuhtml = buildNavMenuTabs(jMenu);
$("#main").html(menuhtml);
if (json.hasOwnProperty('announcements')) {
renderAnnouncement(json['announcements']);
}
}
if (json.timezone == null) {
// set the timezone in the database
let endpoint = '/update_user_timezone/';
let params = {};
params.endpoint = endpoint;
params.params = {};
params.params.timezone_id = Intl.DateTimeFormat().resolvedOptions().timeZone;
ajaxCall(endpoint, params, null);
}
if (json.account_type === 'P' || json.account_type === 'S') {
window.Appcues.identify(
json.user_id,
{
role: json.account_type
}
);
}
if (json.account_type === 'P' || json.account_type === 'S' || json.account_type === 'A') {
aiEnabled = json.domain_info.ai_enabled;
}
if (window.hasOwnProperty('newrelic') && window.newrelic !== undefined) {
window.newrelic.setUserId(json.user_id.toString());
}
// if we have a predetermined destination, don't autoload anything
if (sessionStorage.getItem('destination')) {
$(".section-autoload").removeClass("section-autoload");
}
// init nav tabs
if (initOutput()) {
// when we're actually done init-ing the nav tabs, THEN process our direct link stuff
if (sessionStorage.getItem('destination')) {
let params = sessionStorage.getItem('destination');
sessionStorage.clear();
$.getScript(scriptbase + 'direct_link.js', function () {
processDirectLink(params);
});
}
if (json.hasOwnProperty('needs_baa') && json.needs_baa === true) {
if (json.account_type === 'P' && json.hasOwnProperty('is_domain_admin') && json.is_domain_admin === true) {
// this is the user that needs to sign the BAA
ajaxCall('/provider_get_baa/', [], function(json) {
if (json.status === 1) {
renderBAAForSignature(json);
}
}, true);
} else {
ajaxCall('/nag_domain_admin_about_baa/', [], function(json) {
renderBBABlockerModalForNonDomainAdmin(json);
});
}
}
}
} else if (endpoint === '/account_settings/') {
var replacedomArr = replacedom.split('-');
replacedom = replacedomArr[0];
var innerCallbackFunction = function (replacedomArrPart2) {
var theMyTeamSettingInterval = setInterval(function () {
const teamTab = $('#' + replacedomArrPart2);
if (teamTab.length === 1) {
clearInterval(theMyTeamSettingInterval);
const settingsBsTab = new bootstrap.Tab('#mainnavul a.nav-link[href="#settings"]');
settingsBsTab.show();
const teamBsTab = new bootstrap.Tab(teamTab);
teamBsTab.show();
objectClick(teamTab);
}
}, 5);
}
$.getScript(scriptbase + "account.js", function () {
// accountLoaded = 1;
renderAccountSettings(json, replacedom);
$('a.nav-menu-item[data-endpoint="/account_settings/"]').tab('show');
if (replacedomArr.length === 2) {
innerCallbackFunction(replacedomArr[1]);
}
});
} else if (endpoint === '/domain_admin_toggle_private_messaging/' ||
endpoint === '/domain_admin_toggle_virtual_clinic/') {
if (json['status'] === 1) {
setTimeout(function () {
document.location.href = document.location.origin;
}, 1500);
}
} else if (endpoint === '/upload_photo/') {
if ($('#' + replacedom).hasAttr('data-uuid')) {
$.getScript(scriptbase + 'content_libraries.js', function () {
renderContentLibraryPhotoAlbum(json, replacedom);
});
} else {
$.getScript(scriptbase + "photos.js", function () {
// photosLoaded = 1;
updatePhotoAlbum(json, replacedom);
});
}
} else if (endpoint === '/clear_job/') {
clearJobStatus(json);
} else if (endpoint === '/patient_staff_messages/') {
if (json['status'] == 0) {
$("#mainnavul li").find("[href='#messages']").remove();
$("#messages").remove();
} else {
$.getScript(scriptbase + "messages.js", function () {
// messagesLoaded = 1;
renderStaffMessages(json, replacedom);
});
}
} else if (endpoint === '/messages/') {
if (json['status'] == 0) {
$("#mainnavul li").find("[href='#messages']").remove();
$("#messages").remove();
} else {
$.getScript(scriptbase + "messages.js", function () {
// messagesLoaded = 1;
renderMessages(json, replacedom);
});
}
} else if (endpoint === '/program/') {
loadScript('plans.js', function () {
loadScript('program.js', function () {
Program.renderProgram(json, replacedom);
if (json.redirectToPage !== undefined) {
if ($('a[href^="#' + json.redirectToPage + '"]').length > 0) {
$('a[href^="#' + json.redirectToPage + '"]').trigger('click');
}
}
});
});
} else if (endpoint === '/provider_edit_meal/' ||
endpoint === '/provider_update_meal_food_serving_count/' ||
endpoint === '/provider_remove_meal_food_item/' ||
endpoint === '/provider_add_food_to_meal/') {
$.getScript(scriptbase + "meals.js", function () {
// mealsLoaded = 1;
if (endpoint === '/provider_update_meal_food_serving_count/' ||
endpoint === '/provider_remove_meal_food_item/' ||
endpoint === '/provider_add_food_to_meal/') {
document.cookie = "dirty_recipe_editor=true";
$('#done-editing-recipe-btn').removeClass('btn-secondary').addClass('btn-primary').prop('disabled', false);
}
renderProviderEditRecipe(json, replacedom);
});
} else if (endpoint === '/send_private_message/' || endpoint === '/send_private_message_to_staff/') {
if (accountType == 'P' || accountType == 'S') {
if ($('.compose-message-modal').hasClass('show')) {
$('.compose-message-modal').removeModal();
}
if (replacedom == 'messages') {
$.getScript(scriptbase + 'messages.js', function () {
renderProviderMessages(json, replacedom);
});
} else if (replacedom == 'conversation-detail') {
$.getScript(scriptbase + 'messages.js', function () {
renderMessageConversation(json, replacedom);
});
} else if (replacedom == 'patient-detail-messages') {
$.getScript(scriptbase + 'patient_detail.js', function () {
sendPatientMessageCallback(json, replacedom);
});
}
} else {
$.getScript(scriptbase + "messages.js", function () {
newProviderMessageCallback(json);
});
}
} else if (endpoint == '/provider_check_baa_signature_status/') {
checkContractSignedCallback(json, replacedom);
} else if (endpoint === '/provider_opt_out_of_baa/') {
optOutOfBAACallback(json);
} else if (endpoint === '/save_survey_answer/') {
loadScript('surveys.js', function () {
answerQuestionCallback(json);
});
loadScript("patients.js", function () {
updateSurveyStartDate(json);
});
} else if (endpoint === '/finish_survey/') {
loadScript('surveys.js', function () {
finishSurveyCallback(json);
});
if (accountType === 'P' || accountType === 'S') {
loadScript("patient_detail.js", function () {
renderManagePatientSurveys(json, replacedom);
});
} else if (accountType === 'U') {
loadScript("program.js", function () {
Program.finishSurveyCallback(json, replacedom);
});
}
} else if (endpoint === "/admin_update_transaction_email/") {
if ( parseInt( json['status'] ) === 1 )
$('#'+replacedom).html( json['data']['email'] ).prev('td').find('.updateBuyerPatientEmail').data('email', json['data']['email']);
} else if (endpoint === '/set_user_calorie_goal/') {
if (accountType === 'U') {
loadScript('food.js', function () {
renderSetCalorieGoalCallback(json);
});
} else if (accountType === 'P') {
loadScript('patients.js', function () {
updateCalorieGoalCallback(json);
});
}
} else if (endpoint === '/get_bonus_tab_content/') {
let tabID = json['data']['tab_id'];
if (replacedom === 'edit-plan-bonus-tab-content-' + tabID) {
// rendering tab content when editing a plan requires a different rendering function
loadScript('edit_plan.js', function () {
renderEditPlanBonusTabContent(json, replacedom);
});
} else {
loadScript('program.js', function () {
Program.renderProgramBonusTabContent(json, replacedom);
});
}
} else if (endpoint === '/update_custom_food_serving/') {
loadScript('food.js', function () {
renderUpdateCustomFoodServing(json, replacedom);
});
if (accountType === 'P') {
loadScript('meals.js', function () {
renderUpdateCustomFoodList(json);
});
}
} else if (endpoint === '/add_custom_food_serving/') {
loadScript('food.js', function () {
renderNewServingAdded(json, replacedom);
});
if (accountType === 'P') {
loadScript('meals.js', function () {
renderUpdateCustomFoodList(json);
});
}
} else if (endpoint === '/update_custom_food/') {
if (accountType === 'P') {
loadScript('meals.js', function () {
renderUpdateCustomFoodList(json);
});
}
} else if (endpoint === '/update_custom_food_photo/') {
if (accountType === 'P') {
loadScript('meals.js', function () {
renderUpdateCustomFoodList(json);
});
}
} else if (endpoint === '/preview_plan_day_as_email/') {
if (json.status == 1) {
$('#' + replacedom).removeModal();
}
} else if (endpoint === '/provider_edit_recipe_in_place/') {
loadScript('meals.js', function () {
editingRecipeInPlace = replacedom;
renderProviderEditRecipe(json, replacedom);
});
} else if (endpoint === '/provider_edit_exercise_in_place/') {
loadScript('exercises.js', function () {
editingExerciseInPlace = replacedom;
renderExerciseEditor(json, replacedom);
});
} else if (endpoint === '/provider_update_inbody_api_credentials/') {
if (accountType == 'P') {
loadScript('account.js', function () {
renderInbodyAPIAccessCallback(json, replacedom);
});
}
} else if (endpoint === '/provider_resell_premium_plan/' ||
endpoint === '/provider_sell_exclusive_plan/') {
loadScript('plans.js', function () {
if ($('div.modal.show').length > 0) {
$('div.modal.show').removeModal();
}
renderEditPlan(json, replacedom);
});
} else if (endpoint === '/upload_photo_tinymce/') {
$.getScript(HTTP_PATH + '/image_browser/image_browser.js', function () {
managePhotoAlbumImageBrowser(json, replacedom);
});
}
}
}
}
}
function renderErrorModal(json, modalSize, showHeader) {
modalSize = (undefined === modalSize) ? null : modalSize;
showHeader = (undefined === showHeader) ? true : showHeader;
let html = '';
let modalID = 'error-message-' + generateUUID();
const message = (json.hasOwnProperty('modal_message')) ? json.modal_message : json.lg_modal_message;
html += `
`;
html += '
';
html += '
';
if (showHeader) {
html += '
';
html += '
Oops...
';
html += '
'; // modal-header
}
html += '
';
html += '
' + message + '
';
html += '
'; // modal-body
html += ''; // modal-footer
html += '
'; // modal-content
html += '
'; // modal-content
html += '
'; // modal
$('body').append(html);
if ($('div.modal.show').length) {
// if there is a modal showing currently,
// we should hide it so we can show the timeout warning
// and then show it again if the user chooses to stay logged in
let currentModalID = $('div.modal.show').attr('id');
$('#' + currentModalID).modal('hide');
}
$('#' + modalID).modal({ backdrop: 'static' }).modal('show');
}
function jsonResponseMessage( json )
{
// check for ajax message box, add to DOM if necessary
if($(".ajax-message").length == 0)
{
if( ismobile )
$("body").append('');
else
$("#mainnavbar").parent().prepend('');
}
if ($('.pvbtn-card').length > 0 && $('.pvbtn-card-ajax-message').length == 0)
{
$('.previewmain').prepend('');
}
else if ($('.modal-dialog').length > 0 && $('.modal-dialog-ajax-message').length == 0 && $('.modal-dialog').is(':visible'))
{
$('.modal-body:visible').prepend('');
}
var alertClass = '';
var sMsgHtml = '';
if( json['status'] == 1 && json.hasOwnProperty('message') )
{
// Success
alertClass = 'alert-success';
}
if( json['status'] == 2 && json.hasOwnProperty('message') )
{
alertClass = 'alert-info';
}
if( json['status'] == 0 && json.hasOwnProperty('message') )
{
// Something went wrong or didn't save/update AND we have a message to display to the user
alertClass = 'alert-warning';
// If we have an action called reset
if( json.hasOwnProperty('action') && json['action'] == 'reset' )
{
// Clear the page and show an alert box (such as maybe their session timed out)
$(".ajax-message").empty();
if ($('.pvbtn-card').length > 0)
{
$('.pvbtn-card').empty().remove();
}
$("#mainbody").empty().html('
');
$("#user_email,#user_password").focus(function(){$("#login-message").html(' ');});
}
}
}
});
} else {
if( email.length < 6 ) {
emailInput.addClass('is-invalid');
}
if( pw.length < 1 ) {
passwordInput.addClass('is-invalid');
}
}
}
function resizeStuff()
{
if( $(window).width() < 992 )
{
if( subdomainLogoFile !== '' && subdomainLogoFile != null)
{
$("#toggle_width").parent().hide();
if( $(window).width() < 768 )
$("#site_logo").attr("src",subdomainLogoFile);
else
$("#site_logo").attr("src",subdomainSplashFile);
}
else
{
$("#site_logo").parent().html(subdomainCompanyName);
}
}
else
{
$("#toggle_width").parent().show();
if( subdomainLogoFile !== '' && subdomainLogoFile != null)
{
$("#site_logo").attr("src",subdomainLogoFile);
}
else
{
$("#site_logo").parent().html(subdomainCompanyName);
}
}
if ($('nav#main-navbar-nav').length > 0) {
const navBarHeight = $('nav#main-navbar-nav').outerHeight();
let mainBodyTopMargin = navBarHeight + 10;
if ($('#announcement-container').length > 0) {
const announcementHeight = $('#announcement-container').outerHeight();
mainBodyTopMargin = announcementHeight + navBarHeight + 10;
}
$('#main').css('margin-top', mainBodyTopMargin);
}
}
function prepareJSONparams( object )
{
return JSON.stringify(object).replace(/'/g,"'").replace(/"/g,""");
}
function generateUUID()
{
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)
{
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
}
function nl2br( str )
{
return (str != null) ? str.toString().replace(/\r\n/ig," ").replace(/\n/ig," ") : '';
}
/* getTodayDateForDatePicker()
usage: var sToday = getTodayDateForDatePicker();
returns "03/18/2016"
*/
function getTodayDateForDatePicker(options) {
if (undefined !== options && options !== null) {
return new Date().toLocaleDateString('en-US', options).replace(/\u200e/g, '');
} else {
return new Date().toLocaleDateString().replace(/\u200e/g, '');
}
}
function getTodayDateForServer() {
// the server expects the date in the US format, regardless of the user's actual locale
let dateobj = new Date();
let month = (dateobj.getMonth() + 1);
let date = dateobj.getDate();
let year = dateobj.getFullYear();
return month.toString() + '/' + date.toString() + '/' + year.toString();
}
function formatLocalDate(datestr)
{
var d = datestr.replace(/\-/g,"/");
var date = new Date( d + " UTC" );
return date.toLocaleString();
}
function formatLocalDateFromTimestamp(timestamp) {
timestamp = parseInt(timestamp);
const date = new Date(timestamp * 1000);
return date.toLocaleString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'});
}
function formatLocalDateTime(timestamp) {
let date = new Date();
if (undefined != timestamp && timestamp != null && timestamp > 0) {
date = new Date(timestamp * 1000);
}
return date.toLocaleString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric', hour: 'numeric', minute: 'numeric'});
}
function addModal( sModalID, sModalTitle, hModalBody, hModalFooter ) {
var sNewModalBodyID = 'modal-body_'+sModalID;
var modalhtml = '';
modalhtml += '
';
modalhtml += '
';
modalhtml += '
';
modalhtml += '
';
modalhtml += '
' + sModalTitle + '
';
modalhtml += '
';
modalhtml += '
';
modalhtml += hModalBody;
modalhtml += '
';
modalhtml += '';
modalhtml += '
';
modalhtml += '
';
modalhtml += '
';
//
$("body").append( modalhtml );
const modal = new bootstrap.Modal('#' + sModalID);
modal.show();
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i .close').on('click', function() {
let bannerID = $(this).attr('data-banner-id');
$('#' + bannerID).remove();
});
}
}
});
function renderBanner(packageID, companyName) {
let html = '';
let bannerID = generateUUID() + '-app-banner';
html += '
';
}
}
return html;
}
function renderExerciseDescription( oExerciseData, replacedom )
{
var html = '';
if( undefined !== replacedom && oExerciseData.hasOwnProperty('exercise_description') && oExerciseData['exercise_description'] != null && replacedom !== 'program' && replacedom.indexOf("preview") == -1 )
{
html += oExerciseData['exercise_description'];
html += ' ';
}
//
// check if this exercise is NOT being rendered on a Plan Preview
if (undefined !== replacedom && replacedom !== 'program' && replacedom.indexOf("preview") == -1 )
{
html += renderExerciseImagesVideo( oExerciseData );
}
//
return html;
}
function renderExerciseImagesVideo(oExerciseData) {
var html = '';
// exercise images and video
html += '
';
if (oExerciseData.hasOwnProperty('exercise_image_1') && oExerciseData.exercise_image_1 != MISSING_PHOTO) {
html += '
';
html += '';
html += '
';
}
if (oExerciseData.hasOwnProperty('exercise_video')) {
html += '
';
// if flv/mp4 video
if (oExerciseData['exercise_video']['type'] === 'mp4') {
html += '
';
html += '';
html += '
'; // embed-responsive
} else if (oExerciseData['exercise_video']['type'] === 'youtube' && oExerciseData.exercise_video.video_id != '') {
var player_id = 'exercise_video' + generateUUID();
var youtubeid = oExerciseData['exercise_video']['video_id'];
html += embedYouTube(player_id, youtubeid);
}
html += '
';
}
if (oExerciseData.hasOwnProperty('exercise_image_2') && oExerciseData.exercise_image_2 != MISSING_PHOTO) {
html += '
';
html += '';
html += '
';
}
html += '
';
//
return html;
}
function renderExercisePlanObject(oExerciseData, bEditMetrics) {
let metrics = '';
let exerciseDescUUID = generateUUID();
let html = '';
bEditMetrics = (undefined !== bEditMetrics) ? bEditMetrics : false;
if (!bEditMetrics && oExerciseData.hasOwnProperty('exercise_metrics') &&
oExerciseData['exercise_metrics'] != null &&
oExerciseData['exercise_metrics'].length > 0 &&
oExerciseData['exercise_metrics'][0] != '') {
// if we have metrics AND they're not all blank
for (k in oExerciseData['exercise_metrics']) {
let thisMetric = oExerciseData['exercise_metrics'][k];
metrics += thisMetric+' ';
}
}
//html += '
';
html += '
';
html += '
';
if (metrics != '') {
html += '
';
html += '
';
html += ''+metrics+'';
html += '
'; // col-md-12
html += '
'; // row
}
html += '
';
html += '
';
html += '
' + oExerciseData['exercise_title'] + '
';
html += '
'; // col-md-12
html += '
'; // row
html += '
'; // card-header
html += '
';
html += renderExerciseDescription(oExerciseData, 'exercise_details');
if (bEditMetrics) {
html += '
';
html += '
';
html += '
';
var aMetrics = oExerciseData['exercise_metrics'];
var sMetric0 = '';
var sMetric1 = '';
var sMetric2 = '';
var sMetric3 = '';
if (undefined != aMetrics && aMetrics.length > 0) {
if (hasNum(aMetrics[0])) {
sMetric0 = aMetrics[0];
}
if (undefined != aMetrics[1] && !hasNum(aMetrics[1]) && exerciseMetric0Descriptors.indexOf(aMetrics[1]) >= 0) {
sMetric1 = aMetrics[1];
}
if (sMetric0 != '' && sMetric1 != '') {
if (hasNum(aMetrics[2])) {
sMetric2 = aMetrics[2];
}
if (undefined != aMetrics[3] && !hasNum(aMetrics[3]) && exerciseMetric2Descriptors.indexOf(aMetrics[3]) >= 0) {
sMetric3 = aMetrics[3];
}
}
}
// amount of exercise
html += '';
// amount type selector (reps, distance, time, etc)
html += '';
// exercise load
html += '';
// load type selector
html += '';
html += '
';
html += '
';
html += '
'; // .row
}
html += '
'; // collapse
html += '
'; // card
//html += '
'; // col-md-12
return html;
}
function renderProtocolObject(obj, clinicDiscount) {
let html = '';
let uuid = generateUUID();
clinicDiscount = (undefined !== clinicDiscount) ? clinicDiscount : 0;
html += '
';
html += '
';
html += '
' + obj.name + '
';
html += '
'; // card-header
html += '
';
if (obj.personal_message !== null && obj.personal_message !== '') {
html += '
' + obj.personal_message + '
';
}
if (obj.hasOwnProperty('recommendations') && obj.recommendations != null && obj.recommendations.length > 0) {
obj.recommendations.forEach((recommended_product) => {
html += renderRecommendationProduct(recommended_product, clinicDiscount);
});
}
html += '
'; // card-body
html += '
'; // card
return html;
}
function renderRecommendationProduct(recommended_product, discount) {
let html = '';
html += '
';
html += '
';
html += '
';
html += ``;
html += '
'; // col-3
html += '
';
html += '
' + recommended_product.product.name + '
';
html += '
' + recommended_product.product.brand.name + '
';
if (discount !== null && discount > 0) {
let patientPrice = (recommended_product.msrp * ((100 - discount) / 100));
html += '
';
}
if (recommended_product.hasOwnProperty('units_to_purchase')) {
html += '
Quantity: ' + recommended_product.units_to_purchase + ' units
';
}
html += '
'; // col-3
html += '
'; // row
html += ''; // list-group-item
return html;
}
function print_r(o)
{
return JSON.stringify(o,null,'\t').replace(/\n/g,' ').replace(/\t/g,' ');
}
function iVeryTop(elems)
{
var maxIndex = 0;
elems = (typeof(elems) !== 'undefined') ? elems : $("*");
$(elems).each(function()
{
maxIndex = (parseInt(maxIndex) < parseInt($(this).css('z-index'))) ? parseInt($(this).css('z-index')) : maxIndex;
iTopZIndex = maxIndex + 1;
});
return iTopZIndex;
}
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", "5px");
this.css("z-index", 5000);
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
function getUnits(system, metric)
{
var units = '';
switch (metric.toUpperCase())
{
case 'WEIGHT':
case 'FAT MASS':
case 'MUSCLE MASS':
units = (system == 'imperial') ? 'lbs' : 'kgs';
break;
case 'HIPS':
case 'WAIST':
case 'CHEST':
case 'ARMS':
case 'THIGHS':
case 'CALVES':
units = (system == 'imperial') ? 'ins' : 'cm';
break;
case 'BODY FAT %':
units = '%';
break;
case 'RESTING HEART RATE':
units = 'BPM';
break;
case 'BLOOD PRESSURE':
units = 'S/D';
break;
case 'BLOOD SUGAR (MG/DL)':
units = 'mg/dL';
break;
default:
units = '';
}
return units;
}
function debounce(func, wait, immediate)
{
var timeout;
return function()
{
var context = this; args = arguments;
var later = function()
{
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function renderNotificationTable(aNotificationSettings, iUserID) {
var html = '';
var email = {name: 'method', value: 'email'};
var sms = {name: 'method', value: 'sms'};
var userID = {name: 'user_id', value: iUserID};
html += '
';
// table headers
html += '';
html += '
';
html += '
Notification Type
';
html += '
Email
';
html += '
SMS
';
html += '
Push Notifications
';
html += '
';
html += '';
// table body
html += '';
for (let i in aNotificationSettings) {
let type = i;
let settings = aNotificationSettings[type];
let emailCheckboxID = type+'-email-cb';
let emailChecked = (settings['email_status'] !== 'W') ? 'checked' : '';
let smsCheckboxID = type+'-sms-cb';
let smsChecked = (settings['sms_status']) ? 'checked' : '';
let pushCheckboxID = type+'-push-cb';
let pushChecked = (settings['push_status']) ? 'checked' : '';
html += '
';
// LABEL
html += '
'+settings['label']+'
';
// EMAIL SETTINGS
html += '
';
if (settings.allow_email) {
const jEmailSettingParams = [
{ name: 'notification_type', value: type },
{ name: 'user_id', value: userID },
{ name: 'checked', is_checked: emailCheckboxID },
{ name: 'method', value: 'email' }
];
html += '';
}
html += '
';
// SMS SETTINGS
html += '
';
if (settings.allow_sms) {
const jSMSSettingParams = [
{ name: 'notification_type', value: type },
{ name: 'user_id', value: userID },
{ name: 'checked', is_checked: smsCheckboxID },
{ name: 'method', value: 'sms' }
];
html += '';
}
html += '
';
// PUSH NOTIFICATION SETTINGS
html += '
';
if (settings.allow_push) {
const jPushSettingParams = [
{ name: 'notification_type', value: type },
{ name: 'user_id', value: userID },
{ name: 'checked', is_checked: pushCheckboxID },
{ name: 'method', value: 'push' }
];
html += '';
}
html += '
'; // text-center
html += '
';
}
html += '';
html += '
';
return html;
}
function drawBodyCompChart(aUserLogs, sUserDisplayUnits, sFromDate, sToDate, sChartContainerID)
{
// get logs
var aWeightLogs = (aUserLogs.hasOwnProperty('weight') && aUserLogs['weight'].hasOwnProperty('logs')) ? aUserLogs['weight']['logs'] : null;
var aMuscleMassLogs = (aUserLogs.hasOwnProperty('muscle mass') && aUserLogs['muscle mass'].hasOwnProperty('logs')) ? aUserLogs['muscle mass']['logs'] : null;
var aFatMassLogs = (aUserLogs.hasOwnProperty('fat mass') && aUserLogs['fat mass'].hasOwnProperty('logs')) ? aUserLogs['fat mass']['logs'] : null;
var aBodyFatPercLogs = (aUserLogs.hasOwnProperty('body fat %') && aUserLogs['body fat %'].hasOwnProperty('logs')) ? aUserLogs['body fat %']['logs'] : null;
// are we calculating lean mass?
var bCalculateLeanMass = (aWeightLogs && (aFatMassLogs || aBodyFatPercLogs)) ? true : false;
var aChartDataArray = []; // data array for google chart
var aHeader = []; // first item in data array, specifies what columns will be in the array
// indexes of items in each row of the charts data array
const iDateIndex = 0;
var iWeightIndex = 0;
var iMuscleMassIndex = 0;
var iFatMassIndex = 0;
var iLeanMassIndex = 0;
var index = 0; // incremented, used to set other indexes
// make the first (header) row of the data array
aHeader[iDateIndex] = 'Date';
if (aWeightLogs)
{
index++;
aHeader[index] = 'Weight';
iWeightIndex = index;
}
if (aMuscleMassLogs)
{
index++;
aHeader[index] = 'Muscle Mass';
iMuscleMassIndex = index;
}
if (aFatMassLogs)
{
index++;
aHeader[index] = 'Fat Mass';
iFatMassIndex = index;
}
if (bCalculateLeanMass)
{
if (aFatMassLogs == null)
{
index++;
aHeader[index] = 'Fat Mass';
iFatMassIndex = index;
}
index++;
aHeader[index] = 'Lean Mass';
iLeanMassIndex = index;
}
aChartDataArray.push(aHeader);
var sThisDate = sFromDate; // sets the first date to start with
// store the previous log values, to be used if there is no log for that metric for that date
var fLastWeightVal = 0.00;
var fLastMuscleMassVal = 0.00;
var fLastFatMassVal = 0.00;
var fLastBodyFatPercVal = 0.00;
// incrementers for looping through the different sets of logs, we only advance through the logs if we have added a new value
var w = 0;
var x = 0;
var y = 0;
var z = 0;
var nextWeightLogDate = (aWeightLogs != null) ? aWeightLogs[0]['date'] : null;
var nextMuscleMassLogDate = (aMuscleMassLogs != null) ? aMuscleMassLogs[0]['date'] : null;
var nextFatMassLogDate = (aFatMassLogs != null) ? aFatMassLogs[0]['date'] : null;
var nextBodyFatPercLogDate = (aBodyFatPercLogs != null && aFatMassLogs == null) ? aBodyFatPercLogs[0]['date'] : null;
// loop through each day starting with the earliest date we have logs for, ending with the last date we could possibly have logs for
while (sThisDate != null) {
var chartData = [];
var bAdd = false;
chartData[iDateIndex] = sThisDate;
if (aWeightLogs && aWeightLogs[x] != undefined) {
var fWeightVal = 0.00;
if (Date.parse(aWeightLogs[x]['date']) == Date.parse(sThisDate))
{
// add this value
fWeightVal = formatDecimal(aWeightLogs[x]['value']);
fLastWeightVal = fWeightVal;
nextWeightLogDate = (aWeightLogs[x + 1] !== undefined) ? aWeightLogs[x + 1]['date'] : null;
x++;
bAdd = true;
} else {
fWeightVal = fLastWeightVal;
}
chartData[iWeightIndex] = parseFloat(fWeightVal);
} else if (fLastWeightVal > 0) {
chartData[iWeightIndex] = parseFloat(fLastWeightVal);
}
if (aMuscleMassLogs && aMuscleMassLogs[y] != undefined) {
var fMuscleMassVal = 0.00;
if (Date.parse(aMuscleMassLogs[y]['date']) == Date.parse(sThisDate))
{
// add this value
fMuscleMassVal = formatDecimal(aMuscleMassLogs[y]['value'], 2);
fLastMuscleMassVal = fMuscleMassVal;
nextMuscleMassLogDate = (aMuscleMassLogs[y + 1] !== undefined) ? aMuscleMassLogs[y + 1]['date'] : null;
y++;
bAdd = true;
} else {
fMuscleMassVal = fLastMuscleMassVal;
}
chartData[iMuscleMassIndex] = parseFloat(fMuscleMassVal);
} else if (fLastMuscleMassVal > 0) {
chartData[iMuscleMassIndex] = parseFloat(fLastMuscleMassVal);
}
if (aFatMassLogs && aFatMassLogs[z] != undefined) {
var fFatMassVal = 0.00;
if (Date.parse(aFatMassLogs[z]['date']) == Date.parse(sThisDate))
{
// add this value
fFatMassVal = formatDecimal(aFatMassLogs[z]['value'], 2);
fLastFatMassVal = fFatMassVal;
nextFatMassLogDate = (aFatMassLogs[z + 1] !== undefined) ? aFatMassLogs[z + 1]['date'] : null;
z++;
bAdd = true;
} else {
fFatMassVal = fLastFatMassVal;
}
chartData[iFatMassIndex] = parseFloat(fFatMassVal);
chartData[iLeanMassIndex] = chartData[iWeightIndex] - fFatMassVal;
} else if (fLastFatMassVal > 0) {
chartData[iFatMassIndex] = parseFloat(fLastFatMassVal);
chartData[iLeanMassIndex] = chartData[iWeightIndex] - fLastFatMassVal;
}
if (bCalculateLeanMass && aFatMassLogs == null) {
if (aBodyFatPercLogs[w] != undefined) {
// if we don't have fat mass logs to use, calculate the lean mass from the body fat %
var fLeanMassVal = 0.00;
var fFatMassVal = 0.00;
if (Date.parse(aBodyFatPercLogs[w]['date']) == Date.parse(sThisDate)) {
// add this value
fFatMassVal = (aBodyFatPercLogs[w]['value'] * 0.01) * chartData[iWeightIndex];
fFatMassVal = formatDecimal(fFatMassVal, 2);
fLeanMassVal = chartData[iWeightIndex] - fFatMassVal;
fLeanMassVal = formatDecimal(fLeanMassVal, 2);
fLastBodyFatPercVal = aBodyFatPercLogs[w]['value'];
nextBodyFatPercLogDate = (aBodyFatPercLogs[w + 1] !== undefined) ? aBodyFatPercLogs[w + 1]['date'] : null;
w++;
bAdd = true;
} else {
if (fLastBodyFatPercVal > 0) {
fFatMassVal = (fLastBodyFatPercVal * 0.01) * chartData[iWeightIndex];
fFatMassVal = formatDecimal(fFatMassVal, 2);
fLeanMassVal = chartData[iWeightIndex] - fFatMassVal;
fLeanMassVal = formatDecimal(fLeanMassVal, 2);
} else {
fFatMassVal = 0;
fLeanMassVal = 0;
}
}
chartData[iFatMassIndex] = parseFloat(fFatMassVal);
chartData[iLeanMassIndex] = parseFloat(fLeanMassVal);
}
else if (fLastBodyFatPercVal > 0)
{
fFatMassVal = (fLastBodyFatPercVal * 0.01) * chartData[iWeightIndex];
fLeanMassVal = chartData[iWeightIndex] - fFatMassVal;
fLeanMassVal = formatDecimal(fLeanMassVal, 2);
fFatMassVal = formatDecimal(fFatMassVal, 2);
chartData[iFatMassIndex] = parseFloat(fFatMassVal);
chartData[iLeanMassIndex] = parseFloat(fLeanMassVal);
}
}
var orderedNextDates = [];
if (nextWeightLogDate) {
orderedNextDates.push(nextWeightLogDate);
}
if (nextMuscleMassLogDate) {
orderedNextDates.push(nextMuscleMassLogDate);
}
if (nextFatMassLogDate) {
orderedNextDates.push(nextFatMassLogDate);
}
if (nextBodyFatPercLogDate) {
orderedNextDates.push(nextBodyFatPercLogDate);
}
if (orderedNextDates.length > 0) {
orderedNextDates.sort((a, b) => {
let parsedA = Date.parse(a);
let parsedB = Date.parse(b);
if (parsedA > parsedB) {
return 1;
} else if (parsedA === parsedB) {
return 0;
} else {
return -1;
}
});
sThisDate = orderedNextDates[0];
} else {
sThisDate = null;
}
if (bAdd) {
aChartDataArray.push(chartData);
}
}
if (aChartDataArray.length > 1)
{
var chartData = google.visualization.arrayToDataTable(aChartDataArray);
var seriesOptions = {};
if (iFatMassIndex > 0)
{
if (iMuscleMassIndex > 0)
{
var iMuscleSeries = parseInt(iMuscleMassIndex - 1);
seriesOptions[iMuscleSeries] = {color: 'orange'};
}
var iFatSeries = parseInt(iFatMassIndex - 1);
seriesOptions[iFatSeries] = {color: 'red'};
}
var options = { title: 'Body Composition',
curveType: 'function',
legend: {position: 'bottom'},
height: 500,
vAxis: {minValue: 0},
chartArea: {width:'85%'},
series: seriesOptions };
var chart = new google.visualization.AreaChart(document.getElementById(sChartContainerID));
chart.draw(chartData, options);
}
}
// checks to see if the given string contains a number
// returns true if it does
// returns false if not
function hasNum(sIn)
{
if (undefined != sIn) {
var type = typeof(sIn);
if (type == 'string') {
var match = sIn.match(/\d+/g);
if (match != null)
return true;
else
return false;
}
else if (type == 'number') {
return true;
}
}
else {
return false;
}
}
function userProfilePhotoExists(sPhotoURL)
{
if (sPhotoURL && sPhotoURL != NO_PHOTO)
return true;
else
return false;
}
function nullToBlank(sIn)
{
if (sIn == null)
return '';
else
return sIn;
}
function getUserStatusString(iUserStatus)
{
var statusStr = '';
switch (iUserStatus)
{
case USER_STATUS_ACTIVATED:
statusStr = 'Activated';
break;
case USER_STATUS_UNACTIVATED:
statusStr = 'Unactivated';
break;
case USER_STATUS_DEACTIVATED:
case USER_STATUS_PROVIDER_CREATED_DEACTIVATED:
statusStr = 'Deactivated';
break;
case USER_STATUS_ADMIN_CREATED_UNACTIVATED:
statusStr = 'Unactivated (Admin Created)';
break;
case USER_STATUS_PROVIDER_CREATED_UNACTIVATED:
statusStr = 'Unactivated (Provider Created)';
break;
case USER_STATUS_PROVIDER_CREATED_ACTIVATED:
statusStr = 'Activated (Provider Created)';
break;
case USER_SELF_ENROLLMENT:
statusStr = 'Unactivated (Self Enrolled)';
break;
case USER_STATUS_DISABLE_ACTIVATION_EMAILS:
statusStr = 'Unactivated (Activation Emails Disabled)';
break;
case USER_STATUS_NEEDS_EMAIL_VALIDATION:
statusStr = 'Unactivated (Needs Email Validation)';
break;
default:
break;
}
return statusStr;
}
function renderClearFilterBtn(sTableID)
{
$("#"+sTableID+"_filter").find("input:first").wrap('');
$("#"+sTableID+"_filter").parent().addClass("col-xs-4");
$("#"+sTableID+"_filter").find("div.input-group:first").append('');
$('#'+sTableID+'_filter-clear').off().on("click",function()
{
var oTable = $("#"+sTableID).DataTable();
oTable.search('').columns().search('').draw();
});
}
function renderTodayIcon() {
let today = new Date();
let html = ''+today.getDate()+'';
return html;
}
function isSmallWindow() {
if ($(window).width() < 768) {
return true;
} else {
return false;
}
}
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
function updateCalorieData(date, eaten, burned, remaining) {
$('.total_calories_consumed [data-date="+date+"]').text(Math.round(eaten));
$('.total_calories_burned [data-date="+date+"]').text(Math.round(burned));
$('.total_difference [data-date="+date+"]').text(Math.round(remaining));
}
function getLogoPath(thirdPartyName) {
let path = '';
switch (thirdPartyName.toLowerCase()) {
case 'fitbit':
path = fitbitLogo;
break;
case 'inbody':
path = inbodyLogo;
break;
case 'withings':
path = withingsLogo;
break;
case 'innotech':
path = INNOTECH_LOGO;
break;
case 'apple health':
path = APPLE_HEALTH_LOGO;
break;
case 'oura':
path = OURA_LOGO;
break;
case 'iglucose':
path = IGLUCOSE_LOGO;
break
default:
break;
}
return path;
}
jQuery.fn.createDatePicker = function() {
let options = {
allowInput: true,
dateFormat: 'm/d/Y'
};
if (this.hasAttr('data-format')) {
let formatParam = this.attr('data-format');
options.dateFormat = formatParam;
}
let dateVal = $(this).val();
options.defaultDate = new Date(dateVal);
if (this.hasAttr('data-endpoint')) {
let input = $(this);
options.onChange = function() {
executeAjaxCall(input);
};
}
if ($(this).hasAttr('data-time-picker') && $(this).attr('data-time-picker') === 'true') {
$(this).css({
"width": "12em",
"text-align": "center",
"max-width": "12em"
});
options.enableTime = true;
options.dateFormat = 'm/d/Y h:i K';
} else {
$(this).css({
"width": "10em",
"text-align": "center",
"max-width": "10em"
});
}
$(this).flatpickr(options);
this.addClass('datepicker-initialized');
return this;
};
function makeFoodServingLabel(servingName, numServings) {
// look for any number of digits, zero or one decimal, followed by any number of digits
// ex. 6 medium or 0.25 cup
// in order to get the number of items in the current serving
servingName = servingName.toString();
let regExp = /^\d*\.?\d*/;
let match = regExp.exec(servingName);
if (match != null && match != '') {
let servingNameNumServings = match * numServings;
servingName = servingName.replace(regExp, servingNameNumServings);
} else {
servingName = numServings + ' ' + servingName;
}
return servingName;
}
function renderFoodPhoto(food) {
let html = '';
let hasPhoto = (food.hasOwnProperty('food_photo') && food['food_photo'] != null && food['food_photo'].search('nix-apple-grey.png') == -1);
if (hasPhoto) {
html += '';
} else {
html += '
';
}
return html;
}
function reSortDataTable(sTableID) {
// get the current filter
var sFilter = $("#" + sTableID + "_filter").find("input:first").val();
// get the table object and it's settings
var oTable = $("#" + sTableID).DataTable();
var initSettings = oTable.init();
// destroy the current table
oTable.destroy();
// init new table
$("#" + sTableID).DataTable(initSettings);
renderClearFilterBtn(sTableID);
// put the filter back in the search box
$("#" + sTableID + "_filter").find("input:first").val(sFilter);
// search with the filter
var oTable = $("#" + sTableID).DataTable();
oTable.search(sFilter).draw();
// 'hack' for when there's no rows left after the filter is applied
if ($("#" + sTableID + " tbody").find("td:first").hasClass("dataTables_empty")) {
$("#" + sTableID + " tbody").find("td:first").attr("colspan", 2);
}
}
function makePageHeader(sPageTitle, sEndpoint, sReplaceDOM, aParams, bShowWaiter) {
let html = '';
bShowWaiter = (undefined === bShowWaiter) ? false : bShowWaiter;
html += '
';
html += sPageTitle;
if (undefined !== sEndpoint) {
html += '';
}
html += '
';
return html;
}
function br2nl(input) {
let regex = / ]*>/gi;
let output = input.replace(regex, "\n");
return output;
}
function activateTab(tab) {
const bsTab = new bootstrap.Tab(tab);
bsTab.show();
}
function goToNavItem(endpoint) {
const navItem = $("#mainnavul a[data-endpoint='/" + endpoint + "/']");
const bsNavItem = new bootstrap.Tab(navItem);
bsNavItem.show();
objectClick(navItem);
}
function closeModal() {
return '';
}
function formatPhoneNumber(phoneNumberString) {
let cleaned = ('' + phoneNumberString).replace(/\D/g, '');
let match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
let intlCode = (match[1] ? '+1 ' : '');
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
}
return '';
}
function strCompare(strA, strB) {
// do both strings begin with numbers
let numPatt = /^\d+/;
if (numPatt.test(strA) && numPatt.test(strB)) {
// compare the numbers
let numA = numPatt.exec(strA);
numA = parseInt(numA[0]);
let numB = numPatt.exec(strB);
numB = parseInt(numB[0]);
if (numA < numB) {
return -1;
} else if (numA > numB) {
return 1;
} else {
return 0;
}
} else {
// just compare the strings
if (strA.toUpperCase() < strB.toUpperCase()) {
return -1;
} else if (strA.toUpperCase() > strB.toUpperCase()) {
return 1;
} else {
return 0;
}
}
}
jQuery.fn.initWistiaUploader = function() {
let uploader_id = $(this).attr('id');
window._wapiq = window._wapiq || [];
_wapiq.push(function (W) {
window.wistiaUploader = new W.Uploader({
accessToken: WISTIA_ACCESS_TOKEN,
dropIn: uploader_id,
beforeUpload: function() {
return {
then: function(resolve, reject) {
setTimeout(function() {
// create a project to upload to
$.ajax({
url: AJAXURI + '/get_wistia_project_id/',
method: 'POST',
dataType: 'JSON',
headers: {
'X-CSRF-Token': Math.random().toString(20).substr(2, 20)
},
success: function(json) {
if (json.status == 1) {
wistiaUploader.setProjectId(json.data.wistia_project_id);
resolve();
} else {
console.log(json.message);
reject();
}
},
error: function(xhr) {
console.log(xhr);
reject();
}
})
}, 1000);
}
}
}
});
wistiaUploader.bind('uploadstart', function(file) {
let html = '';
html += '
Your video is uploading! Don\'t navigate away from this page until it finishes.
';
$(html).insertAfter('#' + uploader_id);
});
wistiaUploader.bind('uploadsuccess', function(file, media) {
// add the video to the user's library via ajax
let params = {};
params['params'] = {};
params['params']['video_source_ref_id'] = media.id;
params['params']['video_thumbnail_href'] = media.thumbnail.url;
params['params']['video_description'] = media.name;
ajaxCall('/add_uploaded_video_to_library/', params, function(json) {
let html = '';
if (json.status == 1) {
$('#add-video-modal').find('button.close').addClass('abtn').attr('data-endpoint', '/video_library/').attr('data-replace-dom', 'videos');
let jChangeNameParams = [];
jChangeNameParams.push({ name: 'video_name', value_of: 'change-uploaded-video-name' });
jChangeNameParams.push({ name: 'video_ref_id', value: media.id });
html += '
';
html += 'Your video has been successfully uploaded and added to your library!
';
html += '';
html += '
';
html += ``;
html += ``;
html += '
'; // input-group
html += '
'; // alert
} else {
html += '
';
html += 'Oops! There was a problem adding this video to your library';
html += '
'; // alert
}
$('#' + uploader_id + '_message').html(html);
});
});
});
};
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function datediff(first, second) {
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
return Math.round((parseDate(second)-parseDate(first))/(1000*60*60*24));
}
function getSelectedRadioVal(btnObjects) {
let ret = '';
btnObjects.each(function() {
let btn = $(this);
if (btn.prop('checked') === true) {
ret = btn.val();
}
});
return ret;
}
function handleTableSearch(table_id) {
let oTable = $("#" + table_id).DataTable();
let timerName = generateUUID() + '_timer';
window[timerName] = null;
$('#' + table_id + '_filter input').off().on('keyup', function() {
if (window[timerName] != null) {
clearTimeout(window[timerName]);
}
let searchVal = $(this).val();
// we don't want to hit the database with the user's answer every single time they press a key
// so wait 1 second and then trigger event that will save the answer
window[timerName] = setTimeout(function() {
oTable.search(searchVal).draw();
}, 750);
});
}
function makeTaskNameStr(task, viewing) {
let name = '';
viewing = (undefined !== viewing) ? viewing : false;
if (task.action != undefined) {
switch (task.action) {
case "/save_new_body_log/":
if (task.hasOwnProperty('action_params') && task.action_params.hasOwnProperty('metric_name')) {
name = 'Track ' + task.action_params.metric_name.toLowerCase();
} else {
name = 'Track a body metric';
console.log('Task ' + task.task_id + ' missing metric name');
}
break;
case "/save_body_goal/":
if (task.hasOwnProperty('action_params') && task.action_params.hasOwnProperty('metric_name')) {
name = 'Set a ' + task.action_params.metric_name.toLowerCase() + ' goal';
} else {
name = 'Set a body metric goal';
console.log('Task ' + task.task_id + ' missing metric name');
}
break;
case "/save_activity/":
case "/track_custom_activity/":
if (task.hasOwnProperty('action_params') && task.action_params.hasOwnProperty('activity_title')) {
name = 'Track ' + task.action_params.activity_title.toLowerCase();
} else {
name = 'Track an activity';
console.log('Task ' + task.task_id + ' missing activity title');
}
break;
case "custom":
if (task.hasOwnProperty('action_params') && task.action_params.hasOwnProperty('prompt')) {
name = task.action_params.prompt;
if (!viewing) {
if (task.action_params.completion === 'checkbox') {
name += '';
} else if (task.action_params.completion === 'feedback') {
name += '';
}
}
} else {
name = 'Custom Task';
console.log('Task ' + task.task_id + ' missing prompt');
}
break;
case "/track_sleep/":
name = 'Track sleep';
break;
case "/track_steps/":
name = 'Track steps';
break;
case "/track_water/":
name = 'Track water intake';
break;
default:
let selAction = ACTION_CHOICES.filter(function (choice) {
return choice.endpoint === task.action;
});
if (selAction.length === 1) {
name = selAction[0].action;
}
break;
}
} else {
switch (task.plan_object_type) {
case 'NOTE':
name = 'Read program content';
break;
case 'EXERCISE':
name = 'Did an exercise';
break;
case 'YOUTUBE':
case 'VIMEO':
case 'WISTIA':
name = 'Watched a video';
break;
default:
break;
}
}
return name;
}
function toBool(str) {
return str.toLowerCase() === 'true';
}
function loadScript(sFileName, fnCallback) {
if (undefined === fnCallback) {
fnCallback = function() { void(0); };
}
if (!window.scripts_loaded.includes(sFileName)) {
$.ajax({
url: scriptbase + sFileName,
dataType: 'script',
success: fnCallback,
async: true,
complete: function (xhr, status) {
window.scripts_loaded.push(sFileName);
},
error: function(xhr, status, error) {
console.log(error);
}
});
} else {
fnCallback.call(null);
}
initOutput();
}
function makePOSTParams(params) {
return encodeURIComponent(JSON.stringify(params));
}
function formatMacroTotal(val) {
return (val < 1 && val > 0) ? '< 1' : Math.round(val);
}
function renderBAAForSignature(json) {
let html = '';
$.getScript('https://cdncf.esignatures.io/assets/iframeResizer.4.2.10.min.js');
html += '
';
html += '
';
html += '
';
html += '
';
html += '
Let\'s handle HIPAA before you log in . . .
';
html += '
'; // modal-header
html += '
';
html += '
Please sign our updated Business Associate Agreement (BAA) and then click Go to My Dashboard to proceed. A BAA protects the privacy of your patients and is required in accordance with HIPAA.
';
html += '';
html += '
'; // modal-body
html += ''; // modal-footer
html += '
'; // modal-content
html += '
'; // modal-dialog
html += '
'; // modal
$('body').append(html);
$('#sign-baa-modal').modal({
backdrop: 'static',
keyboard: false,
}).modal('show');
let modalBodyElement = document.querySelector('#sign-baa-modal .modal-body');
modalBodyElement.onscroll = function(event) {
if ((modalBodyElement.scrollTop) === (modalBodyElement.scrollHeight - modalBodyElement.offsetHeight)) {
// we're at the bottom, enable the button
$('#done-signing-baa-button').prop('disabled', false).removeClass('disabled');
}
};
}
function checkContractSignedCallback(json, replacedom) {
if (json.status === 1) {
$('#' + replacedom).modal('hide').removeModal(true);
if (json.data.contract_status === 'WITHDRAWN') {
let html = '';
html += '
';
html += '
';
html += '
';
html += '
';
html += '
Oops!
';
html += '
'; // modal-header
html += '
';
html += '
Oops! You withdrew from signing a Business Associate Agreement (BAA). In order to access your account immediately, please click on the button below to temporarily access your account without a BAA. We\'ll follow up with you shortly to make sure you have a BAA if you need one or to confirm your opt out status.
';
html += '';
html += '
'; // modal-body
html += '
'; // modal-content
html += '
'; // modal-dialog
html += '
'; // modal
$('body').append(html);
$('#user-withdrawn-opt-out').modal({
backdrop: 'static',
keyboard: false
}).modal('show');
}
}
}
function renderBBABlockerModalForNonDomainAdmin(json) {
let html = '';
let domainAdminUser = json.data.domain_admin_info;
html += '
';
html += '
';
html += '
';
html += '
';
html += '
Hold on a minute...
';
html += '
'; // modal-header
html += '
';
html += '
Hey! We updated our BAA recently and we need ' + domainAdminUser.user_display_name + ' to log in and sign it before you can proceed. We already sent them an email reminder at ' + domainAdminUser.user_email + '. If you have any questions you can call us at (561) 247-3839.
';
html += '
'; // modal-body
html += ''; // modal-footer
html += '