// ! *** VARIABLES Logged in users starts *** // ! *** VARIABLES Not logged in users starts *** var favStablesJSON = []; var isStablePersonnel = 0; // ! *** VARIABLES Not logged in users ends *** var hopotiRewardsData = []; var hopotiAdsData = []; // ! *** FUNCTIONS Everyone starts *** /* !Skill selection starts */ /* usage: loadSkills(3,8); */ var buttonsSelected = 0; var firstPosition; var secondPosition; var newPosition; var distanceFirst; var distanceSecond; var minSkill; var maxSkill; var userLevel; // user set skill from settings var userConfirmed; var userConfirmedPerson; var userConfirmedDate; var userConfirmedStable; var $window = $(window); var windowsize; var oldwindowsize; var totalUserWalletCredits; var currentStableLink; // currently selected stable var selectedHorseId; var combousercalendarevents = true; // if user calendar events are combined var eventSummaryAlmostFull = 75; // percentage setting for almost full color display on summary // Init default ID values for card types var idStablecards = 1; var idMemberships = 4; var idGiftcards = 3; var userStableCardsArray = []; // Allowed file upload types var fileUploadTypes = ".jpeg,.jpg,.png,.gif,.bmp,.pdf,.doc,.docx,.odt,.txt,.rtf,.xls,.xlsx,.ppt,.zip,.avi,.mov,.mpg,.mpeg,.mp4,.wmv,.flv,.f4v,.mp3,.mp4,.wma,.wav,.acc,.m4a,.flac"; var carbonOffsetInfo = [ { date: "2022-01-01", g: 2600 } ]; function cancellationPolicyModalAdmin(policy){ policyFlexible = ''; policyStandard = ''; policyStrict = ''; policyNoreturn = ''; policyFull = ''; switch(policy) { case 'flexible': policyFlexible = 'active'; break; case 'strict': policyStrict = 'active'; break; case 'noreturn': policyNoreturn = 'active'; break; case 'full': policyFull = 'active'; break; default: policyStandard = 'active'; } BootstrapDialog.show({ type: BootstrapDialog.TYPE_INFO, title: 'Cancellation policies', message: '
For every lesson, course and event, the business can choose from a variety of cancellation policies. Paid lessons are not refunded in cash as such as the purchase is for a leisure event with a specified date and time. Cancelled events are instead usually refunded with new credits added to the Stablecard. Refunded credits can be used to book an alternative event before the end of the validity period. The "No return" category is an exception, which is meant to be used with seasons and camps as they can’t be returned. Instead, lessons within seasons can be cancelled and refunded in line with the business’s selected cancellation policy.

Full: 0 hours before the start of the event

Flexible: 12 hours before the start of the event

Standard: 24 hours before the start of the event

Strict: 48 hours before the start of the event

No return

' }); } function cancellationPolicyModalClient(policy){ policyFlexible = ''; policyStandard = ''; policyStrict = ''; policyNoreturn = ''; policyFull = ''; switch(policy) { case 'flexible': policyFlexible = 'active'; break; case 'strict': policyStrict = 'active'; break; case 'noreturn': policyNoreturn = 'active'; break; case 'full': policyFull = 'active'; break; default: policyStandard = 'active'; } BootstrapDialog.show({ type: BootstrapDialog.TYPE_INFO, title: 'Cancellation policies', message: '
Paid lessons are not refunded in cash as such as the purchase is for a leisure event with a specified date and time. Cancelled events are instead usually refunded with new credits added to the Stablecard. Refunded credits can be used to book an alternative event before the end of the validity period. The "No return" category is an exception, which is meant to be used with seasons and camps as they can’t be returned.

Full: 0 hours before the start of the event

Flexible: 12 hours before the start of the event

Standard: 24 hours before the start of the event

Strict: 48 hours before the start of the event

No return

' }); } //!Common help dialog error dialog [help][dialog][error] function commonHelpDialog(title,message,type){ var dialogType = BootstrapDialog.TYPE_INFO; if(type == "INFO"){ dialogType = BootstrapDialog.TYPE_INFO; } else if(type == "DEFAULT"){ dialogType = BootstrapDialog.TYPE_DEFAULT; } else if(type == "PRIMARY"){ dialogType = BootstrapDialog.TYPE_PRIMARY; } else if(type == "SUCCESS"){ dialogType = BootstrapDialog.TYPE_SUCCESS; } else if(type == "WARNING"){ dialogType = BootstrapDialog.TYPE_WARNING; } else if(type == "DANGER"){ dialogType = BootstrapDialog.TYPE_DANGER; } BootstrapDialog.show({ type: dialogType, title: title, message: message }); } var cacheViewmode; // !Responsive width changes // show elements after window resize function checkWidth() { console.log("checkWidth"); windowsize = $window.width(); if (windowsize != oldwindowsize){ if(windowsize < 480) { //console.log("xxs"); viewmode = 'xxs'; $('.mainimage').append($('#editimageprofile')); //$('.mobilemenu').hide(); //$('.fullmenu').not('.loginlink').hide(); //$('header li').removeClass("mobilemenu-topmargin"); } else if(windowsize < 768) { // MOBILE //console.log("xs"); viewmode = 'xs'; $('.mainimage').append($('#editimageprofile')); //$('.mobilemenu').hide(); //$('.fullmenu').not('.loginlink').hide(); } else if (windowsize < 992) { //console.log("sm"); viewmode = 'sm'; //$('.mobilemenu').hide(); //$('.fullmenu').show(); } else if (windowsize < 1200) { //console.log("md"); viewmode = 'md'; //$('.mobilemenu').hide(); //$('.fullmenu').show(); } else { //console.log("lg"); viewmode = 'lg'; } // save viewmode variable to body for later use $('body').attr("data-viewmode",viewmode); contentAreaSubnaviCheck(); changeFixedWidthElements(); } var mobiledesktopChange = 0; var calendarmodeChange = 0; // trigger only when view mode changes between modes if(viewmode != cacheViewmode && cacheViewmode != null){ // trigger only when viewmode changes if(cacheViewmode == "xxs" || cacheViewmode == "xs"){ // trigger only when previous viewmode was mobile if(viewmode != "xxs" && viewmode != "xs"){ // when changing from mobile to desktop console.log("mobile > desktop"); mobiledesktopChange = 1; showHideMobileMenu2022(1); } } else { if(viewmode == "xxs" || viewmode == "xs"){ // when changing from desktop to mobile console.log("desktop > mobile"); mobiledesktopChange = 1; } } if(cacheViewmode == "xxs"){ // trigger only when previous viewmode was mobile if(viewmode != "xxs"){ // when changing from mobile to desktop console.log("cal list - cal grid"); calendarmodeChange = 1; } } else { if(viewmode == "xxs"){ // when changing from desktop to mobile console.log("cal grid - cal list"); calendarmodeChange = 1; } } } if(mobiledesktopChange){ // if change between mobile - desktop console.log("mobile - desktop"); // refresh all horses hc cal var hcCalPresent = $('.horsecare-calendar-allhorses').children().closest('.horsecare-calendar'); if(hcCalPresent.length){ $(hcCalPresent).fullCalendar('destroy'); $(hcCalPresent).attr('data-dateselector-added', 0); horseCareOptionsReady = 0; $(hcCalPresent).find('.horsecare-options-menu').remove(); horsecareCalendar(); } } if(calendarmodeChange){ var stableEventCalendarPresent = $('.page-booking-2019 #calendar'); if(stableEventCalendarPresent.length){ changeCalendar(); } } cacheViewmode = viewmode; oldwindowsize = windowsize; } // !show confirmed/unconfirmed extra tags on top of skill selection widget function initConfirmedSkill() { // addition - confirmed user skill info userLevel = $('.skillSelection').data("userlevel"); userConfirmed = $('.skillSelection').data("confirmed"); userConfirmedPerson = $('.skillSelection').data("confirmed-person"); userConfirmedDate = $('.skillSelection').data("confirmed-date"); userConfirmedStable = $('.skillSelection').data("confirmed-stable"); confirmedTag = ''; unconfirmedTag = ''; userlevelSkillButton = $(".skillSelection a[data-value='"+userLevel+"']"); originalContent = userlevelSkillButton.attr("data-content"); if(userLevel > 0 && userConfirmed >= userLevel){ // skill level confirmed userlevelSkillButton.append(confirmedTag); userlevelSkillButton.attr('data-content', originalContent + '

Skill level confirmed'); } else { if(userLevel > 0){ // skill level unconfirmed userlevelSkillButton.append(unconfirmedTag); userlevelSkillButton.attr('data-content', originalContent + '

You have changed your skill level, but this has not yet been confirmed by your riding instructor'); } } } var scaled = 0; function scaleCalendarTimes(paddingHours,calendarselector){ console.log("scaleCalendarTimes | paddingHours: "+paddingHours+" | scaled: "+scaled); if(viewmode == "xs" || viewmode == "xxs"){ return false; } if(!calendarselector){ calendarselector = $("#calendar"); } else { calendarselector = $(calendarselector); } var viewStart = calendarselector.fullCalendar('getView').start; var viewEnd = calendarselector.fullCalendar('getView').end; var viewType = calendarselector.fullCalendar('getView').type; if(viewType != "agendaThreeDay" && viewType != "agendaWeek" && viewType != "agendaDay"){ return false; } var serviceCalPadding = true; if($("body").hasClass("pageStableServices") && servicecalMode == 1){ serviceCalPadding = false; } var padding = paddingHours; var firstStart; var firstStartEvent; var firstEnd; var firstEndEvent; var lastStart; var lastStartEvent; var lastEnd; var lastEndEvent; var evts = calendarselector.fullCalendar('clientEvents'); if(scaled == 0 && evts.length){ scaled = 1; // add extra filters here if not ok servicefilter etc var visibleRangeEvents = $.grep(evts, function(e){ // get only events on displayed range return !e.isException == true && e.start && e.end && e.start < e.end && e.start.isBetween(viewStart, viewEnd, undefined, '[)') || !e.isException == true && e.start && e.end && e.start < e.end && e.end.isBetween(viewStart, viewEnd, undefined, '(]'); }); // console.log("visibleRangeEvents.length: "+visibleRangeEvents.length); // console.log(visibleRangeEvents); if(visibleRangeEvents.length){ $(visibleRangeEvents).each(function(index, event){ if(!event.end || !event.start || event.allDay || event.started || event.rendering == "background"){ return true; } var currentstart = event.start; var currentstarttime = currentstart.format('HH:mm'); var comparestart = moment("2000-01-01 "+currentstarttime); var currentend = event.end; var currentendtime = currentend.format('HH:mm'); var compareend = moment("2000-01-01 "+currentendtime); if(currentendtime == "00:00"){ compareend = moment("2000-01-02"+currentendtime); } if(!firstStart || comparestart < moment("2000-01-01 "+firstStart)){ firstStart = currentstarttime; firstStartEvent = event; } if(!firstEnd || compareend < moment("2000-01-01 "+firstEnd)){ firstEnd = currentendtime; firstEndEvent = event; } if(!lastStart || comparestart > moment("2000-01-01 "+lastStart)){ lastStart = currentstarttime; lastStartEvent = event; } if(!lastEnd || compareend > moment("2000-01-01 "+lastEnd)){ lastEnd = currentendtime; lastEndEvent = event; } }); // // console.log("firstStart"); // console.log(firstStart); // console.log(firstStartEvent); // // console.log("firstEnd"); // console.log(firstEnd); // console.log(firstEndEvent); // // console.log("lastStart"); // console.log(lastStart); // console.log(lastStartEvent); // // console.log("lastEnd"); // console.log(lastEnd); // console.log(lastEndEvent); } var mintime; var minmoment; if(firstEndEvent){ var selectedStart = firstEndEvent.start.format("HH:mm"); var firstEndEventDuration = moment.duration(firstEndEvent.end.diff(firstEndEvent.start)); if(firstEndEventDuration > 3600000*2 && serviceCalPadding && lastStartEvent.scheduleservices){ // longer than 2 hours selectedStart = firstEndEvent.end.subtract(2, "hours").format("HH:mm"); } if(moment("2000-01-01 "+firstEnd) < moment("2000-01-01 "+selectedStart)){ // if event over two dates minmoment = moment("2000-01-01 "+firstEnd).subtract(firstEndEventDuration).startOf('hour'); } else { minmoment = moment("2000-01-01 "+selectedStart).startOf('hour'); } if(padding){ minmoment.subtract(padding, "hours"); } } // // console.log("minmoment"); // console.log(minmoment.format("YYYY-MM-DD HH:mm:ss")); if(!minmoment || minmoment > moment("2000-01-01 14:00")){ mintime = "14:00"; } else if(minmoment < moment("2000-01-01 00:00:00")){ mintime = "00:00"; } else { mintime = minmoment.format("HH:mm"); } var maxtime; var maxmoment; if(lastStartEvent){ var selectedEnd = lastStartEvent.end.format("HH:mm"); if(selectedEnd == "00:00"){ selectedEnd = "24:00"; } var lastStartEventDuration = moment.duration(lastStartEvent.end.diff(lastStartEvent.start)); if(lastStartEventDuration > 3600000*2 && serviceCalPadding && lastStartEvent.scheduleservices){ // longer than 2 hour service event selectedEnd = lastStartEvent.start.add(2, "hours").format("HH:mm"); } if(moment("2000-01-01 "+lastStart) > moment("2000-01-01 "+selectedEnd)){ maxmoment = moment("2000-01-01 "+lastStart).add(lastStartEventDuration).endOf('hour').add(1, "minutes"); } else { maxmoment = moment("2000-01-01 "+selectedEnd).endOf('hour').add(1, "minutes"); } if(padding){ maxmoment.add(padding, "hours"); } } // console.log("firstEndEvent"); // console.log(firstEndEvent); // console.log("lastStartEvent"); // console.log(lastStartEvent); if(!maxmoment || maxmoment < moment("2000-01-01 18:00")){ maxtime = "18:00"; } else if(maxmoment >= moment("2000-01-02 00:00:00")){ maxtime = "24:00"; } else { maxtime = maxmoment.format("HH:mm"); } console.log('scale cal | mintime: '+mintime+" | maxtime: "+maxtime); calendarselector.fullCalendar('option', { minTime: mintime, maxTime: maxtime, }); scaled = 0; } } function setSkillsForm(target) { var skilltarget = $('.skillSelection'); if(target){ skilltarget = target.find('.skillSelection'); } minSkill = skilltarget.find('.first').data("value"); maxSkill = skilltarget.find('.second').data("value"); skilltarget.nextAll('.minSkill').val(minSkill); skilltarget.nextAll('.maxSkill').val(maxSkill); if(maxSkill == null){ skilltarget.nextAll('.maxSkill').val(minSkill); } } function resetSkills(target) { var skilltarget = $('.skillSelection'); if(target){ skilltarget = target.find('.skillSelection'); } skilltarget.find("a").removeClass("active first second"); skilltarget.nextAll('.minSkill').val(); skilltarget.nextAll('.maxSkill').val(); minSkill = null; maxSkill = null; buttonsSelected = 0; } function loadSkills(minSkillInit, maxSkillInit, target) { // target is a parent container for skill selection form elements var skilltarget = $('.skillSelection'); if(target){ skilltarget = target.find('.skillSelection'); } resetSkills(target); if (minSkillInit != null) { var first = skilltarget.find("a[data-value='"+minSkillInit+"']"); first.addClass("active first"); firstPosition = skilltarget.find(".first").index(); buttonsSelected = 1; } else { return false; } if (maxSkillInit == minSkillInit) { } else if (maxSkillInit != null && maxSkillInit != 0) { var second = skilltarget.find("a[data-value='"+maxSkillInit+"']"); second.addClass("active second"); skilltarget.find('a.first').nextUntil('a.second').addClass("active"); buttonsSelected = 2; secondPosition = skilltarget.find(".second").index(); } setSkillsForm(target); } /* !Skill selection ends */ /* !Server response feedback for user */ /* Usage: put after ajax call, takes server result, add logic here*/ /* You can add a div class as a second variable if you have a dedicated error div instead of displaying the feedback next to the button */ /*
*/ /* serverResponseFeedback(result,responseElement) */ var buttonPressed; // which ui element was pressed for form submit, use to view note next to an element function serverResponseFeedback(result,responseElement) { $('.alert-inline').remove(); var answer; var message; if(result == "ok" || result == "success!"){ answer = "positive"; message = 'Changes saved'; } else if(result == "fail" || result == "error") { answer = "negative"; message = 'Saving failed for some reason'; } else if(result == "fail-existing-account") { answer = "negative"; message = 'An account with entered email address already exists!'; } else if(result == "invalid-email") { answer = "negative"; message = 'Fill a valid email address'; } else if(result == "old pwd was not correct") { answer = "negative"; message = 'Old password was not correct, please try again'; } else { if(typeof result === 'object'){ answer = "negative"; message = 'Saving failed for some reason'; } else { message = result; } } var successHtml = '\
\ '+ message +'\
\ '; var failHtml = '\
\ '+ message +'\
\ '; var neutralHtml = '\
\ '+ message +'\
\ '; var dedicatedResponseSection = $(responseElement); var location = 'after'; if(dedicatedResponseSection.length != ""){ buttonPressed = dedicatedResponseSection; location = 'append'; } if(answer == "positive"){ buttonPressed[location](successHtml); $('.alert-inline').hide().fadeIn(100).delay(3000).fadeOut(300); } else if(answer == "negative") { buttonPressed[location](failHtml); $('.alert-inline').hide().fadeIn(100); } else { buttonPressed[location](neutralHtml); $('.alert-inline').hide().fadeIn(100); } buttonPressed = null; } /* Server response feedback ends */ // second level navigation readjustment var totalnavWidth = 0; var tolerance = 5; // calculate total width of visible items function menuItemsWidth(){ totalnavWidth = 0; $('.contentnav ul li:visible').each(function(index) { totalnavWidth += parseInt($(this).outerWidth(), 10); }); totalnavWidth = totalnavWidth + tolerance; } // build second level menu for mobiles function buildMenu() { console.log("buildMenu"); // not needed for .register if($('body').hasClass('register') || $('body').hasClass('stablepage') || $('body').hasClass('pageStable')){ return false; } // reset menu if you scale screen bigger if ($('#contentnav-mobile').length) { $("#contentnav-mobile li").appendTo(".contentnav ul"); $('#contentnav-mobile').remove(); $('#contentnav-more').remove(); } menuItemsWidth(); // max space available var contentnavUlWidth = $(".contentnav ul").width(); // add extra menu if needed if (totalnavWidth > contentnavUlWidth) { if (!$('#contentnav-mobile').length) { $(".maincontainer").prepend(''); $(".contentnav ul").append('
  • '); } } var max = 0; // move items one by one to extra menu until everything fits! while(totalnavWidth > contentnavUlWidth && max < 10) { $(".contentnav li:last").prev("li").prependTo("#contentnav-mobile"); menuItemsWidth(); max++; } // exception on horse pages if($('body').hasClass('pageHorse')){ if(viewmode == "xs" || viewmode == "xxs") { $(".contentnav").find(".right").not("#contentnav-more").prependTo("#contentnav-mobile"); } } if(viewmode == "xs" || viewmode == "xxs"){ $('.contentnav').hide().removeClass("invisible-xs").delay(100).fadeIn(400); } } // !add spinner to selected element, hide disk image function addSavingIndicator(selector){ var selector = $('body').find(selector); selector.addClass("disabled"); selector.find(".glyphicon-ok").addClass("hidden"); selector.append('
    '); } // !remove spinner and present a green ok mark function removeSavingIndicator(selector){ var selector = $('body').find(selector); selector.find(".saving-indicator, .glyphicon-ok-sign").remove(); selector.append(''); selector.removeClass("disabled"); setTimeout(function(){ selector.find(".glyphicon-ok-sign").fadeOut(500); selector.find(".glyphicon-ok").delay(500).hide().removeClass("hidden").fadeIn(100); }, 500); setTimeout(function(){ selector.removeClass("btn-success"); }, 1000); } // add/remove full screen spinner with optional title text - blocks all interactions and disables scroll // usage fullscreenSpinner('open/close','Title here') function fullscreenSpinner(option,titletext){ var spinnerTitle = ""; if(titletext){ spinnerTitle = '
    '+titletext+'
    '; } var spinnerHtml = '\
    \ '+spinnerTitle+'\
    \
    \
    \
    \
    \
    '; if(option == 'open'){ if(!$('body').hasClass("fullscreen-spinner-body")){ // prevent additional spinners $('body').append(spinnerHtml); $('.headercontainer, .headercontainer-2019, .maincontainer, .mainimage').addClass("disabled"); $('header, footer').addClass("disabled-opaque"); $('body').addClass("fullscreen-spinner-body"); } } else { $('.fullscreen-spinner').remove(); $('.headercontainer, .headercontainer-2019, .maincontainer, .mainimage').removeClass("disabled"); $('header, footer').removeClass("disabled-opaque"); $('body').removeClass("fullscreen-spinner-body"); } } function changeAccountOverlay(option,titletext){ console.log("changeAccountOverlay"); console.log(ownInfoObject); var spinnerTitle = ""; var userImage = 'user.png'; if(ownInfoObject.UserImage){ userImage = ownInfoObject.UserImage; } var spinnerHtml = '\
    \
    \ You are logged into account '+ownInfoObject.Name+' \ User image\
    \
    '; $('body').append(spinnerHtml); $('.headercontainer, .headercontainer-2019, .maincontainer, .mainimage').addClass("disabled"); $('header, footer').addClass("disabled-opaque"); $('body').addClass("fullscreen-spinner-body"); setTimeout(function(){ $('.fullscreen-spinner').fadeOut(300); }, 2000); setTimeout(function(){ $('.fullscreen-spinner').remove(); $('.headercontainer, .headercontainer-2019, .maincontainer, .mainimage').removeClass("disabled"); $('header, footer').removeClass("disabled-opaque"); $('body').removeClass("fullscreen-spinner-body"); $('#userHeaderImage').addClass("attentionblink-infinite"); }, 2300); setTimeout(function(){ $('#userHeaderImage').removeClass("attentionblink-infinite"); }, 5000); } function changeAccountDialog(urltarget, helptext, mode, modedata){ logging("changeAccountDialog | mode: "+mode); // logging("userChildrenJSON"); // logging(userChildrenJSON); // logging("urltarget"); // logging(urltarget); // logging("helptext"); // logging(helptext); // logging("modedata"); // logging(modedata); var helpHtml = ""; var accountList = ""; if(parentMode == "parent" || parentMode == "child"){ accountList = accountListHtml(userChildrenJSON, urltarget, mode, modedata); } else { return false; } if(helptext){ helpHtml = '
    '+helptext+'
    '; } BootstrapDialog.show({ title: 'Switch account', message: helpHtml+accountList, closable: true, type: BootstrapDialog.TYPE_PRIMARY, cssClass: 'dialog-change-account dialog-gray-bg '+parentMode, onshow: function(dialog) { dialog.getModalFooter().hide(); } }); } function accountListHtml(data, urltarget, mode, modedata){ var returnHtml = ""; var urlRoutingTarget = ""; if(urltarget){ urlRoutingTarget = 'data-target="'+urltarget+'"'; } if(data && parentMode == "parent"){ $.each(data, function(index, user){ var userImageHtml = ''; if(user.UserImage){ userImageHtml = ''; } // add extra labels for waiver sign info var extraHelp = ""; if(mode == "sign-waiver"){ extraHelp = 'Form not submitted'; if(modedata && modedata.length){ if(modedata.includes(user.UserId)){ extraHelp = ' Form submitted'; } } } returnHtml += ' '+userImageHtml+user.FirstName+' '+user.LastName+extraHelp+''; }); } else { returnHtml = ' Back to parent account'; } if(returnHtml){ returnHtml = '
    '+returnHtml+'
    '; } return returnHtml; } // return country formatted prices, if currency is defined, then returns with € etc marking, otherwise with two digits on user country format function currencyFormat(val,currency){ var langcode = ''; if(!langcode){ langcode = ''; } var val = Number(val); if(currency){ val = val.toLocaleString(langcode, { style: 'currency', currency: currency }); } else { val = val.toLocaleString(langcode, {minimumFractionDigits: 2, maximumFractionDigits: 2}); } return val; } // currency with two values (30,00 - 32,00 €) function currencyFormatRange(smallval, bigval, currency){ var langcode = ''; if(!langcode){ langcode = ''; } var bigval = Number(bigval); var smallval = Number(smallval); bigval = bigval.toLocaleString(langcode, { style: 'currency', currency: currency }); smallval = smallval.toLocaleString(langcode, {minimumFractionDigits: 2, maximumFractionDigits: 2}); var finalval = smallval + ' - ' + bigval; return finalval; } function vatAmountFormat(val,vat,currency){ var val = Number(val); var vat = Number(vat); var langcode = ''; if(!langcode){ langcode = ''; } var finalval = (val - (val / (vat + 100)*100)); if(currency){ finalval = finalval.toLocaleString(langcode, { style: 'currency', currency: currency }); } else { finalval = finalval.toLocaleString(langcode, {minimumFractionDigits: 2, maximumFractionDigits: 2}); } return finalval; } function vatAmounts(val, vat){ var val = Number(val); var vat = Number(vat); var vatlessval = val / (vat + 100)*100; var vatlessval = vatlessval.toFixed(2); var vatamount = val - vatlessval; vatamount = vatamount.toFixed(2); var returnobject = {}; returnobject.vatlessamount = vatlessval; returnobject.vatamount = vatamount; return returnobject; } /* Parse parameters */ /* USE: parameters = parseParms(hash); */ /* alert(parameters['horseremoved']); */ function parseParms(str) { var pieces = str.split("&"), data = {}, i, parts; // process each query pair for (i = 0; i < pieces.length; i++) { parts = pieces[i].split("="); if (parts.length < 2) { parts.push(""); } data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } return data; } // New test var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; var externalLoaded = 0; // if ajax data has been loaded already (1 prevents refreshing) // Function for handling url hash changes function hashAction() { console.log("hashAction"); var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character var multi = hash.split('-'); // split to check if we have more than meets the eye there // all parameters in an array parameters = parseParms(hash); // register complete dialog if(multi[0] == "guide") { accountReadyDialog(); } // edit user profile if(hash == "intercomtest"){ addIntercomTestBanner(); } else if(hash == "settings-feed"){ userFeedSettingsDialog(); } else if(hash == "settings-language"){ changeLanguageDialog(); } else if(hash == "install-app"){ hopotiAppInstall(true); } else if(multi[0] == "settings") { $.get("https://hopoti.com/editprofile", function(data) { settingsDialog("user", data); }); } if(hash == "reloadads"){ // force reloading ads forceAdReload = true; } // edit stable settings if(multi[0] == "stablesettings" && !settingsDialogOpen) { $.get(currentStableLink+"/stablesettings", function(data) { settingsDialog("stable", data); }); } if(multi[0] == "hopotimarketing"){ hopotiBusinessMarketing(); } if(multi[0] == "hopotiservices"){ hopotiBusinessServices(); } if(multi[0] == "hopotiservicesOK"){ hopotiBusinessServices(true); history.replaceState({}, document.title, window.location.pathname + window.location.search + "#hopotiservices"); } } // hashActions ends // !Remove hash with # sign from url function removeHash() { history.pushState("", document.title, window.location.pathname + window.location.search); } // !Change skill labels function relabelSkills(selector) { // console.log("relabelSkills"); // console.log(selector); // $(selector).each(function(index) { var label; var UserLevel = $(this).data("userlevel"); var SkillLevelConfirmed = $(this).data("confirmed"); var maxconfirmed = $(this).data("max-confirmed"); // highest confirmed by stable var NoConfirmation = $(this).data("noconfirmation"); var UnconfirmedLabelHtml = ''; var HorseMinLevel = $(this).data("horselevel"); var HorseMaxLevel = $(this).data("horsemaxlevel"); $(this).empty().append(label); // console.log("SkillLevelConfirmed: "+SkillLevelConfirmed); // console.log("UserLevel: "+UserLevel); // if(UserLevel > 0 && !NoConfirmation){ if(maxconfirmed){ if(maxconfirmed < UserLevel){ $(this).append(UnconfirmedLabelHtml); } } else { if(!SkillLevelConfirmed){ $(this).append(UnconfirmedLabelHtml); } } // if(maxconfirmed < UserLevel){ // console.log("this??"); // $(this).append(UnconfirmedLabelHtml); // } else if(!SkillLevelConfirmed){ // $(this).append(UnconfirmedLabelHtml); // } //if(SkillLevelConfirmed != 1 && UserLevel > 0){ //} } else if(!NoConfirmation){ if(UserLevel > 0){ // $(this).append(UnconfirmedLabelHtml); } } // if(SkillLevelConfirmed && !NoConfirmation){ // // if(SkillLevelConfirmed != 1 && UserLevel > 0){ // $(this).append(UnconfirmedLabelHtml); // } // // } else if(!NoConfirmation){ // if(UserLevel > 0){ // $(this).append(UnconfirmedLabelHtml); // } // } if(HorseMaxLevel != null){ // is horse $(this).empty(); var skillSlotsHtml = '
    0
    1
    2
    3
    4
    '; $(this).append(skillSlotsHtml); if(HorseMinLevel == "0"){ $(this).find(".level0").addClass("selected"); } else if (HorseMinLevel == 1) { $(this).find(".level1").addClass("selected"); } else if (HorseMinLevel == 2) { $(this).find(".level2").addClass("selected"); } else if (HorseMinLevel == 3) { $(this).find(".level3").addClass("selected"); } else if (HorseMinLevel == 4) { $(this).find(".level4").addClass("selected"); } if (HorseMaxLevel == 1) { $(this).find(".level1").addClass("selected"); } else if (HorseMaxLevel == 2) { $(this).find(".level2").addClass("selected"); } else if (HorseMaxLevel == 3) { $(this).find(".level3").addClass("selected"); } else if (HorseMaxLevel == 4) { $(this).find(".level4").addClass("selected"); } if (HorseMaxLevel != HorseMinLevel){ $(this).find(".selected").first().nextUntil(".selected").addClass("selected"); } } else { // is user if(UserLevel == 0){ label = "No experience"; } else if (UserLevel == 1) { label = "Beginner"; } else if (UserLevel == 2) { label = "Basic skills"; } else if (UserLevel == 3) { label = "Advanced"; } else if (UserLevel == 4) { label = "Experienced"; } else { label = "-"; } $(this).append(label); if(viewmode == "xxs"){ $(this).popover({placement : 'top'}); } } }); } // relabelSkills ends // !relabelCurrency // parse all selected classes for values and convert those to localized prices if contains only numbers, dots and commas - otherwise use as it is function relabelCurrency(selector) { $(selector).each(function(index) { var value = $(this).data("value"); var currency = $(this).data("currency"); var finalvalue = value; var isValid = /^[0-9,.]*$/.test(value); if(isValid){ // turn comma to dot if(value.toString().indexOf(",") >= 0){ value = value.replace(/,/, '.'); } value = parseFloat(value).toFixed(2); finalvalue = currencyFormat(value,currency); } $(this).html(finalvalue); }); } // !escape special characters function htmlEscape(str) { if(str){ return str .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); } } // !unescape special characters function htmlUnescape(str){ if(str){ return str .replace(/"/g, '"') .replace(/'/g, "'") .replace(/</g, '<') .replace(/>/g, '>') .replace(/&/g, '&'); } } //!Progress counter function progressBarCounter(index,total,element,custommessage){ var progressCounter = index + 1; $(element).removeClass("hidden"); console.log(progressCounter+'/'+total); if(progressCounter >= total){ console.log("progress done"); } fetchprogress = Math.floor(((progressCounter)/total)*100); fetchprogress = fetchprogress + "%"; if(custommessage){ $(element).find('.progress-bar').css('width', fetchprogress).html(custommessage); } else { $(element).find('.progress-bar').css('width', fetchprogress).html(fetchprogress); } } // !parse stable like links [fav] function parseFavStableLinks(target){ $(target).each(function() { var stablefav = $(this).attr("data-fav"); var helpText = 'Add to favourites'; var icon = 'glyphicon-heart-empty'; if(stablefav == 1){ helpText = 'Remove from favourites'; icon = 'glyphicon-heart'; } if(!myUserId || myUserId < 0){ helpText = 'Sign in to add favourites!'; } var buttonHtml = '\
    '+helpText+'
    \ \ '; $(this).empty().html(buttonHtml).removeClass("disabled open disabled-opaque"); }); } // !Add date selector for calendar var settingDate = 0; function addDateSelectorForCalendar(target, view, optTarget, forceadd, placement, container){ settingDate = 1; var target = $(target); var calendarDateSelectorAdded = target.data("dateselector-added"); console.log("addDateSelectorForCalendar | added:"+calendarDateSelectorAdded); var placementTooltip = 'top'; var placementDatepicker = 'auto'; if(placement == 'bottom'){ placementTooltip = 'bottom'; placementDatepicker = 'bottom'; } var pickerContainer = '.fc-header-toolbar'; if(container){ pickerContainer = container; } var currentCalendarDate = $(target).fullCalendar('getDate'); var currentCalendarDatepicker = currentCalendarDate.format('DD.MM.YYYY'); if(!calendarDateSelectorAdded || forceadd){ if(forceadd){ target.find('.calendar-selectday').remove(); } calendarButtonTooltip = ' data-toggle="tooltip" data-placement="'+placementTooltip+'" data-container="'+pickerContainer+'" title="Select day"'; if(viewmode == "xs" || viewmode == "xxs"){ calendarButtonTooltip = ""; } var calendarButton = '\ '; if(optTarget){ $(optTarget).find('.calendar-selectday').remove(); $(optTarget).prepend(calendarButton); } else { //target.find('.fc-left .fc-button-group').prepend(calendarButton); target.find('.fc-left').prepend(calendarButton); } // var currentCalendarDate = $(target).fullCalendar('getDate'); // var currentCalendarDatepicker = currentCalendarDate.format('DD.MM.YYYY'); var currentCalendarDateBackend = currentCalendarDate.format("YYYY-MM-DD"); var calendarDayOptions = { format: 'dd.mm.yyyy', // dd.mm.yyyy autoclose: true, language: 'en-GB', // fi todayHighlight: true, todayBtn: true, calendarWeeks: true, orientation: placementDatepicker, container: container, weekStart: 1 } $('.calendar-selectday').datepicker(calendarDayOptions); $('.calendar-selectday').datepicker('setDate', currentCalendarDatepicker); $('.calendar-selectday').on('changeDate', function() { if(!settingDate){ var menuSelectedDate = $(this).datepicker('getDate'); target.fullCalendar('gotoDate', menuSelectedDate); $('.tooltip').hide(); } }); $('.calendar-selectday').on('click', function() { $('.tooltip').hide(); }); target.attr("data-dateselector-added", 1); $('[data-toggle="tooltip"]').tooltip(); calendarDateSelectorAdded = 1; } var buttonTitle; var pickerDate; // if(view && view.title){ // use calendar title format if available // buttonTitle = view.title; // pickerDate = view.start.format('DD.MM.YYYY'); if(view && view.intervalStart && view.intervalEnd){ // use calendar view settings if available var startingmoment = view.intervalStart.clone(); var endingmoment = view.intervalEnd.clone().subtract(1, "days"); // select previous from end moment if(startingmoment.isSame(endingmoment, 'day')){ buttonTitle = startingmoment.format("DD/MM/YYYY"); } else { buttonTitle = formatDateRange(startingmoment, endingmoment); } pickerDate = startingmoment.format('DD.MM.YYYY'); } else { buttonTitle = currentCalendarDate.format("DD/MM/YYYY"); pickerDate = currentCalendarDatepicker; } if(optTarget){ $(optTarget).find('.calendar-selectday-title').html(buttonTitle); } else { target.find('.calendar-selectday-title').html(buttonTitle); } $('.calendar-selectday').datepicker('setDate', pickerDate); // set any possible targets for custom date display (printing) $('body').find('.calendar-date-target').html(buttonTitle); settingDate = 0; } // !Add custom next prev buttons to calendar function addNextPrevButtonsForCalendar(target, labels, buttondiv, view) { console.log("addNextPrevButtonsForCalendar"); var elementtarget; if(buttondiv){ elementtarget = $(buttondiv); } else { elementtarget = $(target); } elementtarget.each( function(index, e){ var elem = $(e); var calendarNextPrevAdded = elem.data("nextprevbuttons-added"); var buttonAmount = 2; var naviStyle = "arrow"; var addCalendarButton = 0; var scrollTarget =""; if(buttondiv){ if($(buttondiv).attr("data-navi-style")){ naviStyle = elem.attr("data-navi-style"); } if($(buttondiv).attr("data-calendar-button")){ addCalendarButton = elem.attr("data-calendar-button"); } if($(buttondiv).attr("data-scroll-target")){ scrollTarget = 'data-scroll-target="'+elem.attr("data-scroll-target")+'"'; } } if(calendarNextPrevAdded){ return false; } var prevLabel = ''; var nextLabel = ''; var prevClass = ""; var currentClass = ""; var nextClass = ""; if(naviStyle == "month"){ var prevGone = view.intervalStart < moment(); if(prevGone){ prevClass = " gone"; } var currentGone = view.intervalEnd < moment(); if(currentGone){ currentClass = " gone"; } var nextGone = view.intervalEnd.clone().add(1, "month") < moment(); if(nextGone){ nextClass = " gone"; } var prevThis = view.intervalStart.clone() < moment().add(1, "month") && moment().add(1, "month") < view.intervalEnd.clone(); if(prevThis){ prevClass = " this-month"; } var currentThis = view.intervalStart.clone() < moment() && moment() < view.intervalEnd.clone(); if(currentThis){ currentClass = " current-this-month"; } var nextThis = view.intervalStart.clone() < moment().subtract(1, "month") && moment().subtract(1, "month") < view.intervalEnd.clone(); if(nextThis){ nextClass = " this-month"; } prevLabel = view.intervalStart.clone().subtract(1, "month").format('MMMM'); nextLabel = view.intervalStart.clone().add(1, "month").format('MMMM'); } else if(labels){ prevLabel = ' Older'; nextLabel = 'Newer '; } var dateButton = ""; if(view){ if(addCalendarButton){ var dateButtonTitle = view.intervalStart.format('MMMM YYYY'); dateButton = '\ \ '; buttonAmount++; } } var buttonHtml = '\ '; elem.find('.nextprev-buttons-custom').remove(); elem.append(buttonHtml); if(!buttondiv){ // static next/prev label buttons, do not rerender always elem.attr("data-nextprevbuttons-added", 1); } }); } // !MODAL add or edit unregistered user under reservecourse / stable clients / family account var openDialog; var selectedActiontype; var addunregisteredClientModalOpen = 0; function addunregisteredClientModal(actiontype, identifier) { if(addunregisteredClientModalOpen){ return false; } addunregisteredClientModalOpen = 1; selectedActiontype = actiontype; console.log("addunregisteredClientModal / " + actiontype); var dialogTitle = 'Add participant'; var dialogAcceptText = 'Add'; var passwordContent = ''; var toggleContent = ''; var addchildRequired = ''; var ageRequired = ''; var measuresRequired = ' required="required"'; var phoneRequired = ""; var randomid = Math.floor(Math.random()*10000000); var notesHtml = '\
    \
    \ \ \
    \
    \ State here if the participant has any medical or other conditions the riding instructors should be aware of, such as epilepsy, diabetes, visual impairment, etc. This information is only visible to service provider personnel.\
    \
    '; if(actiontype == 'new-child' || actiontype == 'edit-child'){ // password part only for adding child accounts and not editing addchildRequired = "required"; ageRequired = 'required'; toggleContent = '\
    \ \
    \ '; passwordContent = '\ \ '; dialogTitle = 'New account'; if(identifier){ dialogTitle = 'Edit child account'; dialogAcceptText ='Save changes'; } addclienthelp1 = 'Add a child without existing Hopoti account. Fill in the fields as accurately as possible so that the business gets precise information about the client.'; if(actiontype == 'edit-child'){ addclienthelp1 = 'Fill in the fields as accurately as possible so that the business gets precise information about the client.'; } addclienthelp2 = ''; phoneRequired = " required"; } else if(actiontype == 'new-client' || actiontype == 'edit-client' || actiontype == "new-client-lesson"){ measuresRequired = ""; dialogTitle = 'Add a new client'; addclienthelp1 = 'In general, clients should register themselves, then email addresses and other information will be filled in correctly. However, you can use this form to create a client account by asking the client for the required information. The client will receive a Hopoti invitation by email and they can agree on rules and other terms with their own device. Once an account has been created, it can be used immediately for upkeeping.'; addclienthelp2 = 'A client can be added also without an email address. This way, the created preliminary account is meant for temporary use - a client cannot receive notifications about lessons or sign in to their account.'; var notesHtml = '\
    \
    \ \ \
    \
    \ This information is not visible to the customer\
    \
    '; if(identifier){ dialogTitle = 'Edit preliminary client'; dialogAcceptText ='Save changes'; } } else { // add/edit friend addclienthelp1 = 'Add participant without a Hopoti account. Fill in the fields as accurately as possible so that the service provider gets precise information about the client.'; addclienthelp2 = 'By filling in the email, you can rest assured that the event entry information will be also sent to the participant. The participant can then log in to Hopoti with their email address and control their events and other information.'; if(identifier){ dialogTitle = 'Edit participant'; dialogAcceptText ='Save changes'; } } var addunregisteredClientContent = '\
    \ \ \
    \
    \
    \ '+addclienthelp1+'\
    \ '+toggleContent+'\
    \
    \
    \ '+addclienthelp2+'\
    \
    \
    \
    \
    \ \ \
    \
    \
    \ \ \
    \
    \
    \ \ \
    \
    \
    \ \ \
    \
    \
    \ \ '+ passwordContent +'\
    \ \
    \ \
    \ \ kg\
    \ \
    \
    \ \
    \ \ lb\
    \ \
    \
    \ \
    \ \ st\ \ lb\
    \ \
    \ \
    \ \
    \ \ cm\
    \ \
    \
    \ \
    \ \ in\
    \ \
    \
    \ \
    \ \ ft\ \ in\
    \ \
    \ \
    \ '+notesHtml+'\ \ \ \ \
    \ '; BootstrapDialog.show({ size: BootstrapDialog.SIZE_WIDE, title: dialogTitle, message: addunregisteredClientContent, type: BootstrapDialog.TYPE_PRIMARY, cssClass: 'dialogAddnewClient', closable: false, buttons: [{ id: 'btn-ok', label: ' '+dialogAcceptText, cssClass: 'btn-success btn-sm pull-left', autospin: false, action: function(dialogRef){ openDialog = dialogRef; $(document).find('.addnewparticipantform').submit(); } },{ id: 'btn-cancel', label: ' Cancel', cssClass: 'btn-default btn-sm', autospin: false, action: function(dialogRef){ dialogRef.close(); } }], onshow: function(){ fullScreenModalOpen = 1; }, onshown: function(){ var selectedParticipant; attachDatepickers("user-birthdate", 2); if(selectedActiontype == 'new-child'){ checkTelInputFields(); $('input[data-toggle=toggle]').bootstrapToggle(); $('.addclienthelp-2 .independent-login-off').removeClass("hidden"); loadSkills(0); } else if(selectedActiontype == 'edit-child') { $('input[data-toggle=toggle]').bootstrapToggle(); $('.addnewparticipantform').addClass("disabled"); var query = "childUserId="+identifier; // load child data $.post( '/getChildInfo', query, function(data){ //alert('Saved successfully - the page will be updated for the changes to take effect.'); //window.location.reload(); }).done(function(data){ var childUserName = data[0].UserName; var childFirstName = data[0].FirstName; var childLastName = data[0].LastName; var childSkillLevel = data[0].SkillLevel; var childWeight = data[0].Weight; var childHeight = data[0].Height; var childNote = data[0].Note; var childContactInfoValue = data[0].ContactInfoValue; var childBirth = data[0].Birth; if(childFirstName){ $('.addnewparticipantform input[name="userFirstname"]').val(childFirstName); } if(childLastName){ $('.addnewparticipantform input[name="userLastname"]').val(childLastName); } if(childSkillLevel > -1){ loadSkills(childSkillLevel); } if(childWeight){ $('.addnewparticipantform input[name="userWeight"]').val(childWeight).change(); } if(childHeight){ $('.addnewparticipantform input[name="userHeight"]').val(childHeight).change(); } if(childNote){ $('.addnewparticipantform textarea[name="userNote"]').val(childNote); } if(childContactInfoValue){ $('.addnewparticipantform input[name="userPhone"]').data("initial-value", childContactInfoValue); } if(childBirth && childBirth != "0000-00-00"){ var birthdate = moment(childBirth, "YYYY-MM-DD").toDate(); $('.addnewparticipantform input.user-birthdate').datepicker('setDate', birthdate); } $('.addnewparticipantform input[name="childUserId"]').val(identifier); if(childUserName){ temporaryUserExtension = '@random.hopoti.com'; if(childUserName.indexOf(temporaryUserExtension) != -1){ // is temporary user $('.addnewparticipantform .independent-login-off').removeClass("hidden"); } else { // is proper user with mail $('.addnewparticipantform .addclienthelp-2').hide(); $('.addnewparticipantform .checkbox').hide(); } } checkTelInputFields(); $('.addnewparticipantform').removeClass("disabled"); }).fail(function(xhr, status, error) { BootstrapDialog.show({ title: 'Saving failed for some reason', message: 'This may be because of the information you entered, a weak Internet connection or temporary disruption in the service. Please check the information you entered and your Internet connection and try again in a moment. If the problem persists, contact our customer service.', buttons: [{ label: 'OK', action: function(failDialog) { failDialog.close(); //dialog.close(); } }], closable: false, type: BootstrapDialog.TYPE_DANGER }); }); } else if(selectedActiontype == 'edit-client') { getStableTempCustomerInfo(identifier); } else if(selectedActiontype == 'new-friend' || selectedActiontype == 'edit-friend' ) { $('.independent-login-email').removeClass("hidden"); if(identifier > -1){ selectedParticipant = selectedParticipants[identifier]; console.log("selectedParticipant"); console.log(selectedParticipant); // Populate form $('input[name="index"]').val(identifier); $('input[name="userFirstname"]').val(selectedParticipant.FirstName); $('input[name="userLastname"]').val(selectedParticipant.LastName); $('.addnewparticipantform input[name="userPhone"]').data("initial-value", selectedParticipant.userPhone); $('textarea[name="userNote"]').val(selectedParticipant.userNote); $('input[name="userWeight"]').val(selectedParticipant.userWeight); $('input[name="userHeight"]').val(selectedParticipant.userHeight); $('input[name="action"]').val(selectedParticipant.action); if(selectedParticipant.userBirth && selectedParticipant.userBirth != "0000-00-00"){ var birthdate = moment(selectedParticipant.userBirth, "YYYY-MM-DD").toDate(); $('.addnewparticipantform input.user-birthdate').datepicker('setDate', birthdate); } if(selectedParticipant.SkillLevel){ loadSkills(selectedParticipant.SkillLevel); } else { loadSkills(0); } if(selectedParticipant.UserName){ $('input[type="email"]').val(selectedParticipant.UserName); } } else { loadSkills(0); } checkTelInputFields(); } else { $('.independent-login-email').removeClass("hidden"); checkTelInputFields(); } $("[data-toggle=popover]").popover(); $('.addnewparticipantform').validator('update'); // force validation on editing if(selectedActiontype == 'edit-friend' || selectedActiontype == 'edit-child' || selectedActiontype == 'edit-client' || selectedActiontype == 'new-client-lesson' ){ setTimeout(function(){ $('.addnewparticipantform').validator('validate'); }, 1000); } }, onhide: function(){ fullScreenModalOpen = 0; addunregisteredClientModalOpen = 0; } }); }// full screen modal for add unregistered user ends // !SUBMIT Add new participant dialog $(document).on('submit', '.addnewparticipantform', function(e){ if (e.isDefaultPrevented()) { // handle the invalid form... } else { // everything looks good! e.preventDefault(); $('#btn-ok').addClass("disabled"); if(selectedActiontype == "new-child"){ submitNewChildAccount("new-child"); } else if(selectedActiontype == "edit-child") { submitNewChildAccount("edit-child"); } else if(selectedActiontype == "new-friend" || selectedActiontype == "edit-friend") { var formdata = getFormData($('.addnewparticipantform')); var userbirth = ""; var userbirthdate = $('.addnewparticipantform .user-birthdate:visible').datepicker('getDate'); if(moment(userbirthdate).isValid()){ var converteddate = moment(userbirthdate).format("YYYY-MM-DD"); formdata.userBirth = converteddate; } formdata.action = selectedActiontype; addNewFriend(formdata, selectedActiontype); openDialog.close(); } else if(selectedActiontype == "new-client" || selectedActiontype == "new-client-lesson"){ submitNewClientAccount(selectedActiontype); } else if(selectedActiontype == "edit-client"){ submitTempClientEdit(); } } }) // !POST new child account data function submitNewChildAccount(actiontype){ var query = $('.addnewparticipantform').serialize(); console.log(query); var reserveServicePage = false; if($('body').hasClass("page-reserveservice-v1")){ reserveServicePage = true; } if(actiontype == "new-child"){ submiturl = "/addNewChild"; } else { // edit submiturl = "/editChild"; } var userbirth = ""; var userbirthdate = $('.addnewparticipantform .user-birthdate:visible').datepicker('getDate'); if(moment(userbirthdate).isValid()){ var converteddate = moment(userbirthdate).format("YYYY-MM-DD"); userbirth = '&userBirth='+converteddate; } $.post( submiturl, query+userbirth, function(data){ // console.log("after submit child!"); // console.log(data); if(reserveServicePage){ loadFriends("buy-service", data); } else { // editing under user settings alert('Saved successfully - the page will be updated for the changes to take effect.'); window.location.reload(); } }) .fail(function(xhr, status, error) { BootstrapDialog.show({ title: 'Saving failed for some reason', message: 'This may be because of the information you entered, a weak Internet connection or temporary disruption in the service. Please check the information you entered and your Internet connection and try again in a moment. If the problem persists, contact our customer service.', buttons: [{ label: 'OK', action: function(failDialog) { failDialog.close(); //dialog.close(); } }], closable: false, type: BootstrapDialog.TYPE_DANGER }); }).always(function() { $('#btn-ok').removeClass("disabled"); }); } //!Load friends [services] function loadFriends(action, actiondata){ console.log("loadFriends | action: "+action); $.ajax({ url: '/profile//friends', type: 'POST', error: function(err) { }, success: function(data) { // console.log("after friends reload!"); // console.log(data); if(action == "buy-service"){ friendsJSON = data; friendsJSON.push(myInfoObject); if(actiondata && actiondata[0].UserId){ addFriendToService(actiondata[0].UserId); } buildParticipantSelection(selectedParticipants, participantCount, serviceTags); openDialog.close(); } } }); } //!Menu stable search function function searchAndFilter(searchTerm) { $('.menu-stable-hidden').addClass("hidden"); if (searchTerm == '') { $("#topFavStables li").show() } else { $("#topFavStables li a.favStableLink").each(function() { var currentText = $(this).text(); currentText = currentText.toUpperCase(); searchTerm = searchTerm.toUpperCase(); if (currentText.indexOf(searchTerm) >= 0) { $(this).parent().removeClass("hidden").show(); } else { $(this).parent().hide(); } }); } } // !Build common event calendar - list courses function buildCommonEventCalendar(data, targetelement, mode, userid){ console.log("buildCommonEventCalendar"); if(!data.length || !targetelement){ return false; } $(targetelement).empty(); if(!mode){ mode = "admin"; } var listTitle = 'Lessons related to invoice'; if($(targetelement).data("list-title")){ listTitle = $(targetelement).data("list-title"); } var calendarId = 'invoicecourses'; if($(targetelement).data("calendar-id")){ calendarId = $(targetelement).data("calendar-id"); } var targetInputField; if($(targetelement).data("select-input")){ targetInputField = $(document).find('#'+$(targetelement).data("select-input")); } var editPpButton = ""; $(targetelement).addClass("panel panel-default"); $(targetelement).attr('id', calendarId); instanceCalEvents = []; var firstdate; var firstEventId; var deletedAmount = 0; var deletedAlert = ""; $.each(data, function (index, value) { // get first invoice date var currentinvoicedate = value['EventStartDateTime'].substr(0, 10); var currentinvoicedatemoment = moment(currentinvoicedate); if(currentinvoicedatemoment < moment(firstdate)){ firstdate = currentinvoicedate; } if(!firstEventId){ firstEventId = value.EventInstanceId; } if(value.Deleted){ deletedAmount++; } instanceCalEvents.push({ id: value['EventInstanceId'], title: value['InstanceName'], start: value['EventStartDateTime'], end: value['EventEndDateTime'], usermaxcount: value['UserMaxCount'], reservationcount: value['ReservedCount'], eventprice: value['EventPrice'], eventsalesstatustypeid: value['EventSalesStatusTypeId'], deleted: value['Deleted'] }); }); if(mode == "admin"){ var editPppButton = $('body').find('.dialog-edit-pending-payment-plan .change-ppp-events'); editPppButton.removeClass("hidden"); editPppButton.attr("data-userid", userid); editPppButton.attr("data-eventinstanceid", firstEventId); var markAsPaidButton = $('body').find('.dialog-edit-pending-payment-plan .invoice-mark-paid'); markAsPaidButton.attr("data-invoice-lesson-amount", data.length); } var selectButtons = ""; if(mode == "select" || mode == "select-preselect"){ selectButtons = '\
    \ \ Select all\ \ \ Remove selection\ \
    ' } var panelHtml = '\ \
    \
    \ '+selectButtons+'\ \
    \
    '; $(targetelement).append(panelHtml); if(mode == "user" && deletedAmount){ // show alert under user var amountString = ' lesson'; if(deletedAmount > 1){ amountString = ' lessons'; } var deletedHelp = 'Some invoice-related lessons have been canceled on behalf of the business. When the invoice is paid you will receive Stablecard credits ([x]) with which to book a replacement lesson.'.replace("[x]", ''+deletedAmount+amountString+''); deletedAlert = '\ '; $(targetelement).parent().prepend(deletedAlert); } var ntoday = new Date().getTime(); var offset = new Date().getTimezoneOffset() ntoday = ntoday - offset; var renderedEventIds = []; // already rendered events to block multiday event extra rows var tooltipPlacement = "left"; var viewmode = $('body').attr("data-viewmode"); $(targetelement).find('.common-event-calendar-courses').fullCalendar({ defaultView: 'agendaYearList', events: instanceCalEvents, defaultDate: moment(firstdate), // show list based on first event date locale: 'en-GB', timeFormat: 'HH:mm', titleFormat: 'DD/MM/YYYY', slotLabelFormat: 'HH:mm', views: { agendaYearList: { type: 'listYear', duration: { months: 24 }, } }, eventClick: function(event, jsEvent, view) { if(mode == "select" || mode == "select-preselect"){ if($(jsEvent.target).hasClass("btn")){ // exclude button clicks under list element return false; } $(this).toggleClass("selected"); if(targetInputField){ // pick event ids to separate input field if present var currentValues = targetInputField.val(); var currentValueArray = []; if(currentValues){ currentValueArray = currentValues.split(","); } if(currentValueArray.indexOf(event.id.toString()) > -1){ currentValueArray.splice(currentValueArray.indexOf(event.id.toString()), 1); } else { currentValueArray.push(event.id.toString()); } targetInputField.val(currentValueArray).change(); } } }, eventRender: function(event, element, view) { var buttons = ""; var preselectedClass = ""; startDateTime = moment(event.start, "YYYY-MM-DD HH:mm"); endDateTime = moment(event.end, "YYYY-MM-DD HH:mm"); eventStartTime = moment(event.start).format("HH:mm"); eventEndTime = moment(event.end).format("HH:mm"); eventStartDate = moment(event.start).format("DD/MM/YYYY"); eventEndDate = moment(event.end).format("DD/MM/YYYY"); eventStartDayname = moment(event.start).format('dd'); eventEndDayname = moment(event.end).format('dd'); var eventGone = 0; // filter off all already rendered multiday event rows var eventAlreadyRendered = commonmatch(event.id, renderedEventIds); if(eventAlreadyRendered.length){ return false; } if (!endDateTime){ if (startDateTime < ntoday){ eventGone = 1; } } else { if (endDateTime < ntoday){ eventGone = 1; } } renderedEventIds.push(event.id); var unpaidClass = ""; if(event.userhaspaid != 1){ unpaidClass = " pending-danger"; } var deletedClass = ""; var deletedHelp = ""; if(event.deleted){ deletedClass = " event-deleted"; deletedHelp = 'Event deleted'; } eventTimes = ''+eventStartDate+' ('+eventStartDayname+') '+eventStartTime+'-'+eventEndTime; if(eventEndDate != eventStartDate){ eventTimes = ''+eventStartDate+' ('+eventStartDayname+') '+eventStartTime+' - '+eventEndDate+' ('+eventEndDayname+') '+eventEndTime; } var eventSymbols = ""; if(mode == "select" || mode == "select-preselect"){ unpaidClass = ""; eventSymbols = ' '; } if(mode == "select-preselect"){ preselectedClass = " selected"; } var eventMeta = '\ \ '+event.reservationcount+' / '+event.usermaxcount+'\ \ \ \ '; if(mode == "user"){ eventMeta = ""; } if(mode == "select" || mode == "select-preselect"){ eventMeta = ""; if(!event.deleted){ // do not show event edit button if deleted buttons = '\ \ \ '; } if(event.eventsalesstatustypeid == 1){ buttons += ' '; } else if(event.eventsalesstatustypeid == 2){ buttons += ' '; } } // build a custom returned element calendarRowHtml = '\ \ \ '+eventSymbols+eventTimes+'\ \ \ '+buttons+event.title+deletedHelp+'\ \ '+eventMeta+'\ \ '; return $(calendarRowHtml); }, eventAfterAllRender: function() { $(targetelement).find('.fc-list-heading, .fc-toolbar').remove(); $(targetelement).addClass("common-event-calendar").removeClass("hidden"); $("[data-toggle=tooltip]").tooltip(); if(mode == "select-preselect" && targetInputField){ targetInputField.val(renderedEventIds).change(); $(targetelement).find('.common-event-calendar-courses-btn[data-scope="all"]').addClass("disabled"); } if(mode == "select" && targetInputField){ targetInputField.val("").change(); $(targetelement).find('.common-event-calendar-courses-btn[data-scope="none"]').addClass("disabled"); } if(selectButtons){ $(targetelement).find('.common-event-calendar-courses-btn').on('click', function(e) { e.preventDefault(); $(this).addClass("disabled"); if($(this).data("scope") == "all"){ targetInputField.val(renderedEventIds).change(); $(targetelement).find(".fc-list-item").addClass("selected"); //$(targetelement).find('.common-event-calendar-courses-btn[data-scope="none"]').removeClass("disabled"); } else if($(this).data("scope") == "none"){ targetInputField.val("").change(); $(targetelement).find(".fc-list-item").removeClass("selected"); //$(targetelement).find('.common-event-calendar-courses-btn[data-scope="all"]').removeClass("disabled"); } }); } if(targetInputField){ targetInputField.on('change', function(e) { var currentSelectedAmount = 0; if($(this).val()){ currentSelectedAmount = $(this).val().split(',').length; } if(currentSelectedAmount > 0){ $(targetelement).find('.common-event-calendar-courses-btn[data-scope="none"]').removeClass("disabled"); } else { $(targetelement).find('.common-event-calendar-courses-btn[data-scope="none"]').addClass("disabled"); } console.log(renderedEventIds); if(currentSelectedAmount == renderedEventIds.length){ $(targetelement).find('.common-event-calendar-courses-btn[data-scope="all"]').addClass("disabled"); } else { $(targetelement).find('.common-event-calendar-courses-btn[data-scope="all"]').removeClass("disabled"); } // renderedEventIds // alert(currentSelectedAmount); }); } } }) } var cancellation; // string var cancellationHtml; // visible content for end user // set up cancellation policy options function setCancellationPolicy(policy, generatelink, target){ if(policy > -1){ cancellationPolicy = policy; } cancelTimeUnit ='hours'; if(cancellationPolicy == 4){ // not cancellable at all cancelTime = ''; cancellation = 'noreturn'; cancellationHtml = 'No return'; cancelTerms = 'No return
    You cannot get refund credits on your Stablecard. If you cannot attend the lesson, you should still cancel it so that the riding instructor will get the information.'; } else { // cancellable if(cancellationPolicy == 3){ cancelTime = '48'; cancellation = 'strict'; cancellationHtml = 'Strict (48h)'; } else if(cancellationPolicy == 1){ cancelTime = '12'; cancellation = 'flexible'; cancellationHtml = 'Flexible (12h)'; } else if(cancellationPolicy == 0){ cancelTime = '0'; cancellation = 'full'; cancellationHtml = 'Full (0h)'; } else { // default 24 if strange values cancelTime = '24'; cancellation = 'standard'; cancellationHtml = 'Standard (24h)'; } cancelTerms = 'Lesson cancel time has expired
    ' + ' The lesson needs to be cancelled '+ cancelTime + ' ' + cancelTimeUnit + ' ' + 'before it starts if you want to receive credits on your Stablecard. If you cannot attend the lesson, you should still cancel it so that the service provider will get the correct information.'; } var policyElement = $('.cancellationPolicy'); var cancellationNoteElement = $('#eventAlertCancelling'); if(target){ policyElement = $(target).find('.cancellationPolicy'); cancellationNoteElement = $(target).find('#eventAlertCancelling'); } policyElement.empty().html(cancellationHtml); cancellationNoteElement.empty().append(cancelTerms); //console.log(cancelTime); if(policy > -1 && generatelink){ cancellationLinkHtml = ''+cancellationHtml+' '; return cancellationLinkHtml; } else { return cancelTime; } } function showPreviousCourseHelp(){ BootstrapDialog.show({ title: 'Horse on lesson before your lesson', message: 'Even though your horse should be ready for riding after the previous lesson, please arrive your lesson well in advance of the starting time. There might be changes to horse assign on the day.', cssClass: 'help-dialog', }); } function showNoPreviousCourseHelp(){ BootstrapDialog.show({ title: 'The horse doesn´t have any lessons before your lesson', message: 'Please arrive for your lesson well in advance of the starting time – your horse doesn´t have any planned lessons before your lesson and is not immediately ready for riding. There might be changes to the horse assign during the day.', cssClass: 'help-dialog', }); } function showNextCourseHelp(){ BootstrapDialog.show({ title: 'Horse is reserved for the next lesson', message: 'After your lesson, the horse will immediately continue to the next lesson. Even so, please set aside some time to take care of the horse, as there might be changes to horse assign during the day.', cssClass: 'help-dialog', }); } function showNoNextCourseHelp(){ BootstrapDialog.show({ title: 'Horse is not reserved for the next lesson', message: 'Your horse won't continue to the next lesson, so set aside some time to take care of the horse. On the day, there might be changes to the horse assign.', cssClass: 'help-dialog', }); } //!Check valid stablecards [services] function checkValidStablecards(wallets, tags, date, returntypes){ console.log("checkValidStablecards"); // console.log(wallets); // console.log(tags); // console.log(date); var resultObject = {}; var compareDate; if(date){ compareDate = moment(date+" 23:59:59", "YYYY-MM-DD HH:mm:ss"); } var validCards = []; var invalidTagsCards = []; var invalidDateCards = []; if(wallets.length){ $(wallets).each( function(index, card){ console.log(card); var datematch = false; var tagsmatch = commonmatch([tags], [card.WalletTags]); var walletValidDate = moment(card.ValidDate, "YYYY-MM-DD HH:mm:ss"); var typematch = true; if(compareDate && walletValidDate >= compareDate){ datematch = true; } if(!compareDate){ datematch = true; } if(returntypes){ // which cards are returned: 1 = stablecard, 4 = membership, 3 = giftcard var typesmatch = commonmatch([returntypes], card.TypeId); if(typesmatch.length){ typematch = true; } else { typematch = false; } } if(typematch){ if(tagsmatch.length && datematch){ validCards.push(card); } else if(!tagsmatch.length){ invalidTagsCards.push(card); } else if(!datematch){ invalidDateCards.push(card); } } }); } if(validCards.length){ resultObject.valid = validCards; } if(invalidTagsCards.length){ resultObject.invalidtags = invalidTagsCards; } if(invalidDateCards.length){ resultObject.invaliddate = invalidDateCards; } if(!$.isEmptyObject(resultObject)){ return resultObject; } else { return false; } } // ! turn form content to json object jQuery.fn.serializeObject = function() { var arrayData, objectData; arrayData = this.serializeArray(); objectData = {}; $.each(arrayData, function() { var value; if (this.value != null) { value = this.value; } else { value = ''; } if (objectData[this.name] != null) { if (!objectData[this.name].push) { objectData[this.name] = [objectData[this.name]]; } objectData[this.name].push(value); } else { objectData[this.name] = value; } }); return objectData; }; //!Unit conversion [units] function unitconversion(changedfield){ // console.log("unitconversion"); var conversion = changedfield.data("unitconversion"); var value = Number(changedfield.val()); var id = changedfield.data("randomid"); var unit = changedfield.data("unit"); var minim = changedfield.attr("min"); var qty; if(isNaN(value)){ return false; } if(minim > 0 && value == 0){ // if minimum set return false; } if(unit == "submit-cm" || unit == "submit-kg"){ if(unit == "submit-cm"){ unit = "cm"; } if(unit == "submit-kg"){ unit = "kg"; } } if(unit == "combo-lb" || unit == "combo-stone"){ if(unit == "combo-lb"){ unit = "lb"; } if(unit == "combo-stone"){ unit = "stone"; } var lbvalue = Number($('input[data-unit="combo-lb"][data-randomid="'+id+'"]').val()); var stvalue = Number($('input[data-unit="combo-stone"][data-randomid="'+id+'"]').val()); var totallb = 14*stvalue + lbvalue; qty = new Qty(totallb, "lb"); } else if (unit == "combo-foot" || unit == "combo-inch"){ if(unit == "combo-foot"){ unit = "foot"; } if(unit == "combo-inch"){ unit = "inch"; } var inchvalue = Number($('input[data-unit="combo-inch"][data-randomid="'+id+'"]').val()); var footvalue = Number($('input[data-unit="combo-foot"][data-randomid="'+id+'"]').val()); var totalinch = 12*footvalue + inchvalue; qty = new Qty(totalinch, "inch"); } else { // normal case qty = new Qty(value, unit); } // target fields $('[data-unitconversion="'+conversion+'"][data-randomid="'+id+'"]').each( function( index, element ){ var convertunit = $(this).attr("data-unit"); if(convertunit == "combo-lb" || convertunit == "combo-stone"){ var convertedqty = qty.to('lb').toPrec('lb').scalar; var totalst = Math.floor(convertedqty / 14); // total stones var restlb = convertedqty - (totalst*14); $('input[data-unit="combo-stone"][data-randomid="'+id+'"]').val(totalst); $('input[data-unit="combo-lb"][data-randomid="'+id+'"]').val(restlb); } else if (convertunit == "combo-foot" || convertunit == "combo-inch"){ var convertedqty = qty.to('inch').toPrec('inch').scalar; var totalfoot = Math.floor(convertedqty / 12); // total stones var restinch = convertedqty - (totalfoot*12); $('input[data-unit="combo-foot"][data-randomid="'+id+'"]').val(totalfoot); $('input[data-unit="combo-inch"][data-randomid="'+id+'"]').val(restinch); } else if (convertunit == "submit-cm"){ var convertedqty = qty.to('cm'); var convertednumber = convertedqty.toPrec(0.01).scalar; $(this).val(convertednumber); } else if(convertunit == "submit-kg"){ var convertedqty = qty.to('kg'); var convertednumber = convertedqty.toPrec(0.01).scalar; $(this).val(convertednumber); } else { var convertedqty = qty.to(convertunit); var convertednumber = convertedqty.toPrec(convertunit).scalar; $(this).val(convertednumber); } }); } var weightUnitPoundCountries = ["us"]; // countries which use pounds weight var weightUnitStoneCountries = ["gb"]; // countries which use stones/pounds combo weight var heightUnitFootCountries = ["gb","us"]; // countries which use inch/foot height function convertunits(target){ var converttarget = $('.convertunits'); if(target){ converttarget = $(target); } var selectedcountry = $('body').attr("countrycode"); $(converttarget).each( function( index, element ){ var value = $(this).data("value"); value = parseFloat(value); if(isNaN(value)){ $(this).html("-"); return true; } var unit = $(this).data("originalunit"); var conversiontype = $(this).data("unitconversion"); var qty = new Qty(value, unit); if(conversiontype == "height" && heightUnitFootCountries.includes(selectedcountry)){ var heightunit = "inch"; // foot/inch var convertedqty = qty.to(heightunit); var convertednumber = convertedqty.toPrec(heightunit).scalar; var totalfoot = Math.floor(convertednumber / 12); // total stones var restinch = convertednumber - (totalfoot*12); $(this).html(''+ totalfoot + "'" + restinch + '"'); // hidden = fix for old column sorting } else if(conversiontype == "weight" && weightUnitStoneCountries.includes(selectedcountry)){ var weightunit = "lb"; // stone/lb var convertedqty = qty.to(weightunit); var convertednumber = convertedqty.toPrec(weightunit).scalar; var totalstone = Math.floor(convertednumber / 14); // total stones var restpound = convertednumber - (totalstone*14); $(this).html('' + totalstone + "st " + restpound + "pd"); } else if(conversiontype == "weight" && weightUnitPoundCountries.includes(selectedcountry)){ var weightunit = "lb"; // lb var convertedqty = qty.to(weightunit); var convertednumber = convertedqty.toPrec(weightunit).scalar; $(this).html('' + convertednumber + "pd"); } else { var convertednumber = qty.to(unit).toPrec(unit).scalar; $(this).html(''+ convertednumber + ' ' + ''+unit+''); // hidden = fix for old column sorting } }); } function returnconvertunit(value, unit, conversiontype){ var selectedcountry = $('body').attr("countrycode"); var returnValue = ""; value = parseFloat(value); if(isNaN(value)){ return "-"; } // var unit = $(this).data("originalunit"); // var conversiontype = $(this).data("unitconversion"); var qty = new Qty(value, unit); if(conversiontype == "height" && heightUnitFootCountries.includes(selectedcountry)){ var heightunit = "inch"; // foot/inch var convertedqty = qty.to(heightunit); var convertednumber = convertedqty.toPrec(heightunit).scalar; var totalfoot = Math.floor(convertednumber / 12); // total stones var restinch = convertednumber - (totalfoot*12); returnValue = totalfoot + "’" + restinch + '”'; } else if(conversiontype == "weight" && weightUnitStoneCountries.includes(selectedcountry)){ var weightunit = "lb"; // stone/lb var convertedqty = qty.to(weightunit); var convertednumber = convertedqty.toPrec(weightunit).scalar; var totalstone = Math.floor(convertednumber / 14); // total stones var restpound = convertednumber - (totalstone*14); returnValue = totalstone + "st" + restpound + "pd"; } else if(conversiontype == "weight" && weightUnitPoundCountries.includes(selectedcountry)){ var weightunit = "lb"; // lb var convertedqty = qty.to(weightunit); var convertednumber = convertedqty.toPrec(weightunit).scalar; returnValue = convertednumber + "pd"; } else { var convertednumber = qty.to(unit).toPrec(unit).scalar; returnValue = convertednumber + unit; } return returnValue; } // !Convert server time stamps to local format (skipping times) function convertDate(target){ var convertdatetarget = $('.convertdate'); if(target){ convertdatetarget = $(target); } $(convertdatetarget).each( function( index, element ){ var value = $(this).data("value"); if(value){ value = value.substr(0, 10); datevaluemoment = moment(value); if(datevaluemoment.isValid()){ $(this).html(datevaluemoment.format('DD/MM/YYYY')); } else { $(this).html("-"); } } }); } function sortByKeyNumDesc(array, key) { // sort array by key, descending return array.sort(function (a, b) { var x = a[key]; var y = b[key]; if(!isNaN(parseFloat(x)) && isFinite(x)){ x = parseInt(x); } if(!isNaN(parseFloat(y)) && isFinite(y)){ y = parseInt(y); } return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }); } function sortByKeyNumAsc(array, key) { // sort array by key, ascending return array.sort(function (a, b) { var x = a[key]; var y = b[key]; if(!isNaN(parseFloat(x)) && isFinite(x)){ x = parseInt(x); } if(!isNaN(parseFloat(y)) && isFinite(y)){ y = parseInt(y); } return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); } function sortByKeyAlpDesc(array, key) { // sort array by key, descending return array.sort(function (a, b) { var x = ""; if(a[key]){ x = a[key].toUpperCase(); } var y = ""; if(b[key]){ y = b[key].toUpperCase(); } return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }); } function sortByKeyAlpAsc(array, key) { // sort array by key, ascending return array.sort(function (a, b) { var x = ""; if(a[key]){ x = a[key].toUpperCase(); } var y = ""; if(b[key]){ y = b[key].toUpperCase(); } return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); } function sortByKey(array, key, direction) { // sort by any key if(direction == "ASC-NUM"){ temparray = sortByKeyNumAsc(array, key); } else if(direction == "DESC-NUM"){ temparray = sortByKeyNumDesc(array, key); } else if(direction == "ASC-ALP"){ temparray = sortByKeyAlpAsc(array, key); } else { temparray = sortByKeyAlpDesc(array, key); } return temparray; } function sortClusterized(key, direction, arrayname, targetelement) { // sort data and refresh clusterized data console.log("sortClusterized"); array = eval(arrayname); console.log(array); temparray = sortByKey(array, key, direction); if(targetelement == ".dialogEditClient"){ customerInvoices = buildClusterizeInvoiceData(temparray); customerInvoicesClusterize.update(customerInvoices); } else { allData = buildClusterizeData(temparray); clusterize.update(allData); } } function filterByKey(array, searchkey, searchvalue) { // filter array by key var results = $.map(array, function(val, key) { searchvalue = jQuery.makeArray(searchvalue); var match = commonmatch(val[searchkey],searchvalue); if(match.length){ return val; } }); return results; } var clusterCacheSearch; var clusterCacheValue; var clusterCacheArrayname; function filterClusterized(searchkey, searchvalue, arrayname, targetelement) { // sort data and refresh clusterized data clusterCacheSearch = searchkey; clusterCacheValue = searchvalue; clusterCacheArrayname = arrayname; array = eval(arrayname); temparray = filterByKey(array, searchkey, searchvalue); workArray = temparray.slice(0); // for sorting just the work array if(targetelement == ".dialogEditClient"){ customerInvoices = buildClusterizeInvoiceData(temparray); customerInvoicesClusterize.update(customerInvoices); } else { allData = buildClusterizeData(temparray); clusterize.update(allData); } } function updateClusterized(){ filterClusterized(clusterCacheSearch, clusterCacheValue, clusterCacheArrayname); } var preferredCountrylist = ["au", "be", "ca", "ee", "fi", "fr", "de", "ie", "nl", "pt", "es", "se", "gb", "us"]; // used for telephone input validation recommendation function htmlRegionContent(action){ //language and region selector for user dialog and post boost console.log("htmlRegionContent | action:"+action); var intButton = ""; if(action == "user-change-region"){ intButton = '\
    '; } var allCountriesButton = ""; var allLanguagesButton = ""; if(action == "admin-post-boost"){ allCountriesButton = '\
    '; allLanguagesButton = '\
    '; } var content = '\
    \
    \
    \

    Country | Country

    \
    \
    \ '+allCountriesButton+'\
    \
    \
    \
    \
    \
    \
    \
    \
    \
    \
    \
    \
    \
    \ '+intButton+'\
    \
    \
    \
    \
    \
    \

    Language | Language

    \
    \
    \ '+allLanguagesButton+'\ \
    \
    \
    \
    \
    \
    \
    \
    \
    \
    \
    \ \
    '; return content; } // Common change language dialog function changeLanguageDialog(noCancel) { changeLanguageDialogButtons = [{ label: 'Save | Save', cssClass: 'btn-success btn-sm', action: function(dialogRef){ this.disable(); this.spin(); var queryOk = true; var query = {}; query.language = $('[data-langcode].active').attr('data-langcode'); query.country = $('[data-countrycode].active').attr('data-countrycode'); if(!query.language){ queryOk = false; } if(!query.country || query.country === "other"){ query.country = ""; } if(queryOk){ store.remove('hopoti-ads'); // remove ads var urlPathArray = window.location.pathname.split('/'); var changeLanguageDialogCode = query.language; if(query.country){ changeLanguageDialogCode += '-'+query.country; } urlPathArray.splice(1, 1, changeLanguageDialogCode); var urlPath = window.location.protocol + "//" + window.location.host + urlPathArray.join("/"); window.location.replace(urlPath); }else{ this.enable(); this.stopSpin(); BootstrapDialog.show({ type: BootstrapDialog.TYPE_WARNING, title: 'Oops!', message: 'Fill in required fields' }); } } }]; if(!noCancel || noCancel == null){ changeLanguageDialogButtons.push({ label: 'Cancel | Cancel', cssClass: 'btn-sm btn-default', action: function(dialogRef){ dialogRef.close(); } }); } BootstrapDialog.show({ size: BootstrapDialog.SIZE_WIDE, closable: false, title: 'Choose | Choose', message: '\
    \ '+htmlRegionContent("user-change-region")+'\
    ', buttons: changeLanguageDialogButtons, onshow: function(dialog){ BootstrapDialog.closeAll(); }, onshown: function(){ var sessionLang = null; var sessionCountry = null; if(sessionCountry){ $('[data-countrycode="'+sessionCountry+'"]').addClass('btn-primary active').removeClass('btn-default'); }else{ $('[data-countrycode="other"]').addClass('btn-primary active').removeClass('btn-default'); } $('[data-langcode="'+sessionLang+'"]').addClass('btn-primary active').removeClass('btn-default'); if($('[data-langcode="'+sessionLang+'"]').hasClass("changeLanguageBeta")){ $('[data-langcode="'+sessionLang+'"]').find(".changeLanguageBetaLabel").show("fast"); $(".changeLanguageBetaNotice").show("fast"); } preferLanguageChange(sessionCountry); } }); } function preferLanguageChange(chosenCountry){ var preferredLanguages = []; switch(chosenCountry){ case 'fi': preferredLanguages = ["fi"]; break; case 'fr': preferredLanguages = ["fr"]; break; case 'se': preferredLanguages = ["sv"]; break; case 'gb': preferredLanguages = ["en"]; break; case 'au': preferredLanguages = ["en"]; break; case 'be': preferredLanguages = ["nl","fr"]; break; case 'nl': preferredLanguages = ["nl"]; break; case 'ie': preferredLanguages = ["en"]; break; case 'ee': preferredLanguages = ["et"]; break; case 'ca': preferredLanguages = ["en","fr"]; break; case 'us': preferredLanguages = ["en"]; break; case 'de': preferredLanguages = ["de"]; break; default: preferredLanguages = ["en"]; } $(".langBtn").css("box-shadow", "0px 0px 0px 0px rgba(6,107,147,0.75)"); $.each(preferredLanguages, function(){ $('[data-langcode="'+this+'"]').css("box-shadow", "inset 0px 0px 5px 0px rgba(6,107,147,0.5)"); }); } // !merge two arrays and remove duplicates function merge(a1, a2) { var hash = {}; var arr = []; for (var i = 0; i < a1.length; i++) { if (hash[a1[i]] !== true) { hash[a1[i]] = true; arr[arr.length] = a1[i]; } } for (var i = 0; i < a2.length; i++) { if (hash[a2[i]] !== true) { hash[a2[i]] = true; arr[arr.length] = a2[i]; } } return arr; } // !get only unique values out of array function unique(list) { var result = []; $.each(list, function(i, e) { if ($.inArray(e, result) == -1) result.push(e); }); return result; } // !return only values which are multiple times in array function onlyMultiple(array){ var originalArray = array; var uniqueArray = unique(array); var finalArray = []; $(uniqueArray).each(function(index, item){ var count = originalArray.filter(function(x){return x==item}).length; // gets amount of occurrences from array if(count > 1){ finalArray.push(item); } }); return finalArray; } // remove duplicate objects from an array of objects (JSON for example) // based on certain selector (id,name, etc) // usege: removeDupIds(objarray,"id") function removeDupIds(objarray,selector) { var list = {}, ids; for (var i = 0; i < objarray.length; i++) { ids = objarray[i][selector]; if (ids in list) { // found a dup id, remove it objarray.splice(i, 1); // correct for loop index so it will process the item // that just moved down in place of the one we just removed --i; } else { // add the id to our map list[ids] = true; } } } // compare two arrays and return true/false if arrays are the same function comparearrays(arr1,arr2){ if(JSON.stringify(arr1) != JSON.stringify(arr2)){ return false; } else { return true; } } function commonmatch(csl1,csl2) { var firstArray = []; var secondArray = []; firstArray = csl1.toString().split(","); secondArray = csl2.toString().split(","); common = []; firstArray.sort(); secondArray.sort(); for(var i = 0; i < firstArray.length; i += 1) { if(secondArray.indexOf( firstArray[i] ) > -1){ common.push( firstArray[i] ); } } return common; } function getServerTime() { return $.ajax({async: false}).getResponseHeader( 'Date' ); } // get from array by id function getById(arr, id) { for (var d = 0, len = arr.length; d < len; d += 1) { if (arr[d].id === id) { return arr[d]; } } } // !Create common minute countdown timers // Rechecks server time once a minute // Usage: // var timerIntervals = []; var recheckinterval; function createTimers(){ console.log("createTimers"); clearTimers(); clearInterval(recheckinterval); $('.timer').each(function () { var obj = $(this); var time = obj.attr("data-time"); // timestamp var remainingSeconds = obj.attr("data-countdown"); // seconds var servertime = obj.attr("data-servertime"); if(servertime){ time = moment.utc(time, "YYYY-MM-DD HH:mm:ss", true); } else { time = moment(time, "YYYY-MM-DD HH:mm:ss", true); } var localDifference = moment().diff(time, 'seconds'); var remainingSeconds = remainingSeconds - localDifference if(remainingSeconds > 0){ timerIntervals.push(setInterval(function(){ remainingSeconds--; if(remainingSeconds > 0 && remainingSeconds < 86400){ duration = moment.duration(remainingSeconds*1000, 'milliseconds'); var remainingHours = duration.hours(); var remainingMinutes = duration.minutes(); var remainingSec = duration.seconds(); if(remainingHours < 1){ remainingHours = ""; } else { remainingHours = remainingHours+":"; } if(remainingMinutes.toString().length < 2){ remainingMinutes = "0"+remainingMinutes; } if(remainingSec.toString().length < 2){ remainingSec = "0"+remainingSec; } formatted = remainingHours+remainingMinutes+':'+remainingSec; } else { formatted = ""; createTimers(); } obj.html(formatted); }, 1000)); } }); if(timerIntervals.length > 0){ recheckinterval = setInterval(function(){ console.log("rechecktimers"); createTimers(); }, 60000); } } function clearTimers(){ timerIntervals.forEach(clearInterval); timerIntervals = []; } //!util function to check if an element has a scrollbar present // usage: var hasScrollbar = dialogRef.getModalBody().hasScrollBar('vertical'); jQuery.fn.hasScrollBar = function(direction) { if (direction == 'vertical') { return this.get(0).scrollHeight > this.innerHeight(); } else if (direction == 'horizontal') { return this.get(0).scrollWidth > this.innerWidth(); } else { // tests either without direction provided var hasScroll = false; if(this.get(0).scrollHeight > this.innerHeight() || this.get(0).scrollWidth > this.innerWidth()){ hasScroll = true; } return hasScroll; } } // Street address formats by company location (not by user location) var addressFormats = { "au": " , ", // australia "fi": " , ", "se": " , ", // sweden "generic": " , " // generic if not defined elsewhere } // !Format address based on country code - by default parses elements with class "format-address" // usage: // function addressFormat(selector){ console.log("addressFormat"); var selected = $('.format-address'); if(selector){ selected = $(selector); } selected.each(function(index, item){ var countryid = $(item).data("countryid"); var addressformat = addressFormats[countryid]; if(!addressformat){ addressformat = addressFormats.generic; } var street = $(item).data("streetname"); var streetno = $(item).data("streetno"); var zipcode = $(item).data("zipcode"); var city = $(item).data("city"); var state = $(item).data("state"); if(!street){ street = ""; } if(!streetno){ streetno = ""; } if(!zipcode){ zipcode = ""; } if(!city){ city = ""; } if(!state){ state = ""; } if(!street && !streetno && !zipcode && !city && !state){ return true; } var mapObj = { '' : street, '' : streetno, '' : city, '' : zipcode, '' : state, }; var convertedAddress = addressformat.allReplace(mapObj); $(this).html(convertedAddress); }); } String.prototype.allReplace = function(obj) { var retStr = this; for (var x in obj) { retStr = retStr.replace(new RegExp(x, 'g'), obj[x]); } return retStr; }; // add date picker button in addition to field and bind events function attachDatepickers(target, startview, todaybutton, onlyfuture){ console.log("attachDatepickers :"+target); var trg; if(target){ trg = $('[data-picker="'+target+'"]'); //console.log(trg); } //var onlypast = 0; var enddate = null; if(target == "user-birthdate"){ // onlypast = 1; enddate = Date.today(); } if(trg.data("limitend")){ // limit end by data attr enddate = moment(trg.data("limitend")).toDate(); } if(startview){ startview = startview; } else { startview = 0; } if(todaybutton){ todaybutton = true; } else { todaybutton = false; } if(onlyfuture){ startdate = Date.today(); } else if(trg.data("limitstart")){ // limit start by data attr startdate = moment(trg.data("limitstart")).toDate(); } else { startdate = null; } trg.each(function(index, item){ // add indexes and extra mobile buttons if(!$(item).attr('data-index')){ $(item).addClass(target).attr('data-index', index); $(item).attr('autocomplete', "off"); var pickerSize = ""; if($(item).hasClass("input-sm")){ pickerSize = " btn-sm"; } var required = "false"; if($(item).attr("required")){ required = "true"; } var mobileDatepicker = ''; $(item).before(mobileDatepicker); } }); $('[data-picker="'+target+'"]').datepicker({ format: 'dd/mm/yyyy', maxViewMode: "years", language: 'en-GB', // fi todayHighlight: true, startView: startview, immediateUpdates: true, autoclose: true, forceParse: true, todayBtn: todaybutton, startDate: startdate, endDate: enddate, weekStart: 1 }).on('changeDate clearDate', function(e) { // console.log("change"); var thisDate = $(this).datepicker('getDate'); var thisIndex = $(this).data("index"); var thisMoment = moment(thisDate); var humanDate = 'Select date'; var thisRequired = $(this).data("required"); if(thisMoment.isValid()){ humanDate = thisMoment.format('DD/MM/YYYY'); } if($(this).hasClass("btn")){ if(thisRequired && !thisMoment.isValid()){ $(this).addClass("required"); } else { $(this).removeClass("required"); } } $('body').find('.btn[data-picker="'+target+'"][data-index="'+thisIndex+'"]').html(' '+humanDate); //Testing $('body').find('.btn[data-picker="'+target+'"][data-index="'+thisIndex+'"]').datepicker('update', thisDate); if($(this).is(":visible")){ // console.log("setinvisible") $('[data-picker="'+target+'"][data-index="'+thisIndex+'"]').not($(this)).datepicker('setDate', thisDate); // change hidden element value } }); } // !Add read more button at the end of the content and compare height to some other element function readMoreContentHeight(target){ // console.log("readMoreContentHeight"); var targets = $('body').find(target); if(targets.length){ targets.each(function(index, item){ console.log(item); var comparisonHeight; var mobile = false; if (viewmode == "xxs" && $(item).data("maxheight-mobile") || viewmode == "xs" && $(item).data("maxheight-mobile")){ comparisonHeight = $(item).data("maxheight-mobile"); mobile = true; } else if($(item).data("compare-element")){ var targetComparison = $(item).data("compare-element"); comparisonHeight = $(targetComparison).outerHeight(); } else if($(item).data("max-height")){ comparisonHeight = $(item).data("max-height"); } else { return true; } var targetHeight = $(item).outerHeight(); // console.log(targetHeight); // console.log(comparisonHeight); if(targetHeight > comparisonHeight || mobile){ $(item).css({ "height" : comparisonHeight+"px" }); var showMoreLabel = '\
    \
    \ Show more \
    \
    '; $(item).append(showMoreLabel); $(item).attr("data-original-height", targetHeight+"px"); $(item).addClass("more-info-button-added"); } }); } } // !Build displayed stablecard function buildDisplayCard(carddata, size, stable){ // console.log("buildDisplayCard"); // console.log(carddata); //console.log(carddata); $('.product-details-card').empty(); var userWalletId; var walletCount; var walletOriginalCount; var userWalletTypeId; var typeId; var walletValidDate; var walletValidDateDb; var useatonce; var walletTags; var userWalletDescription; var stablename; var stablelink; var stablecardStableId; var stablecardTransfermode; var tooltipData = ''; var cardtransferHtml = ''; var cardActions = ''; var stablecardValidDate; var newCard = 0; if(carddata.OriginalCount){ // card is prepurchased existing client card userWalletId = carddata.UserWalletId; walletCount = carddata.Count; walletOriginalCount = carddata.OriginalCount; userWalletTypeId = carddata.UserWalletTypeId; typeId = carddata.TypeId; walletValidDate = carddata.ValidDate; walletValidDateDb = carddata.ValidDate; useatonce = carddata.UseAtOnce; walletTags = carddata.UserWalletTags; userWalletDescription = carddata.Description; if(stable){ stablename = stable; } else { stablename = carddata.StableName; } stablecardStableId = carddata.StableId; stablecardTransfermode = carddata.CardTransferMode; stablelink = carddata.StableLinkName; if(carddata.EventStartDateTime){ var lessonMoment = moment(carddata.EventStartDateTime, "YYYY-MM-DD HH:mm:ss", true); if(lessonMoment.isValid()){ var lessonDate = lessonMoment.format('DD/MM/YYYY HH:mm'); userWalletDescription = userWalletDescription+' '+lessonDate; } } } else { // new card newCard = 1; walletCount = carddata.hours; walletPrice = carddata.price; walletValidDate = carddata.ValidDate; useatonce = carddata.UseAtOnce; walletTags = carddata.WalletTags; userWalletId = carddata.UserWalletId; typeId = carddata.UserWalletTypeId; userWalletDescription = carddata.name; stablename = currentStableName; } var cardtype = "stablecard"; if(typeId == idMemberships){ cardtype = "membership"; } else if (typeId == idGiftcards){ cardtype = "giftcard"; } var validUntil = ''; if(carddata.ValidUntil){ validUntil = carddata.ValidUntil; } else if(carddata.ValidDate){ validUntil = carddata.ValidDate; } var validUntilHtml = 'Valid until [x]'; if(validUntil){ validUntil = moment(validUntil, "YYYY-MM-DD").format('DD/MM/YYYY'); validUntilHtml = validUntilHtml.replace("[x]", ''+validUntil+''); } var imagesubject = "mira-pattern-stablecard.png"; var extraClass = ""; var cardOwner = ""; var cardValue = ""; var cardValid = '
    '+validUntilHtml+'
    '; var cardDots = '
    '; var cardCredits = '
    Credits left
    '; var cardOriginalValue = ""; var expirationNoteHtml = ""; var expirationNoteTooltip = ""; if(cardtype == "membership"){ imagesubject = "drawing-stable-2.png"; extraClass = " membership-card"; if(myUsername){ cardOwner = '

    '+myUsername+'

    '; } cardDots = ""; cardCredits = ""; if(!newCard){ cardActions = '\ '; } } else if (cardtype == "giftcard"){ imagesubject = "drawing-stable-2.png"; extraClass = " gift-card"; cardOwner = ''; cardDots = ""; cardCredits = ""; if(!newCard){ walletCount = currencyFormat(walletCount,carddata.CurrencyKey); walletOriginalCount = currencyFormat(walletOriginalCount,carddata.CurrencyKey); if(walletCount != walletOriginalCount){ cardOriginalValue = '\
    \ Value remaining '+walletCount+'
    \ Original value '+walletOriginalCount+'\
    '; } else { cardOriginalValue = '\
    \ Value '+walletCount+'\
    '; } cardActions = '\ '; } } if(walletValidDate){ var weekFromToday = moment().add(7, 'days'); if(walletValidDate){ walletValidDate = moment(walletValidDate, "YYYY-MM-DD HH:mm:ss"); if(walletValidDate < weekFromToday){ expirationNoteHtml = ''; expirationNoteTooltip = "
    Expiring soon!"; } stablecardValidDateDb = moment(walletValidDateDb, "YYYY-MM-DD HH:mm:ss").toISOString(); stablecardValidDate = walletValidDate.format('DD/MM/YYYY'); } } var tinyInfo = ""; if(size == "big" || size == "small"){ if(size == "small"){ extraClass = extraClass + " order"; } else { extraClass = extraClass + " disorder"; } // tags if(walletTags == null){ walletTags = "2"; } else { walletTags = "2,"+walletTags; } if(stablecardTransfermode > 0){ cardtransferHtml = '\ Transfer credits\ '; } else { cardtransferHtml = '\ Credit cannot be transferred\ '; } if(size == "small"){ tooltipData = ' data-toggle="tooltip" data-trigger="manual" data-original-title="'+stablename+': '+walletCount+'
    '+userWalletDescription+'
    Valid until: '+stablecardValidDate+''+expirationNoteTooltip+'" data-html="true" data-container="body" data-animation="false"'; tinyInfo = '
    '+walletCount+'
    '; } else if (typeId != idMemberships && typeId != idGiftcards){ cardActions = '\
    \ Show valid lessons\ '+cardtransferHtml+'\
    '; } } if(stable){ cardActions = ""; } walletCardHtml ='\
    \ '+expirationNoteHtml+'\ \ '+tinyInfo+'\

    '+stablename+'

    \

    '+userWalletDescription+'

    \ '+cardOwner+'\
    \
    \
    \ '+cardActions+'\ '+cardCredits+'\ '+cardValid+'\ '+cardOriginalValue+'\ '+cardDots+'\
    \
    \
    '; if(size){ return walletCardHtml; } else { $('.product-details-card').append(walletCardHtml); buildStablecardDots(); } } function buildStablecardDots(){ $( ".stableCard" ).each(function() { // fill the credit info var count = $(this).attr("data-count"); $(this).find('.stableCard-dots').empty(); var extraCount; var workCount = count; var iterateCount; if(workCount > 10) { extraCount = workCount - 9; iterateCount = 9; } else { iterateCount = workCount; } for (i = 1; i <= iterateCount; i++) { $(this).find('.stableCard-dots').append('
    '+i+'
    '); } if(extraCount) { $(this).find('.stableCard-dots').append('
    +'+extraCount+'
    ') } $(this).find('.stableCard-credits span').empty().append(workCount); }); } //function swedishIdCheck(a,b,c,d){c='';for(b=d=0;b<10;b++)c+=b!=6?a[b]*(d++%2||2):'';b=0;for(d in c)b+=c[d]*1;return b*9%10==a[10]} function isValidSwedishSSN(ssn) { ssn = ssn .replace(/\D/g, "") // strip out all but digits .split("") // convert string to array .reverse() // reverse order for Luhn .slice(0, 10); // keep only 10 digits (i.e. 1977 becomes 77) // verify we got 10 digits, otherwise it is invalid if (ssn.length != 10) { return false; } var sum = ssn // convert to number .map(function(n) { return Number(n); }) // perform arithmetic and return sum .reduce(function(previous, current, index) { // multiply every other number with two if (index % 2) current *= 2; // if larger than 10 get sum of individual digits (also n-9) if (current > 9) current -= 9; // sum it up return previous + current; }); // sum must be divisible by 10 return 0 === sum % 10; }; // !Replace all text strings String.prototype.replaceAllText = function(searchStr, replaceStr) { var str = this; // no match exists in string? if(str.indexOf(searchStr) === -1) { // return string return str; } // replace and remove first match, and do another recursirve search/replace return (str.replace(searchStr, replaceStr)).replaceAllText(searchStr, replaceStr); } // !Build Checkout Payment options [checkout] function buildCheckoutPaymentoptions(paymentResponse){ console.log("buildCheckoutPaymentoptions"); // if paying under stable or user var mode = "stable"; if($('body').hasClass("pageUserPendingPayments")){ mode = "user"; } var paymentOptions = paymentResponse; var paymentOptionsHtml = ''; if(!paymentResponse){ return false; } var checkoutGrouping = [ { "group": "bank", "title": "Online banking", "amount": 0, "html": "", "logohtml": "" },{ "group": "creditcard", "title": "Card payments", "amount": 0, "html": "", "logohtml": "" },{ "group": "mobile", "title": "Mobile payments", "amount": 0, "html": "", "logohtml": "" },{ "group": "credit", "title": "Credit payments", "helptitle": "Invoice and part payment options", "amount": 0, "html": "", "logohtml": "" },{ "group": "other", "title": "Other", "amount": 0, "html": "", "logohtml": "" } ]; var extraDescriptionOplaskuId = 'oplasku'; var extraDescriptionOplaskuId2 = 'oplaskuV1'; var extraDescriptionOplasku = 'Pay all at once or split the payment into instalments. An invoice received by email will have a payment time of 45 days with no interest added. Credit includes fixed interest rate and monthly service fee. Continue to pay for more details.'; var extraDescriptionCollectorId = 'collectorb2c'; var extraDescriptionCollector = 'Pay all at once or, if you are granted an account credit, you can also split the payment into instalments. You will receive an invoice via email, and you can easily apply for an account credit online. Continue to pay for more details.'; var lastPaymentType; if(store.get('settings-payment')){ lastPaymentType = store.get("settings-payment").lastpaymenttype; } var lastUsedFound = 0; var lastUsedGroup = ""; $('body').find('.checkoutForm').remove(); $('.payment-options').empty(); $.each(paymentOptions, function(key, paymentOption) { // console.log("paymentoption"); var paymentName = paymentOption.name; var paymentCode = paymentOption.id; var paymentGroup = paymentOption.group; var paymentLogo = paymentOption.icon; var formOptions = paymentOption.parameters; var paymentId = paymentCode + "-"+key; var lastUsedHelp = ""; if(paymentId == lastPaymentType && paymentGroup != "credit"){ // exclude credit options from preselected payment type lastUsedFound = 1; lastUsedGroup = paymentGroup; lastUsedHelp = 'Last used payment type'; } var extraDescription = ''; if(paymentCode == extraDescriptionCollectorId){ extraDescription = extraDescriptionCollector; } else if (paymentCode == extraDescriptionOplaskuId || paymentCode == extraDescriptionOplaskuId2){ extraDescription = extraDescriptionOplasku; } if(extraDescription){ extraDescription = '
    '+extraDescription+'
    '; } var extraInfoSetting = 0; if(paymentGroup == "credit"){ extraInfoSetting = 1; } var paymentOptionHtml = '\ '; var groupindex = checkoutGrouping.map(function(d) { return d['group']; }).indexOf(paymentGroup); if(groupindex < 0){ groupindex = checkoutGrouping.map(function(d) { return d['group']; }).indexOf("other"); } var currentamount = 0; currentamount = checkoutGrouping[groupindex].amount; checkoutGrouping[groupindex].amount = currentamount + 1; var currenthtml = ""; currenthtml = checkoutGrouping[groupindex].html; checkoutGrouping[groupindex].html = currenthtml + paymentOptionHtml; var currentlogohtml = ""; currentlogohtml = checkoutGrouping[groupindex].logohtml; if(paymentLogo){ var paymentLogoHtml = ''; checkoutGrouping[groupindex].logohtml = currentlogohtml + paymentLogoHtml; } }); $.each(checkoutGrouping, function(key, paymentGroup) { if(paymentGroup.amount > 0){ var paymentHelp = ""; if(paymentGroup.helptitle){ paymentHelp = ''+paymentGroup.helptitle+''; } var paymentGroupOptionHtml = '\
    \ \
    \
    \ '+paymentGroup.html+'\
    '; paymentOptionsHtml = paymentOptionsHtml + paymentGroupOptionHtml; } }); var checkoutExtraInfoHtml = '\ '; var checkoutFooterHtml = '\
    \ \
    '; var finalOptionsHtml = '
    '+ paymentOptionsHtml + checkoutFooterHtml +'
    '; if(mode == "user"){ // user pay invoice dialog var userDialogExtrainfoWrapper ='\
    \ \
    '; finalOptionsHtml = '
    '+ paymentOptionsHtml + userDialogExtrainfoWrapper + checkoutFooterHtml+'
    '; $('body').find(".dialogPaymentSelection .payments-pendingpayments").append(finalOptionsHtml); $('body').find('#paymentExtraInfo').validator('update'); } else { // under stable $('.payment-options').append(finalOptionsHtml); $('.panel-extra-form').append(checkoutExtraInfoHtml); $('body').find('#paymentExtraInfo').validator('update'); } // if(lastUsedFound){ // removing preselected payment type per eu regulations 16.08.2023 // selectPaymentOption(lastPaymentType, mode); // var target = $('.payment-group-'+lastUsedGroup); // target.addClass("in"); // } } var checkoutPreSubmitConfirmationOk = 0; // !Checkout reminder to return to Hopoti after payment function checkoutPreSubmitConfirmation(mode){ var preSubmitContentHtml = 'Return to Hopoti after the payment!

    After a successful transaction, tap \"Return to service\" or similar button. Don\'t close the window until you see the Hopoti confirmation page. If you close the window immediately after the transaction and before the Hopoti confirmation page, the payment will appear in Hopoti after 1–3 days delay.'; var checkoutPreSubmitConfirmDialog = BootstrapDialog.show({ title: 'You are redirected to payment service', message: preSubmitContentHtml, type: BootstrapDialog.TYPE_WARNING, closable: false, btnOKLabel: 'messages-general.ok', btnOKClass: 'btn-default btn-sm pull-left', buttons: [{ icon: 'glyphicon glyphicon-ok', label: 'OK', cssClass: 'btn-default btn-sm', autospin: false, action: function(dialogRef){ checkoutPreSubmitConfirmationOk = 1; dialogRef.close(); if(mode == "user-invoices"){ submitCheckoutPaymentRequest(); } else { buildSubmitQuery("submit"); } } }] }); checkoutPreSubmitConfirmDialog.open(); } // ! *** Select payment option (bank etc) *** function selectPaymentOption(paymentOptionId, mode){ console.log("selectPaymentOption"); console.log(paymentOptionId); $('.payment-options button, .payment-options-loaded button').removeClass("active"); $('.select-payment-option-button[data-payment-id="'+paymentOptionId+'"]').addClass("active").removeClass("hidden").parent().removeClass("hidden"); var paymentProvider = $('.select-payment-option-button[data-payment-id="'+paymentOptionId+'"]').attr("data-payment-provider"); if(paymentProvider == "checkout") { // checkout } else { // mt $('.select-payment-option-button:not(.active)').parent().slideUp(300); $('.btn-change-payment-type').show().removeClass("hidden"); } selectedPaymentOption = {}; selectedPaymentOption.code = paymentOptionId; selectedPaymentOption.name = $('.select-payment-option-button[data-payment-id="'+paymentOptionId+'"]').attr("data-payment-name"); selectedPaymentOption.extrainfo = $('.select-payment-option-button[data-payment-id="'+paymentOptionId+'"]').attr("data-payment-extrainfo"); selectedPaymentOption.paymentgroup = $('.select-payment-option-button[data-payment-id="'+paymentOptionId+'"]').attr("data-payment-group"); if(viewmode == "xs" || viewmode == "xxs"){ if($("#select-payment").length){ $('html, body').animate({ scrollTop: $("#select-payment").offset().top }, 500); } if(paymentProvider == "checkout") { // hide other checkout options on mobile $('.select-payment-option-button:not(.active)').parent().slideUp(300); $('.select-payment-group-button').removeClass("open"); setTimeout(function(){ $('.select-payment-option-button:not(.active)').parent().addClass("hidden").show(); }, 300); } } if(mode != "user"){ processSelection(); } else { validatePaymentForm(); } } function resetPaymentOption(){ console.log("resetPaymentOption"); $('.payment-options button, .payment-options-loaded button').removeClass("active"); $('.panel-extra-info').addClass("hidden"); $('#summaryPaymentmethod').html(' Please choose payment method') selectedPaymentOption = null; } //!contentAreaSubnaviCheck [scroll] function contentAreaSubnaviCheck(){ if(viewmode == "xs" || viewmode == "xxs"){ // console.log("contentAreaSubnaviCheck"); var subnavielement = $('ul.horizontal-scroll-navi'); subnavielement.find(".scroll-indicator-left, .scroll-indicator-right").remove(); subnavielement.removeClass("scroll-horizontally scroll-right scroll-left"); if(subnavielement.length){ var naviwidth = subnavielement.width(); var contentwidth = 0; $(subnavielement.find('li').not('.hidden-xs')).each(function(index, item){ var itemwidth = $(item).outerWidth(); contentwidth = contentwidth + itemwidth; }); // add scrolling if content doesn't fit if(naviwidth < contentwidth){ subnavielement.addClass("scroll-horizontally scroll-right"); var scrollIndicators = '
  • '; subnavielement.append(scrollIndicators); } // scroll automatically to active navi item only if it doesn't fit to navi var activeItem = subnavielement.find('.active'); if(activeItem.length){ var activeLeft = activeItem.position().left; var activeWidth = activeItem.outerWidth(); if(activeLeft+activeWidth > naviwidth){ $('ul.horizontal-scroll-navi').animate({scrollLeft: activeLeft-15}, 700); } } } } } //!horizontalScrollCheck [scroll] function horizontalScrollCheck(item){ console.log("horizontalScrollCheck"); item.removeClass("scroll-both scroll-left scroll-right"); var width = item.outerWidth() var scrollWidth = item[0].scrollWidth; var scrollLeft = item.scrollLeft(); if (scrollWidth - width === scrollLeft){ item.addClass("scroll-left"); } else if (scrollLeft == 0){ item.addClass("scroll-right"); } else { item.addClass("scroll-both"); } } // !Check if element vs content is scrollable (with tolerance) function isScrollableY (element) { var elementheight = element.outerHeight(); var childheight = element.children().outerHeight(); var tolerance = 3; // how many pixels to scroll before considering element scrollable if(childheight > elementheight + tolerance){ return true; } else { return false; } } function checkClusterHeaders(){ $('.clusterize-content').each(function(index, item){ var clusterWidth = $(this).width(); var clusterHeaderTarget = $(this).closest(".clusterize").find(".clusterize-div-table-header"); if(clusterWidth && clusterHeaderTarget.length){ clusterHeaderTarget.width(clusterWidth); } }); } //!just return glyphicon from string function getIcon(icon){ //console.log(icon); if(icon && icon.match("_")){ icon = icon.replace("_"," "); } if(!icon){ return ""; } if (icon.match("glyphicon-")) { return ' '; } else if(icon.match("fa-")){ if(icon.match("fa-solid") || icon.match("fa-regular" || icon.match("fa-light") || icon.match("fa-thin") || icon.match("fa-duotone") || icon.match("fa-sharp"))){ return ' '; } else { return ' '; } } else { return ""; } } var shareLinkDialogOpen = 0; var shareLinkDialog; // !Common share link button etc function buildShareLinkContent(element, link, linktext, messagetext, dialogMode, showDialog){ // console.log("buildShareLinkContent"); // console.log(element); var target; if(element){ target = $(element); } var shareLink = link; var shareText = messagetext; var shareLinkClass = "hidden"; var shareButtonClass = ""; var shareLinkButton = '\ \ '+linktext+'\ '; var shareLinkArea = ''; if(!dialogMode){ shareLinkArea = '\ '; } else { shareLinkClass = ""; } var shareLinkContent = '\
    \ \
    '; if(showDialog){ if(shareLinkDialogOpen){ return false; } shareLinkDialog = BootstrapDialog.show({ title: linktext, message: shareLinkContent, type: BootstrapDialog.TYPE_PRIMARY, cssClass: 'dialog-share-link', closable: true, onshow: function(){ shareLinkDialogOpen = 1; }, onshown: function(dialog){ }, onhide: function(){ shareLinkDialogOpen = 0; } }); } else if(target){ if(dialogMode){ target.empty().append(shareLinkButton).removeClass("hidden"); } else { target.empty().append(shareLinkContent).removeClass("hidden"); } } } //! Create form from object, append to document and and submit function submitform(formobject, url){ $('body').find('.submit-form').remove(); var formContent = ""; $.each(formobject, function(key, value) { formContent += ""; }); var submitform = $(''); $('body').append(submitform); submitform.submit(); } //!time formatting for single date or range (moment object input) function formatEventDate(start, end){ var startDateString = start.format('DD/MM/YYYY'); var startTimeString = start.format('HH:mm'); var finalFormat = ""; if(end){ var endDateString = end.format('DD/MM/YYYY'); var endTimeString = end.format('HH:mm'); if(startDateString == endDateString){ finalFormat = ''+startDateString +' '+startTimeString+' - '+endTimeString+''; } else { finalFormat = '\ '+startDateString +' '+startTimeString+' – \ '+endDateString+' '+endTimeString+''; } } else { finalFormat = ''+startDateString +' '+startTimeString+''; } return finalFormat; } //!date formatting for range function formatDateRange(start, end){ var returnDate = ""; var startY = start.format("YYYY"); var endY = end.format("YYYY"); if(startY == endY){ returnDate += start.format('D/M'); } else { returnDate += start.format('DD/MM/YYYY'); } returnDate += ' - '+end.format('DD/MM/YYYY'); return returnDate; } // !format date/time duration function formatEventDuration(start, end, duration){ var startDateString = start.format('DD/MM/YYYY'); var startTimeString = start.format('HH:mm'); var endDateString = end.format('DD/MM/YYYY'); var endTimeString = end.format('HH:mm'); var eventDayAmount = duration/86400000; var eventDayModulus = duration % 86400000; var finalEventStartTime = start.format("HH:mm"); var finalFormat = ""; // event can be split to all day events if(Number.isInteger(eventDayAmount) && eventDayModulus == 0 && finalEventStartTime == "00:00"){ console.log("full days"); if(startDateString == endDateString){ finalFormat = ''+startDateString +''; } else { finalFormat = ''+startDateString +''+endDateString +''; } } else { if(startDateString == endDateString){ finalFormat = ''+startDateString +' '+startTimeString+' – '+endTimeString+''; } else { finalFormat = '\ '+startDateString +' '+startTimeString+' – \ '+endDateString+' '+endTimeString+''; } } return finalFormat; } var enumerateDaysBetweenDates = function(startDate, endDate, format) { var now = startDate, dates = []; while (now.isSameOrBefore(endDate)) { if(format == "moment"){ dates.push(now.clone()); } else { dates.push(now.format('YYYY-MM-DD')); } now.add(1, 'days'); } return dates; }; function memberTagsCheck(tagArray, date){ // console.log("memberTagsCheck"); // console.log(tagArray); // console.log(date); if (typeof memberTagsJSON !== 'undefined') { var membertagMatches = $.grep(memberTagsJSON, function(e){ return commonmatch(e.WalletTags.split(','), tagArray).length && moment(e.ValidDate, "YYYY-MM-DD HH:mm:ss") > date; }); // console.log("membertagMatches"); // console.log(membertagMatches); if(membertagMatches.length){ return true; } else { return false; } } else { console.log("memberTagsJSON not defined"); return false; } return false; } var entityMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/', '`': '`', '=': '=' }; function escapeHtml(string, loose) { if(loose){ // loose leaves slashes and some characters for urls return String(string).replace(/[<>"'`]/g, function (s) { return entityMap[s]; }); } else { return String(string).replace(/[&<>"'`=\/]/g, function (s) { return entityMap[s]; }); } } function numberMinMax(array){ var min = Math.min.apply(null, array); var max = Math.max.apply(null, array); if(min != max){ return [min, max]; } else { return [min]; } } // add small event mark to fullcalendar function addEventBlip(event, element, view){ // console.log("addEventBlip"); // console.log(event); var eventrange = enumerateDaysBetweenDates(event.start.clone(), event.end.clone(), "moment"); var userId = ""; if(event.UserId){ userId = ' data-userid="'+event.UserId+'"'; } var blipHtml = ''; var blipPlusHtml = ''; $(eventrange).each(function(index, day){ var day = day.format("YYYY-MM-DD"); //var blipTarget = $('.fc-widget-content[data-date="'+day+'"]'); var blipTarget = $('.fc-widget-content .fc-day-top[data-date="'+day+'"]'); var blipAmount = blipTarget.attr("data-blip-amount"); if(blipAmount){ blipAmount++; blipTarget.attr("data-blip-amount", blipAmount); } else { blipTarget.attr("data-blip-amount", 1); } if(blipAmount == 5){ blipTarget.append(blipPlusHtml); } else if(!blipAmount || blipAmount < 5){ blipTarget.append(blipHtml); } }); return false; // no normal event html added } function removeEventBlips(){ $('.event-blip').remove(); $(document).find("[data-date]").removeAttr("data-blip-amount"); } function buildEventParticipantsProgress(totalamount, reservedamount){ console.log("buildEventParticipantsProgress | totalamount: "+totalamount+" | reservedamount: "+reservedamount); var participantsFreeHtml = ''; var participantsBookedHtml = ''; var singleProgWidth = 100/totalamount; var userIcon = ''; if(totalamount > 10){ userIcon = ''; // no icon if more than 10 } if(totalamount <= 20){ // made progress bar slots if 20 or less places on event for(var i =0; i < totalamount - reservedamount; i++){ participantsFreeHtml = participantsFreeHtml + '\
    \
    '; } for(var i =0; i < reservedamount; i++){ participantsBookedHtml = participantsBookedHtml + '\
    \ '+userIcon+'\
    '; } } else { participantsBookedHtml = '
    '; if(totalamount - reservedamount > 0){ participantsFreeHtml = '
    '; } } var finalParticipantsProgress = '\
    \
    '+participantsBookedHtml+participantsFreeHtml+'
    \
    '; return finalParticipantsProgress; } function getEventSubtypeSettings(subtype){ // get subtype settings for events !camp var settings = {}; if(subtype == null){ subtype = 0; } settings.subtypeid = subtype; settings.subtypeclass = "normal"; settings.subtypedetails = "Normal event"; settings.horseallocation = true; settings.renderselectcourse = true; settings.renderreservecourse = true; settings.renderdaysummary = true; settings.titledefinition = ""; if(subtype == 1){ // Camp main event (event length) settings.subtypeclass = "camp"; settings.subtypedetails = "Camp - main camp event, length"; settings.horseallocation = false; settings.titledefinition = "Main event"; settings.renderreservecourse = false; // no main event in season cal settings.renderdaysummary = false; // no main event in day summary } else if(subtype == 2){ // Camp riding event settings.subtypeclass = "camp"; settings.subtypedetails = "Camp - riding event"; settings.renderselectcourse = false; settings.titledefinition = "Riding lesson"; } else if(subtype == 3){ // Camp teaching settings.subtypeclass = "camp"; settings.subtypedetails = "Camp - theory event"; settings.horseallocation = false; settings.renderselectcourse = false; settings.titledefinition = "Theory lesson"; } else if(subtype == 4){ // Camp other settings.subtypeclass = "camp"; settings.subtypedetails = "Camp - other"; settings.horseallocation = false; settings.renderselectcourse = false; settings.titledefinition = "Other"; } return settings; } function getHumanDuration(start, end){ console.log("getHumanDuration"); var durationString = ""; var duration = moment.duration(end.diff(start)); console.log(duration); //Get Days and subtract from duration //var days = duration.asDays(); var days = Math.floor(duration.asDays()); duration.subtract(moment.duration(days,'days')); //Get hours and subtract from duration var hours = duration.hours(); duration.subtract(moment.duration(hours,'hours')); //Get Minutes and subtract from duration var minutes = duration.minutes(); duration.subtract(moment.duration(minutes,'minutes')); //Get seconds var seconds = duration.seconds(); // console.log("Days: ",days); // console.log("Hours: ",hours); // console.log("Minutes: ",minutes); var durationArray = []; if(days > 0){ durationArray.push(days + " days"); } if(hours > 0){ durationArray.push(hours + " h"); } if(minutes > 0){ durationArray.push(minutes + " min"); } durationString = durationArray.join(' '); return durationString; } //!process booking calendar events function postProcessBookingEvents(events){ console.log("postProcessBookingEvents"); console.log(events); var processedEvents = []; $(events).each(function(index, event){ var finalEventStart = moment(event.start, "YYYY-MM-DD HH:mm"); var finalEventEnd = moment(event.end, "YYYY-MM-DD HH:mm"); var duration = finalEventEnd.diff(finalEventStart); var eventDayAmount = duration/86400000; var eventDayModulus = duration % 86400000; if(event.EventSubTypeId == 1 && eventDayAmount > 1){ // camp main event! event.allDay = true; event.campstart = event.start; event.campend = event.end; var eventNewStart = moment(event.start, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD"); eventNewStart += " 00:00"; event.start = eventNewStart; var eventNewEnd = moment(event.end, "YYYY-MM-DD HH:mm:ss").add(1, "days").format("YYYY-MM-DD"); eventNewEnd += " 00:00"; event.end = eventNewEnd; } processedEvents.push(event); }); console.log("processedEvents"); console.log(processedEvents); return processedEvents; } // !images generic change image button function changeImageButton(targetelement, blob, picurl){ console.log("changeImageButton"); console.log(picurl); var buttonType = 'small'; var imageFormat = 'common'; var imageAction; if($(targetelement).data("button-type")){ buttonType = $(targetelement).data("button-type"); } if($(targetelement).data("image-format")){ imageFormat = $(targetelement).data("image-format"); } if($(targetelement).data("image-action")){ imageAction = $(targetelement).data("image-action"); } if(picurl){ $(targetelement).attr("data-image-url", '/images/comment-lg/'+picurl); } console.log("imageAction"); console.log(imageAction); var removeButton = ""; var imageContent = ''; var imageButtonTitle = "Add photo"; var bgImageContent = ""; var imageAddedClass = ""; if(blob || picurl){ imageButtonTitle = "Change image"; imageAddedClass = " image-added"; if(blob){ imageContent = ''; bgImageContent = ' style="background-image: url(\''+blob+'\')"'; } else { imageContent = ''; //![eventimages] bgImageContent = ' style="background-image: url(\'/images/cover-md/'+picurl+'\')"'; } removeButton = '\ \ \ '; } else { } var buttonElements = ''; if(buttonType == "big"){ buttonElements = '\ \ '+removeButton; } else { buttonElements = '\ '; } if(imageAction == "validate-diary"){ validateDiary(); } if(blob){ return buttonElements; } else { $(targetelement).empty().append(buttonElements); $(targetelement).removeClass("hidden"); $('[data-toggle="tooltip"]').tooltip(); } } //!images remove common image function removeCommonImage(targetelement){ console.log("removeCommonImage"); $('[data-toggle="tooltip"]').tooltip("hide"); var buttonElementTarget = targetelement.closest(".image-button-parent"); changeImageButton(buttonElementTarget); var formName = buttonElementTarget.data('formname'); buttonElementTarget.append(''); } function checkBetaFeatures(betalevel){ console.log("checkBetaFeatures - level:"+betalevel); if(betalevel && betalevel > 0 && !hopotiPlusPublished){ //Insert beta note button to elements var betaHtml = '\ \ Learn more about the Beta Program\ '; $('.beta-alert').append(betaHtml).removeClass("hidden"); } else { $('.beta-alert').remove(); } } function betaTesterDialog(){ var betaDialogContent = '\
    \
    \
    Congratulations, you are now a member of the Hopoti Beta Program! This means you can use Hopoti features that are still under development and will be released later, well ahead of other users. In return, we would love to hear your feedback on the features under development, as user feedback is one of the most important tools for us. Thanks!

    Here are a few things to keep in mind:
    • Features are still under development, so unfortunately you may occasionally encounter errors.
    • In case of an error, be sure to contact us via feedback or chat.
    • Features and availability may still change in the final version.
    • Please do not publicise the features of the beta program, especially with images or videos.
    Thank you in advance for participating in our Beta Program!

    Hopoti Team
    \
    '; BootstrapDialog.show({ title: 'Learn more about the Beta Program', message: betaDialogContent, type: BootstrapDialog.TYPE_DANGER, cssClass: 'dialog-beta-tester', buttons: [ { // id: 'btn-ok', label: ' Send feedback', cssClass: 'btn-success btn-sm pull-left btn-beta-feedback', autospin: false, action: function(dialogRef){ } }, { id: 'btn-cancel', label: 'Close', cssClass: 'btn-default btn-sm', autospin: false, action: function(dialogRef){ dialogRef.close(); } }], onshow: function(){ }, onshown: function(){ }, onhide: function(){ } }); } //!Mobile calendar navi [calendar][diary] var naviCalRenderedHcGroupEvents = []; var naviCalRenderedEventIds = []; function initNaviCalendar(target, mother){ $(target).fullCalendar({ customButtons: { customPrev: { click: function() { animateCalendarStart(mother); $(mother).fullCalendar('prev'); } }, customNext: { click: function() { animateCalendarStart(mother); $(mother).fullCalendar('next'); } }, customToday: { text: 'Today', click: function() { animateCalendarStart(mother); $(mother).fullCalendar('today'); } } }, buttonIcons: { customPrev: 'fc-icon-left-single-arrow', customNext: 'fc-icon-right-single-arrow' }, header: { left: 'customPrev,customNext customToday title', right: '' }, titleFormat: 'MMMM YYYY', // DD.MM.YYYY firstDay: 1, eventRender: function(event, element, view) { var countType = "event"; if(event.type == "polar" && userCalendarFilters.includes(7) && !commonmatch(userCalendarFilters, [1,2,6]).length && event.connected){ // is polar return false; } else if(event.type == "polar" && event.connected){ countType = "polar"; } if(event.invoiceevent && !userCalendarFilters.includes(5)){ // is invoice return false; } else if(event.invoiceevent){ countType = "invoice"; } if (event.horseeventtypeid && !userCalendarFilters.includes(4)){ //is horsecare return false; } else if(event.horseeventtypeid && userCalendarFilters.includes(4)){ // prevent counting hc events multiple times if(naviCalRenderedHcGroupEvents.includes(event.sourceObject.HorseEventGroupId)){ return false; } else { countType = "horsecare"; naviCalRenderedHcGroupEvents.push(event.sourceObject.HorseEventGroupId); } } if (event.DiaryEventId && !userCalendarFilters.includes(3)){ // is diary return false; } else if(event.DiaryEventId) { countType = "diary"; } if(event.userevent && !userCalendarFilters.includes(1)){ // filter own events return false; } if(event.childevent && !userCalendarFilters.includes(2)){ // filter child events return false; } if(event.trainerevent && !userCalendarFilters.includes(6)){ // filter training events return false; } if(event.lessonevent && !userCalendarFilters.includes(8)){ // filter gone events (shown if rating not done) //return false; } // if(event.lessonevent && event.end.clone().add(14, "days") < moment() && !userCalendarFilters.includes(7)){ // filter gone events (shown if rating not done) // return false; // } var eventrange; if(event.start && event.end && event.start.format("YYYY-MM-DD") != event.end.clone().subtract(1, "days").format("YYYY-MM-DD")){ eventrange = enumerateDaysBetweenDates(event.start.clone(), event.end.clone(), "moment"); } else if(event.start){ eventrange = [event.start]; } if(event.id && !event.trainerevent){ if(naviCalRenderedEventIds.includes(event.id)){ return false; } else { naviCalRenderedEventIds.push(event.id) } } if(eventrange){ $(eventrange).each(function(index, item){ var startdate = item.format("YYYY-MM-DD"); var caltarget = $(target).find('.fc-day[data-date="'+startdate+'"]'); var currentvalue = caltarget.attr('data-'+countType+'-count'); if(currentvalue == 0 || !currentvalue){ currentvalue = 1; } else { currentvalue++; } caltarget.attr('data-'+countType+'-count', currentvalue); }); } return false; }, eventAfterAllRender: function(event, element, view) { $('.fc-day[data-event-count]').each(function(index, item){ var eventcount = $(this).data("event-count"); $(this).append(''+eventcount+''); }); $('.fc-day[data-diary-count]').each(function(index, item){ var eventcount = $(this).data("diary-count"); if(eventcount == 1){ eventcount = ""; } $(this).append(''+eventcount+''); }); $('.fc-day[data-horsecare-count]').each(function(index, item){ var eventcount = $(this).data("horsecare-count"); if(eventcount == 1){ eventcount = ""; } $(this).append(''+eventcount+''); }); $('.fc-day[data-invoice-count]').each(function(index, item){ var eventcount = $(this).data("invoice-count"); if(eventcount == 1){ eventcount = ""; } $(this).append(''+eventcount+''); }); naviCalRenderedHcGroupEvents = naviCalRenderedEventIds = []; }, dayClick: function(date, jsEvent, view) { // clicked outside current month if(date < view.intervalStart){ $(mother).fullCalendar('prev'); } else if(date > view.intervalEnd){ $(mother).fullCalendar('next'); } else { $(mother).fullCalendar('gotoDate', moment(date)); animateCalendarDayScroll(moment(date)); setTimeout(function(){ $('body').removeClass("show-header-date-picker"); }, 100); } } }); $('.navi-calendar-wrapper').on('click', function(e) { if($(e.target).hasClass("navi-calendar-wrapper")){ setTimeout(function(){ $('body').removeClass("show-header-date-picker"); }, 100); } }); } function refreshNaviCalendar(target, mother, events){ console.log("refreshNaviCalendar"); // console.log(events); var motherdate = $(mother).fullCalendar('getDate'); $(target).fullCalendar('gotoDate', moment(motherdate)); $(target).find('.fc-day').attr('data-event-count', null); $(target).find('.fc-day').attr('data-horsecare-count', null); $(target).find('.fc-day').attr('data-invoice-count', null); $(target).find('.fc-day').attr('data-diary-count', null); $(target).find('.event-count, .horsecare-count, .invoice-count, .diary-count').remove(); $(target).fullCalendar('removeEvents'); $(target).fullCalendar('addEventSource', events); } function animateCalendarDayScroll(momentdate){ console.log("animateCalendarDayScroll"); console.log(momentdate); var dateformat = momentdate.format("YYYY-MM-DD"); var datedate = momentdate.toDate(); var target = $(document).find('.fc-list-heading[data-date="'+dateformat+'"]'); if(!target.length){ // selected date doesn't contain events - find the closest one which does var allHeadings = $('.fc-list-heading[data-date]'); var availableDates = []; $(allHeadings).each(function(index, item){ var singleDate = $(item).data("date"); availableDates.push(moment(singleDate, "YYYY-MM-DD").toDate()); }); var closestDates = availableDates.sort(function(a, b) { var distancea = Math.abs(datedate - a); var distanceb = Math.abs(datedate - b); return distancea - distanceb; }); var closestDateFormat = moment(closestDates[0]).format("YYYY-MM-DD"); target = $(document).find('.fc-list-heading[data-date="'+closestDateFormat+'"]'); } if(target.length){ $('html, body').animate({ scrollTop: $(target).offset().top-60 }, 700); } } function animateCalendarStart(mother){ var position = $(mother).position().top; var headercontainerheight = $('.headercontainer-2019').height(); $('html, body').animate({ scrollTop: position+headercontainerheight-15 }, 700); } function truncate(str, limit) { var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF'; var reg = new RegExp('(?=[' + trimmable + '])'); var words = str.split(reg); var count = 0; var result = words.filter(function(word) { count += word.length; return count <= limit; }).join(''); if(count > limit){ result += '...'; } return result; } //!Common validate for submit button - disables button click, shows error field title and slides dialog to missing info location on click [validate] function validationButtonFail(target, saveButton){ console.log("validationButtonFail"); var erroramount = 0; var fieldLabel = []; var fieldLabelContent; var errorTooltip = ""; target.find('.has-error:visible').each(function() { erroramount++; if(erroramount == 1){ fieldLabel = $(this).find('label'); if(fieldLabel.length){ fieldLabelContent = fieldLabel.html(); } } }); if(fieldLabel.length && erroramount > 0){ var errorAmountString = ""; if(erroramount == 2){ errorAmountString = ' and one more detail'; } else if(erroramount > 2){ errorAmountString = ' and [x] more details'.replace("[x]", erroramount-1); } errorTooltip = 'Info missing: '+fieldLabelContent+''+errorAmountString; saveButton.unbind(); saveButton.bind("click", function() { fieldLabel[0].scrollIntoView({ behavior: "smooth", block: "start" }); }); } validationButtonDisable(saveButton, errorTooltip); } // disable submit function validationButtonDisable(saveButton, tooltip, showtooltip){ saveButton.addClass("disabled-continue"); if(tooltip){ var errorString = ""; if(tooltip.constructor === Array){ // if given an array of errors if(!tooltip.length){ return false; // empty array } var errorAmountString = ""; if(tooltip.length == 2){ errorAmountString = ' and one more detail'; } else if(tooltip.length > 2){ errorAmountString = ' and [x] more details'.replace("[x]", tooltip.length-1); } errorString = 'Info missing: '+tooltip[0]+''+errorAmountString; } else { // only an error string errorString = tooltip; } saveButton.attr('data-toggle', 'tooltip'); saveButton.attr('data-trigger', 'hover focus'); saveButton.attr('data-html', 'true'); saveButton.attr('data-original-title', errorString); if(showtooltip){ saveButton.tooltip("show"); } else { saveButton.tooltip(); } } } //!Common validate ok, remove tooltip and disabled class function validationButtonOk(saveButton){ console.log("validationButtonOk"); saveButton.tooltip('destroy'); saveButton.removeClass("disabled-continue"); } // cross reference multiple arrays // USAGE: // values: ['name', 'credits'] // source: ['name', 'credits', 'price', 'vat', 'validNumber', 'description'] // target: ['Nimi', 'Saldo', 'Hinta', 'ALV', 'Voimassa', 'Kuvaus'] // return: ['Nimi', 'Saldo'] function getArrayMatches(values, source, target){ console.log("getArrayMatches"); var tempArray = []; $.each(values, function(index, value) { var valueindex = source.indexOf(value) if(valueindex > -1){ var matchtarget = target[valueindex]; if(matchtarget){ tempArray.push(matchtarget); } } }); return tempArray; } //Add "more" label to bottom of dialog if dialog content is scrollable function addDialogMoreInfoLabel(dialogRef){ console.log("addDialogMoreInfoLabel"); $('.more-info-note').remove(); var showMoreLabel = '\ '; setTimeout(function(){ var scrollable = isScrollableY(dialogRef.getModalBody()); if(scrollable){ dialogRef.getModalFooter().prepend(showMoreLabel); $('.more-info-note').hide().removeClass("hidden").fadeIn(300); $(".modal-body").bind('scroll', function() { $('.more-info-note').fadeOut(300); setTimeout(function(){ $('.more-info-note').remove(); }, 300); }); } }, 500); } function addEventBookingError(reason, target, type){ console.log("addEventBookingError"); var target = $(document).find(target); var errorClass = 'alert-info'; var errorIcon = ' '; if(type == "danger"){ errorClass = "alert-danger"; errorIcon = ' '; } else if(type == "warning"){ errorClass = "alert-warning"; errorIcon = ' '; } var errorHtml = '\
    \
    \
    '+errorIcon+reason+'
    \
    \
    ' target.append(errorHtml); } function addCalendarIcons(element){ $(element).each(function(index, e){ // if($(this).data("calendar-icons-added")){ // return true; // } var monthIcon = ' '; var weekIcon = ' '; var dayIcon = ' '; var listIcon = ' '; var workIcon = ' '; if(element == ".horsecare-calendar"){ if(!$(this).find('.fc-month-button i').length){ $(this).find('.fc-month-button').prepend(monthIcon); } if(!$(this).find('.fc-listMonth-button i').length){ $(this).find('.fc-listMonth-button').prepend(monthIcon); } if(!$(this).find('.fc-listWeek-button i').length){ $(this).find('.fc-listWeek-button').prepend(weekIcon); } if(!$(this).find('.fc-basicWeek-button i').length){ $(this).find('.fc-basicWeek-button').prepend(weekIcon); } if(!$(this).find('.fc-listDay-button i').length){ $(this).find('.fc-listDay-button').prepend(dayIcon); } if(!$(this).find('.fc-basicDay-button i').length){ $(this).find('.fc-basicDay-button').prepend(dayIcon); } if(!$(this).find('.fc-workView-button i').length){ $(this).find('.fc-workView-button').prepend(workIcon); } } else { if(!$(this).find('.fc-month-button i').length){ $(this).find('.fc-month-button').prepend(monthIcon); } if(!$(this).find('.fc-agendaWeek-button i').length){ $(this).find('.fc-agendaWeek-button').prepend(weekIcon); } if(!$(this).find('.fc-basicWeek-button i').length){ $(this).find('.fc-basicWeek-button').prepend(weekIcon); } if(!$(this).find('.fc-agendaDay-button i').length){ $(this).find('.fc-agendaDay-button').prepend(dayIcon); } if(!$(this).find('.fc-basicDay-button i').length){ $(this).find('.fc-basicDay-button').prepend(dayIcon); } if(!$(this).find('.fc-listDay-button i').length){ $(this).find('.fc-listDay-button').prepend(listIcon); } } // $(this).attr("data-calendar-icons-added", 1); }); } // change fixed elements width to inline css based on maincontainer width // for example: //
    // add fixed-width-mobile="1" if fixed element is mobile, otherwise styles will be removed in mobile view function changeFixedWidthElements(){ console.log("changeFixedWidthElements"); var contentWidth = $('.maincontainer').outerWidth(); var naviWidth = contentWidth/12; $('[data-fixed-width]').each(function(index, e){ if(viewmode == "xs" || viewmode == "xxs"){ if(!$(this).data("fixed-width-mobile")){ $(this).removeAttr('style'); return true; } } var thisWidth = $(this).data("fixed-width"); var thisMargin = $(this).data("fixed-width-margin"); $(this).css("width", naviWidth*thisWidth+"px"); if(thisMargin){ $(this).css("margin-left", naviWidth*thisMargin+"px"); } }); } function initSearch() { // init search stables var hopotiSearchSelectize = $('#hopotiSearch').selectize({ valueField: 'HSid', labelField: 'HSname', searchField: ['HSname', 'HSdesc', 'CompanyName'], sortField: [{ field: "HSorder", direction: "asc" },{ field: "$order", direction: "asc" }], options: [], plugins: ['preserve_on_blur'], create: false, highlight: false, maxOptions: 15, loadThrottle: 600, dropdownParent: 'body', score: function() { return function(search) { return 1; } }, onType: function(str){ $('.hopotiSearchTooltipArea').removeClass('danger warning'); $('.hopotiSearchTooltip').tooltip('hide'); }, onItemAdd: function(value, $item){ hopotiSearchSelectize[0].selectize.lock(); $("#hopotiSearch-selectized").addClass("noPointerEvents"); if (this.options[value]['HStype'] === "stable"){ window.location.href = "https://hopoti.com/stable/"+this.options[value]['StableLinkName']; } else{ var geoRequest = { placeId: value, fields: ['geometry'] }; geoService = new google.maps.places.PlacesService(document.createElement('div')); geoService.getDetails(geoRequest, geoCallback); function geoCallback(place, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { $("#hopotiSearch-selectized").remove(); window.location.href = "https://hopoti.com/search/stables?place="+encodeURI($($item).text())+"&lat="+place.geometry.location.lat()+"&lng="+place.geometry.location.lng(); } else { hopotiSearchSelectize[0].selectize.clear(); hopotiSearchSelectize[0].selectize.clearOptions(); hopotiSearchSelectize[0].selectize.renderCache['option'] = {}; hopotiSearchSelectize[0].selectize.renderCache['item'] = {}; hopotiSearchSelectize[0].selectize.blur(); hopotiSearchSelectize[0].selectize.unlock(); $("#hopotiSearch-selectized").removeClass("noPointerEvents"); } } } }, render: { option: function(item, escape) { if (item.HStype == "stable") { return '

    '+item.HSname+'

    '+item.HSdesc+'

    '; } return '

    '+item.HSname+'

    '+item.HSdesc+'

    '; } }, load: function(query, callback) { var hopotiSearchEmpty = false; var hopotiSearchFirstDone = false; hopotiSearchSelectize[0].selectize.clear(); hopotiSearchSelectize[0].selectize.clearOptions(); hopotiSearchSelectize[0].selectize.renderCache['option'] = {}; hopotiSearchSelectize[0].selectize.renderCache['item'] = {}; if (!query.length) return callback(); $.ajax({ url: '/searchstable?name=' + encodeURIComponent(query), type: 'POST', error: function(err) { callback(); $('.hopotiSearchTooltip').data('bs.tooltip').options.title = "Search failed
    Please try again"; $('.hopotiSearchTooltip').tooltip('show'); $('.hopotiSearchTooltipArea').removeClass('warning'); $('.hopotiSearchTooltipArea').addClass('danger'); }, success: function(data) { if (hopotiSearchFirstDone){ if (hopotiSearchEmpty){ if (data.length < 1){ $('.hopotiSearchTooltip').data('bs.tooltip').options.title = "No results
    Try searching for something else"; $('.hopotiSearchTooltip').tooltip('show'); $('.hopotiSearchTooltipArea').removeClass('danger'); $('.hopotiSearchTooltipArea').addClass('warning'); } } } else { hopotiSearchFirstDone = true; if (data.length < 1){ hopotiSearchEmpty = true; } } $.each(data, function(index, value) { data[index]['HSid'] = "stable-"+data[index]['StableId']; data[index]['HSname'] = data[index]['StableName']; data[index]['HSdesc'] = data[index]['StableCity']; data[index]['HStype'] = 'stable'; data[index]['HSorder'] = 1; }); callback(data.slice(0, 3)); } }); var displaySuggestions = function(predictions, status) { if (status != google.maps.places.PlacesServiceStatus.OK) { if (hopotiSearchFirstDone){ if (hopotiSearchEmpty){ if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS){ $('.hopotiSearchTooltip').data('bs.tooltip').options.title = "No results
    Try searching for something else"; $('.hopotiSearchTooltip').tooltip('show'); $('.hopotiSearchTooltipArea').removeClass('danger'); $('.hopotiSearchTooltipArea').addClass('warning'); } } } else { hopotiSearchFirstDone = true; if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS){ hopotiSearchEmpty = true; } } if (status != google.maps.places.PlacesServiceStatus.ZERO_RESULTS){ $('.hopotiSearchTooltip').data('bs.tooltip').options.title = "Search failed
    Please try again"; $('.hopotiSearchTooltip').tooltip('show'); $('.hopotiSearchTooltipArea').removeClass('warning'); $('.hopotiSearchTooltipArea').addClass('danger'); } return; } $.each(predictions, function(index, value) { predictions[index]['HSid'] = predictions[index]['place_id']; predictions[index]['HSname'] = predictions[index]['structured_formatting']['main_text']; predictions[index]['HSdesc'] = predictions[index]['structured_formatting']['secondary_text']; predictions[index]['HStype'] = 'place'; predictions[index]['HSorder'] = 2; }); callback(predictions.slice(0, 5)); }; var service = new google.maps.places.AutocompleteService(); service.getQueryPredictions({ input: query }, displaySuggestions); }, onInitialize: function(){ $(".selectize-dropdown.plugin-preserve_on_blur").append('
    '); $('.hopotiSearchTooltip').tooltip({ title: "hopotiSearchTooltip", trigger: "manual", html: "true", template: '' }); }, onFocus: function(){ $("#hopotiSearch-selectized").typed({ strings: ['Search centres by name...', 'Search centres by location...', 'Search centres by name...', 'Search centres by address...'], attr: 'placeholder', typeSpeed: 2, startDelay: 300, backDelay: 3000, loop: true, cursorChar: '|', showCursor: false, }); } }); } function ImagetoPrint(source, type){ // // // // // // // // // var content = ""; if(type == "pdf"){ content = ""; } return "function step1(){\n" + "setTimeout('step2()', 10);}\n" + "function step2(){window.print();window.close()}\n" + "\n" + content+""; } function printcontent(source, type){ // !print console.log("printcontent"); console.log(source); var Pagelink = "about:blank"; var pwa = window.open(Pagelink, "_new"); pwa.document.open(); pwa.document.write(ImagetoPrint(source, type)); pwa.document.close(); } function stablecardDialog(data){ console.log("stablecardDialog"); console.log(data); if(!data){ return false; } creditTransferred = false; var bigStablecardHtml = buildDisplayCard(data, "big"); var dialogTitle = ' Stablecard Information'; var cardHelpString = 'With the card, you can book suitable events and services from the company's calendar. Please contact [stablename] if you have any questions about the card or the event eligibility.'; var nameLabel = 'Stablecard'; var transferLabel = 'Transfer credits'; var noTrasfersLabel = 'Credit cannot be transferred'; if(data.TypeId == idGiftcards){ // giftcard labels transferLabel = 'Transfer card'; noTrasfersLabel = 'Card cannot be transferred'; } var stablecardActionButtons = [{ label: ' '+data.StableName, cssClass: 'btn-default btn-sm pull-left btn-stable-link', autospin: false, action: function(dialogRef){ window.location.href = 'https://hopoti.com/stable/'+data.StableLinkName; } },{ id: 'btn-close', label: 'Close', cssClass: 'btn-default btn-sm', autospin: false, action: function(dialogRef){ dialogRef.close(); } }]; var transferButton = { label: ' '+transferLabel, cssClass: 'btn-default btn-sm pull-left btn-transfer-credits', autospin: false, action: function(dialogRef){ dialogRef.getModalDialog().find('.btn-transfer-credits, .btn-stable-link, .btn-book-link').remove(); dialogRef.getModalDialog().find('.btn-accept-transfer').removeClass("hidden"); moveStablecardCredit(data, dialogRef); } }; var noTransfersButton = { label: ' '+noTrasfersLabel, cssClass: 'btn-default btn-sm pull-left grayed-out', autospin: false, action: function(dialogRef){ if(data.TypeId == idGiftcards){ // giftcard labels noMoveReasonDialog("card-no-transfers"); } else { noMoveReasonDialog("credit-no-transfers"); } } }; var acceptTransferButton = { label: ' Accept transfer', cssClass: 'btn-success btn-sm pull-left hidden btn-accept-transfer', autospin: false, action: function(dialogRef){ submitMoveStablecardCredit(data, dialogRef) } }; var walletTags; if(data.WalletTags == null){ walletTags = "2"; } else { walletTags = "2,"+data.WalletTags; } var stablecardValidDateDb = moment(data.ValidDate, "YYYY-MM-DD HH:mm:ss").toISOString(); var bookButton = { label: ' Show valid lessons', cssClass: 'btn-default btn-sm pull-left btn-book-link', autospin: false, action: function(dialogRef){ window.location.href = 'https://hopoti.com/stable/'+data.StableLinkName+'/booking?free=1&part=1&sc='+data.UserWalletId+'&tags='+walletTags+'&valid='+stablecardValidDateDb+'&cal=all'; } }; var validUntil = moment(data.ValidDate, "YYYY-MM-DD HH:mm:ss").format('DD/MM/YYYY'); var validString = 'Valid until [x]'.replace('[x]', validUntil); var validRow = '\ \  \ '+validString+'\ '; var giftcardValue = ""; if(data.TypeId == idMemberships){ dialogTitle = ' Membership information'; cardHelpString = 'From the membership description you can find more information about the membership's content and benefits. Please contact [stablename] if you have any questions about membership.'; nameLabel = 'Membership name'; } else if(data.TypeId == idGiftcards){ // giftcard dialogTitle = ' Redeeming a gift card'; cardHelpString = 'From the gift card description you can find more information about the gift card's content and redeem instructions. Please contact [stablename] if you have any questions about gift card.'; nameLabel = 'Gift card name'; giftcardValue = '\ \ Value remaining\ '+currencyFormat(data.Count,data.CurrencyKey)+'\ '; if(data.Count != data.OriginalCount){ giftcardValue += '\ \ Original value\ '+currencyFormat(data.OriginalCount,data.CurrencyKey)+'\ '; } if(data.CardTransferMode){ stablecardActionButtons.push(transferButton); stablecardActionButtons.push(acceptTransferButton); } else { stablecardActionButtons.push(noTransfersButton); } } else { // basic stablecard if(data.CardTransferMode){ stablecardActionButtons.push(transferButton); stablecardActionButtons.push(acceptTransferButton); } else { stablecardActionButtons.push(noTransfersButton); } stablecardActionButtons.push(bookButton); } var cardHelp = cardHelpString.replaceAllText('[stablename]', ''+data.StableName+''); cardHelp = cardHelp.replace("[date]", ''+validUntil+''); var additionalText = ""; if(data.AdditionalText){ additionalText = '\ \ Description\ '+data.AdditionalText+'\ '; } var stablecardInfo = '\
    \
    \
    \ '+bigStablecardHtml+'\
    \
    \
    \ \ \ \ \ \ \ '+additionalText+'\ '+giftcardValue+'\ \ \ \ \
    '+nameLabel+'\ '+data.Description+'\ \
    \
    \
    \
    '+cardHelp+'
    \
    \
    \
    '; BootstrapDialog.show({ size: BootstrapDialog.SIZE_NORMAL, title: dialogTitle, message: stablecardInfo, type: BootstrapDialog.TYPE_PRIMARY, cssClass: 'dialog-display-stablecard', closable: true, buttons: stablecardActionButtons, onshow: function(){ }, onshown: function(dialog){ buildStablecardDots(); }, onhide: function(){ console.log(userAllCardsDial); if(userAllCardsDial && userAllCardsDial.opened && creditTransferred){ userAllCardsDial.close(); userAllCardsDialog(); } } }); } function addLatestExerciseDiaryLink(data){ console.log("addLatestExerciseDiaryLink"); console.log(data); var target = userCalendarActionDial.getModalDialog().find('.panel-diary .list-group'); var exercisestart = moment(data.start); var exercisestartFormatted = exercisestart.format('DD/MM/YYYY HH:mm'); var exerciseduration = moment.duration(data.Duration); //console.log(exerciseduration); exerciseduration = formatDuration(exerciseduration); latestSportEventData = data; var latestExerciseLink = '\
  • Latest sports watch exercise
  • \ \ '+data.DetailedSportType+'
    \ '+exercisestartFormatted+' '+exerciseduration+'\
    '; target.prepend(latestExerciseLink); target.find(".diary-type-select").removeClass("hidden"); } function formatDuration(momentDuration){ var eventDuration = Math.round(momentDuration.asMinutes()); var eMinutes = eventDuration % 60; var eHours = (eventDuration-eMinutes)/60; var eTimeDurationTitle = ""; if(eHours){ eTimeDurationTitle += eHours + 'h'; } if(eMinutes){ eTimeDurationTitle += " " + eMinutes + 'min'; } return eTimeDurationTitle; } function formatMetresAsKilometres(metres){ var eTotalM = metres/1000; var eMetres = metres % 1000; var eKilometres = (metres - eMetres)/1000; var eTitle = ""; if(eKilometres){ eTitle += eKilometres + " km" } if(eMetres){ eTitle += " "+eMetres+" m"; } return eTitle; } function initExerciseData(data){ //!polar console.log("initExerciseData"); var mapdata; if(data.ExercisePayload){ mapdata = data.ExercisePayload; } //!exercise data common STARTS if(data){ //Riding distance if(data.Distance){ var eTitle = formatMetresAsKilometres(data.Distance); var eTotalM = data.Distance/1000; var distanceValue = { length: eTotalM, title: eTitle }; if(diaryLengthSelectize){ diaryLengthSelectize[0].selectize.addOption(distanceValue); diaryLengthSelectize[0].selectize.setValue(eTotalM, true); } } if(data.ExerciseStartDateTime && data.Duration){ var eventStartMoment = moment(data.ExerciseStartDateTime); var eventDuration = Math.round(moment.duration(data.Duration).asMinutes()); console.log("eventDuration"); console.log(eventDuration); var eMinutes = eventDuration % 60; var eHours = (eventDuration-eMinutes)/60; var eTimeDurationTitle = ""; if(eHours){ eTimeDurationTitle += eHours + " h"; } if(eMinutes){ eTimeDurationTitle += " " + eMinutes + " min"; } var durationValue = { duration: eventDuration, title: eTimeDurationTitle }; if(diaryDurationSelectize){ diaryDurationSelectize[0].selectize.addOption(durationValue); diaryDurationSelectize[0].selectize.setValue(eventDuration, true); initMovingTypeSlider(eventDuration); } $('.diary-form').find('.date-start').datepicker('setDate', eventStartMoment.toDate()); // start date $('.diary-form').find('.timepicker.start').timepicker('setTime', eventStartMoment.format("HH:mm:ss")); // start time } var fitnessTable = exerciseTableHtml(data); $('.fitnessdata-table').hide().empty().append(fitnessTable).removeClass("hidden").slideDown(300); } //!exercise data common ENDS //!Map data STARTS if(mapdata){ setTimeout(function(){ initMapBox("diarymap", mapdata); }, 50); } //!Map data ENDS } function exerciseTableHtml(data){ var returnHtml = ""; // fitnessCommonInfo += '\ // \ // Device\ // '+data.Device+'\ // '; returnHtml += '\ \ Heart rate\ \ '+data.HeartRateAverage+'AVG / '+data.HeartRateMax+'MAX\ \ '; var fatProgress = '\
    \
    \
    \
    \
    '; var fatLabels = '\
    \
    \ Carbohydrate
    \ '+data.CarboHydratePercentage+'%\
    \
    \
    \ Protein
    \ '+data.ProteinPercentage+'%\
    \
    \
    \ Fat
    \ '+data.FatPercentage+'%\
    '; var carbsRow = '\ \ Calories\ '+data.Calories+' kcal
    '+fatProgress+fatLabels+'\ '; returnHtml = ''+returnHtml+carbsRow+'
    '; return returnHtml; } var map; var bounds; function initMapBox(id, data){ // !polar !Mapbox console.log("initMapBox"); mapboxgl.accessToken = 'pk.eyJ1IjoiaG9wb3RpIiwiYSI6ImNrd295bDd5ZTA3azcybmxjNnNvaGM0cmUifQ.wE1Zc3_beUvfNFxPxUTIeQ'; var domxml = (new DOMParser()).parseFromString(data, 'text/xml'); // if xml as variable var trackdataGpx = toGeoJSON["gpx"](domxml); var coordinates = trackdataGpx.features[0].geometry.coordinates; console.log("coordinates"); console.log(coordinates); bounds = coordinates.reduce(function(bounds, coord) { return bounds.extend(coord); }, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0])); map = new mapboxgl.Map({ container: id, style: 'mapbox://styles/mapbox/streets-v11', center: coordinates[0], zoom: 11, // bounds: bounds, pitch: 50, dragPan: false, scrollZoom: false, boxZoom: false, dragRotate: false, keyboard: false, doubleClickZoom: false, touchZoomRotate: false }); var naviControl = new mapboxgl.NavigationControl(); class MinimizeControl { onAdd(map) { this.map = map; this.btn = document.createElement('button'); this.btn.className = 'mapboxgl-ctrl mapbox-minimize'; this.btn.textContent = 'nope'; this.btn.onclick = function() { map.removeControl(minimizeControl, 'top-right'); map.removeControl(naviControl, 'top-left'); map["dragPan"].disable(); map["scrollZoom"].disable(); map["boxZoom"].disable(); map["doubleClickZoom"].disable(); var diaryTarget = $('.diary-form .fitness-map'); var singlepostTarget = $('.single-post-dialog .fitness-map'); if(diaryTarget.length){ diaryTarget.removeClass('large').addClass("col-md-4 small"); } else if(singlepostTarget.length){ singlepostTarget.removeClass('large').addClass("col-sm-4 pull-right small"); } setTimeout(function(){ fitMap(); }, 300); } this.container = document.createElement("div"); this.container.className = "mapboxgl-ctrl-group mapboxgl-ctrl"; this.container.appendChild(this.btn); return this.container; } onRemove() { this.container.parentNode.removeChild(this.container); this.map = undefined; } } var minimizeControl = new MinimizeControl(); map.on('load', () => { map.addSource('diarymap', { type: 'geojson', data: trackdataGpx }); map.fitBounds(bounds, { padding: 20, pitch: 0 }); map.addLayer({ 'id': 'diarymap', 'type': 'line', 'source': 'diarymap', 'layout': { 'line-join': 'round', 'line-cap': 'round' }, 'paint': { 'line-color': '#066b93', 'line-width': 4 } }); }).on('mousedown', (e) => { var diaryTarget = $('.diary-form .fitness-map'); var singlepostTarget = $('.single-post-dialog .fitness-map'); var target; if(diaryTarget.length){ target = diaryTarget; } else if(singlepostTarget.length){ target = singlepostTarget; } if(target){ // under diary event if(target.hasClass("small")){ e.preventDefault(); if(diaryTarget.length){ target.removeClass('col-md-4 small').addClass("large"); } else if(singlepostTarget.length){ target.removeClass('col-sm-4 pull-right small').addClass("large"); } setTimeout(function(){ map.resize(); map.fitBounds(bounds, { padding: 20, pitch: 0 }); // Add zoom and rotation controls to the map. map.addControl(minimizeControl, 'top-right'); map.addControl(naviControl, 'top-left'); map["dragPan"].enable(); map["scrollZoom"].enable(); map["boxZoom"].enable(); map["doubleClickZoom"].enable(); $(document).find("#"+id+' .mapbox-minimize').empty().append('').css("margin", "0"); }, 300); } } }); } function fitMap(){ map.resize(); map.fitBounds(bounds, { padding: 20, pitch: 0 }); } var commonmapbox; function initCommonMapbox(target, data){ console.log("initCommonMapbox"); //console.log(data); mapboxgl.accessToken = 'pk.eyJ1IjoiaG9wb3RpIiwiYSI6ImNrd295bDd5ZTA3azcybmxjNnNvaGM0cmUifQ.wE1Zc3_beUvfNFxPxUTIeQ'; commonmapbox = new mapboxgl.Map({ container: target, // Choose from Mapbox's core styles, or make your own style with Mapbox Studio //style: 'mapbox://styles/mapbox/satellite-streets-v11', style: 'mapbox://styles/mapbox/streets-v11', zoom: 1, center: [30, 50], projection: 'globe' }); //map.on('load', () => { // Set the default atmosphere style //map.setFog({}); //}); if(data.length){ mpAddPoints(data); } else { setTimeout(function(){ commonmapbox.resize(); // map.fitBounds(bounds, { // padding: 20, // pitch: 0 // }); }, 300); } } var mpMarkers = []; function mpAddPoints(data){ // console.log("mpAddPoints"); // console.log(data); var checkedData = []; var boundsData = []; $.each(data, function(key, value) { if(value[0] && value[1]){ checkedData.push(value); } }); $.each(checkedData, function(key, value) { // console.log("value"); // console.log(value); var markerColor = '#ff7f0e'; var popup = ' Riding diary'; if(value[2] && value[3]){ markerColor = '#1f77b4'; popup = ' '+value[2]+''; } const marker = new mapboxgl.Marker({ color: markerColor }).setLngLat([value[0], value[1]]) .setPopup(new mapboxgl.Popup().setHTML(popup)) .addTo(commonmapbox); boundsData.push([value[0], value[1]]); mpMarkers.push(marker); }); var bounds = boundsData.reduce(function(bounds, coord) { return bounds.extend(coord); }, new mapboxgl.LngLatBounds(boundsData[0], boundsData[0])); var zoomsettings = { padding: 100, pitch: 0, duration: 4000 }; if(checkedData.length < 2){ // zoom farther if only one target zoomsettings = { padding: 100, pitch: 0, duration: 4000, zoom: 13 }; } commonmapbox.fitBounds(bounds, zoomsettings); } function mpRemoveMarkers(markerarray){ $.each(markerarray, function(key, value) { value.remove(); }); } function mpZoomOut(){ console.log("mpZoomOut"); commonmapbox.flyTo({ zoom: 1, duration: 2000 }); } var infiniteListView; // !Load feed function loadFeed(element){ //logging("loadFeed"); var pArea = element; var pAreaWaitAsync = pArea.attr("data-wait-async"); if(pAreaWaitAsync){ // wait for other functions to complete return false; } console.log("proceed"); // Create necessary inner HTML to p-areas pArea.append(pAreaInnerHTML); var pAreaId = pArea.data("area"); var pAreaPermission = pArea.data("permission"); var pAreaPost = pArea.data("post"); var pAreaDelete = pArea.data("delete"); var pAreaTimestamp = pArea.attr("data-timestamp"); var pAreaInfinite = pArea.data("infinite"); var pAreaSource = pArea.data("source"); var pAreaCounter = pArea.data("counter"); var pInfiniteTarget = pArea.find('.p-area-main-middle'); // Checking current p-area for permission to see it if (pAreaPermission === true){ // Show loading message postMsg("initLoading", pAreaId); if(pAreaInfinite){ infiniteListView = pInfiniteTarget; pLoadData = postLoadInfinite(pAreaId, 10, pAreaTimestamp, pAreaId, true, pAreaPost, pAreaDelete, true, pAreaSource, pAreaCounter); $(window).bind('scroll', function() { var endReached = pArea.attr("data-endreached"); if(endReached){ return false; } var scrollOffset = window.innerHeight/2; // offset from the scroll end (how early to load next data from the end of the page) if($(window).scrollTop() >= pArea.offset().top + pArea.outerHeight() - window.innerHeight - scrollOffset) { pAreaCounter = pArea.attr("data-counter"); pAreaTimestamp = pArea.attr("data-timestamp"); pLoadData = postLoadInfinite(pAreaId, 10, pAreaTimestamp, pAreaId, true, pAreaPost, pAreaDelete, false, pAreaSource, parseInt(pAreaCounter)); } }); } else { // Load initial comments pLoadData = postLoad(pAreaId, 10, pAreaTimestamp, pAreaId, true, pAreaPost, pAreaDelete, true); } } else { // Show no permission message postMsg("noPermission", pAreaId); } } function reloadInfiniteFeed(target){ console.log("reloadInfiniteFeed"); console.log(target); postLoadTime = undefined; endReached = false; lastDataNumbers = []; oldDataNumbers = undefined; renderedPosts = []; renderedDiaries = []; loadingInfiniteData = false; userFeedHeroContent = []; userFeedHeroLastAmount = 0; hopotiAdCounter = 0; pInfiniteTarget = $(target).find('.p-area-main-middle'); $(target).find('.p-area-bottom').empty(); $(pInfiniteTarget).empty(); $(target).removeAttr("data-endreached"); infiniteListView = pInfiniteTarget; $(target).each(function(index, item){ pArea = $(this); pAreaId = pArea.data("area"); pAreaPermission = pArea.data("permission"); pAreaPost = pArea.data("post"); pAreaDelete = pArea.data("delete"); pAreaInfinite = pArea.data("infinite"); pAreaSource = pArea.data("source"); pAreaTimestamp = "latest"; //force reload pAreaCounter = -1; userFeedAdIntervalCounter = 0; totalInfinitePosts = 0; console.log("refresh infinite load"); postLoadInfinite(pAreaId, 10, pAreaTimestamp, pAreaId, true, pAreaPost, pAreaDelete, false, pAreaSource, parseInt(pAreaCounter)); }); } // !Common promise solver - returns data as object for Promise.all, // also if an array with given identifier is found, populates it with data immediately function getPromise(url, params, identifier) { //TODO getpromise changes if(params){ params = buildParams(params); } let promise = new Promise(function (resolve, reject) { let req = new XMLHttpRequest(); req.open("POST", url, true); req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); req.setRequestHeader('X-CSRF-TOKEN', 'XTRDWCOVfMIhqvXCpPng98R96cXoX9QajCDgxD5Q'); req.onload = function () { if (req.status == 200) { //console.log("promise return"); if (identifier && typeof window[identifier] !== 'undefined') { window[identifier] = JSON.parse(req.response); } var returnResponse = {}; returnResponse.result = req.response; returnResponse.identifier = identifier; returnResponse.responseUrl = req.responseURL; resolve(returnResponse); } else { console.error("Promise error!"); reject("error"); } }; if(params){ req.send(params); } else { req.send(); } }); return promise; } function buildParams(data) { const params = new URLSearchParams() Object.entries(data).forEach(([key, value]) => { if (Array.isArray(value)) { $.each(value, function(i, a) { if(typeof a === 'object' && a !== null){ // is object - parse all object values to array parts for (const [okey, ovalue] of Object.entries(a)) { var thisValue = ""; if(typeof ovalue !== "undefined" && ovalue !== null){ thisValue = ovalue.toString(); } params.append(key+"["+i+"]["+okey+"]", thisValue); } } else { params.append(key+"[]", a.toString()); } }); } else { if(value){ params.append(key, value.toString()); } else { params.append(key, value); } } }); return params.toString() } var forceAdReload = false; // if true, ads are always reloaded from backend var adMaxAgeDuration = moment.duration(1, 'hours'); // how long ads loaded from localstorage until refreshed // Load ads and rewards async - use local storage versions if last load time was less than adMaxAgeDuration function getHopotiAdsAndRewards(action){ console.log("getHopotiAdsAndRewards | action: "+action); if(store.get('hopoti-ads') && !forceAdReload){ var adTimestamp = store.get('hopoti-ads').time; if(adTimestamp){ var adUpdateTime = moment(adTimestamp).add(adMaxAgeDuration); if(moment() < adUpdateTime && store.get('hopoti-ads').ads){ // use cached ads hopotiPlusAdArray = store.get('hopoti-ads').ads; hopotiPlusAdArray = reorderAdArray(hopotiPlusAdArray); console.log("use cached ads"); if($('body').hasClass('user-wall-feed')){ var feedElement = $('.p-area-user-feed'); feedElement.removeAttr("data-wait-async"); loadFeed(feedElement); } checkLazyAds(); return false; } } } // load ads and rewards let getHopotiAds = getPromise('https://hopoti.com/getHopotiAdverts', null, "hopotiAdsData"); let getHopotiRewards = getPromise('https://hopoti.com/getHopotiRewards', null, "hopotiRewardsData"); Promise.all([getHopotiAds, getHopotiRewards]).then( values => console.log(values) ).catch( error => console.error(error.message) ).finally(() => { hopotiAdsData = filterAdLanguages(hopotiAdsData); hopotiPlusAdArray = hopotiRewardsData.concat(hopotiAdsData); // combine rewards with regular ads hopotiPlusAdArray = reorderAdArray(hopotiPlusAdArray); store.set('hopoti-ads', { ads: hopotiPlusAdArray, time: Date.now() }); if($('body').hasClass('user-wall-feed')){ var feedElement = $('.p-area-user-feed'); feedElement.removeAttr("data-wait-async"); loadFeed(feedElement); } checkLazyAds(); }); } function reorderAdArray(array){ // console.log("reorderAdArray"); // console.log(array); if(!array.length){ return []; } var hopotiAds = $.grep(array, function(e){ return e.DataTypeId == 10000; }); var otherAds = $.grep(array, function(e){ return e.DataTypeId != 10000; }); if(otherAds.length){ // reorder external ads by date // otherAds = otherAds.sort(function(a, b) { // return moment(b.FromDateTime) - moment(a.FromDateTime); // }); // shuffle external ads otherAds = otherAds.map((value) => ({ value, sort: Math.random() })).sort((a, b) => a.sort - b.sort).map(({ value }) => value); } if(hopotiAds.length){ // shuffle hopoti ads hopotiAds = hopotiAds.map((value) => ({ value, sort: Math.random() })).sort((a, b) => a.sort - b.sort).map(({ value }) => value); } finalArray = braidArrays(otherAds, hopotiAds); // combine every second // logging("final reloaded ads"); // console.log(finalArray); return finalArray; } function filterAdLanguages(array){ // use LanguageCodes for ads if match - but use "NULL langcode versions" (english) if no lang match (same OrderId check) var userLang = ''; var returnArray = []; $.each(array, function(i, ad) { if(!ad.OrderId){ returnArray.push(ad); return true; } if(ad.LanguageCodes){ var adLangMatch = commonmatch(ad.LanguageCodes.split(","), userLang); if(adLangMatch.length){ returnArray.push(ad); return true; } } var langMatch = $.grep(array, function(e){ return e.OrderId == ad.OrderId && e.LanguageCodes && commonmatch(e.LanguageCodes.split(","), userLang).length; }); if(!ad.LanguageCodes && !langMatch.length){ returnArray.push(ad); } }); return returnArray; } // process slow ad html elements function checkLazyAds(){ $('.lazy-ad-frame').each(function(index, item){ var settings = $(this).data("settings"); var lazyAdHtml = adFrameHtml(settings); $(this).replaceWith(lazyAdHtml); }); } function testNumeric(value){ if (!$.isNumeric(value)){ return 0; } else { return value; } } function testRatingValue(value){ if (!$.isNumeric(value) || value == 0) { return "-"; } else { return value; } } function testRatingLevel(value){ if (value >= 4.3) { return 5; } else if (value >= 3.8 && value < 4.3) { return 4; } else if (value >= 2.8 && value < 3.8) { return 3; } else if (value >= 1.8 && value < 2.8) { return 2; } else if (value >= 1.0 && value < 1.8) { return 1; } else { return 0; } } function testRatingPercent(value,amount){ if (value >= 90) { return 5; } else if (value >= 70 && value < 90) { return 4; } else if (value >= 50 && value < 70) { return 3; } else if (value >= 30 && value < 50) { return 2; } else if (value > 0 && value < 30) { return 1; } else if (value >= 0 && value < 30 && amount > 0) { return 1; } else { return 0; } } var iconList = []; // hopoti icons function getHopotiIcons(groupid, action, buttonelement, fieldname, recommendedid){ var query = {}; var route = '/hopotiicons'; if(groupid){ query.groupid = groupid; route = '/hopotigroupicons'; } $.post(route, query, function(data){ if(data.length){ iconList = data; } console.log("hopoti icons"); console.log(data); if(action == "iconselector"){ iconSelector(buttonelement, fieldname, recommendedid); } }); } // parse through all icon placeholders function populateIcons(selector){ if(!selector){ selector = '.icon-placeholder'; } $(selector).each(function(index, item){ var thisIcon = $(this).data("icon"); var iconHtml = getIcon(thisIcon); $(this).replaceWith(iconHtml); }); } function initIconSelectors(selector){ console.log("initIconSelectors"); $(selector).each(function(index, item){ console.log(item); var originalIcon = $(this).data("icon"); var selectorId = $(this).data("id"); var recommendedId = $(this).data("recommendedid"); var selectorClass = 'icon-select-form-'+selectorId; var iconFieldHtml = ''; var iconButton = getIconSelectorButtons(originalIcon, selectorClass, recommendedId); $(this).empty().append(iconButton); $(this).parent().append(iconFieldHtml); }); } function getIconSelectorButtons(data, fieldname, recommendedid){ console.log("getIconSelectorButtons"); console.log(data); // console.log("recommendedid: "+recommendedid); if(!iconList.length){ getHopotiIcons(); } var selectbuttons = '\
    \ Select icon\
    '; if(data){ selectbuttons = '\
    '+getIcon(data)+'
    \
    '+getIcon("fa-solid fa-xmark")+'
    '; } return selectbuttons; } function iconSelector(buttonelement, fieldname, recommendedid){ console.log("iconSelector"); // console.log("recommendedid"); // console.log(recommendedid); if(!iconList.length){ getHopotiIcons(null, "iconselector", buttonelement, fieldname, recommendedid); return false; } var promode = 0; // font awesome icon can be inputted through input field var allowuserpro = 0; // if user allowed to use input if($("body").hasClass("pageStable")){ // pro mode allowed under stable pages (no user) allowuserpro = 1; } var preselected = $(document).find('.'+fieldname).val(); if(preselected == "undefined"){ preselected = ""; } if(recommendedid == "undefined"){ recommendedid = 1; } var selectedIcon; if(preselected){ selectedIcon = preselected; } var preselectedGroup; var preObject; var preIconHtml = ""; if(preselected){ preObject = $.grep(iconList, function(e){ return e.IconName == preselected; }); preIconHtml = getIcon(preselected); } if(preObject && preObject.length){ preselectedGroup = preObject[0].IconClassId; } else if(preselected && allowuserpro){ // no icon found from backend list promode = 1; } else if(recommendedid){ preselectedGroup = recommendedid; } var iconselectorContent = ""; var iconselectorGroupContent = ""; var groupHeaders = []; $(iconList).each(function(index, icon){ var hiddenClass = "hidden"; var activeClass = "btn-default"; if(preselectedGroup && preselectedGroup == icon.IconClassId){ hiddenClass = ""; } else if(!preselectedGroup && icon.IconClassId == 1){ hiddenClass = ""; } if(icon.IconName == preselected){ activeClass = "btn-primary"; } iconselectorContent += '
    '+getIcon(icon.IconName)+'
    '; if(!groupHeaders[icon.IconClassId]){ // select first class icons as header navi icons var activeClass = ""; if(preselectedGroup && preselectedGroup == icon.IconClassId){ activeClass = "active"; } else if(!preselectedGroup && icon.IconClassId == 1){ activeClass = "active"; } groupHeaders[icon.IconClassId] = ''; } }); iconselectorGroupContent = ''; var hidePromode = "display: none;"; if(promode){ hidePromode = ""; } iconselectorContent = '\
    \
    '+iconselectorGroupContent+'
    \
    \
    \ '+preIconHtml+'\ \ Icons' Fontawesome-code\
    \
    \
    '+iconselectorContent+'
    \
    '; function keypress(event){ if(event.originalEvent.keyCode == 80){ $(document).off('keydown', keypress); $(document).find('.pro-selector').slideDown(300); promode = 1; } } var promodevalid = 1; BootstrapDialog.show({ type: BootstrapDialog.TYPE_PRIMARY, cssClass: 'dialog-select-icon', title: 'Select icon', message: iconselectorContent, onshow: function(dialog) { dialog.getModalFooter().hide(); }, onshown: function(dialog) { var target = dialog.getModal(); target.on('click', '.btn-icon', function(e) { selectedIcon = $(this).data("iconname"); $('.btn-icon.btn-primary').removeClass("btn-primary").addClass("btn-default"); if(promode){ $(this).addClass("btn-primary"); target.find('input[name="icon"]').val(selectedIcon); target.find('input[name="icon"]').removeClass("bg-danger"); var iconHtml = getIcon(selectedIcon); target.find('.input-icon').html(iconHtml); promodevalid = 1; } else { dialog.close(); } }); target.on('click', '.nav-tabs a', function(e) { // navigate e.preventDefault(); var icongroup = $(this).data("icongroup"); target.find('.btn-icon').addClass("hidden"); target.find('.btn-icon[data-icongroup="'+icongroup+'"]').removeClass("hidden"); target.find('.nav-tabs li').removeClass("active"); $(this).parent().addClass("active"); }); target.on('change keyup blur', 'input[name="icon"]', function(e){ // change pro field var iconvalue = $(this).val(); var strippedvalue = iconvalue.match(/(?:"[^"]*"|^[^"]*$)/); if(strippedvalue){ iconvalue = strippedvalue[0].replace(/"/g, ""); $(this).val(iconvalue); } var iconHtml = getIcon(iconvalue); if(iconHtml){ $('.btn-icon.btn-primary').removeClass("btn-primary").addClass("btn-default"); } target.find('.input-icon').html(iconHtml); var newiconwidth = target.find('.input-icon span').width(); if(newiconwidth){ target.find('input[name="icon"]').removeClass("bg-danger"); promodevalid = 1; selectedIcon = iconvalue; } else { target.find('input[name="icon"]').addClass("bg-danger"); promodevalid = 0; } }); if(!promode && allowuserpro){ $(document).on('keydown', keypress); } }, onhide: function(dialog) { var target = dialog.getModal(); $(document).off('keydown', keypress); var buttonTarget; console.log("promode: "+promode+" | promodevalid: "+promodevalid); if(!promode || promodevalid){ // update values on pro mode only if "valid" if(buttonelement){ buttonTarget = buttonelement.closest('.icon-selector-buttons'); } else { buttonTarget = $(document).find('.icon-selector-buttons'); } buttonTarget.empty(); buttonTarget.append(getIconSelectorButtons(selectedIcon, fieldname, recommendedid)); $(document).find('.'+fieldname).val(selectedIcon).change(); } } }); } function testSubmitQuery(query, returnmissingvalues){ test = true; var missingvaluefields = []; $.each(query, function(key, value) { console.log("key: "+key+" | value: "+value); if(!value){ test = false; if(returnmissingvalues){ missingvaluefields.push(key); } } }); if(returnmissingvalues){ return missingvaluefields; } else { if (test){ return true; } else{ return false; } } } function forceSameContainerHeights(elements){ var maxheight = 0; $(elements).each(function(index, item){ console.log($(this).outerHeight()); if($(this).outerHeight() > maxheight){ maxheight = $(this).outerHeight(); } }); if(maxheight){ maxheight = Math.ceil(maxheight); $(elements).css("height", maxheight+'px'); } } function forceSameContentHeights(inputelements, heightelements){ var maxheight = 0; $(inputelements).each(function(index, item){ var thisItemHeight = 0; $(item).children().each(function(){ thisItemHeight += $(this).outerHeight(true); }); if(thisItemHeight > maxheight){ maxheight = thisItemHeight; } }); if(maxheight && heightelements){ maxheight = Math.ceil(maxheight); $(heightelements).css("min-height", maxheight+'px'); } } function addTooltip(target, tooltip){ target.attr('data-toggle', 'tooltip'); target.attr('data-trigger', 'hover focus'); target.attr('data-html', 'true'); target.attr('data-original-title', tooltip); target.tooltip(); } function removeTooltip(target){ target.tooltip('destroy'); target.removeAttr("data-toggle").removeAttr("data-trigger").removeAttr("data-html").removeAttr("data-original-title"); } function openImageDialog(imageurl){ BootstrapDialog.show({ type: BootstrapDialog.TYPE_DEFAULT, size: BootstrapDialog.SIZE_WIDE, cssClass: 'image-display-dialog', title:'', message: '' }); } var postId; var postDatatypeid; var postAction; function getSinglePostContent(id, datatypeid, action, url, dialog){ console.log("getSinglePostContent | id: "+id+" | datatypeid: "+datatypeid+" | action: "+action+" | url: "+url); if(singlePostDial){ return false; } postId = id; postDatatypeid = datatypeid; postAction = action; if(url){ changePostUrl(url, action); } var query = {}; query.objectid = id; query.type = datatypeid; query.action = action; $.ajax({ url: '/getSinglePostContent', type: 'POST', data: query, error: function(err) { commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); }, success: function(data) { console.log("singlepost data"); console.log(data); if(dialog){ // open in dialog if(data.length && data[0].SportType){ // load map data var actionData = {}; actionData.action = "singlepost-dialog"; actionData.data = data[0]; actionData.query = query; loadExerciseData(data[0].DataNumber, actionData); } else if(data.length){ singlePostDialog(data[0], query); } else { commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } } else { // inpage if(data.length && data[0].SportType){ // load map data var actionData = {}; actionData.action = "singlepost-inpage"; actionData.data = data[0]; actionData.query = query; loadExerciseData(data[0].DataNumber, actionData); } else if(data.length){ singlePostInpage(data[0], query); } else { commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } } } }); } var singlePostDial; function singlePostDialog(data, query){ // Display post in dialog console.log("singlePostDialog"); console.log(data); console.log(query); if(singlePostDial){ return false; } var datatypeid = data.DataTypeId; var postid = data.CommentId; if(data.DataTypeId == 1 || data.DataTypeId == 7){ // user diary postid = data.DataNumber; } console.log("datatypeid: "+datatypeid+" | postid: "+postid); var dialogButtons = []; var settings = {}; settings.singlepostdialog = true; var content = infinitePostConstruct(data, settings); // console.log("infinite content"); // console.log(content); var dialogTitle = getIcon('fas fa-pencil-alt')+' messages-riders.post-post'; var reportHidden = "hidden"; if(query.action == "report"){ reportHidden = ""; } var reportHelp = '\
    \ \
    '; var reportPostButton = { label: getIcon('fas fa-flag-alt')+' Report content', cssClass: 'btn-danger btn-sm pull-left post-action-report-post', autospin: false, action: function(dialogRef){ } }; dialogButtons.push(reportPostButton); var diaryClass = "p-area-post-diary"; if(content.posttype != "diary"){ diaryClass = ""; } var postPermission = false; if(myUserId){ postPermission = true; } var finalContent = '\
    \
    \ '+content.contentHtml+'\ '+content.footerHtml+'\
    \ '+reportHelp+'\
    '; singlePostDial = BootstrapDialog.show({ type: BootstrapDialog.TYPE_INFO, size: BootstrapDialog.SIZE_WIDE, cssClass: 'single-post-dialog dialog-big-close-button p-area post-type-'+content.posttype, // dialog-fixed??? title: content.headerHtml, message: finalContent, closable: false, buttons: dialogButtons, onshow: function(dialogRef){ dialogRef.getModal().attr("data-action", query.action); dialogRef.getModalFooter().hide(); if(query.action == "report"){ dialogRef.getModalFooter().show(); } }, onshown: function(dialogRef){ dialogRef.setClosable(true); if(data.ExercisePayload){ setTimeout(function(){ initMapBox("diarymap", data.ExercisePayload); }, 50); } dialogRef.getModalDialog().find('.post-action[data-action="report"]').on('click', function(e) { dialogRef.getModalFooter().show(); dialogRef.getModalDialog().find('.report-help-content').removeClass("hidden"); $('.single-post-dialog').animate({ scrollTop: $(".single-post-dialog .modal-footer").offset().top }, 500); $('.tooltip').tooltip('hide'); }); singlePostDialogConstructComments(data, dialogRef, undefined); autosize(dialogRef.getModalDialog().find('textarea')); $('[data-toggle="tooltip"]').tooltip(); }, onhide: function(dialogRef){ singlePostDial = undefined; changePostUrl(); } }); } // Function to open/hide comments function singlePostDialogConstructComments(data, dialogRef, target){ console.log("singlePostDialogConstructComments"); var commentTarget; var pArea; var pAreaPost; if(dialogRef){ var modal = dialogRef.getModalDialog(); commentTarget = dialogRef.getModal(); pArea = modal.find("[data-area]"); pAreaPost = modal.find(".p-area-post"); } else if(target){ commentTarget = target; pArea = target.find("[data-area]"); pAreaPost = target.find(".p-area-post"); } else { return false; } pAreaId = pArea.data("area"); pAreaPermission = pArea.data("post"); pAreaDelete = pArea.data("delete"); pAreaTimestamp = pArea.attr("data-timestamp"); pAreaPostId = $(pAreaPost).attr("data-id"); pAreaPostTimestamp = $(pAreaPost).attr("data-timestamp"); console.log("commentTarget"); console.log(commentTarget); console.log("pArea"); console.log(pArea); console.log("pAreaId"); console.log(pAreaId); pArea.find('.panel-footer').append(''); var pAreaPostFooter = pArea.find(".p-area-post-footer"); if (pAreaPermission){ $(pAreaPostFooter).hide().append(pAreaPostForm); pArea.find(".p-area-form").addClass("col-md-6"); } $(pAreaPostFooter).hide().append('
    '); $(pAreaPostFooter).fadeIn("slow"); postLoad(pAreaPostId, 10, pAreaPostTimestamp, pAreaId, false, pAreaPermission, pAreaDelete, true, commentTarget); } function singlePostInpage(data, query){ // Display post inpage NOT IN USE ATM console.log("singlePostInpage"); var settings = {}; settings.inpagepost = true; var content = infinitePostConstruct(data, settings); console.log("content"); console.log(content); var reportHelp = ""; var diaryClass = "p-area-post-diary"; if(content.posttype != "diary"){ diaryClass = ""; } var postTarget = $(document).find('.load-single-post'); postTarget.append(content.allHtml); if(data.ExercisePayload){ setTimeout(function(){ initMapBox("diarymap", data.ExercisePayload); }, 50); } singlePostDialogConstructComments(data, undefined, postTarget.parent()); } function changePostUrl(url, action){ console.log("changePostUrl | url: "+url+" | action: "+action); var back = 1; var pagerooturl = $('body').data("pagerooturl"); // use page defined base url if(!url){ if(pagerooturl){ window.history.replaceState("", document.title, pagerooturl); } return false; } var Paction = ''; if(action && !url.endsWith(action)){ // add action if not already present Paction = '/'+action; } query = url+Paction; if(back == 1){ window.history.pushState("", document.title, checkUrlExtraParameters(query)); } else { window.history.replaceState("", document.title, checkUrlExtraParameters(query)); } } // DOM element visibility test - add observer to elements. Adds classes based on element position on screen const observerconfig = { root: null, rootMargin: '0px', threshold: [0.1, 0.5, 0.7, 1] }; let previousY = 0; let previousRatio = 0; let observer = new IntersectionObserver(function(entries) { var now = Date.now(); entries.forEach(entry => { const currentY = entry.boundingClientRect.y const currentRatio = entry.intersectionRatio const isIntersecting = entry.isIntersecting const element = entry.target; var postSeen = $(element).attr("data-postseen"); var postId = $(element).attr("data-id"); var dataTypeId = $(element).attr("data-datatypeid"); var postIndex = $(element).attr("data-post-index"); var postType = $(element).attr("data-posttype"); var adType = $(element).attr("data-adtype"); var carouselVisible = 0; $(element).attr("data-observed", 1); var seen = {}; seen.postindex = Number(postIndex); if(postId && dataTypeId){ seen.id = postType+"-"+postId; seen.postid = Number(postId); seen.datatypeid = Number(dataTypeId); } else if(postId && adType){ seen.id = adType+"-"+postId; seen.postid = Number(postId); seen.adtype = adType; } var savedseen = $.grep(postSeenArray, function(e){ return e.id == seen.id; }); // use object already in array if(savedseen.length){ seen = savedseen[0]; } element.classList.remove("outview-top", "inview-top", "inview-bottom", "outview-bottom", "inview", "outview"); if (entry.isIntersecting) { element.classList.add("inview"); if(entry.intersectionRatio >= 0.5){ seen.intime = now; carouselVisible = 1; } } else { element.classList.add("outview"); delete seen.intime; } if($(element).hasClass("user-hero-content")){ // carousel additions $(element).attr("data-carousel-visible", carouselVisible); } if(seen.id){ insertOrUpdate(postSeenArray, seen); } if (currentY < previousY) { // Scrolling up const className = (currentRatio >= previousRatio) ? "inview-top" : "outview-top"; element.classList.add(className); } else if (currentY > previousY) { // Scrolling down const className = (currentRatio <= previousRatio) ? "outview-bottom" : "inview-bottom"; element.classList.add(className); } // add extra style if content too long var postContent = $(element).find('.p-area-post-content'); if(checkScroll(postContent)){ element.classList.add("readmore"); } previousY = currentY previousRatio = currentRatio }) if(submitGaData){ //console.log(postSeenArray); submitGaInterval(); } }, observerconfig); function checkScroll(element){ //console.log(postContent.prop('scrollHeight')+" | "+postContent.outerHeight()) if (element.prop('scrollHeight') > element.outerHeight()+10 ) { // 10 for error margin return true; } else { return false; } } function findZIndex(elements){ var index_highest = 0; $(elements).each(function() { var index_current = parseInt($(this).css("zIndex"), 10); if(index_current > index_highest) { index_highest = index_current; } }); return index_highest; } //! Common insert or update to object array // based on "id" - modifies object in array if found, otherwise adds function insertOrUpdate(array, element) { const i = array.findIndex(_element => _element.id === element.id); if (i > -1) array[i] = element; // (2) else array.push(element); } // common loading error dialog with refresh button // remove target content and append function loadingError(removetarget, appendtarget){ var errorHtml = '\
    \ Loading failed\

    Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.\

    \
    '; if(removetarget){ removetarget.remove(); } if(appendtarget){ appendtarget.append(errorHtml); $('body').on('click', '.btn-refresh-page-error', function(e) { e.preventDefault(); location.reload(); }); } } // Use classes hopoti-plus-status-active-show or hopoti-plus-status-inactive-remove to remove or show plus related classes function checkPlusStatus(){ console.log("checkPlusStatus | hopotiPlusActive: "+hopotiPlusActive); if(!hopotiPlusPublished){ return false; } if(hopotiPlusActive){ $(document).find('.hopoti-plus-status-active-show').removeClass("hidden"); $(document).find('.hopoti-plus-status-active-hide').addClass("hidden"); $(document).find('.hopoti-plus-status-active-remove').remove(); } else { $(document).find('.hopoti-plus-status-inactive-show').removeClass("hidden"); $(document).find('.hopoti-plus-status-inactive-hide').addClass("hidden"); $(document).find('.hopoti-plus-status-inactive-remove').remove(); } } // common discard changes question which closes the parent dialog if accepted function discardChangesNag(dialogRef){ BootstrapDialog.confirm({ title: 'Unsaved changes', message: 'Unsaved changes. Are you sure you want to close the window without saving?', type: BootstrapDialog.TYPE_WARNING, btnCancelLabel: 'Cancel', btnCancelClass: 'btn-default btn-sm', btnOKLabel: 'Discard changes', btnOKClass: 'btn-warning btn-sm pull-left', callback: function(result) { // If modal confirm, then submit info if(result) { dialogRef.close(); } else { // cancel console.log('cancel'); } } }); } // !Load new horsecare event types only if version has changed [diary][horsecare] function getHorseCareEventTypes(target){ console.log("getHorseCareEventTypes"); console.log(target); if(horseCareOptionsReady){ return false; } var reloadalways = false; // !Force reload CACHE var versionnumber = '2'; // change version number for user hard refresh var cachedEventtypes = store.get('horsecare-eventtypes'); var cachedversion; var cachedlang; var langcode = ''; if(reloadalways && eventTypesReseted == 0){ eventTypesReseted = 1; cachedEventtypes = null; } if(cachedEventtypes){ cachedversion = store.get('horsecare-eventtypes').version; cachedlang = store.get('horsecare-eventtypes').language; } if(versionnumber == cachedversion && langcode == cachedlang){ console.log("use cached event types"); var horsecareOptionsData = store.get('horsecare-eventtypes').html; var horsecareOptionsDialogData = store.get('horsecare-eventtypes').dialoghtml; var actionmenuhtml = store.get('horsecare-eventtypes').actionmenuhtml; horsecareEventTypeDialogButtons = horsecareOptionsDialogData; horsecareEventTypeJson = store.get('horsecare-eventtypes').json; eventTypesJson = store.get('horsecare-eventtypes').eventtypesjson; if(target){ var menuplaced = $(target).find(".horsecare-options-menu"); if(!menuplaced.length){ if(target == '.horsecare-action-navi'){ $(document).find(target).append(actionmenuhtml); return actionmenuhtml; } else if(target != ".horsecare-calendar-allhorses"){ // remove extra filters under single horse dialogs var horsecareOptionsData = $(horsecareOptionsData).clone(); horsecareOptionsData.find(".dropdown-toggle, .dropdown-menu").remove(); } else { $(target).find('.horsecare-horselist').remove(); $(target).find('.fc-toolbar').after(horseCareHorseList); activateHorseCareHorses(); } $(target).find('.fc-toolbar').after(horsecareOptionsData); activateHorseCareFilters(target); horseCareOptionsReady = 1; } } } else { console.log("load new event types"); eventTypesLoaded = 1; $.post( 'https://hopoti.com/getCommonEventTypes' , function(data){ }).done(function(data) { parseHorsecareEventTypes(data, versionnumber, langcode, target); }).fail(function(data) { commonHelpDialog('Loading failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); }).always(function() { }); } }; var horseCareOptionsReady = 0; var horsecareEventTypeDialogButtons; var horsecareEventTypeJson; var eventTypesJson; var eventTypesReseted = 0; var excludeHcIds = [0,100,101,102,200]; // do not show these options to user function parseHorsecareEventTypes(data, versionnumber, langcode, target){ console.log(data); // calendar top options var horseCareOptionsHtml = ""; var horseCareTreatments = ""; var horseCareActivities = ""; var horseCareOther = ""; // edit dialog options var horsecareOptionsDialogHtml = ""; var horseCareDialogTreatments = ""; var horseCareDialogActivities = ""; var horseCareDialogOther = ""; var horsecareeventtypes = data.horsecareeventtypes; var eventtypes = data.eventtypes; horsecareeventtypes = horsecareeventtypes.sort((a, b) => parseFloat(a.Order) - parseFloat(b.Order)); $.each(horsecareeventtypes, function(key, value) { if(commonmatch(value.HorseEventTypeId, excludeHcIds).length){ return true; } var eventtypeid = value.HorseEventTypeId; // calendar top buttons var singleOptionButton = '\ '; // dialog buttons var singleOptionDialogButton = '\ \ '+value.EventType+'\ '; if(value.EventClassId == 2){ // activities horseCareActivities = horseCareActivities + singleOptionButton; horseCareDialogActivities = horseCareDialogActivities + singleOptionDialogButton; } else if(value.EventClassId == 3){ // treatment horseCareTreatments = horseCareTreatments + singleOptionButton; horseCareDialogTreatments = horseCareDialogTreatments + singleOptionDialogButton; } else if(value.EventClassId == 1){ // other horseCareOther = horseCareOther + singleOptionButton; horseCareDialogOther = horseCareDialogOther + singleOptionDialogButton; } }); if(horseCareActivities){ horseCareActivities = '\
    \
    \
    \ '+horseCareActivities+'\
    \
    '; horseCareDialogActivities = '\
    \ \
    '+horseCareDialogActivities+'
    \
    '; } if(horseCareTreatments){ horseCareTreatments = '\
    \
    \
    \ '+horseCareTreatments+'\
    \
    '; horseCareDialogTreatments = '\
    \ \
    '+horseCareDialogTreatments+'
    \
    '; } if(horseCareOther){ horseCareOther = '\
    \
    \
    \ '+horseCareOther+'\
    \
    '; horseCareDialogOther = '\
    \ \
    '+horseCareDialogOther+'
    \
    '; } var horseCareButtons = '\
    \
    \
    \ \ \ \
    \
    \
    \
    \ \
    \
    \
    \
    \ \
    \
    \
    '; horseCareOptionsHtml = '
    '+horseCareActivities+horseCareTreatments+horseCareOther+horseCareButtons+'
    '; horsecareOptionsDialogHtml = horseCareDialogActivities+horseCareDialogTreatments+horseCareDialogOther; horsecareEventTypeJson = horsecareeventtypes; eventTypesJson = eventtypes; store.set('horsecare-eventtypes', { version: versionnumber, json: horsecareeventtypes, eventtypesjson: eventtypes, html: horseCareOptionsHtml, //dialoghtml: horsecareOptionsDialogHtml, actionmenuhtml: horsecareOptionsDialogHtml, language: langcode }); } function postConstructDiaryContent(data, settings){ // console.log("postConstructDiaryContent"); // console.log(data); // console.log("settings"); // console.log(settings); var diaryPostContent = ""; var ratingLesson = ""; var ratingRider = ""; var ratingHorse = ""; var sportSummary = ""; var ratingBlockAmount = 0; if(data.RatingLesson){ ratingBlockAmount++; ratingLesson = '\
    \ Overall rating\
    \ '+buildRatingStars(data.RatingLesson, "star-all")+'\
    \
    '; } if(data.RatingRider){ ratingBlockAmount++; ratingRider = '\
    \ Rider\
    \ '+buildRatingStars(data.RatingRider, "emoji-all")+'\
    \
    '; } if(data.RatingHorse){ ratingBlockAmount++; var horseName = ''; if(data.HorseName){ horseName = ''+data.HorseName+''; } ratingHorse = '\
    \ Horse'+horseName+'\
    \ '+buildRatingStars(data.RatingHorse, "emoji-all")+'\
    \
    '; } var ratingDivs = ""; if(ratingBlockAmount){ ratingDivs = '\
    \ '+ratingLesson+'\ '+ratingRider+'\ '+ratingHorse+'\
    '; } var mapContent = ''; // var tableContent = ''; var fitnessContent = ''; if(settings && settings.singlepostdialog && data.SportType || settings && settings.inpagepost && data.SportType){ if(data.ExercisePayload){ mapContent = '\
    \
    \
    '; } fitnessContent = '\
    \ '+mapContent+'\
    \ '+exerciseTableHtml(data)+'\
    \
    '; } var openDialogButtons = ""; if(settings && settings.feed && data.SportType){ openDialogButtons = '\ '; } diaryPostContent = '\
    \
    \
    \ Riding diary\
    \ '+getSportDataSummary(data, settings)+'\ '+ratingDivs+'\ '+fitnessContent+'\ '+openDialogButtons+'\
    \
    '; var diaryTextAreaContent = ""; if(data.Comment){ diaryTextAreaContent += '
    '+postConstructContent(data.Comment)+'
    '; } if(data.Feedback){ diaryTextAreaContent += '
    '+postConstructContent(data.Feedback)+'
    '; } if(data.Learning){ diaryTextAreaContent += '
    '+postConstructContent(data.Learning)+'
    '; } if(data.CommentFileName){ var diaryPostImage = ''; diaryTextAreaContent += diaryPostImage; } if(diaryTextAreaContent){ diaryPostContent += '
    '+diaryTextAreaContent+'
    '; } return diaryPostContent; } // !Transform diary event data [usercalendar][diary] function diaryEventDataTransform(data){ // var ro = new Object(); // // ro.start = data.StartDateTime; // ro.end = data.EndDateTime; // ro.DiaryEventId = data.DiaryEventId; data.start = data.StartDateTime; data.end = data.EndDateTime; data.sort = "2"; return data; //return ro; } function buildRatingStars(value, type){ logging("buildRatingStars | value: "+value+" | type: "+type); var stars = ""; var emoji = ""; var leftStars = 5-value; if(type == "star"){ while(value > 0) { stars += ''; value--; } while(leftStars > 0) { stars += ''; leftStars--; } } else if(type == "star-all"){ stars = '\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ '; } else if(type == "emoji"){ var emojis = []; emojis[1] = ''; emojis[2] = ''; emojis[3] = ''; emojis[4] = ''; emojis[5] = ''; emoji = emojis[value]; } else if(type == "emoji-all"){ var emojiActive = []; emojiActive[1] = emojiActive[2] = emojiActive[3] = emojiActive[4] = emojiActive[5] = "fa-regular"; emojiActive[value] = "fa-solid rating-active"; emoji = '\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ '; } var ratingHtml = '\
    \ '+stars+'\ '+emoji+'\
    '; return ratingHtml; } function getSportDataSummary(data, settings){ console.log("getSportDataSummary"); // console.log(data); // console.log(settings); if(!data.Distance || !data.Duration || !data.HeartRateAverage || !data.HeartRateMax || !data.Calories){ return ""; } var extraClass = ""; if(settings && settings.feed || settings && settings.singlepostdialog){ extraClass = "col-xxs-12 col-xs-9 col-md-9 col-sm-9 col-xs-12"; } var tDistance = formatMetresAsKilometres(data.Distance); var exerciseduration = moment.duration(data.Duration); // sport data var duration = ' '+formatDuration(exerciseduration)+''; var distance = ' '+tDistance+''; var heartbeat = ' '+data.HeartRateAverage+'/'+data.HeartRateMax+''; var calories = ' '+data.Calories+' kcal'; if(settings && settings.singlepostdialog){ heartbeat = calories = ""; } var eMessage = '\
    \ '+duration+'\ '+distance+'\ '+heartbeat+'\ '+calories+'\
    '; ; return eMessage; } //! General reload page after a time var pageTimer; var reloadPageTime = 7200000; //2h //var reloadPageTime = 5000; //5sec test var openPageDialogOnFocus = false; var reloadTimerClassList = ['page-user', 'pageStable', 'stablepage']; // activate reload counter on pages containing these body styles function reloadPageTimer(){ var classList = $('body').prop('className').split(' '); if(!commonmatch(classList, reloadTimerClassList).length){ return false; } clearInterval(pageTimer); pageTimer = setInterval(function() { var currentTime = (new Date()).getTime(); var forceRefresh = false; // if (currentTime > (lastLoadIntervalTime + 10000)) { // ignore small delays // console.log('Probably just woke up!'); // forceRefresh = true; // } if(currentTime > lastLoadTime + reloadPageTime){ console.log('total time exceeded!'); forceRefresh = true; } if(forceRefresh){ console.log(moment(currentTime).format("YYYY-MM-DD HH:mm:ss")); console.log("time to refresh"); clearInterval(pageTimer); if(pageFocus){ reloadPageDialog(); } else { openPageDialogOnFocus = true; } } lastLoadIntervalTime = currentTime; }, 5000); // 5sec interval } function reloadPageDialog(){ console.log("reloadPageDialog"); openPageDialogOnFocus = false; var pageLoaded = $('body').attr('data-page-loaded'); var timeago = jQuery.timeago(pageLoaded); var loadedAgoString = 'Page was loaded [x] and its content may have changed.'.replace("[x]", timeago); var spinnerHtml = '\
    \
    \

    '+loadedAgoString+'

    \ \ \
    \
    '; $('body').append(spinnerHtml); $('.headercontainer, .headercontainer-2019, .maincontainer, .mainimage').addClass("disabled"); $('header, footer').addClass("disabled-opaque"); $('body').addClass("fullscreen-spinner-body"); } function closePageDialog(){ $('.headercontainer, .headercontainer-2019, .maincontainer, .mainimage').removeClass("disabled"); $('header, footer').removeClass("disabled-opaque"); $('body').removeClass("fullscreen-spinner-body"); $('body').find('.fullscreen-spinner.refresh-view').remove(); setTimeout(function(){ reloadPageTimer(); }, 3600000); //1h } var gaInterval; function submitGaInterval(){ console.log("submitGaInterval"); clearInterval(gaInterval); gaInterval = setInterval(function() { var submitSeenArray = $.grep(postSeenArray, function(e){ return e.intime && !e.submitted; }); // use object already in array // console.log("submitSeenArray"); // console.log(submitSeenArray); if(submitSeenArray.length){ addToSubmitBackendQueue(JSON.parse(JSON.stringify(submitSeenArray))); // backend submit, clone just in case addToSubmitGaQueue(submitSeenArray); } }, 1000); // 1sec interval } var submitGaQueue = []; function addToSubmitGaQueue(data){ logging("addToSubmitGaQueue"); logging(data); $(data).each(function(index, item){ item.submitted = 1; insertOrUpdate(postSeenArray, item); var source = "Source empty"; var category = "No category"; var label = "No label"; if(submitGaDataSource){ source = submitGaDataSource; } var typeData = returnDatatypeid(item.datatypeid); if(typeData){ if(typeData.category == "ad"){ category = typeData.category + " - " +typeData.type; } else { category = typeData.category; } label = typeData.type; } var submitObject = {}; submitObject.hitType = 'event'; submitObject.eventCategory = source + " - " + category; if(item.carouselindex){ submitObject.eventAction = "Show - C"+item.carouselindex; } else if(item.postindex) { submitObject.eventAction = "Show - P"+item.postindex; } submitObject.eventLabel = label; submitObject.eventValue = 1; // logging("submitObject"); // console.log(submitObject); submitGaQueue.push(submitObject); }); submitGaDataArray(); } var submitGaDataInterval; function submitGaDataArray(){ //console.log("submitGaDataArray"); if(!submitGaQueue.length){ //console.log("nothing to submit!"); return false; } clearInterval(submitGaDataInterval); submitGaDataInterval = setInterval(function() { var submitdata = submitGaQueue.shift(); //console.log(submitdata); if(submitdata){ //console.log("submit data"); ga('send', submitdata); } else { //console.log("queue empty"); clearInterval(submitGaDataInterval); } }, 2000); // submit every 2sec } var submitBackendQueue = []; var submitBackendDataInterval; var submitBackendAsked = false; function addToSubmitBackendQueue(data){ // console.log("addToSubmitBackendQueue"); // console.table(data); if(!submitBackendSeenData){ return false; } if(data){ submitBackendQueue = submitBackendQueue.concat(data); } if(!submitBackendQueue.length){ console.log("nothing to submit!"); return false; } if(!submitBackendAsked){ submitBackendAsked = true; setTimeout(function(){ submitBackendArray(); }, 5000); // 5sec } } function submitBackendArray(){ // logging("submitBackendArray"); if(!submitBackendQueue.length){ return false; } // console.log(submitBackendQueue); var query = {}; query.seendata = submitBackendQueue; submitBackendQueue = []; submitBackendAsked = false; $.ajax({ url: 'https://hopoti.com/userPostsSeen', type: 'POST', data: query, error: function(err) { }, success: function(data) { } }); } //! Common categorization for datatypeids function returnDatatypeid(id){ var returnobj = {}; if(id == 1){ returnobj.note = "User own diary"; // explanation returnobj.category = "own"; // post category/owner returnobj.type = "diary"; // post visual type } else if(id == 2){ returnobj.note = "Any comment under posts/diaries"; returnobj.category = "comment"; returnobj.type = "comment"; } else if(id == 3){ returnobj.note = "Horse post"; returnobj.category = "horse"; returnobj.type = "post"; } else if(id == 4){ returnobj.note = "Business post"; returnobj.category = "business"; returnobj.type = "post"; } else if(id == 5){ returnobj.note = "Friend post"; returnobj.category = "friend"; returnobj.type = "post"; } else if(id == 6){ returnobj.note = "User own post"; returnobj.category = "own"; returnobj.type = "post"; } else if(id == 7){ returnobj.note = "Friend diary"; returnobj.category = "friend"; returnobj.type = "diary"; } else if(id == 8){ returnobj.note = "Hopoti suggested user post"; returnobj.category = "hopoti"; returnobj.type = "post"; } else if(id == 9){ returnobj.note = "Hopoti suggested user diary"; returnobj.category = "hopoti"; returnobj.type = "diary"; } else if(id == 10){ returnobj.note = "Hopoti boosted single diary"; returnobj.category = "hopoti"; returnobj.type = "diary"; } else if(id == 11){ returnobj.note = "Hopoti boosted single post"; returnobj.category = "hopoti"; returnobj.type = "post"; } else if(id == 10000){ // ads returnobj.note = "Hopoti ad"; returnobj.category = "ad"; returnobj.type = "hopoti"; } else if(id == 10001){ returnobj.note = "Hopoti reward ad"; returnobj.category = "ad"; returnobj.type = "reward"; } else if(id == 10002){ returnobj.note = "External ad"; returnobj.category = "ad"; returnobj.type = "externalad"; } if(returnobj.note || returnobj.category || returnobj.type){ return returnobj; } else { return null; } } function returnCallToAction(id){ logging("//FIXME add more call to action options"); var returnTitle = ""; if(id == 1){ returnTitle = 'Check'; } else if(id == 2){ returnTitle = 'Show offer'; } else if(id == 3){ returnTitle = 'Read more'; } if(returnTitle){ return returnTitle; } else { return false; } } //!Check all inputted or type="tel" fields, use plugin to format and display telephone numbers with validation var errorMap = ["Invalid number", "Invalid area code", "Too short number", "Too long number", "Invalid number"]; function checkTelInputFields(input){ console.log("checkTelInputFields"); var telInput; if(input){ telInput = input; } else { telInput = $('input[type="tel"]'); } telInput.each(function(i, el) { var cTel = $(el); if(cTel.data("tel-checked")){ //console.log("already tel checked"); return true; } cTel.attr("data-tel-checked", 1); var initialValue = cTel.data("initial-value"); var initialSubmitValue = ""; var initialValueIsValid = false; var randomId = Math.floor(1000000 + Math.random() * 9000000); cTel.attr("data-tel-input-id", randomId); var inputName = $(this).attr('name'); var submitFieldName = ""; if (typeof inputName !== 'undefined' && inputName !== false) { cTel.removeAttr('name'); submitFieldName = inputName; } var requiredHtml = ""; var inputRequired = $(this).attr('required'); if (typeof inputRequired !== 'undefined' && inputRequired !== false) { cTel.removeAttr('inputRequired'); requiredHtml = ' required="required"'; } var hopotiCountry = ""; var countrylist = preferredCountrylist; if(!countrylist.includes(hopotiCountry)){ countrylist.unshift(hopotiCountry); } if(initialValue){ initialValueIsValid = intlTelInputUtils.isValidNumber(initialValue); if(initialValueIsValid){ initialSubmitValue = initialValue; } } var iti = window.intlTelInput(el, { preferredCountries: preferredCountrylist, initialCountry: hopotiCountry, separateDialCode: true, utilsScript: "/static/plugins/intl-tel-input-17.0.0/js/utils.js" }); var submitField = '' cTel.after(submitField); cTel.on('keyup keypress blur change', function(e) { cTel.attr("data-is-valid", 0); if (cTel[0].value.trim()) { if (iti.isValidNumber()) { // number is valid cTel.attr("data-is-valid", 1); $('input[name="'+submitFieldName+'"]').val(iti.getNumber()); cTel.closest('.form-group').removeClass("has-error has-danger"); $('input[name="'+submitFieldName+'"]').attr("data-error", "Number ok!"); if(cTel.data("init-complete")){ cTel.closest('.form-group').find('.help-block').empty().html('
    • Number ok!
    '); } } else { // number invalid $('input[name="'+submitFieldName+'"]').val(""); var errorCode = iti.getValidationError(); $('input[name="'+submitFieldName+'"]').attr("data-error", errorMap[errorCode]); //addition for stable settings cTel.closest('.form-group').find('.help-block').empty().html('
    • '+errorMap[errorCode]+'
    '); cTel.closest('.form-group').addClass("has-error has-danger"); } } else { $('input[name="'+submitFieldName+'"]').val(""); $('input[name="'+submitFieldName+'"]').attr("data-error", "Info missing"); } }); if(initialValue && initialValueIsValid){ // populate field if initial value is valid initialValue = String(initialValue); iti.setNumber(initialValue); } else if(initialValue && !initialValueIsValid){ // add note with old number to update var noteString = 'Old number is [x] - check the number and country code'.replace("[x]", ''+initialValue+''); var oldNumberNote = '
    '+noteString+'
    '; cTel.closest('.form-group').append(oldNumberNote); } setTimeout(function(){ cTel.data("init-complete", 1); }, 500); }); } // custom console logging, only for superadmins function logging(data, color){ } //takes date and time variables in date or moment format and outputs either fixed string or moment objects function getCombinedDateTime(date, time, format){ var datemoment; var timemoment; if(date instanceof Date){ // is date variable datemoment = moment(date); } else if(date.isValid()){ // is moment already datemoment = date; } else { return null; } if(time instanceof Date){ // is date variable timemoment = moment(time); } else if(time.isValid()){ // is moment already timemoment = time; } else { return null; } var dateString = datemoment.format("YYYY-MM-DD"); var timeString = timemoment.format("HH:mm"); var combinedString = dateString + " " + timeString; if(format == "moment"){ return moment(combinedString, "YYYY-MM-DD HH:mm"); } else { return combinedString; } } // combine any amount of arrays picking array items every second // usage: braidArrays(['a','b','c','d'], [1,2,3], [99,98,97,96,95]); const braidArrays = (...arrays) => { const braided = []; for (let i = 0; i < Math.max(...arrays.map(a => a.length)); i++) { arrays.forEach((array) => { if (array[i] !== undefined) braided.push(array[i]); }); } return braided; }; function clickAnimateToElement(element){ logging("clickAnimateToElement"); var target = element.data("scroll-target"); var scrollAmount = $(target).offset().top; var scrollTime = scrollAmount/2; $([document.documentElement, document.body]).animate({ scrollTop: $(target).offset().top-15 }, scrollTime); } var stableAllWaivers = []; var stableOpenWaiver; var loadingAllWaivers = false; var forceRefreshWaivers = false; // dev force waiver reload always without cache var userWaiverStableIds = []; var userWaiverStableUsers = []; function loadStableActiveWaivers(initquery){ // load active waivers for any users (testing for now) if(!waiversFeature){ return false; } console.log("loadStableActiveWaivers"); console.log(initquery); if(loadingAllWaivers){ return false; } loadingAllWaivers = true; var query = {}; if(initquery){ query = initquery; } query.url = '/getStableActiveWaivers'; if(!query.stableids && typeof currentStableId !== "undefined"){ query.stableids = [currentStableId]; } else if(userWaiverStableIds.length){ query.stableids = userWaiverStableIds; } if ($('body').hasClass("pageStableFrontpage")) { // reload forms faster on stable front page query.cachetime = [1, "minutes"]; } var refreshWaivers = true; if(store.get('forms-user-'+myUserId) && !forceRefreshWaivers){ refreshWaivers = false; // check if stable ids found from asked cache if(query.stableids.every(r => store.get('forms-user-'+myUserId).stableids.includes(r))){ logging("cache contains all stableids"); } else { logging("cache DOES NOT contain all stableids"); refreshWaivers = true; } var formsCacheTime = store.get('forms-user-'+myUserId).timestamp; var formsCacheMoment = moment.unix(formsCacheTime/1000); var cacheEndingMoment; if(query.cachetime){ cacheEndingMoment = formsCacheMoment.add(query.cachetime[0], query.cachetime[1]); } else { cacheEndingMoment = formsCacheMoment.add(1, 'hours'); } if(moment() > cacheEndingMoment){ // check cache time refreshWaivers = true; } if(typeof stableActiveWaiver !== 'undefined' && stableActiveWaiver && stableActiveWaiver.StableWaiverTypeId){ var activeWaiverMatch = $.grep(store.get('forms-user-'+myUserId).forms, function(e){ return e.StableWaiverTypeId == stableActiveWaiver.StableWaiverTypeId }); if(!activeWaiverMatch.length){ refreshWaivers = true; } } if(!refreshWaivers){ logging("use waiver cache", "teal"); stableAllWaivers = store.get('forms-user-'+myUserId).forms; initStableAllWaivers(stableAllWaivers); if(query.openwaiver){ waiverSign(query.openwaiver); } loadingAllWaivers = false; return false; } } logging("load waivers", "teal"); stableAllWaivers = []; let getStableActiveWaivers = getPromise(query.url, query); getStableActiveWaivers.then( (values) => { stableAllWaivers = JSON.parse(values.result); store.set('forms-user-'+myUserId, { forms: stableAllWaivers, stableids: query.stableids, timestamp: moment().format('x') }); logging("stableAllWaivers"); logging(stableAllWaivers); initStableAllWaivers(stableAllWaivers); if(query.openwaiver){ waiverSign(query.openwaiver); } loadingAllWaivers = false; } ).catch( (error) => { console.error(error.message); loadingAllWaivers = false; commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } ).finally(() => { }); } function removeWaiverCache(){ if(myUserId){ store.remove('forms-user-'+myUserId); } } function reloadWaivers(){ $('[data-append-waiver]').each(function(index, item){ $(item).find('.waiver-append-content').remove(); $(item).removeAttr("data-waiver-added"); }); loadStableActiveWaivers(); } function initStableActiveWaivers(data){ // init everything waiver related if active waiver found logging("initStableActiveWaivers"); logging(data); if(!data.length){ return false; // no active waiver found } // logging("userWaiverStableUsers"); // logging(userWaiverStableUsers); var userCalendarPage = $('body').hasClass('pageUserCalendar-v2'); var userFeedPage = $('body').hasClass('user-wall-feed'); if(userCalendarPage || userFeedPage){ // add extra waiver elements for user pages if(userWaiverStableUsers.length){ $(userWaiverStableUsers).each(function(index, item){ if(userFeedPage){ var waiverMissingRow = '
    '; $('body').not('[append-waivers-added]').find('.user-feed-summary').prepend(waiverMissingRow); } else { var waiverMissingRow = '
    '; $('body').not('[append-waivers-added]').find('.content').prepend(waiverMissingRow); } }); $('body').attr('append-waivers-added', 1); } } $(data).each(function(index, waiver){ // logging("single waiver"); // logging(waiver); if(waiver.UserSignRequire){ $('[data-append-waiver]').each(function(index, item){ //logging("parsing waivers", "red"); var waiverAdded = $(item).attr("data-waiver-added"); var waiverSetup = {}; waiverSetup.action = $(item).attr("data-append-waiver"); waiverSetup.stableid = $(item).attr("data-waiver-stableid"); waiverSetup.eventdate = $(item).attr("data-waiver-event-date"); if($(item).attr("data-userids")){ waiverSetup.users = $(item).attr("data-userids").toString().split(","); } if(waiver.StableId == waiverSetup.stableid && !waiverAdded){ // correct stable and note not added var waiverSignInfo = getWaiverSignHtml(waiverSetup, waiver); logging("waiverSignInfo", "teal"); logging(waiverSignInfo); if(waiverSignInfo.html){ $(item).append(waiverSignInfo.html).attr("data-waiver-added", 1); if(waiverSetup.action == "event-dialog-user-row"){ // remove switch account link if missing waivers to not confuse user $(document).find('.dialog-user-calendar-event .participant-item .switchaccount-account').remove(); } } if(waiverSignInfo.datewarning){ var blinkingWarning = '
    '; $(document).find('[data-append-waiver="user-page"]:not([data-datewarning="1"]) .info-waiver .list-group').prepend(blinkingWarning); $(document).find('[data-append-waiver="user-page"]').attr("data-datewarning", 1); } } }); } }); } function getWaiverSignHtml(setup, waiver){ logging("getWaiverSignHtml"); logging("setup"); logging(setup); logging("waiver"); logging(waiver); var usersValid = false; var waiverUsersValid = []; var waiverUsersInvalid = []; var returnData = {}; returnData.datewarning = false; if(!setup.users && myUserId){ setup.users = [myUserId.toString()]; } if(!setup.eventdate){ setup.eventdate = moment().format("YYYY-MM-DD HH:mm:ss"); // use current moment if no date } else { if(moment() < moment(setup.eventdate) && moment(setup.eventdate) < moment().add(3, "days")){ returnData.datewarning = true; } } //logging(setup); if(setup.users){ // check each users for valid/invalid waivers $(setup.users).each(function(index, userid){ var signatureMatch = $.grep(waiver.UserSignatures, function(e){ if(e.ValidToDateTime){ return e.UserId == userid && moment(e.ValidToDateTime) > moment(setup.eventdate); } else { return e.UserId == userid; } }); if(signatureMatch.length){ waiverUsersValid.push(parseInt(userid)); } else { waiverUsersInvalid.push(parseInt(userid)); } }); if(waiverUsersValid.length == setup.users.length){ usersValid = true; } } // logging("usersValid: "+usersValid); // logging("waiverUsersValid"); // logging(waiverUsersValid); // logging("waiverUsersInvalid"); // logging(waiverUsersInvalid); returnData.usersvalid = usersValid; returnData.waiverusersvalid = waiverUsersValid; returnData.waiverusersinvalid = waiverUsersInvalid; var extraStyles = ""; var signWaiverLink = ""; var waiverHelpText = "Participation in the events requires acceptance of the Registration Form."; var signButton = ""; var waiverUrlLink = 'https://hopoti.com/stable/'+waiver.StableInfo[0].StableLinkName+'/?page=forms&f='+waiver.StableWaiverId; var waiverStableLink = 'https://hopoti.com/stable/'+waiver.StableInfo[0].StableLinkName; var childData = []; //if(waiverUsersInvalid.length && waiverUsersInvalid[0] != myUserId){ var childData = $.grep(userChildrenJSON, function(e){ return waiverUsersInvalid.includes(e.UserId) }); logging("childData", "red"); logging(childData); if(waiverUsersInvalid.includes(myUserId)){ // current account signButton = ' Sign Registration Form'; } else if(childData.length){ // other than current account = child signButton = '\ \ Sign the Registration Form for the child account\ '; } if(setup.action == "event-calendar-user"){ if(usersValid){ // user calendar event ok return returnData; } else { // user calendar event waiver missing var eventLabel = '
    Sign Registration Form!
    '; returnData.html = eventLabel; return returnData; } } else if(setup.action == "event-dialog-user"){ if(usersValid){ return returnData; } waiverHelpText = "You have booked an event in which participation requires acceptance of a Registration Form. Fill and sign the form before the start of the event or the service provider may deny participation."; if(waiverUsersInvalid.length > 1){ waiverHelpText += " Signature is missing from [x] accounts.".replace('[x]',''+waiverUsersInvalid.length+''); } signWaiverLink = '\ '; } else if(setup.action == "event-dialog-user-row"){ if(usersValid){ var dialogWaiverValidRow = '\
    \ \
    \ Registration Form signed\
    \
    '; returnData.html = dialogWaiverValidRow; return returnData; } else { var signWaiverRow = '\
    \ \
    \ '+signButton+'\
    \
    '; returnData.html = signWaiverRow; return returnData; } } else if(setup.action == "event-booking"){ extraStyles = "no-padding"; } else if(setup.action == "booking"){ // no option to sign waiver on payment page extraStyles = "col-md-6"; signButton = ""; waiverHelpText += " Sign the Registration Form for all participants before the event begins or the service provider may deny participation. You can sign the form immediately after booking or later under your calendar."; } else if(setup.action == "confirm"){ // booking confirmation page extraStyles = "col-sm-6"; waiverHelpText = "You have booked an event in which participation requires acceptance of a Registration Form. Fill and sign the form before the start of the event or the service provider may deny participation. You can also find a link to sign the Registration Form in your email or under your calendar bookings."; } else if(setup.action == "user-page"){ // under user feed and calendar common top alert if(usersValid){ return returnData; } waiverHelpText = "You have booked an event in which participation requires acceptance of a Registration Form. Fill and sign the form before the start of the event or the service provider may deny participation."; if(waiverUsersInvalid.length > 1){ waiverHelpText += " Signature is missing from [x] accounts.".replace('[x]',''+waiverUsersInvalid.length+''); } var signRows = '\ '; if(waiverUsersInvalid.includes(myUserId)){ signRows += '\
    \ '+myUsername+'\ Sign\
    '; } if(childData.length){ $(childData).each(function(index, child){ signRows += '\
    \ '+child.FirstName+' '+child.LastName+'\ \ Sign\ \
    '; }); } signWaiverLink += '\
    \ \ \
    \
    '+signRows+'
    '; signButton = ""; } if(usersValid){ return returnData; } if(signButton){ signWaiverLink = '\ '; } var waiverFrontpageHtml = '\
    \
    \
    \ '+waiverHelpText+'\
    \ '+signWaiverLink+'\
    \
    '; returnData.html = waiverFrontpageHtml; return returnData; } function initStableAllWaivers(data){ // init all active waivers under stable, for rider logging("initStableAllWaivers"); logging(data); logging("waiversActiveStables"); logging(waiversActiveStables); if (typeof currentStableId !== 'undefined') { // filter current stable forms data = $.grep(data, function(e){ return e.StableId == currentStableId }); } // date check var validwaivers = []; $(data).each(function(index, waiver){ if(waiversActiveStables){ // filter only active stable waivers if variable set if(!waiversActiveStables.includes(waiver.StableId)){ return true; } } if(waiver.ValidFromDateTime && moment(waiver.ValidFromDateTime) > moment()){ return true; } if(waiver.ValidToDateTime && moment(waiver.ValidToDateTime) < moment()){ return true; } validwaivers.push(waiver); }); if(!validwaivers.length){ return false; // no active waiver found } //if stable main page var stableMain = $('body').hasClass('pageStableFrontpage'); if(stableMain){ var urlPage = getUrlParameter('page'); // remove info $(document).find('.stable-waiver-info').remove(); if(validwaivers.length){ var formsLink = '\ '; var editFormsButton = ''; if(adminlevel == "full" || adminlevel == "edit"){ editFormsButton = ''; } var formsContent ='\ \
    '; $(document).find('.nav.navi-info').append(formsLink); $(document).find('.info-upper-part').append(formsContent); if(urlPage == "forms"){ changePagePart("forms", 1); } } else { if(urlPage == "forms"){ // if empty waivers, open first page changePagePart("info", 1); } } } initStableActiveWaivers(validwaivers); } function getAllStableWaiversHtml(data){ logging("getAllStableWaiversHtml"); logging(data); data = sortByKey(data, "WaiverTypeId", "ASC-NUM"); var waiversListHtml = ""; var lastWaiverType; $(data).each(function(index, item){ var signedWaiver = ""; var signedWaiverNote = ""; var unsignedExtraNote = ""; if(!lastWaiverType || lastWaiverType != item.WaiverTypeId){ if(item.WaiverTypeId == 1){ waiversListHtml += 'Registration Form'; unsignedExtraNote = ' Participation in the events requires acceptance of this document'; } else if(item.WaiverTypeId == 2){ waiversListHtml += 'Other waivers'; } else if(item.WaiverTypeId == 3){ waiversListHtml += 'Contracts'; } else if(item.WaiverTypeId == 4){ waiversListHtml += 'Surveys'; } else if(item.WaiverTypeId == 5){ waiversListHtml += 'Forms'; } lastWaiverType = item.WaiverTypeId; } var waiverMatchData; if(item.UserSignatures.length){ var waiverMatch = $.grep(item.UserSignatures, function(e){ return e.UserId == myUserId && !e.UserSignedWaiverExpired }); if(waiverMatch.length){ waiverMatchData = waiverMatch[waiverMatch.length-1]; } } if(waiverMatchData){ // signed waiver found var UserSignedWaiverTime = moment(waiverMatchData.UserSignedWaiverTime, "YYYY-MM-DD HH:mm:ss").format("DD/MM/YYYY HH:mm"); signedWaiver = ' '; signedWaiverNote = 'Form submitted on [x]'.replace('[x]', UserSignedWaiverTime); unsignedExtraNote = ""; } waiversListHtml += '\ \
    \ '+getIcon("fa-file-signature")+'\
    \
    '+item.WaiverHeader+'
    \ '+signedWaiver+signedWaiverNote+unsignedExtraNote+'\
    '; }); return waiversListHtml; } function initWaiversPage(){ logging("initWaiversPage"); $('#waivers').find('[data-show-section]').addClass("hidden"); $('#waivers').find('[data-show-section="signed"]').removeClass("hidden"); $('.waiver-filtering-buttons .btn').removeClass("active"); $('.waiver-filtering-buttons .btn[data-section="signed"]').addClass("active"); if(!stableWaiverTypesLoaded){ loadStableWaiverTypes(); } if(!stableSignedWaiversLoaded){ loadStableSignedWaivers(); } } var stableSignedWaiversLoaded = false; var stableSignedWaivers = []; function loadStableSignedWaivers(){ logging("loadStableSigned - load stable client signed waivers"); var query = {}; query.stableid = currentStableId; let getStableWaivers = getPromise(currentStableLink+'/getStableWaivers', query); getStableWaivers.then( (values) => { stableSignedWaiversLoaded = true; stableSignedWaivers = JSON.parse(values.result); initStableSignedWaivers(stableSignedWaivers); } ).catch( (error) => { console.error(error.message); commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } ).finally(() => { }); } var stableWaiversClusterize; function initStableSignedWaivers(data){ logging("initStableSignedWaivers - init stable client signed waivers"); logging(data); var signedWaiverAmount = 0; if(data){ signedWaiverAmount = data.length; } $('.btn[data-section="signed"] .badge').html(signedWaiverAmount).removeClass("hidden"); data = sortByKey(data, "MessageSentDateTime", "NUM"); waiverClusterizeData = buildClusterizeWaiverData(data, "stable"); // Clusterize setup stableWaiversClusterize = new Clusterize({ rows: waiverClusterizeData, scrollId: 'scrollAreaSignedWaivers', contentId: 'contentAreaSignedWaivers', no_data_text: 'No search results', rows_in_block: 20, callbacks: { clusterChanged: function() { checkClusterHeaders(); }, scrollingProgress: function() { } } }); } var userDialogWaiversClusterize; var userDialogWaivers; function initUserDialogWaivers(data){ if(!waiversFeature){ return false; } logging("initUserDialogWaivers - init stable user dialog waivers"); logging(data); userDialogWaivers = data; var waiverAmount = 0; if(data){ waiverAmount = data.length; } $('.btn[data-section="forms"] .badge').html(waiverAmount).removeClass("hidden"); data = sortByKey(data, "MessageSentDateTime", "NUM"); var waiverClusterizeData = buildClusterizeWaiverData(data, "user-dialog"); // Clusterize setup userDialogWaiversClusterize = new Clusterize({ rows: waiverClusterizeData, scrollId: 'scrollAreaUserWaivers', contentId: 'contentAreaUserWaivers', no_data_text: 'No search results', rows_in_block: 20, callbacks: { clusterChanged: function() { checkClusterHeaders(); }, scrollingProgress: function() { } } }); } var waiverFilterTimeout; function filterStableWaivers(data){ // filter client filled waivers by type and search field logging("filterStableWaivers"); logging(data); clearTimeout(waiverFilterTimeout); waiverFilterTimeout = setTimeout(function(){ var showWaiverTypes = []; $('.waivers-filtering-dropdown-menu input[type="checkbox"]').each(function(index, item){ if($(this).is(':checked')){ showWaiverTypes.push(parseInt($(this).val())); } }); logging("showWaiverTypes"); logging(showWaiverTypes); if(showWaiverTypes.length != 5){ data = $.grep(data, function(e){ return showWaiverTypes.includes(e.WaiverTypeId) }); } var searchTerm = $('.search-waivers .search').val(); logging("searchTerm"); logging(searchTerm); var name = searchTerm.normalize('NFD').replace(/[\u0300-\u036f]/g, "").toUpperCase().replace(/[^A-Za-z]/g, ""); var results = $.map(data, function(entry) { var fullname = entry.FirstName + " " + entry.LastName; var match = fullname.toUpperCase().replace(/[^A-Za-z]/g, "").indexOf(name) !== -1; return match ? entry : null; }); var filteredWaivers = buildClusterizeWaiverData(results, "stable"); stableWaiversClusterize.update(filteredWaivers); // reset view }, 100); } function buildClusterizeWaiverData(array, mode){ logging("buildClusterizeWaiverData - build user clusterize html | mode: "+mode); var resultdata = []; var waiverAction = "stable-view"; if(mode == "user"){ waiverAction = "user-view"; } $(array).each(function(index, item){ var userDetails = '\
    \ '+getWaiverTypeSettings(item.WaiverTypeId).icon+'\
    \ '+item.FirstName+' '+item.LastName+'\
    '; if(mode == "user-dialog"){ userDetails = ""; } var singleRow = '\
    \
    \ '+userDetails+'\ '+getWaiverTypeSettings(item.WaiverTypeId).waivertypename+'\ '+item.WaiverHeader+'\
    \
    \ #'+item.StableWaiverId+'\
    \
    \ '+moment(item.MessageSentDateTime, "YYYY-MM-DD HH:mm:ss").format('DD/MM/YYYY HH:mm')+'\
    \
    '; resultdata.push(singleRow); }); if(resultdata.length){ return resultdata; } else { return ['No filled forms']; // empty clusterize label } } var stableWaiverTypesLoaded = false; var stableWaiverTypes = []; function loadStableWaiverTypes(editId){ // load stable waiver templates logging("loadStableWaiverTypes"); stableWaiverTypes = []; var query = {}; query.stableid = currentStableId; let getStableWaiverTypes = getPromise(currentStableLink+'/getStableWaiverTypes', query); getStableWaiverTypes.then( (values) => { stableWaiverTypesLoaded = true; stableWaiverTypes = JSON.parse(values.result); logging("stableWaiverTypes loaded"); logging(stableWaiverTypes); $('.waiver-status-note').remove(); initStableWaiverTypes(stableWaiverTypes); initStableWaiverTypeSummaries(stableWaiverTypes); var activeWaiver = $.grep(stableWaiverTypes, function(e){ return e.StatusId === 2 }); if(activeWaiver.length && stableInfo.WaiversActive){ var noWaiverSettingActiveHtml = '\ '; $('.waivers-sidebar').prepend(noWaiverSettingActiveHtml); } else if(activeWaiver.length && !stableInfo.WaiversActive){ var noWaiverSettingActiveHtml = '\
    \
    \
    \ Registration Form has been created and published, but the feature has been turned off in the settings. The form is not shown to customers. Activate the feature in settings if you want to enable the feature.\
    \
    \
    '; $('#waivers').prepend(noWaiverSettingActiveHtml); } else if(!activeWaiver.length && stableInfo.WaiversActive){ var noActiveWaiverHtml = '\
    \
    \
    \ The feature has been activated in settings, but no Registration Form has been published. Create a Registration Form and set its state published.\
    \
    \
    '; $('#waivers').prepend(noActiveWaiverHtml); } var stableWaiverAmount = 0; if(stableWaiverTypes){ stableWaiverAmount = stableWaiverTypes.length; } if(stableWaiverAmount > 0){ $('.btn[data-section="waivers"] .badge').html(stableWaiverAmount).removeClass("hidden"); } $('.waiver-filtering-buttons .btn[data-section="waivers"]').removeClass("disabled"); if(editId){ waiverEdit(editId); } } ).catch( (error) => { console.error(error.message); commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service. - 213123'); } ).finally(() => { }); } var waiverTypeClusterize; function initStableWaiverTypes(data){ logging("initStableWaiverTypes"); logging(data); data.sort(function (a, b) { return b.StatusId > 1 || b.StableWaiverId - a.StableWaiverId; }); waiverTypeClusterizeData = buildClusterizeWaiverTypeData(data); // Clusterize setup waiverTypeClusterize = new Clusterize({ rows: waiverTypeClusterizeData, scrollId: 'scrollAreaWaivers', contentId: 'contentAreaWaivers', no_data_text: 'No search results', rows_in_block: 30, callbacks: { clusterChanged: function() { checkClusterHeaders(); $('[data-toggle="tooltip"]').tooltip(); }, scrollingProgress: function() { } } }); } function buildClusterizeWaiverTypeData(array){ // build Clusterize html content logging("buildClusterizeWaiverTypeData - stable waiver types"); logging(array); var resultdata = []; $(array).each(function(index, item){ var waiverStatus = ""; var bgClass = ""; if(item.StatusId > 1){ waiverStatus = ' '; bgClass = " active"; } var waiverComment = ""; if(item.WaiverComment){ waiverComment = '
    '+item.WaiverComment+''; } var waiverAmountLabel = ""; if(item.WaiverFilledCount){ var amountTooltip = 'Total submitted forms [x]'.replace('[x]', item.WaiverFilledCount); waiverAmountLabel = ' '+item.WaiverFilledCount+''; } var singleRow = '\
    \
    \
    \ '+getWaiverTypeSettings(item.WaiverTypeId).icon+'\
    \ '+waiverStatus+item.WaiverHeader+'\
    '+getWaiverTypeSettings(item.WaiverTypeId).waivertypename+'\ '+waiverComment+'\
    \
    \ #'+item.StableWaiverId+'\
    \
    \ '+waiverAmountLabel+'\
    \
    \ '+moment(item.InsertSystemTime, "YYYY-MM-DD HH:mm:ss").format('DD/MM/YYYY HH:mm')+'\
    \
    '; resultdata.push(singleRow); }); return resultdata; } // function noActiveWaiverWarning(){ // // logging("noActiveWaiverWarning"); // // if(stableInfo.WaiversActive){ // var noActiveWaiverHtml = '\ //
    \ //
    \ //
    \ // The feature has been activated in <a href="#stablesettings-waivers">settings</a>, but no Registration Form has been published. Create a Registration Form and set its state <strong>published</strong>.\ //
    \ //
    \ //
    '; // $('#waivers').prepend(noActiveWaiverHtml); // //} // } var waiverSummaryDisplayedTypes = [4]; function initStableWaiverTypeSummaries(data){ logging("initStableWaiverTypeSummaries"); logging(data); $('.filled-forms-summary').empty().addClass("hidden"); var summaryLink = ""; $(data).each(function(index, waiver){ if(waiver.WaiverFilledCount && waiverSummaryDisplayedTypes.includes(waiver.WaiverTypeId)){ var amountTooltip = 'Total submitted forms [x]'.replace('[x]', waiver.WaiverFilledCount); summaryLink = '\ \ #'+waiver.StableWaiverId+" "+waiver.WaiverHeader+'\
    '+waiver.WaiverFilledCount+'\
    '+summaryLink; } }); if(summaryLink){ summaryLink = '\
    \
    Form summaries
    \ '+summaryLink+'\
    '; $('.filled-forms-summary').append(summaryLink).removeClass("hidden"); } } function showStableWaiverSummary(id){ logging("showStableWaiverSummary | id: "+id); logging(stableSignedWaivers); var singleWaivertypeData = $.grep(stableSignedWaivers, function(e){ return e.StableWaiverTypeId == id}); var waiverTypeData = $.grep(stableWaiverTypes, function(e){ return e.StableWaiverTypeId == id}); var returnArrayHeaders = []; var returnArrayContentType = []; var returnArrayContent = []; var firstDate; var lastDate; var returnAmount = singleWaivertypeData.length; $(singleWaivertypeData).each(function(index, waiver){ var formContent = JSON.parse(waiver.Content); // logging("formContent here", "red"); // logging(formContent); if(!firstDate || moment(waiver.MessageSentDateTime) < moment(firstDate)){ firstDate = waiver.MessageSentDateTime; } if(!lastDate || moment(waiver.MessageSentDateTime) > moment(lastDate)){ lastDate = waiver.MessageSentDateTime; } $(formContent).each(function(index, row){ if(!returnArrayHeaders[index] && row.label){ returnArrayHeaders.push(row.label); } if(!returnArrayContentType[index]){ returnArrayContentType.push(row.type); } if(row.userData){ if(!returnArrayContent[index]){ returnArrayContent[index] = [row.userData]; } else { returnArrayContent[index].push(row.userData); } } }); }); if(returnArrayHeaders){ var summaryObject = {}; summaryObject.header = returnArrayHeaders; summaryObject.contenttype = returnArrayContentType; summaryObject.content = returnArrayContent; summaryObject.amount = returnAmount; summaryObject.firstdate = firstDate; summaryObject.lastdate = lastDate; summaryObject.waivertypedata = waiverTypeData[0]; stableWaiverSummaryDialog(summaryObject); } } function stableWaiverSummaryDialog(data){ logging("stableWaiverSummaryDialog"); logging(data); var waiverSummaryContent = ""; var filledDates = moment(data.firstdate).format('DD/MM/YYYY')+ ' - '+moment(data.lastdate).format('DD/MM/YYYY') var waiverHelp = 'The form has been submitted a total of [x] times between [y].'.replace("[x]", ''+data.amount+'').replace("[y]", ''+filledDates+''); waiverHelp = '
    '+waiverHelp+'
    '; $(data.header).each(function(index, item){ var type = data.contenttype[index]; logging(type); var values = data.content[index]; logging(values); var itemHeader = ''; if(type == "header"){ itemHeader = '

    '+item+'

    '; } else if(type == "paragraph"){ itemHeader = '

    '+item+'

    '; } var singleContent = ""; if(values){ if(type == "ratingstar" || type == "ratingemoji"){ singleContent += '
    graph
    '; } if(type == "ratingstar"){ singleContent += 'Average'; singleContent += renderReviewBadge("fa-solid fa-star-sharp", values.reduce((a, b) => a + b, 0), values.length); } else if(type == "ratingemoji"){ singleContent += 'Average'; singleContent += renderReviewBadge("fa-light fa-face-laugh-beam", values.reduce((a, b) => a + b, 0), values.length); } else if(type == "textarea"){ $(values).each(function(index, item){ logging("item"); console.log(item[0]); if(item[0]){ singleContent += '
  • '+item[0]+'
  • '; } }); if(singleContent){ singleContent = '
      '+singleContent+'
    '; } } if(singleContent){ singleContent = '
    '+singleContent+'
    '; } } if(type == "ratingstar" || type == "ratingemoji" || type == "textarea"){ waiverSummaryContent += '\
    \
    '+itemHeader+'
    \
    \ '+singleContent+'\
    \
    '; } else { waiverSummaryContent += '\
    \ '+itemHeader+'\ '+singleContent+'\
    '; } }); var waiverSummaryDial = BootstrapDialog.show({ type: BootstrapDialog.TYPE_PRIMARY, size: BootstrapDialog.SIZE_WIDE, cssClass: 'dialog-waiver-summary', title: "Form summaries", message: waiverHelp+waiverSummaryContent, closable: true, onshown: function(dialogRef){ var graphElements = dialogRef.getModalDialog().find('.graph'); $(graphElements).each(function(index, graph){ var graphId = $(this).attr('id'); var graphIndex = $(this).data('index'); var graphValues = data.content[graphIndex]; getRatingGraph('#'+graphId, graphValues); }); } }); } function getRatingGraph(elementid, ratingArray){ logging("getRatingGraph"); // logging(elementid); //logging(ratingArray); var values1 = ratingArray.filter(x => x == 1).length; var values2 = ratingArray.filter(x => x == 2).length; var values3 = ratingArray.filter(x => x == 3).length; var values4 = ratingArray.filter(x => x == 4).length; var values5 = ratingArray.filter(x => x == 5).length; var totalArray = [ values1, values2, values3, values4, values5, ]; var biggestValue = Math.max.apply(Math, totalArray); totalArray = ["Stats"].concat(totalArray); var yTickList = []; for (var i = 1; i <= biggestValue; i++) { yTickList.push(i); } var sRatings = c3.generate({ bindto: elementid, data: { columns: [totalArray], type : 'bar' }, bar: { width: { ratio: .80 } }, axis: { x: { type: 'category', categories: ["1","2","3","4","5"] }, y: { tick: {values: yTickList} } }, legend: { show: false } }); } var waiverEditDial; var waiverChanges = false; function waiverEdit(id, copydata){ logging("waiverEdit: "+id); logging("copydata"); logging(copydata); if(waiverEditDial){ return false; } var disableEditing = false; var waiverdata; var waiverEditTitle = 'Create new form'; var waiverFilledHelp = ""; waiverChanges = false; var panelSelection = ""; var typeSelection = "hidden" if(copydata){ waiverdata = copydata; panelSelection = "hidden"; typeSelection = "" } else if(id){ waiverdata = $.grep(stableWaiverTypes, function(e){ return e.StableWaiverId === id }); if(waiverdata.length){ waiverdata = waiverdata[0]; } else { commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); return false; } waiverEditTitle = 'Edit form'; if(waiverdata.WaiverFilledCount){ disableEditing = true; var helpString = 'The form has been submitted [x] times. After customers have submitted the form, its content can no longer be edited. You can make a copy of the form to which you can make changes.'.replace('[x]', ''+waiverdata.WaiverFilledCount+''); waiverFilledHelp = '\
    '+helpString+'
    \ '; } panelSelection = "hidden"; typeSelection = "" } var existingActiveWaiver = ""; if(stableActiveWaiver){ existingActiveWaiver = ''; } var waiverTypeSelection = '\
    \
    \
    \
    \

    '+getWaiverTypeSettings(1).icon+' '+getWaiverTypeSettings(1).waivertypename+'

    \
    \
    \ '+getWaiverTypeSettings(1).desc+'\
    \
    \
    \
    \
    \
    \

    '+getWaiverTypeSettings(2).icon+' '+getWaiverTypeSettings(2).waivertypename+'

    \
    \
    \ '+getWaiverTypeSettings(2).desc+'\
    \
    \
    \
    \
    \
    \

    '+getWaiverTypeSettings(3).icon+' '+getWaiverTypeSettings(3).waivertypename+'

    \
    \
    \ '+getWaiverTypeSettings(3).desc+'\
    \
    \
    \
    \
    \
    \

    '+getWaiverTypeSettings(4).icon+' '+getWaiverTypeSettings(4).waivertypename+'

    \
    \
    \ '+getWaiverTypeSettings(4).desc+'\
    \
    \
    \
    \
    \
    \

    '+getWaiverTypeSettings(5).icon+' '+getWaiverTypeSettings(5).waivertypename+'

    \
    \
    \ '+getWaiverTypeSettings(5).desc+'\
    \
    \
    \
    \
    \
    \

    '+getWaiverTypeSettings(6).icon+' '+getWaiverTypeSettings(6).waivertypename+'

    \
    \
    \ '+getWaiverTypeSettings(6).desc+'\
    \
    \
    \
    \
    \
    \

    '+getWaiverTypeSettings(7).icon+' '+getWaiverTypeSettings(7).waivertypename+'

    \
    \
    \ '+getWaiverTypeSettings(7).desc+'\
    \
    \
    \
    '; waiverTypeSelection += '\
    \
    \ \ \
    \
    '; var waiverContent = '\ '+existingActiveWaiver+'\
    \
    \
    \
    \
    \
    \
    \
    \ '+waiverFilledHelp+'\ \ '; var saveButton = { label: ' Save', cssClass: 'btn-success btn-sm btn-waiver-save pull-left hidden' }; var copyButton = { label: ' Duplicate', cssClass: 'btn-default btn-sm btn-waiver-copy pull-left hidden' }; var previewButton = { label: ' Preview', cssClass: 'btn-default btn-sm btn-waiver-preview hidden' }; var clearButton = { label: ' Clear', cssClass: 'btn-default btn-sm btn-waiver-clear hidden' }; var closeButton = { label: 'Close', cssClass: 'btn-default btn-sm btn-ok', autospin: false, action: function(dialogRef){ if(waiverChanges){ BootstrapDialog.confirm({ title: 'Unsaved changes', message: 'Unsaved changes. Are you sure you want to close the window without saving?', type: BootstrapDialog.TYPE_WARNING, btnCancelLabel: 'Cancel', btnCancelClass: 'btn-default btn-sm', btnOKLabel: 'Close', btnOKClass: 'btn-default btn-sm pull-left', callback: function(result) { if(result) { dialogRef.close(); } } }); } else { dialogRef.close(); } } }; var waiverDialogButtons = [saveButton, previewButton, clearButton, closeButton]; if(disableEditing){ waiverDialogButtons = [saveButton, copyButton, previewButton, closeButton]; } else if(id && waiverdata){ waiverDialogButtons = [saveButton, copyButton, previewButton, clearButton, closeButton]; } waiverEditDial = BootstrapDialog.show({ type: BootstrapDialog.TYPE_PRIMARY, size: BootstrapDialog.SIZE_WIDE, cssClass: 'dialog-waiver dialog-gray-bg dialog-mobile-flex', title: waiverEditTitle, message: waiverTypeSelection+waiverContent, closable: false, buttons: waiverDialogButtons, onshow: function(dialogRef){ }, onshown: function(dialogRef){ if(viewmode != "xxs"){ var typeSelectionPanels = dialogRef.getModalDialog().find('.panel.select-forms-type'); forceSameContainerHeights(typeSelectionPanels); } if(id || copydata && copydata.copy){ dialogRef.getModalDialog().find('select[name="select-waivertype"]').val(waiverdata.WaiverTypeId); } dialogRef.setClosable(true); var waiverTypeSelect = dialogRef.getModalDialog().find('select[name="select-waivertype"]'); waiverTypeSelect.selectize().on('change', function(e){ var waiverType = $(this).val(); waiverInitNewWaiver(dialogRef, null, waiverType); }); var waiverTypePanelSelect = dialogRef.getModalDialog().find('.panel.select-forms-type'); waiverTypePanelSelect.on('click', function(e){ var waiverType = $(this).data("type"); waiverTypeSelect[0].selectize.setValue(waiverType); dialogRef.getModalDialog().find('.select-waivertype-panels').slideUp(300); dialogRef.getModalDialog().find('.select-waivertype-parent').removeClass("hidden"); }); dialogRef.getModalDialog().on('change', '#waiverstatus', function(e){ dialogRef.getModalDialog().find('.waiverstatus-help[data-waiver-status]').addClass("hidden"); var waiverPublish = $(this).prop('checked'); var waiverType = dialogRef.getModalDialog().find('select[name="select-waivertype"]').val(); var statusChanges = false; if(id){ if(waiverdata.StatusId > 1 && !waiverPublish){ statusChanges = true; } else if(waiverdata.StatusId < 2 && waiverPublish){ statusChanges = true; } } else { statusChanges = true; } if(waiverPublish){ // publishing dialogRef.getModalDialog().find('.waiverstatus-help[data-waiver-status="2"]').removeClass("hidden"); if(id && statusChanges || !id){ // publish editing or new if(statusChanges){ if(waiverType == 1){ // publish waiver commonHelpDialog('Note','Registration Form is published for customers. The form replaces any previously used version.'); } else { commonHelpDialog('Note','By publishing the form, the form can be seen and submitted by customers. After customers have submitted the form, its content can no longer be edited.'); } } } } else { // unpublishing dialogRef.getModalDialog().find('.waiverstatus-help[data-waiver-status="1"]').removeClass("hidden"); if(id){ // editing -> unpublish if(statusChanges){ if(waiverType == 1 && stableActiveWaiver && waiverdata.StableWaiverTypeId == stableActiveWaiver.StableWaiverTypeId){ // unpublish active waiver commonHelpDialog('Note','The Registration Form will be deactivated. Please note that the entire feature will be deactivated - customers will no longer be asked to sign Registration Forms. Create and publish a new Registration Form if you want to activate the feature again.',"DANGER"); } else { commonHelpDialog('Note','The form can no longer be filled out by customers.'); } } } } }); dialogRef.getModalFooter().find('.btn-waiver-save').on('click', function(e) { dialogRef.getModalDialog().find('.modal-body, .modal-footer').addClass("disabled"); var waiverFormData = formBuilder.actions.getData('json'); var waiversettings = {}; var waivernote = dialogRef.getModalDialog().find('textarea[name="waivercomment"]').val(); if(waivernote){ waiversettings.comment = waivernote; } var waiverType = dialogRef.getModalDialog().find('select[name="select-waivertype"]').val(); if(waiverType){ waiversettings.waivertypeid = waiverType; } waiversettings.publish = 0; var waiverStatus = dialogRef.getModalDialog().find('#waiverstatus').is(':checked'); if(waiverStatus){ waiversettings.publish = 1; } waiverSave(waiverFormData, waiversettings, waiverdata, dialogRef); }); dialogRef.getModalFooter().find('.btn-waiver-copy').on('click', function(e) { var copydata = {}; copydata.copy = true; copydata.WaiverComment = waiverdata.WaiverComment; copydata.Content = waiverdata.Content; copydata.WaiverTypeId = waiverdata.WaiverTypeId; waiverEditDial.close(); waiverEdit(null, copydata); }); dialogRef.getModalFooter().find('.btn-waiver-clear').on('click', function(e) { waiverInitNewWaiver(dialogRef, null, waiverTypeSelect.val()); }); dialogRef.getModalFooter().find('.btn-waiver-preview').on('click', function(e) { waiverCheckFormOrder(dialogRef); var waiverData = formBuilder.actions.getData('js'); waiverViewWaiver(waiverData, "stable-preview"); }); dialogRef.getModalDialog().find('#waiver-container').on('change keyup','input, select, textarea, .input-wrap', function (e) { waiverChanges = true; dialogRef.setClosable(false); var waiverData = formBuilder.actions.getData('js'); validateWaiverData(waiverData); }); dialogRef.getModalDialog().find('.waiver-type-content').on('change keyup','input, textarea', function (e) { waiverChanges = true; dialogRef.setClosable(false); }); dialogRef.getModalDialog().on('click', 'a.add-opt, a.del-button, a.copy-button', function(e) { // add option button waiverChanges = true; dialogRef.setClosable(false); waiverCheckFormOrder(dialogRef); }); //strip text formatting from pasted content dialogRef.getModalDialog().find('#waiver-container').on('paste','input, select, textarea, .input-wrap', function (e) { e.preventDefault(); var text = (e.originalEvent || e).clipboardData.getData('text/plain'); document.execCommand("insertHTML", false, text); }); if(waiverdata){ waiverTypeSelect.parent().addClass("disabled"); waiverInitNewWaiver(dialogRef, waiverdata); } else { waiverInitNewWaiver(dialogRef, null, 0); } }, onhide: function(dialogRef){ waiverEditDial = undefined; } }); } function validateWaiverData(waiverData){ logging("validateWaiverData"); logging(waiverData); var buttons = waiverEditDial.getModalFooter().find('.btn-waiver-save, .btn-waiver-preview, .btn-waiver-clear, .btn-waiver-copy'); buttons.addClass("hidden"); var waiverHeader = $.grep(waiverData, function(e){ return e.className ==="waiver-header-element" }); var waiverHeaderValid = false; var waiverContentValid = false; if(waiverHeader[0].label && waiverHeader[0].label.length){ waiverHeaderValid = true; } if(waiverData.length){ waiverContentValid = true; } if(waiverHeaderValid && waiverContentValid){ buttons.removeClass("hidden"); } } // function getChildrenElement(fieldData){ // logging("getAttachmentElement"); // logging("fieldData"); // logging(fieldData); // var returnObject = { // field: '
    ', // onRender: function() { // var attachmentElements = '\ //
    \ //
    '; // var attachmentArea = $(document).find("#"+fieldData.name); // attachmentArea.append(attachmentElements); // } // }; // return returnObject; // } function getAttachmentElement(fieldData, extraclass){ logging("getAttachmentElement"); logging("fieldData"); logging(fieldData); var requiredHtml = ""; if(fieldData.required){ requiredHtml = ' data-attachment-required="1"'; } var returnObject = { field: '
    ', onRender: function() { var attachmentElements = '\
    \
    \ \ \
    \
    '; var attachmentArea = $(document).find("#"+fieldData.name); attachmentArea.append(attachmentElements); } }; return returnObject; } function getAttachmentReadyElement(fieldData){ logging("getAttachmentReadyElement"); logging("fieldData"); logging(fieldData); var returnObject = { field: '
    ', onRender: function() { var attachmentElements = '\
    \
    \ \ Attachment loading missing!\
    \
    '; var attachmentArea = $(document).find("#"+fieldData.name); attachmentArea.append(attachmentElements); } }; return returnObject; } function getStarRatingElement(fieldData){//TODO Form builder star rating var returnObject = { field: '
    ', onRender: function() { // logging("STAR RATING ELEMENTS"); // logging(fieldData); var ratingType = "star-all"; var ratingClass = "rating-stars"; if(fieldData.type == "ratingemoji"){ ratingType = "emoji-all"; ratingClass = "rating-emojis"; } var requiredHtml = ""; if(fieldData.required){ requiredHtml = ' required="required"'; } var ratedInfo = ""; if(fieldData.userData){ // fill rated values ratedInfo = 'data-rated="'+fieldData.userData+'" data-color="'+fieldData.userData+'"'; } var starElements = '\
    \
    \
    \
    \ '+buildRatingStars(null, ratingType)+'\
    \ \
    \
    \
    '; var attachmentArea = $(document).find("."+fieldData.name); attachmentArea.append(starElements); } }; return returnObject; } function getUserInfoElement(fieldData, data){//TODO Form builder user basic info logging("getUserInfoElement"); // logging("fieldData"); // logging(fieldData); // logging("data"); // logging(data); var userInfoHtml = '\
    \
    \ \ The information saved in the user's profile at the time of submit is automatically added to this section\
    \
    '; if(fieldData && fieldData.userData){ // form saved user data userInfoHtml = getUserInfoData(fieldData.userData, true); if(userInfoHtml){ userInfoHtml = '\
    \
    \
    \
    \ '+userInfoHtml+'\
    \ These are the information stored in the user's settings at the time the form is submitted.\
    \
    \
    \
    \
    '; } } else if(data && data.UserFeatures){ // user settings data userInfoHtml = getUserInfoData(data.UserFeatures[0]); if(userInfoHtml){ userInfoHtml = '\
    \
    \
    \
    \ '+userInfoHtml+'\
    \ This is information stored in your settings. Carefully check the accuracy of the information. If necessary, edit the information in your settings.\ Account settings\
    \
    \
    \
    \
    \
    '; } } var returnObject = { field: '
    ', onRender: function() { logging("USER INFO ELEMENTS"); logging(fieldData); var infoElements = '\
    \ '+userInfoHtml+'\
    '; var attachmentArea = $(document).find("."+fieldData.name); attachmentArea.append(infoElements); $('[data-toggle="tooltip"]').tooltip(); } }; return returnObject; } function getUserInfoData(data, userawdata){ // parse user info data for forms logging("getUserInfoData"); logging(data); if(!myUserId){ return ''; } // values which will be used var acceptedValues = ['UserName','InsertDateTime','Phone','Birth','Weight','Height','SkillLevel','Note','ICEFirstName','ICELastName','ICENumber','UserAssociations']; var acceptedValueLabels = ['Login name','Registration date','Phone number','Date of birth','Weight','Height','Skill Level','Rider notes for stable or service provider','ICE First name','ICE Last name','ICE Phone','Club membership']; var userInfo = ""; $(acceptedValues).each(function(index, value){ logging(value); if(data[value]){ if(userawdata){ if(value == "SkillLevel"){ var infoValue = data[value]; var skillTitle = ""; if(infoValue == 1) { skillTitle = "Beginner"; } else if(infoValue == 2) { skillTitle = "Basic skills"; } else if(infoValue == 3) { skillTitle = "Advanced"; } else if(infoValue == 4) { skillTitle = "Experienced"; } else { skillTitle = "No experience"; } var skillLabel = '
    '+skillTitle+'
    '; userInfo += '
    '+acceptedValueLabels[index]+'
    '+skillLabel+'
    '; } else { userInfo += '
    '+acceptedValueLabels[index]+'
    '+data[value]+'
    '; } return true; } var infoValue = rawValue = data[value]; if(value == "InsertDateTime"){ infoValue = rawValue = moment(data[value]).format('DD/MM/YYYY HH:mm'); } else if(value == "Birth"){ infoValue = rawValue = moment(data[value]).format('DD/MM/YYYY'); } else if(value == "Weight"){ infoValue = rawValue = returnconvertunit(data[value], "kg", "weight"); } else if(value == "Height"){ infoValue = rawValue = returnconvertunit(data[value], "cm", "height"); } else if(value == "SkillLevel"){ var skillTitle = ""; if(infoValue == 1) { skillTitle = "Beginner"; } else if(infoValue == 2) { skillTitle = "Basic skills"; } else if(infoValue == 3) { skillTitle = "Advanced"; } else if(infoValue == 4) { skillTitle = "Experienced"; } else { skillTitle = "No experience"; } infoValue = '
    '+skillTitle+'
    '; } else if(value == "UserAssociations"){ var associationData = JSON.parse(infoValue); infoValue = rawValue = ""; $(associationData).each(function(index, association){ // if(association.Status != "paid"){ // return true; // } var associationName = association.AssociationName.toLowerCase(); if(infoValue){ infoValue += ", "+associationName; } else { infoValue = associationName; } if(association.Status !== "paid"){ infoValue += ' (Riding club membership unpaid)' } else { infoValue += ' (Riding club membership paid)' } rawValue = infoValue; }); if(!infoValue){ infoValue = rawValue = "-"; } } userInfo += '
    '+acceptedValueLabels[index]+'
    '+infoValue+'
    '; } }); if(userInfo){ userInfo = '
    '+userInfo+'
    '; } return userInfo; } var formbuilderPreviewLayout = { // form layouts when creating forms -> formbuilder signature: function(fieldData) { var extraClass = ""; if(fieldData.className){ extraClass = fieldData.className; } return { field: '
    ', onRender: function() { console.log("fieldData preview"); console.log(fieldData); var signatureElements = '\
    \
    \
    \
    \ \ \
    \
    '; var signatureArea = $(document).find("#"+fieldData.name); signatureArea.append(signatureElements); } }; }, // files: function(fieldData) { // return getAttachmentElement(fieldData, "disabled-opaque"); // }, ratingstar: function(fieldData) { return getStarRatingElement(fieldData); }, ratingemoji: function(fieldData) { return getStarRatingElement(fieldData); }, userinformation: function(fieldData) { return getUserInfoElement(fieldData); } } function getFormbuilderActiveLayout(data){ var formbuilderActiveLayout = { // form layouts for end user forms -> formrender signature: function(fieldData) { return { field: '
    ', onRender: function() { // console.log("fieldData"); // console.log(fieldData); var signatureArea = $(document).find("#"+fieldData.name); var signatureRequiredHtml = ""; var requiredInputHtml = ""; if(fieldData.required){ signatureRequiredHtml = ' data-signature-required="1"'; requiredInputHtml = ' required="required"'; } var signatureWidth = 450; var elementWidth = signatureArea.width(); if(elementWidth < signatureWidth && elementWidth > 200){ signatureWidth = parseInt(elementWidth); } var signatureElements = '\
    \ \ \
    \
    \ \ \
    \
    '; signatureArea.append(signatureElements); } }; }, files: function(fieldData) { return getAttachmentElement(fieldData); }, ratingstar: function(fieldData) { return getStarRatingElement(fieldData); }, ratingemoji: function(fieldData) { return getStarRatingElement(fieldData); }, userinformation: function(fieldData) { return getUserInfoElement(fieldData, data); } } return formbuilderActiveLayout; } var formbuilderReadyLayout = { // form layouts for filled forms -> formrender signature: function(fieldData) { return { field: '
    ', onRender: function() { console.log("formbuilderReadyLayout"); console.log(fieldData); logging("signature place svg"); logging(fieldData.userData); var signatureArea = '\
    \
    \
    '; if(fieldData.userData){ signatureArea = ''; } var signatureElements = '\
    \ '+signatureArea+'\
    \
    \ \ \
    \
    '; var signatureArea = $(document).find("#"+fieldData.name); signatureArea.append(signatureElements); signatureArea.find("svg").removeAttr("viewBox").removeAttr("width").removeAttr("height"); } }; }, files: function(fieldData) { return getAttachmentReadyElement(fieldData); }, ratingstar: function(fieldData) { return getStarRatingElement(fieldData); }, ratingemoji: function(fieldData) { return getStarRatingElement(fieldData); }, userinformation: function(fieldData) { return getUserInfoElement(fieldData); } } var customFormFields = [{ label: 'Signature', attrs: { type: 'signature', subtype: 'p' }, icon: '' },{ // label: 'Image attachment', // type: 'files', // icon: '' // },{ label: 'Star rating', attrs: { type: 'ratingstar' }, icon: '' },{ label: 'Emoji rating', attrs: { type: 'ratingemoji' }, icon: '' },{ label: 'User information', attrs: { type: 'userinformation' }, icon: '' }]; var waiverTypeContent = []; waiverTypeContent[0] ='\ With the forms feature, you can create documents intended for customers to fill out - for example, Registration Forms, waiver documents, contracts or feedback surveys. Read more about the feature.\ '; waiverTypeContent[1] ='\
    \
    \
    \ \
    \ \ \
    \ \ \ This information is not visible to the customer\
    \
    \
    \

    Registration Form is a mandatory form to be signed before participating lessons.

    \

    Edit the form fields to your liking. Mandatory fields cannot be deleted or reordered. On the right side, you can add fields that you can reorder by dragging with the mouse. With the preview button, you can check how the form looks to customers. You can save the form as a draft, but the feature is activated for customers to use only after the form has been published and the feature is active under business settings. Read more about the feature

    \
    \
    '; waiverTypeContent[2] ='\
    \
    \
    \ \
    \ \ \
    \ \ \ This information is not visible to the customer\
    \
    \
    \

    Other waiver is an optional document that the customer can sign if needed.

    \

    Edit the form fields of the form to your liking. Mandatory fields cannot be deleted or reordered. On the right side, you can add fields that you can reorder by dragging with the mouse. With the preview button, you can check how the form looks to customers. You can save the form as a draft, but the form can be signed by customers only after the form has been published. Read more about the feature

    \
    \
    '; waiverTypeContent[3] ='\
    \
    \
    \ \
    \ \ \
    \ \ \ This information is not visible to the customer\
    \
    \
    \

    A contract is an optional free-form document that the customer can sign if needed.

    \

    Edit the form fields of the form to your liking. Mandatory fields cannot be deleted or reordered. On the right side, you can add fields that you can reorder by dragging with the mouse. With the preview button, you can check how the form looks to customers. You can save the form as a draft, but the form can be signed by customers only after the form has been published. Read more about the feature

    \
    \
    '; waiverTypeContent[4] ='\
    \
    \
    \ \
    \ \ \
    \ \ \ This information is not visible to the customer\
    \
    \
    \

    Feedback form is an optional free-form document that the customer can fill out if needed. Add star or emoji type rating fields to the form. You can later see a summary of all submitted forms.

    \

    Edit the form fields of the form to your liking. On the right side, you can add fields that you can reorder by dragging with the mouse. With the preview button, you can check how the form looks to customers. You can save the form as a draft, but the form is visible for customers only after the form has been published. Read more about the feature

    \
    \
    '; waiverTypeContent[5] ='\
    \
    \
    \ \
    \ \ \
    \ \ \ This information is not visible to the customer\
    \
    \
    \

    The waiting list form can be used to collect, for example, participants for a new season or full lessons.

    \

    Edit the form fields of the form to your liking. On the right side, you can add fields that you can reorder by dragging with the mouse. With the preview button, you can check how the form looks to customers. You can save the form as a draft, but the form is visible for customers only after the form has been published. Read more about the feature

    \
    \
    '; waiverTypeContent[6] ='\
    \
    \
    \ \
    \ \ \
    \ \ \ This information is not visible to the customer\
    \
    \
    \

    The competition form can be used to collect competition registrations.

    \

    Edit the form fields of the form to your liking. On the right side, you can add fields that you can reorder by dragging with the mouse. With the preview button, you can check how the form looks to customers. You can save the form as a draft, but the form is visible for customers only after the form has been published. Read more about the feature

    \
    \
    '; waiverTypeContent[7] ='\
    \
    \
    \ \
    \ \ \
    \ \ \ This information is not visible to the customer\
    \
    \
    \

    The "Forms" type form can be used freely for whatever purposes you want.

    \

    Edit the form fields of the form to your liking. On the right side, you can add fields that you can reorder by dragging with the mouse. With the preview button, you can check how the form looks to customers. You can save the form as a draft, but the form is visible for customers only after the form has been published. Read more about the feature

    \
    \
    '; var defaultFieldsAgreement = [{ type: 'header', label: 'Form title', name: 'waiver-header', className: 'waiver-header-element' },{ type: 'paragraph', subtype: 'p', label: 'Insert legal text here', className: 'waiver-legal-element' },{ type: 'checkbox-group', required: true, label: 'Electronic signature consent', className: 'waiver-accept-element', toggle: false, inline: false, access: false, other: false, values: [{ label: 'Insert accept text here', value: 'accept', selected: false }] },{ type: 'signature', subtype: 'p', required: true, label:"Signature", className: 'waiver-signature-element' }]; var defaultFieldsWaiver = [{ type: 'header', label: 'Registration Form header', name: 'waiver-header', className: 'waiver-header-element' },{ type: 'paragraph', subtype: 'p', label: 'Insert legal text here', className: 'waiver-legal-element' },{ type: 'checkbox-group', required: true, label: 'Electronic signature consent', className: 'waiver-accept-element', toggle: false, inline: false, access: false, other: false, values: [{ label: 'Insert accept text here', value: 'accept', selected: false }] },{ type: 'signature', subtype: 'p', required: true, label:"Signature", className: 'waiver-signature-element' }]; var defaultFieldsFeedback = [{ type: 'header', label: 'Feedback form title', name: 'waiver-header', className: 'waiver-header-element' },{ type: 'ratingstar', label: 'How likely would you recommend us?', className: 'nps-recommend', required: true },{ type: 'ratingstar', label: 'How do you rate the teaching?', className: 'nps-teaching', required: true },{ type: 'ratingstar', label: 'How do you rate horses?', className: 'nps-horses', required: true },{ type: 'ratingstar', label: 'How do you rate the facilities?', className: 'nps-spaces', required: true },{ type: 'textarea', label: 'Open feedback', className: 'form-control' },{ type: 'paragraph', subtype: 'p', label: 'The feedback you send can only be seen by the staff of the business.' }]; var defaultFieldsForm = [{ type: 'header', label: 'Form title', name: 'waiver-header', className: 'waiver-header-element' }]; var formBuilder; function waiverInitNewWaiver(dialog, presetdata, waivertype){ logging("waiverInitNewWaiver | waivertype: "+waivertype); logging("presetdata"); logging(presetdata); var waiverTypeElement = dialog.getModalDialog().find('.waiver-type-content'); var waiverElement = dialog.getModalDialog().find('#waiver-container'); var initReady = false; var presetFields = null; formBuilder = null; var disableEditing = false; var editingCurrentlyActive = false; waiverElement.addClass("disabled"); waiverElement.empty(); dialog.getModalFooter().find('.btn-waiver-save, .btn-waiver-preview, .btn-waiver-clear').addClass("hidden"); if(presetdata){ //normal editing if(presetdata.WaiverTypeId){ waivertype = presetdata.WaiverTypeId; } try { presetFields = JSON.parse(presetdata.Content); } catch (e) { // json not valid commonHelpDialog('Action failed','File is corrupted (JSON not valid)', 'DANGER'); dialog.close(); return false; } if(presetdata.WaiverFilledCount){ // if waiver filled - disable editing disableEditing = true; } if(presetdata.StableWaiverTypeId == stableActiveWaiver.StableWaiverTypeId){ editingCurrentlyActive = true; } } else { if(waivertype == 1 || waivertype == 2){ presetFields = defaultFieldsWaiver; } else if(waivertype == 3){ presetFields = defaultFieldsAgreement; } else if(waivertype == 4){ presetFields = defaultFieldsFeedback; } else { presetFields = defaultFieldsForm; } } waiverTypeElement.empty(); dialog.getModalDialog().find('.alert-existing-waiver').addClass("hidden"); if(waivertype){ waiverTypeElement.append(waiverTypeContent[waivertype]); if(waivertype == 1 && !editingCurrentlyActive){ dialog.getModalDialog().find('.alert-existing-waiver').removeClass("hidden"); } } else { waiverTypeElement.append(waiverTypeContent[0]); return false; } var mobileHelpContent = ''; waiverTypeElement.append(mobileHelpContent) var templates = formbuilderPreviewLayout; var fields = customFormFields; var formBuilderOptions = { disableFields: [ 'autocomplete', 'file', 'date', 'button', 'hidden' ], showActionButtons: false, disabledAttrs: ["access", "className", "inline", "name", "subtype"], controlOrder: ["header", "paragraph"], onAddField: function(fieldId, data) { logging(fieldId); logging(data); if(data.type == "file"){ } if(initReady){ waiverChanges = true; dialog.setClosable(false); } waiverCheckFormOrder(dialog); }, typeUserEvents: { // files: { // onadd: function(fld) { // logging("add file field") // logging(fld); // // var $patternField = $(".fld-pattern", fld); // // var $patternWrap = $patternField.parents(".pattern-wrap:eq(0)"); // // $patternField.prop("disabled", true); // // $patternWrap.hide(); // // fld.querySelector(".fld-subtype").onchange = function(e) { // // var toggle = e.target.value === "password"; // // $patternField.prop("disabled", !toggle); // // $patternWrap.toggle(toggle); // // }; // } // } }, fields, templates }; if(presetFields){ // populate preset content formBuilderOptions.formData = presetFields; formBuilderOptions.dataType = 'json'; } // fill if existing waiver content if(presetdata){ if(presetdata.WaiverComment){ dialog.getModalDialog().find('textarea[name="waivercomment"]').val(presetdata.WaiverComment); } if(presetdata.StatusId == 2 || presetdata.StatusId == 4){ dialog.getModalDialog().find('#waiverstatus').attr("checked", "checked"); } } formBuilder = waiverElement.formBuilder(formBuilderOptions); dialog.getModalDialog().find('#waiverstatus').bootstrapToggle(); //logging("disable waiver attachments temporarily", "teal"); // setTimeout(() => { // dialog.getModalDialog().find('.frmb-control .input-control[data-type="files"]').addClass("disabled overline"); // dialog.getModalDialog().find('.frmb-control .input-control[data-type="files"]').remove(); // }, 1000); autosize(dialog.getModalDialog().find('textarea[name="waivercomment"]')); if(!disableEditing){ waiverElement.removeClass("disabled"); } waiverElement.removeClass("hidden"); setTimeout(() => { if(presetdata && presetdata.copy){ dialog.getModalDialog().find('.select-waivertype-parent .form-group').removeClass("disabled"); } initReady = true; }, 300); } function waiverSave(data, settings, originaldata, dialog){ //TODO Save created waiver logging("waiverSave"); logging("form data"); logging(data); logging("settings"); logging(settings); logging("originaldata"); logging(originaldata); var edit = false; if(originaldata && !originaldata.copy){ edit = true; } if(data.length > 65535){ // prevent too long data for backend commonHelpDialog('Action failed','The content you entered is too long ('+data.length+'/65535)'); dialog.getModalDialog().find('.modal-body, .modal-footer').removeClass("disabled"); return false; } var waiverDataContent = JSON.parse(data); // logging("waiverDataContent"); // logging(waiverDataContent); $(waiverDataContent).each(function(index, row){ // check radio button and checkbox row options if(row.type == "radio-group" || row.type == "checkbox-group" || row.type == "select"){ $(row.values).each(function(index, value){ logging("value"); logging(value); value.value = "option-"+(index+1); }); } }); // logging("waiver checked data before save", "teal"); // logging(waiverDataContent); var waiverHeader = $.grep(waiverDataContent, function(e){ return e.className ==="waiver-header-element" }); var saveData = JSON.stringify(waiverDataContent); var query = {}; query.stableid = currentStableId; query.status = 0; // published/temp query.content = saveData; if(waiverHeader.length){ query.header = waiverHeader[0].label; } query.comment = ""; query.definition = "definition"; query.from = undefined; query.to = undefined; query.waivertypeid = 1; // waiver type if(settings){ // override & add default query if settings found query = Object.assign(query, settings); } var formDataChanged = false; if(originaldata){ // editing query.stablewaivertypeid = originaldata.StableWaiverTypeId; if(query.publish == 1){ if(query.waivertypeid == 1){ query.status = 2; } else { query.status = 4; } } else { query.status = 1; } } else { if(query.publish == 1){ if(query.waivertypeid == 1){ query.status = 2; } else { query.status = 4; } } } var waiverSaveUrl = 'https://hopoti.com/insertWaiverType'; if(edit){ waiverSaveUrl = 'https://hopoti.com/updateWaiverType'; } $.ajax({ url: waiverSaveUrl, type: 'POST', data: query, error: function(err) { commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); dialog.getModalDialog().find('.modal-body, .modal-footer').addClass("disabled"); loadStableWaiverTypes(); removeWaiverCache(); }, success: function(data) { dialog.close(); if(query.copy){ loadStableWaiverTypes(data[0].StableWaiverId); //waiverEdit(data[0].StableWaiverId); } else { //waiverEdit(); loadStableWaiverTypes(); } removeWaiverCache(); } }); } var waiverFormTimeout; function waiverCheckFormOrder(dialog){ console.log("waiverCheckFormOrder"); clearTimeout(waiverFormTimeout); waiverFormTimeout = setTimeout(function(){ waiverAlterForms(dialog); var waiverData = formBuilder.actions.getData('js'); if(waiverData){ var waiverDataCheck = rearrangeWaiverData(waiverData); if(waiverDataCheck.reorder == true){ formBuilder.actions.setData(waiverDataCheck.data); } } var waiverData = formBuilder.actions.getData('js'); validateWaiverData(waiverData); }, 50); } function rearrangeWaiverData(data){ logging("rearrangeWaiverData"); console.log(data); var finalData = []; var reorder = true; var headerindex = data.findIndex(x => x.className ==="waiver-header-element"); //logging("headerindex: "+headerindex); if(headerindex < 0){ var returnObject = {}; returnObject.reorder = false; return returnObject; } var legalindex = data.findIndex(x => x.className ==="waiver-legal-element"); var acceptindex = data.findIndex(x => x.className ==="waiver-accept-element"); var signatureindex = data.findIndex(x => x.className ==="waiver-signature-element"); var childindex = data.findIndex(x => x.className ==="waiver-child-element"); logging("childindex: "+childindex); if(headerindex == 0 && legalindex == 1 && acceptindex == data.length-2 && signatureindex == data.length-1){ // do not reorder form if order ok reorder = false; } else if(headerindex == 0 && legalindex == -1 && acceptindex == -1 && signatureindex == -1){ reorder = false; } var waiverHeader = $.grep(data, function(e){ return e.className ==="waiver-header-element" }); var waiverLegal = $.grep(data, function(e){ return e.className ==="waiver-legal-element" }); var waiverChilds = $.grep(data, function(e){ return e.className ==="waiver-child-element" }); var waiverAccept = $.grep(data, function(e){ return e.className ==="waiver-accept-element" }); var waiverSignature = $.grep(data, function(e){ return e.className ==="waiver-signature-element" }); if(childindex > -1 && childindex != data.length-3){ reorder = true; } //logging(waiverChilds); if(waiverHeader.length){ finalData.push(waiverHeader[0]); } if(waiverLegal.length){ finalData.push(waiverLegal[0]); } $(data).each(function(index, row){ if(row.className == "waiver-header-element" || row.className == "waiver-legal-element" || row.className == "waiver-accept-element" || row.className == "waiver-signature-element" || row.className ==="waiver-child-element"){ return true; } else { finalData.push(row); } }); if(waiverChilds.length){ finalData.push(waiverChilds[0]); } if(waiverAccept.length){ finalData.push(waiverAccept[0]); } if(waiverSignature.length){ finalData.push(waiverSignature[0]); } var returnObject = {}; returnObject.data = finalData; returnObject.reorder = reorder; return returnObject; } function waiverAlterForms(dialog){ // remove unwanted elements after render logging("waiverAlterForms"); var currentDial = dialog.getModalDialog(); var headerElement = currentDial.find('.waiver-header-element').closest(".form-field"); headerElement.find('a[type="remove"], a[type="copy"]').remove(); var legalElement = currentDial.find('.waiver-legal-element').closest(".form-field"); legalElement.find('a[type="remove"], a[type="copy"]').remove(); var acceptElement = currentDial.find('.waiver-accept-element').closest(".form-field"); acceptElement.find('a[type="remove"], a[type="copy"], .toggle-wrap, .other-wrap, .field-options .option-actions').remove(); acceptElement.find('.required-wrap .fld-required').addClass("disabled"); acceptElement.find('.field-options .option-selected').addClass("hidden"); acceptElement.find('.field-options .option-value').addClass("hidden"); acceptElement.find('.field-options .option-label').css("width", "100%"); var signatureElement = currentDial.find('.waiver-signature-element').closest(".form-field"); signatureElement.find('a[type="remove"], a[type="copy"]').remove(); signatureElement.find('.required-wrap .fld-required').addClass("disabled"); signatureElement.find('.placeholder-wrap, .value-wrap').addClass("hidden"); var altSignatureElements = currentDial.find('.signature-element:not(.waiver-signature-element)'); altSignatureElements.each(function(index, item){ var singleElement = $(item).closest('.form-field'); singleElement.find('.placeholder-wrap, .value-wrap').addClass("hidden"); }); var ratingElements = currentDial.find('.ratingstar-field, .ratingemoji-field'); ratingElements.each(function(index, item){ $(item).find('.placeholder-wrap, .value-wrap').addClass("hidden"); }); var userinfoElements = currentDial.find('.userinformation-field'); userinfoElements.each(function(index, item){ $(item).find('.placeholder-wrap, .value-wrap, .required-wrap').addClass("hidden"); }); var attachmentElements = currentDial.find('.files-field'); attachmentElements.each(function(index, item){ $(item).find('.placeholder-wrap, .value-wrap, .required-wrap').addClass("hidden"); }); var optionsElements = currentDial.find('.checkbox-group-field, .radio-group-field, .select-field'); optionsElements.each(function(index, item){ $(item).find('.option-value, .toggle-wrap, .multiple-wrap').addClass("hidden"); // hide option and toggle fields }); var otherOptions = currentDial.find('input.other-option'); otherOptions.each(function(index, item){ $(item).parent().find("label").not('[data-translated]').prepend("Other"); $(item).parent().find("label").attr("data-translated", 1); //fix for "other" translations }); } function waiverSign(waiverId, stableId, action){ logging("waiverSign | waiverId: "+waiverId+" | stableId: "+stableId+" | action:"+action); if(!stableId){ stableId = currentStableId; } if(!action){ action = "user-sign"; } var query = {}; query.stableids = [stableId]; query.waiverid = waiverId; let getStableActiveWaivers = getPromise('/getStableActiveWaivers', query); getStableActiveWaivers.then( (values) => { var waiverdata = JSON.parse(values.result); if(waiverdata.length){ stableOpenWaiver = waiverId; if($('body').hasClass("pageStableFrontpage")){ changeUrl(); } waiverViewWaiver(waiverdata[0], action); } else { commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } } ).catch( (error) => { commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } ).finally(() => { }); } var waiverViewDial; var waiverViewDialChanges = false; function waiverViewWaiver(data, action){ logging("waiverViewWaiver | action: "+action); // actions: stable-preview, user-sign, user-view, stable-view logging("data"); logging(data); if(waiverViewDial){ return false; } if(!myUserId){ action = "view"; } var waiverdata; var waivermeta; var businessdata; var waiverAlreadyFilledHtml = ""; var waiverFillerInfoHtml = ""; var fillerUserHtml = ""; var signDateString = ""; var validToString = ""; var userButton = ""; var waiverMatchData; var signedIds = []; var switchAccount = false; if(store.get('switch-account') && store.get('switch-account').action == "sign-waiver"){ switchAccount = true; } if(data.UserSignatures && data.UserSignatures.length){ var waiverMatchData; var waiverMatch = $.grep(data.UserSignatures, function(e){ return e.UserId == myUserId && !e.UserSignedWaiverExpired }); if(waiverMatch.length){ waiverMatchData = waiverMatch[waiverMatch.length-1]; } $(data.UserSignatures).each(function(index, item){ if(!signedIds.includes(item.UserId && !item.UserSignedWaiverExpired)){ signedIds.push(item.UserId); } }); } // logging("waiverMatchData"); // logging(waiverMatchData); // logging("signedIds"); // logging(signedIds); var changeAccountButton = ""; if(action == "user-sign" && data.StableWaiverId){ if(parentMode == "parent" || parentMode == "child" && userParentId){ var urlLink = 'https://hopoti.com/stable/'+data.StableInfo[0].StableLinkName+'/?page=forms&f='+data.StableWaiverId; changeAccountButton = ''; } } if(action == "stable-view"){ userButton = clientModalButtonHtml(data); } if(data && data.ValidToDateTime){ var validTo = moment(data.ValidToDateTime).format('DD/MM/YYYY'); validToString = 'Valid until [x]'.replace('[x]',validTo) } if(action == "view-active" && stableInfo){ waiverdata = data; businessdata = stableInfo; signDateString = moment().format('DD/MM/YYYY'); } else if(action == "stable-preview" && stableInfo){ waiverdata = data; var arrangedata = rearrangeWaiverData(data); if(arrangedata.reorder){ waiverdata = arrangedata.data; } businessdata = stableInfo; signDateString = moment().format('DD/MM/YYYY'); } else if(action == "user-view" || action == "stable-view"){ if(data.StableInfo){ businessdata = data.StableInfo[0]; } else { businessdata = data; } signDateString = moment(data.ConfirmedDateTime).format('DD/MM/YYYY HH:mm'); } else if(action == "user-sign" || action == "view"){ if(data.StableInfo){ businessdata = data.StableInfo[0]; } else { businessdata = stableInfo; } signDateString = moment().format('DD/MM/YYYY'); if(waiverMatchData){ var filledDate = moment(waiverMatchData.UserSignedWaiverTime).format('DD/MM/YYYY HH:mm'); var alreadyFilledString = 'You have already filled out this form on [x] - if you want, you can fill it out and submit it again.'.replace('[x]', ''+filledDate+''); if(!switchAccount){ // show filled button alreadyFilledString += 'Show filled form
    '; } waiverAlreadyFilledHtml = '
    '+alreadyFilledString+'
    '; } } if(data.Content){ var waivercontent = JSON.parse(data.Content); waiverdata = $.grep(waivercontent, function(e){ return e.type != "meta"; }); // remove meta from form data var waivermetamatch = $.grep(waivercontent, function(e){ return e.type == "meta"; }); // only meta if(waivermetamatch.length){ waivermeta = waivermetamatch[0]; } } var waiverFillerString = ""; var nameChangeString = ""; var metaHtml = ""; if(data.UserId){ fillerUserHtml = ''; waiverFillerString = 'The form has been filled out for account [x]'.replace('[x]', fillerUserHtml); if(waivermeta){ if(data.FirstName != waivermeta.FirstName || data.LastName != waivermeta.LastName){ nameChangeString = '(messages-stables.forms-username-when-filled)'.replace('[x]', ': '+waivermeta.FirstName+' '+waivermeta.LastName+''); } } } else if(typeof myInfoObject != "undefined") { fillerUserHtml = ''; waiverFillerString = 'The form will be filled out for account [x]'.replace('[x]', fillerUserHtml); } if(nameChangeString){ metaHtml += '\
    \ '+nameChangeString+'\
    '; } if(data.UserEmailAddress){ metaHtml += '\
    \ Login name: '+data.UserEmailAddress+'\
    '; } if(metaHtml){ metaHtml = '
    '+metaHtml+'
    '; } if(fillerUserHtml && waiverFillerString){ // fillers information var hopotiWaiverId = ""; if(data.SignedWaiverId){ hopotiWaiverId = 'Document ID: FID'+data.SignedWaiverId+''; } waiverFillerInfoHtml = '\
    \ \
    \ '+metaHtml+'\
    \
    \ Date: '+signDateString+'\
    \
    \ '+validToString+'\
    \
    '; } var formNumber = ""; if(data.StableWaiverId){ formNumber = 'Form number: #'+data.StableWaiverId+'' } var waiverHeaderInfo = '\
    \
    \
    \
    \
    \ Company: '+businessdata.StableName+''+formNumber+'
    \ '+businessdata.CompanyName+'\
    \
    \ '+waiverFillerInfoHtml+'\
    \
    \
    '; var disableClass = ""; if(action == "user-view" || action == "stable-view"){ disableClass = " disabled-opaque"; } var notLoggedInDisabled = ""; var waiverDialogLoginHelp = ""; if(!myUserId){ notLoggedInDisabled = "disabled-log-in"; waiverDialogLoginHelp = ''; } var waiverViewContent = '\
    \ '+waiverHeaderInfo+'\ '+waiverAlreadyFilledHtml+'\ '+waiverDialogLoginHelp+'\
    \
    \
    \
    \
    \
    '; var waiverDialogCloseButton = { label: 'Close', cssClass: 'btn-default btn-sm btn-ok', autospin: false, action: function(dialogRef){ if(waiverViewDialChanges && action == "user-sign" && myUserId){ BootstrapDialog.confirm({ title: 'Unsaved changes', message: 'Unsaved changes. Are you sure you want to close the window without saving?', type: BootstrapDialog.TYPE_WARNING, btnCancelLabel: 'Cancel', btnCancelClass: 'btn-default btn-sm', btnOKLabel: 'Close', btnOKClass: 'btn-default btn-sm pull-left', callback: function(result) { if(result) { dialogRef.close(); } } }); } else { dialogRef.close(); } } }; var dialogTitle = ''; if(waiverdata){ var waiverheader = $.grep(waiverdata, function(e){ return e.type === "header" }); if(waiverheader.length){ dialogTitle = waiverheader[0].label; } if(action == "stable-preview" || action == "view-active"){ dialogTitle = 'Preview: '+dialogTitle; } else if(action == "user-sign"){ dialogTitle = 'Fill form: '+dialogTitle; } else if(action == "user-view" || action == "stable-view"){ dialogTitle = 'Filled form: '+dialogTitle; } if(action == "user-sign" && data.UserChildren && data.UserChildren.length || action == "view-active" && data.UserChildren && data.UserChildren.length ){ var waiverChildContent = getWaiverChildContent(data.UserChildren); waiverdata.push(waiverChildContent); var waiverDataCheck = rearrangeWaiverData(waiverdata); if(waiverDataCheck.reorder == true){ waiverdata = waiverDataCheck.data; } } } var submitLabel = ' Accept and send'; if(action == "stable-preview" || action == "view-active"){ submitLabel += ' (Preview - no submit)'; } var waiverViewDialogButtons = [{ label: submitLabel, cssClass: 'btn-success btn-sm btn-waiver-sign-save disabled-continue pull-left' },{ label: ' Fill in required fields', cssClass: 'pull-left btn-danger noPointerEvents btn-sm btn-waiver-help' },{ label: ' Clear', cssClass: 'btn-default btn-sm btn-waiver-sign-clear hidden' } ]; var waiverDialogLoginButton = { label: ' Log in to sign the form', cssClass: 'btn-default btn-sm pull-left btn-log-in' }; var waiverDialogPdfButton = { label: ' Download', cssClass: 'btn-default btn-sm pull-left btn-waiver-download', action: function(dialogRef){ var waiverFilename = data.FirstName+" "+data.LastName+" - "+(data.StableName || data.StableInfo[0].StableName)+" - "+data.ConfirmedDateTime+".pdf"; var waiverPdfUrl = 'https://hopoti.com/getUserWaiverFile?waiverid='+data.SignedWaiverId+'&filename='+waiverFilename; if(data.UserId != myUserId){ waiverPdfUrl = 'https://hopoti.com/getStableUserWaiverFile?waiverid='+data.SignedWaiverId+'&stableid='+data.StableId+'&filename='+waiverFilename; } downloadURI(waiverPdfUrl); } }; if(action == "user-sign" && !myUserId){ // user not logged in waiverViewDialogButtons = [waiverDialogLoginButton, waiverDialogCloseButton] } else if(action == "user-view" || action == "stable-view"){ waiverViewDialogButtons = [waiverDialogCloseButton, waiverDialogPdfButton]; } else { if(currentStableLink && stableAdminLevel > 0 && data.StableWaiverId){ var shareLinkButton = { label: ' Share link', cssClass: 'btn-default btn-sm btn-share-link', data: { 'link': currentStableLink+'/?page=forms&f='+data.StableWaiverId, 'link-text': 'Share a link to form', 'message-text': 'Here is the link to the businesses' form', 'showdialog': 1 } }; waiverViewDialogButtons.push(shareLinkButton); } waiverViewDialogButtons.push(waiverDialogCloseButton); } waiverViewDial = BootstrapDialog.show({ type: BootstrapDialog.TYPE_PRIMARY, size: BootstrapDialog.SIZE_WIDE, cssClass: 'dialog-waiver', title: dialogTitle, message: waiverViewContent, closable: false, buttons: waiverViewDialogButtons, onshow: function(dialogRef){ }, onshown: function(dialogRef){ dialogRef.setClosable(true); if(action == "user-view" || action == "stable-view"){ waiverInitViewWaiverData(waiverdata, data, dialogRef); if (typeof clientDialogOpen !== 'undefined' && clientDialogOpen) { dialogRef.getModalDialog().find('.clientmodalbutton').addClass("disabled"); } } else { waiverInitWaiverData(waiverdata, data, dialogRef, false, action); } autosize(dialogRef.getModalDialog().find('textarea')); $('[data-toggle="popover"]').popover(); $('[data-toggle="tooltip"]').tooltip(); }, onhide: function(dialogRef){ waiverViewDial = undefined; stableOpenWaiver = null; if (typeof changeUrl !== "undefined"){ changeUrl(); } if(store.get('switch-account') && store.get('switch-account').action == "sign-waiver"){ // BootstrapDialog.confirm({ // ask if user wants to return to parent // title: 'Return to another account?', // message: 'You switched to sign the Registration Form from the parent's account, do you want to return to the account?', // type: BootstrapDialog.TYPE_PRIMARY, // btnCancelLabel: 'Continue on child account', // btnCancelClass: 'btn-default btn-sm', // btnOKLabel: ' Return to parent account', // btnOKClass: 'btn-success btn-sm pull-left', // callback: function(result) { // if(result) { // $.post( '/switchAccount', function(data){ // window.location.replace(store.get('switch-account').returnurl); // store.set('switch-account', { // clearformscache: true // }); // }).fail(function(xhr, status, error) { // alert(error); // }); // } else { // store.remove('switch-account'); // } // } // }); fullscreenSpinner("open", "Returning to parent account..."); $.post( '/switchAccount', function(data){ var returnUrl = store.get('switch-account').returnurl; if(returnUrl.includes("&f=")){ // remove form opening from return url var splitUrl = returnUrl.split("&f="); returnUrl = splitUrl[0]; } window.location.replace(returnUrl); store.set('switch-account', { clearformscache: true }); }).fail(function(xhr, status, error) { alert(error); }); } } }); } function waiverInitViewWaiverData(waiverdata, data, dialog){ logging("waiverInitViewWaiverData"); console.log(waiverdata); $("#myForm :input").prop('readonly', true); var waiverRenderOptions = { dataType: 'json', formData: waiverdata, templates: formbuilderReadyLayout, layoutTemplates: { help: function(helpText) { var helpTemplate = '\ '; return $(helpTemplate); } } }; var waiverElement = dialog.getModalDialog().find('#waiver-view-container'); var formRenderElement = waiverElement.formRender(waiverRenderOptions); formBuilderCheckboxes(waiverdata); dialog.getModalDialog().find("form.form-waiver-sign :input").prop('readonly', true); var otherOptions = dialog.getModalDialog().find('input.other-option'); otherOptions.each(function(index, item){ $(item).parent().find("label").prepend("Other"); //fix for "other" translations }); } function getWaiverChildContent(data){ logging("getWaiverChildContent"); logging(data); var obj = {}; obj.label = "Children on whose behalf the Registration Form is signed"; obj.type = "checkbox-group"; obj.name = "waiver-child-element-"+Math.floor(100000000000 + Math.random() * 1300000000); obj.className = "waiver-child-element"; obj.other = false; obj.required = false; obj.toggle = false; var childArray = []; $(data).each(function(index, item){ var child = {}; var displayedUserName = ""; if(item.UserName && !item.UserName.endsWith("@random.hopoti.com")){ displayedUserName = ' ('+item.UserName+')'; } child.label = item.FirstName + ' ' + item.LastName + displayedUserName; child.value = item.UserId; childArray.push(child); }); obj.values = childArray; return obj; } function formBuilderCheckboxes(data){ //Fix for formbuilder required checkbox groups data.forEach( ( column , key ) => { if(column.type == 'checkbox-group' || column.type == 'radio-group') { $('input[name="'+column.name+'[]"].other-option').removeAttr("checked"); $('input[name="'+column.name+'"].other-option').removeAttr("checked"); $('input#'+column.name+'-other-value').val("").hide(); if(column.userData && column.userData.length){ $.each(column.userData, function(index, value) { logging("value"); logging(value); if(column.type == 'checkbox-group'){ var singleElement; if(value.value){ // checked if(value.key == "other"){ singleElement = $('input[name="'+ column.name + '[]"].other-option'); if(value.data){ $('input#'+column.name+'-other-value').val(value.data).show(); } } else { singleElement = $('input[name="'+ column.name + '[]"][value="'+value.key+'"]'); } singleElement.attr("checked", "checked"); } } else if(column.type == 'radio-group'){ var singleElement; if(value.value){ // checked if(value.key == "other"){ singleElement = $('input[name="'+ column.name + '"].other-option'); if(value.data){ $('input#'+column.name+'-other-value').val(value.data).show(); } } else { singleElement = $('input[name="'+ column.name + '"][value="'+value.key+'"]'); } singleElement.attr("checked", "checked"); } } }); } } }); } var activeSignatures = []; function waiverInitWaiverData(waiverdata, data, dialog, reset, action){ logging("waiverInitWaiverData | action: "+action); logging(waiverdata); logging(data); activeSignatures = []; // reset signatures waiverViewDialChanges = false; var waiverRenderOptions = { dataType: 'json', formData: waiverdata, templates: getFormbuilderActiveLayout(data), layoutTemplates: { help: function(helpText) { var helpTemplate = '\ '; return $(helpTemplate); } } }; var waiverElement = dialog.getModalDialog().find('#waiver-view-container'); var formRenderElement = waiverElement.formRender(waiverRenderOptions); var submitForm = dialog.getModalDialog().find('form.form-waiver-sign'); submitForm.validator('update'); if(submitForm.data('bs.validator').validate().hasErrors()) { console.log("errors"); } var selectFields = dialog.getModalDialog().find('select.form-control'); selectFields.each(function(index, item){ $(item).removeAttr("multiple"); // fix for multiselect (prevent multiselect) }); var otherOptions = dialog.getModalDialog().find('input.other-option'); otherOptions.each(function(index, item){ $(item).parent().find("label").prepend("Other"); //fix for "other" translations }); var signatures = dialog.getModalDialog().find('.signature-sign').not('[data-signature-initiated]'); signatures.each(function(index, item){ var singleSignature = $(item); var signaturePad = new SignaturePad(singleSignature[0]); var clearButton = singleSignature.closest('.formbuilder-signature').find('.btn.clear-signature'); var initialsField = singleSignature.closest('.formbuilder-signature').find('input.signature-name'); signaturePad.required = singleSignature.data("signature-required"); signaturePad.addEventListener("endStroke", () => { console.log("Signature ended"); waiverViewDialChanges = true; dialog.setClosable(false); waiverValidateSend(dialog, submitForm, activeSignatures); dialog.getModalDialog().find('.btn-waiver-sign-clear').removeClass("hidden"); clearButton.removeClass("hidden"); }); activeSignatures.push(signaturePad); singleSignature.attr("data-signature-initiated", 1); clearButton.on('click', function (e) { e.preventDefault(); signaturePad.clear(); initialsField.val("").change(); $(this).addClass("hidden"); }); }); submitForm.on('change keyup','input, select, textarea', function (e) { waiverViewDialChanges = true; dialog.setClosable(false); waiverValidateSend(dialog, submitForm, activeSignatures); }); if(reset){ return false; } dialog.getModalDialog().find('.btn-waiver-sign-clear').on('click', function(){ waiverViewDialChanges = false; dialog.setClosable(true); $(this).addClass("hidden"); dialog.getModalFooter().find('.btn-waiver-sign-save').addClass("disabled-continue"); dialog.getModalFooter().find('.btn-waiver-help').html(' Fill in required fields').removeClass("hidden"); waiverInitWaiverData(waiverdata, null, dialog, true); }); dialog.getModalDialog().find('.btn-waiver-sign-save').on('click', function(){ dialog.getModalFooter().find('.btn-waiver-help').removeClass("attentionblink-3"); dialog.getModalDialog().find('.form-group').removeClass("attention"); if(action == "view"){ dialog.getModalDialog().find('.btn-log-in').removeClass("attentionblink-3"); setTimeout(function(){ dialog.getModalDialog().find('.btn-log-in').addClass("attentionblink-3"); }, 50); return false; } if(!waiverValidateSend(dialog, submitForm, activeSignatures, true)){ dialog.getModalFooter().find('.btn-waiver-help').addClass("attentionblink-3"); dialog.getModalDialog().find('.form-group.has-error').addClass("attention"); var requiredSignatures = dialog.getModalDialog().find('canvas.signature-sign[data-signature-required="1"][data-signature-added="0"]') requiredSignatures.closest(".formbuilder-signature").addClass("attention"); setTimeout(function(){ dialog.getModalFooter().find('.btn-waiver-help').removeClass("attentionblink-3"); }, 3000); $('.dialog-waiver').animate({ scrollTop: $(".attention").first().offset().top }, 500); return false; } if(action == "stable-preview" || action == "view-active"){ commonHelpDialog('Note','Preview - no submit','SUCCESS'); } else { dialog.setClosable(false); dialog.getModalDialog().find('.modal-body, .modal-footer').addClass("disabled"); var finalWaiverData = formRenderElement.userData; waiverSend(dialog, finalWaiverData, activeSignatures, data); } }); dialog.getModalDialog().find('.btn-log-in').on('click', function(){ // log in dialog.close(); $('html, body').scrollTop(0); $('.loginlink a').click(); }); // prevent form actions for unlogged users dialog.getModalDialog().find('.disabled-log-in').on('click','.form-group', function (e) { e.preventDefault(); $(this).blur(); dialog.getModalDialog().find('.btn-log-in').removeClass("attentionblink-3"); setTimeout(function(){ dialog.getModalDialog().find('.btn-log-in').addClass("attentionblink-3"); }, 50); }); dialog.getModalDialog().find('.waiver-help-icon').on('click', function(e){ // prevent form focus when help clicked e.preventDefault(); }); waiverValidateSend(dialog, submitForm, activeSignatures); } function waiverValidateSend(dialog, submitForm, signatures, fastvalidate){ logging("waiverValidateSend | fastvalidate: "+fastvalidate); logging(submitForm); var formErrors = submitForm.data('bs.validator').validate().hasErrors(); var signatureError = false; $(signatures).each(function(index, signaturePad){ var singleCanvasId = signaturePad.canvas.id; if(signaturePad.isEmpty()){ $(document).find("#"+singleCanvasId).attr("data-signature-added", 0); } else { $(document).find("#"+singleCanvasId).attr("data-signature-added", 1); } var singleSignatureError = signaturePad.isEmpty() && signaturePad.required == 1; if(!signaturePad.isEmpty()){ // check initials if signature added var signatureParent = dialog.getModalDialog().find("#"+singleCanvasId).closest('.formbuilder-signature'); var signatureInitials = signatureParent.find('input.signature-name').val(); var signatureCheckEmpty = signatureInitials.split(' ').join(''); // if just empty characters if(!signatureCheckEmpty.length && fastvalidate){ signatureParent.addClass("has-error has-danger attention"); signatureError = true; } } if(singleSignatureError){ signatureError = true; } }); var attachmentError = false; var attachmentElements = dialog.getModalDialog().find(".attachment-parent"); logging(attachmentElements); if(attachmentElements.length){ attachmentElements.each(function(index, item){ var attachmentAmount = parseInt($(item).attr("data-attachment-added")); console.log(attachmentAmount); if($(item).data("attachment-required") && !attachmentAmount){ attachmentError = true; $(item).closest(".formbuilder-files.form-group").addClass("attention"); } else { $(item).closest(".formbuilder-files.form-group").removeClass("attention"); } }); } if(fastvalidate){ if(formErrors || signatureError || attachmentError){ return false; } else { return true; } } if(formErrors || signatureError || attachmentError){ console.log("waiver errors"); var waiverHelpText = ' Please add signature'; if(formErrors){ waiverHelpText = ' Fill in required fields'; } else if(attachmentError){ waiverHelpText = ' Add an attachment'; } dialog.getModalFooter().find('.btn-waiver-help').html(waiverHelpText).removeClass("hidden"); dialog.getModalFooter().find('.btn-waiver-sign-save').addClass("disabled-continue"); } else { console.log("waiver fine!"); dialog.getModalFooter().find('.btn-waiver-sign-save').removeClass("disabled-continue"); dialog.getModalFooter().find('.btn-waiver-help').addClass("hidden"); } } function waiverSend(dialog, waiverformdata, signaturedata, waiversettings){ //TODO send waiver! logging("waiverSend"); logging("waiverformdata"); logging(waiverformdata); logging("signaturedata"); logging(signaturedata); logging("waiversettings"); logging(waiversettings); fullscreenSpinner("open", "Sending..."); $(signaturedata).each(function(index, sig){ // parse each signature and insert data to correct object if(sig.isEmpty()){ return true; } var thisId = $(sig.canvas).attr('id'); var thisIdNo = thisId.replace("sign-signature-", ""); var thisSignature = sig.toDataURL('image/png'); // save as png data source var submitsignaturedata = $.grep(waiverformdata, function(e){ return e.name === "signature-"+thisIdNo }); if(submitsignaturedata.length){ submitsignaturedata[0].userData = thisSignature; } }); // add waiver meta data var waiverMeta = ownInfoObject; waiverMeta.type = "meta"; waiverformdata.push(waiverMeta); $(waiverformdata).each(function(index, datarow){ // find custom data from extra input fields console.log(datarow); if(datarow.type == "ratingstar" || datarow.type == "ratingemoji"){ var rowvalue = dialog.getModalDialog().find('input#'+datarow.name).val(); //logging("rowvalue: "+rowvalue); datarow.userData = parseInt(rowvalue); } else if(datarow.type == "userinformation"){ // user info row //logging("datarow try to find", "red"); var userInfoObject = {}; var datarows = dialog.getModalDialog().find('.field-'+datarow.name+' [data-key]'); $(datarows).each(function(index, datarow){ // logging("datarow submit"); // logging(datarow); var rowDataKey = $(this).data("key"); var rowDataValue = $(this).data("value"); userInfoObject[rowDataKey] = rowDataValue; //logging(rowDataValue); }); // logging("userInfoObject"); // logging(userInfoObject); datarow.userData = userInfoObject; } else if(datarow.type == "signature"){ // signature var signatureInitials = dialog.getModalDialog().find('input#'+datarow.name+'-initials').val(); // logging("signatureInitials"); // logging(signatureInitials); if(signatureInitials){ datarow.userDataInitials = signatureInitials; } } else if(datarow.type == "checkbox-group" || datarow.type == "radio-group"){ var thisgroup = dialog.getModalDialog().find('.field-'+datarow.name); var thisGroupInputs; if(datarow.type == "checkbox-group"){ thisGroupInputs = thisgroup.find('input[type="checkbox"]'); } else if(datarow.type == "radio-group"){ thisGroupInputs = thisgroup.find('input[type="radio"]'); } // remove selected values from submit $(datarow.values).each(function(index, value){ if(value.selected){ delete value.selected; } }); var userData = []; $(thisGroupInputs).each(function(index, input){ var isChecked = $(input).is(":checked"); if (isChecked) { var singleInput = {}; singleInput.value = isChecked; if($(input).hasClass("other-option")){ singleInput.key = "other"; if(singleInput.value){ singleInput.data = dialog.getModalDialog().find('input#'+datarow.name+'-other-value').val(); } } else { singleInput.key = $(input).attr("value"); } userData.push(singleInput); } }); datarow.userData = userData; } }); var query = {}; query.stableid = waiversettings.StableId; query.definition = waiversettings.Content; query.waivertypeid = waiversettings.WaiverTypeId; query.stablewaiverid = waiversettings.StableWaiverTypeId; var waiversValidity = waiversettings.StableInfo[0].WaiversValid; if(waiversettings.WaiverTypeId == 1 || waiversettings.WaiverTypeId == 2){ // save expiration for lesson and open waivers if(waiversValidity > 0 && waiversValidity <= 100){ // x months query.validTo = moment().add(waiversValidity, "months").format("YYYY-MM-DD HH:mm:ss"); } else if(waiversValidity == 1000){ // calendar year query.validTo = moment().endOf("year").format("YYYY-MM-DD HH:mm:ss"); } } query.content = JSON.stringify(waiverformdata); query.file = null; query.signeremail = ""; logging("submit query"); logging(query); if(query.content.length > 65535){ // prevent too long data for backend fullscreenSpinner("close"); commonHelpDialog('Action failed','The content you entered is too long ('+query.content.length+'/65535)'); dialog.getModalDialog().find('.modal-body, .modal-footer').removeClass("disabled"); return false; } if(fileUploads){ logging("fileUploadDropzone"); logging(fileUploadDropzone.files); logging(fileUploadDropzone); } $.ajax({ url: 'https://hopoti.com/insertUserWaiver', type: 'POST', data: query, error: function(err) { fullscreenSpinner("close"); commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); dialog.getModalDialog().find('.modal-body, .modal-footer').removeClass("disabled"); removeWaiverCache(); }, success: function(data) { if(fileUploads){ var fileObject = {}; uploadWaiverFiles(data, dialog, query); return false; } waiverSentSuccess(query, dialog); } }); } function uploadWaiverFiles(data, dialog, query){ console.log("uploadWaiverFiles"); console.log(data); //dialog.getModalDialog().find('form, .bootstrap-dialog-footer-buttons').addClass("disabled"); fileUploadDropzone.on("sending", function(file, xhr, formData) { logging("uploadwaiverfiles sending"); logging(file); logging(xhr); logging(formData); formData.append("UserSignedWaiverId", data[0].UserSignedWaiverId); // formData.append("filesize", file.size); // formData.append("heventid", data.heventid); // formData.append("horseid", data.horseid); // if(data.hgroupeventid){ // formData.append("hgroupeventid", data.hgroupeventid); // } // formData.append("comment", file.name); }); fileUploadDropzone.on('success', function (file, errorMessage) { setTimeout(function(){ fileUploads = false; dialog.close(); waiverSentSuccess(query, dialog); }, 500); }); fileUploadDropzone.on('error', function (file, errorMessage) { // dialog.getModalDialog().find('form, .bootstrap-dialog-footer-buttons').removeClass("disabled"); // commonHelpDialog('Loading failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); }); fileUploadDropzone.processQueue(); } function waiverSentSuccess(data, dialog){ logging("waiverSentSuccess"); logging(data); var activeWaiverTarget = $('[data-append-waiver] .btn-sign-waiver[data-waiverid="'+data.stablewaiverid+'"]').closest('[data-append-waiver]'); var activeWaiverTargetAction = activeWaiverTarget.attr('data-append-waiver'); var divClasses = "col-xs-12"; if(activeWaiverTargetAction == "booking"){ divClasses = "col-xs-12 col-md-6 pull-right"; } else if(activeWaiverTargetAction == "confirm"){ divClasses = "col-xs-12 col-sm-6 pull-right"; } var waiverSuccessHtml = '\
    \ \
    '; if(activeWaiverTarget.length){ activeWaiverTarget.append(waiverSuccessHtml); } removeWaiverCache(); reloadWaivers(); fullscreenSpinner("close"); dialog.close(); } function getUserWaiverInfoHtml(userdata, waiverdata, action){ //TODO Waiver sign html logging("getUserWaiverInfoHtml | action: "+action); logging("userdata"); logging(userdata); logging("waiverdata"); logging(waiverdata); if(!waiversFeature){ return ""; } var activewaivermatch = []; if(waiverdata.RequireLatest){ // latest waiver only activewaivermatch = $.grep(userdata.waivers, function(e){ if(e.ValidToDateTime){ return e.WaiverTypeId == 1 && e.StableWaiverTypeId == waiverdata.StableWaiverTypeId && moment(e.ValidToDateTime) > moment(); } else { return e.WaiverTypeId == 1 && e.StableWaiverTypeId == waiverdata.StableWaiverTypeId; } }); } else { // any signed waiver will do activewaivermatch = $.grep(userdata.waivers, function(e){ if(e.ValidToDateTime){ return e.WaiverTypeId == 1 && moment(e.ValidToDateTime) > moment(); } else { return e.WaiverTypeId == 1; } }); } var waiverMatchData; if(activewaivermatch.length){ waiverMatchData = activewaivermatch[activewaivermatch.length-1]; } var extraStyles = " no-padding"; var inlineData = ""; var waiverTools = ""; var waiverHelpText = ""; if(waiverMatchData){ var waiverdate = moment(waiverMatchData.SystemTime).format('DD/MM/YYYY HH:mm'); waiverHelpText = ' Registration Form signed #'+waiverMatchData.StableWaiverId+' - '+waiverdate+''; waiverTools = '\ '; } else { // not signed waiverHelpText = ' Registration Form not signed'; waiverTools = '\ '; } var userWaiverInfoHtml = '\
    \
    \
    \ '+waiverHelpText+'\
    \ '+waiverTools+'\
    \
    '; return userWaiverInfoHtml; } function checkUserWaiverStatus(waiverdata, userdata){ logging("checkUserWaiverStatus"); logging(waiverdata); logging(userdata); var activewaivermatch = []; if(waiverdata.RequireLatest){ // latest waiver only activewaivermatch = $.grep(userdata.waivers, function(e){ if(e.ValidToDateTime){ return e.WaiverTypeId == 1 && e.StableWaiverTypeId == waiverdata.StableWaiverId && moment(e.ValidToDateTime) > moment(); } else { return e.WaiverTypeId == 1 && e.StableWaiverTypeId == waiverdata.StableWaiverId; } }); } else { // any signed waiver will do activewaivermatch = $.grep(userdata.waivers, function(e){ if(e.ValidToDateTime){ return e.WaiverTypeId == 1 && moment(e.ValidToDateTime) > moment(); } else { return e.WaiverTypeId == 1; } }); } var returnStatus = {}; returnStatus.waivervalid = false; if(activewaivermatch.length){ returnStatus.waivervalid = true; } if(!waiverdata){ returnStatus.waivervalid = true; } return returnStatus; } var userWaivers = []; function getUserSignedWaivers(){ logging("getUserSignedWaivers - load user signed waivers"); userWaivers = []; let getUserSignedWaivers = getPromise('/getUserSignedWaivers'); getUserSignedWaivers.then( (values) => { userWaivers = JSON.parse(values.result); initUserWaivers(userWaivers); } ).catch( (error) => { console.error(error.message); commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } ).finally(() => { }); } var userWaiversClusterize; function initUserWaivers(data){ logging("initUserWaivers - init user signed waivers"); logging(data); data = sortByKey(data, "MessageSentDateTime", "NUM"); var waiverClusterizeData = buildClusterizeWaiverData(data, "user"); // Clusterize setup userWaiversClusterize = new Clusterize({ rows: waiverClusterizeData, scrollId: 'scrollAreaUserWaivers', contentId: 'contentAreaUserWaivers', no_data_text: 'No search results', rows_in_block: 20, callbacks: { clusterChanged: function() { checkClusterHeaders(); }, scrollingProgress: function() { } } }); } //Load user single signed waiver, based on hopoti wide waiverid function waiverOpenSignedWaiver(waiverid){ logging("waiverOpenSignedWaiver | waiverid: "+waiverid); var query = {}; query.waiverid = waiverid; let getUserSignedWaivers = getPromise('/getUserSignedWaivers', query); getUserSignedWaivers.then( (values) => { logging("values"); logging(values.result); if(values.result){ var waiverdata = JSON.parse(values.result); if(waiverViewDial){ waiverViewDialChanges = false; waiverViewDial.setClosable(true); waiverViewDial.close(); } waiverViewWaiver(waiverdata[0], "user-view"); } } ).catch( (error) => { console.error(error.message); commonHelpDialog('Action failed','Please check your Internet connection and try again in a moment. If the problem persists, contact our customer service.'); } ).finally(() => { }); } function waiverView(id, action){ logging("waiverView | id:"+id+" | action: "+action); if(!id){ return false; } var waiverAction = "user-view"; if(action){ waiverAction = action; } var waiverdata = []; if(userWaivers.length){ logging(userWaivers); waiverdata = $.grep(userWaivers, function(e){ return e.SignedWaiverId === id }); } else if(stableSignedWaivers.length){ logging(stableSignedWaivers); waiverdata = $.grep(stableSignedWaivers, function(e){ return e.SignedWaiverId === id }); } // logging("waiverView -> waiverdata"); // logging(waiverdata); if(waiverdata.length){ waiverViewWaiver(waiverdata[0], waiverAction); } } function getWaiverTypeSettings(type){ // get settings for waiver types var settings = {}; settings.waivertypeid = type; settings.waivertypename = "error"; settings.signatureneeded = false; settings.desc = ""; settings.icon = ""; if(type == 1){ // settings.waivertypename = 'Registration Form'; settings.signatureneeded = true; settings.desc = 'When making bookings, customers are asked to fill out the Registration Form'; settings.icon = ''; } else if(type == 2){ // settings.waivertypename = 'Other waivers'; settings.signatureneeded = true; settings.desc = 'Examples: Photo Release Forms, Permission Slips'; settings.icon = ''; } else if(type == 3){ // settings.waivertypename = 'Contracts'; settings.signatureneeded = true; settings.desc = 'Examples: Rental Agreements, Horse Boarding Agreements'; settings.icon = ''; } else if(type == 4){ // settings.waivertypename = 'Surveys'; settings.desc = 'Examples: Feedback Surveys, Wish Surveys'; settings.icon = ''; } else if(type == 5){ // settings.waivertypename = 'Waiting lists'; settings.desc = 'Examples: Waiting lists for stables, lessons or camps'; settings.icon = ''; } else if(type == 6){ // settings.waivertypename = 'Competitions'; settings.desc = 'Examples: Collecting competition registrations and information'; settings.icon = ''; } else if(type == 7){ // settings.waivertypename = 'Forms'; settings.desc = 'Examples: Any other forms'; settings.icon = ''; } return settings; } function waiverInvalidate(waiverId){ alert("waiverInvalidate | waiverId: "+waiverId); } function checkStableEventWaivers(waiver, event){ // logging("checkStableEventWaivers"); // logging(waiver); // logging(event); var activeWaiverId = waiver.StableWaiverTypeId; var requireLatest = waiver.RequireLatest == 1; var waiverAlert = true; if(!event.UserCount){ waiverAlert = false; } else if(event.UserSignedWaiverIds){ var waiverValidUsersArray = []; var userWaiverArray = jQuery.parseJSON(event.UserSignedWaiverIds); $(userWaiverArray).each(function(index, user){ if(!waiverValidUsersArray.includes(user.UserId)){ if(requireLatest){ // latest lesson waiver needed if(user.StableWaiverTypeId == activeWaiverId){ waiverValidUsersArray.push(user.UserId); } } else { // any lesson waiver ok waiverValidUsersArray.push(user.UserId); } } }); if(waiverValidUsersArray.length == event.UserCount){ waiverAlert = false; } } return waiverAlert; } function downloadURI(uri, name) { var link = document.createElement("a"); link.download = name; link.href = uri; document.body.appendChild(link); link.click(); document.body.removeChild(link); delete link; } // check extra url parameters to be included on changeurl functions var extraUrlParameters = [ 'product_tour_id', 'intercom_checklist_id', 'intercom_survey_id', 'utm_id', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'demo' ]; function checkUrlExtraParameters(query){ // console.log("original query"); // console.log(query); var urlExtraParameters = ""; $(extraUrlParameters).each(function(index, par){ var currentPara = getUrlParameter(par); if(currentPara){ urlExtraParameters+='&'+par+'='+currentPara; } }); var finalUrl = ""; var urlparts = query.split('#'); if (urlparts[0]) { // existing paramenters if (urlparts[0].indexOf('?') > -1) { finalUrl += urlparts[0]+urlExtraParameters; } else { finalUrl += urlparts[0]+'?'+urlExtraParameters.substring(1); } } else { finalUrl += '?'+urlExtraParameters.substring(1); } if(urlparts[1]){ // existing hash finalUrl += '#'+urlparts[1]; } return finalUrl; } function scrollFix(){ // force scroll event window.scrollTo(window.scrollX, window.scrollY - 1); window.scrollTo(window.scrollX, window.scrollY + 1); } // ! *** FUNCTIONS Everyone ends *** // ! *** FUNCTIONS Logged in users starts *** // checker for followup action after ajax calls [ajax][followup] // load missing data etc var followupAction; var followupData; $(document).ajaxStop(function () { if(followupAction){ if(followupAction == "new-user-diary"){ editDiaryEvent(); } else if(followupAction == "edit-user-diary"){ editDiaryEvent(followupData); } else if(followupAction == "new-hc-event"){ editHorseCareEvent(1); } else if(followupAction == "diary-content"){ if(userEventData){ diaryContent(undefined, undefined, userEventData); } else { diaryContent(); } } followupAction = null; } }); $(window).on('popstate', function (e) { logging("popstate"); logging(`location: ${document.location}, state: ${JSON.stringify(event.state)}`); var state = e.originalEvent.state; if (state !== null) { //load content with ajax } if(singlePostDial){ singlePostDial.close(); } // console.log(document.location); }); $(document).ready(function() { // Execute on load checkWidth(); contentAreaSubnaviCheck(); // Bind event listener $(window).resize(checkWidth); /* ! Common hash change functions */ // when hash changes $(window).on('hashchange',function(){ hashAction(); }); // initiate hash when page loaded hashAction(); // ! *** CLICKS everyone starts *** $('#cancellationPolicyHelpClient').on('click', function(e) { // for end users e.preventDefault(); cancellationPolicyModalClient(cancellation); }); $('body').on('click', '.cancellationPolicyHelpClient', function(e) { // for end users e.preventDefault(); cancellation = $(this).data("cancellationpolicy"); cancellationPolicyModalClient(cancellation); }); $('body').on('click', '.stablecardValidHelpClient', function(e) { // for end users e.preventDefault(); var dialogTitle = $(this).data("dialogtitle"); var dialogContent = $(this).data("dialogcontent"); commonHelpDialog(dialogTitle,dialogContent); }); // $('#selectCourseHelp').on('click', function(e) { // e.preventDefault(); // selectCourseHelpModal('select'); // }); // // $('#reserveCourseHelp').on('click', function(e) { // e.preventDefault(); // selectCourseHelpModal('reserve'); // }); $('body').on('click', '.previousCourseHelp', function(e) { e.preventDefault(); showPreviousCourseHelp(); }); $('body').on('click', '.noPreviousCourseHelp', function(e) { e.preventDefault(); showNoPreviousCourseHelp(); }); $('body').on('click', '.nextCourseHelp', function(e) { e.preventDefault(); showNextCourseHelp(); }); $('body').on('click', '.noNextCourseHelp', function(e) { e.preventDefault(); showNoNextCourseHelp(); }); $('body').on('click', '.common-help-dialog', function(e) { // common help dialog with .common-help-dialog class e.preventDefault(); var dialogTitle = $(this).data("title"); var dialogContent = $(this).data("content"); commonHelpDialog(dialogTitle,dialogContent); }); // sorting header indicators $(".tablesorter th").on('click', function(e) { $(".tablesorter th .glyphicon").remove(); if($(this).hasClass("headerSortDown")){ $(this).append(''); } else { $(this).append(''); } }); /* !Intercom dialog launcher */ $('.intercomLauncher').on('click', function(e) { e.preventDefault(); Intercom('show'); }); // !CLICK add new user modal select skill $(document).on('click', '.dialogAddnewClient .skillSelection a', function() { $('.skillSelection a').removeClass("active first"); $(this).addClass("active first"); setSkillsForm(); }); $(document).on('click', '.btn-back-to-top', function() { $("html, body").animate({scrollTop: 0}, 500); }); /* !Skill selection starts */ $(document).on('click', '.skillSelectionRange a:not(.active)', function() { var target = $(this).parent(); if (buttonsSelected == 0) { $(this).addClass("active"); $(this).addClass("first"); buttonsSelected = 1; firstPosition = $(this).index(); } else if (buttonsSelected == 1) { firstPosition = target.find(".first").index(); secondPosition = $(this).index(); if (secondPosition < firstPosition) { target.find(".first").removeClass("first").addClass("second"); $(this).addClass("first"); $(this).addClass("active"); firstPosition = target.find(".first").index(); secondPosition = target.find(".second").index(); } else { $(this).addClass("active"); $(this).addClass("second"); } buttonsSelected = 2; target.find('a.first').nextUntil('a.second').addClass("active"); } else { newPosition = $(this).index(); distanceFirst = Math.abs(firstPosition - newPosition); distanceSecond = Math.abs(secondPosition - newPosition); target.find('.skillSelection a').removeClass("active"); if (distanceFirst < distanceSecond) { target.find("a.first").removeClass("first"); firstPosition = $(this).index(); $(this).addClass("first"); } else { target.find("a.second").removeClass("second"); secondPosition = $(this).index(); $(this).addClass("second"); } target.find(".first,.second").addClass("active"); target.find('a.first').nextUntil('a.second').addClass("active"); } setSkillsForm(); }); $(document).on('click', '.skillSelectionRange a.first', function() { var target = $(this).parent().parent(); if (buttonsSelected == 1) { $(this).removeClass("active first"); buttonsSelected = 0 } else { if ($(this).next().hasClass("second")) { $(this).next().removeClass("second active"); buttonsSelected = 1; } $(this).removeClass("active first"); $(this).next().addClass("active first"); } setSkillsForm(target); }); $(document).on('click', '.skillSelectionRange a.second', function() { var target = $(this).parent().parent(); if ($(this).prev().hasClass("first")) { $(this).removeClass("second active"); buttonsSelected = 1; } else { $(this).removeClass("active second"); $(this).prev().addClass("active second"); } setSkillsForm(target); }); $(document).on('click', '.skillSelectionRange a.active:not(.first,.second)', function() { var target = $(this).parent(); target.find(".first, .second").fadeOut(100).fadeIn(150).fadeOut(50).fadeIn(100); }); /* !Skill selection ends */ /* Change language click */ $('.changeLanguageButtonHeader').on('click', function(e) { e.preventDefault(); changeLanguageDialog(); }); $('body').on('click', '.changeLanguageButton, .change-language-button', function(e) { e.preventDefault(); changeLanguageDialog(); }); $('body').on('click', '.languageDialogContent .countryBtn', function(e) { e.preventDefault(); $(".countryBtn").removeClass("btn-primary active").addClass("btn-default"); $(this).addClass("btn-primary active").removeClass("btn-default"); preferLanguageChange($(this).attr("data-countrycode")); }); $('body').on('click', '.languageDialogContent .langBtn', function(e) { e.preventDefault(); $(".langBtn").removeClass("btn-primary active").addClass("btn-default"); $(this).addClass("btn-primary active").removeClass("btn-default"); if($(this).hasClass("changeLanguageBeta")){ $(".changeLanguageBetaLabel").hide("fast"); $(this).find(".changeLanguageBetaLabel").show("fast"); $(".changeLanguageBetaNotice").show("fast"); }else{ $(".changeLanguageBetaLabel").hide("fast"); $(".changeLanguageBetaNotice").hide("fast"); } }); // skill level popover extra info $('body').on('click', '.skilllevel:not(.nopopover)', function(e) { e.preventDefault(); var userlevel = $(this).data("userlevel"); var confirmed = $(this).data("confirmed"); // 1/0 if confirmed (old queries) var maxconfirmed = $(this).data("max-confirmed"); // highest confirmed by stable var noconfirmation = $(this).data("noconfirmation"); var confirmedPerson = $(this).data("confirmed-person"); var confirmedDate = $(this).data("confirmed-date"); var confirmedStable = $(this).data("confirmed-stable"); var title; var label; // var confirmedbyHtml = '

    Skill confirmed by '+confirmedDate+':
    ' + confirmedPerson + ' - ' + confirmedStable; var confirmedHtml = '

    Skill level unconfirmed'; if(confirmed == 1 || maxconfirmed >= userlevel){ confirmedHtml = '

    Skill level confirmed'; } if(noconfirmation){ confirmedHtml = ''; } if(userlevel == 4){ title = "4 - Experienced"; label = "I can ride different types of horses. My technical riding abilities include shoulder-in, half-pass and counter canter."; } else if (userlevel == 3) { title = "3 - Advanced"; label = "I am familiar with equestrian vocabulary. My technical riding abilities include leg yielding in trot and small circles in canter."; } else if (userlevel == 2) { title = "2 - Basic skills"; label = "I can ride walk, trot and canter and know my way around the arena. I can tack the horse without assistance."; } else if (userlevel == 1) { title = "1 - Beginner"; label = "I can steer a horse in walk and trot."; } else { title = "0 - No experience"; label = "I have not ridden a horse before, I need assistance."; } $('.popover').hide(); $(this).attr('data-original-title', title); $(this).attr('data-content',label + confirmedHtml); $(this).attr('data-html', true); $(this).popover('show'); }); relabelSkills('.skilllevel'); $('.skilllevel[data-toggle="popover"]').popover(); // !number plus/minus fields $('body').on('click', '.btn-number', function(e) { e.preventDefault(); fieldName = $(this).attr('data-field'); type = $(this).attr('data-type'); var input = $("input[name='"+fieldName+"']"); var currentVal = parseInt(input.val()); console.log(currentVal); // return false; if (!isNaN(currentVal)) { if(type == 'minus') { if(currentVal > input.attr('min')) { input.val(currentVal - 1).change(); } if(parseInt(input.val()) == input.attr('min')) { $(this).attr('disabled', true); } } else if(type == 'plus') { if(currentVal < input.attr('max')) { input.val(currentVal + 1).change(); } if(parseInt(input.val()) == input.attr('max')) { $(this).attr('disabled', true); } } } else { input.val(0); } }); $('body').on('focusin', '.input-number', function(e) { $(this).data('oldValue', $(this).val()); }); $('body').on('change', '.input-number', function(e) { minValue = parseInt($(this).attr('min')); maxValue = parseInt($(this).attr('max')); valueCurrent = parseInt($(this).val()); var oldValue = $(this).data('oldValue'); name = $(this).attr('name'); $(".btn-number[data-field='"+name+"']").attr('disabled', true); if(valueCurrent > minValue) { $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled'); } else if (valueCurrent < minValue){ alert('Minimum value reached'); if(oldValue){ $(this).val(oldValue); } } if(valueCurrent < maxValue) { $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled'); } else if (valueCurrent > maxValue){ alert('Maximum value reached'); if(oldValue){ $(this).val(oldValue); } } }); $('body').on('keydown', '.input-number', function(e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 && e.ctrlKey === true) || // Allow: home, end, left, right (e.keyCode >= 35 && e.keyCode <= 39)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } }); $('body').on('click', '.btn-show-hide-content', function(e) { e.preventDefault(); var showContent = $(this).data("show-content"); var hideContent = $(this).data("hide-content"); $(showContent).hide().removeClass("hidden").slideDown(300); $(hideContent).slideUp(100); }); // open new settings dialogs $('body').on('click', '.open-settings-dialog', function(e) { // e.preventDefault(); var onlythis = $(this).data("onlythis"); var dialogtype = $(this).data("dialogtype"); settingsDialog(dialogtype, null, onlythis); }); // open invoice courses panel $('body').on('click', '.common-event-calendar .panel-heading[data-toggle="collapse"]', function(e){ setTimeout(function(){ $('.common-event-calendar-courses').removeClass("hidden"); $('.common-event-calendar-courses').fullCalendar('render'); // $("[data-toggle=tooltip]").tooltip(); }, 100); }); $('body').on('change keyup blur', 'input[data-unitconversion]', function(e){ //![units] var changedfield = $(this); unitconversion(changedfield); }); // !CLICK custom next prev calendar buttons $(document).on('click', '.nextprev-buttons-custom button[data-direction]', function(e) { e.preventDefault(); var direction = $(this).data("direction"); var target = $(this).parent().data('button-target'); var scrollTarget = $(this).parent().data('scroll-target'); $(target).fullCalendar(direction); if(scrollTarget){ $('html, body').animate({ scrollTop: $(scrollTarget).offset().top-45 }, 700); } else { $('html, body').animate({ scrollTop: $(target).offset().top-60 }, 700); } }); $(document).on('click', '.more-info-button', function(e) { var target = $(this).closest(".more-info-button-added"); var originalHeight = target.data("original-height"); if(originalHeight == "0px"){ target.removeAttr('style'); } else { target.addClass("more-info-button-removed").css({ "height" : originalHeight }); } }); // !stablecard infobutton $(document).on('click', '.stableCard .infobutton', function(e) { e.preventDefault(); var infotype = $(this).data("info"); var walletid = $(this).closest(".stableCard").data("userwalletid"); var cardData = $.grep(userStableCardsArray, function(e){ return e.UserWalletId == walletid; }); if(cardData){ var card = cardData[0]; var dialogTitle = ' Membership information'; var cardHelpString = 'From the membership description you can find more information about the membership's content and benefits. Please contact [stablename] if you have any questions about membership.'; var nameLabel = 'Membership name'; if(infotype == "giftcard"){ dialogTitle = ' Redeeming a gift card'; cardHelpString = 'From the gift card description you can find more information about the gift card's content and redeem instructions. Please contact [stablename] if you have any questions about gift card.'; nameLabel = 'Gift card name'; } var validUntil = moment(card.ValidDate, "YYYY-MM-DD HH:mm:ss").format('DD/MM/YYYY'); var cardHelp = cardHelpString.replaceAllText('[stablename]', ''+card.StableName+''); cardHelp = cardHelp.replace("[date]", ''+validUntil+''); var additionalText = ""; if(card.AdditionalText){ additionalText = '\
    \
    \ \
    \
    \ '+card.AdditionalText+'\
    \
    '; } var cardHelpString = '\
    \
    \ \
    \
    \ '+card.Description+'\
    \
    \ '+additionalText+'\
    \
    \ '+cardHelp+'\
    \ \
    '; BootstrapDialog.show({ title: dialogTitle, message: cardHelpString, type: BootstrapDialog.TYPE_PRIMARY, closable: true }); } }); // stablecard infobutton ends // !checkout group toggle [checkout] $(document).on('click', '.select-payment-group-button', function(e){ var group = $(this).data('payment-group'); var target = $('.payment-group-'+group); $('.select-payment-group-button').not(this).removeClass("open closed"); $('.payment-group').not(target).collapse("hide"); if($(this).hasClass("open")){ target.collapse("hide"); $(this).removeClass("open"); } else { $('.select-payment-group-button').addClass("closed"); $(this).removeClass("closed"); if(target.hasClass("in")){ target.find('.select-purchase-type.hidden').hide().removeClass("hidden").slideDown(300); } else { target.find('.select-purchase-type').removeClass("hidden"); target.collapse("show"); } $(this).addClass("open"); } resetPaymentOption(); // selectedPaymentOption = {}; // if paying under stable or user if($('body').hasClass("pageUserPendingPayments")){ validatePaymentForm(); } else { processSelection(); } }); $(".scroll-horizontally").scroll(function() { // !Scroll check on .scroll-horizontally elements [scroll] horizontalScrollCheck($(this)); }); $(document).on('click', '.contentnav li:not(.disable-admin,.stable-admin-menu) a', function(e){ $('.contentnav li').removeClass("active"); $(this).parent().addClass("active"); }); // !CLICK - new clusterize sorting addons $(document).on('click', '.sort-clusterized-new', function(e){ $('.sort-clusterized-new').not($(this)).removeClass("asc desc"); $('.sort-clusterized-new').find('.glyphicon-collapse-up, .glyphicon-collapse-down').remove(); if($(this).hasClass("desc")){ // ascending $(this).addClass("asc").removeClass("desc"); $(this).prepend(''); } else { // descending $(this).removeClass("asc").addClass("desc"); $(this).prepend(''); } }); // share link function clicks $(document).on('click', '.btn-share-link', function(e) { e.preventDefault(); var link = $(this).attr("data-link"); var linktext = $(this).attr("data-link-text"); var messagetext = $(this).attr("data-message-text"); var showDialog = $(this).attr("data-showdialog"); if(showDialog == 1){ buildShareLinkContent(undefined, link, linktext, messagetext, 1, showDialog) } else { $(this).hide(); $(this).closest(".share-link-content").find(".share-hidden").removeClass("hidden"); } }); //!images remove common image $(document).on('click', '.remove-common-image', function(e) { e.preventDefault(); removeCommonImage($(this)); }); $(document).on('click', '.favbutton-signin', function(e) { e.preventDefault(); commonHelpDialog('Feature requires login','Sign in or register to Hopoti to perform the action

    Sign in'); }); $(document).on('click', '.btn-beta-tester', function(e) { showHideMobileMenu2022(1); e.preventDefault(); betaTesterDialog(); }); //!Full screen dialog for event images $(document).on('click', '.image-dialog-link', function(e) { var imageurl = $(this).data("image-source"); if(imageurl){ e.preventDefault(); var imageContent = '' BootstrapDialog.show({ title: '', message: imageContent, type: BootstrapDialog.TYPE_PRIMARY, closable: true, cssClass: 'dialog-full-screen dialog-image' }); } }); $(document).on('click', '.btn-select-icon', function(e) { var fieldname = $(this).data("fieldname"); var recommendedId = $(this).data("recommendedid"); iconSelector($(this), fieldname, recommendedId); }); $(document).on('click', '.btn-remove-icon', function(e) { var fieldname = $(this).data("fieldname"); var recommendedId = $(this).data("recommendedid"); var buttonTarget = $(this).parent(); buttonTarget.empty(); buttonTarget.append(getIconSelectorButtons(null, fieldname, recommendedId)); $(document).find('.'+fieldname).val("").change(); }); // //![infinite] // $('#infinite-scrollspy').on('activate.bs.scrollspy', function () { // console.log("end reached"); // }) $(document).on('click', '.color-template', function(e) { e.preventDefault(); var color1 = $(this).data("color1"); var color2 = $(this).data("color2"); var color3 = $(this).data("color3"); var parentElement = $(this).closest("form"); parentElement.find('input[name="color1"]').val("#"+color1); parentElement.find('input[name="color1"]').parent().css("color", "#"+color1); parentElement.find('input[name="color2"]').val("#"+color2); parentElement.find('input[name="color2"]').parent().css("color", "#"+color2); parentElement.find('input[name="color3"]').val("#"+color3).change(); parentElement.find('input[name="color3"]').parent().css("color", "#"+color3); }); //!Limit text amount keyup [limit] // Use class "limit-text-amount-counter" in textarea with data-text-limit-amount="500" // field should have a name, add element for display: // $(document).on('keyup', '.limit-text-amount', function(e){ var textlimit = parseInt($(this).data('text-limit-amount')); var thisName = $(this).attr("name"); var helpTarget = $('.limit-text-amount-counter[data-name="'+thisName+'"]'); helpTarget.removeClass("label-danger attentionblink-infinite").addClass("hidden"); var tlength = $(this).val().length; if(tlength < textlimit/2){ return false; } helpTarget.removeClass("hidden"); if(tlength >= textlimit){ helpTarget.addClass("label-danger attentionblink-infinite"); } $(this).val($(this).val().substring(0,textlimit)); var tlength = $(this).val().length; var remain = parseInt(tlength); helpTarget.html(remain+' / '+textlimit+''); }); // Listener: single post link $(document).on('click', '.p-area .post-action', function(e){ e.preventDefault(); var datatypeid = $(this).data("datatypeid"); var id = $(this).data("id"); var action = $(this).data("action"); var url = $(this).data("singleposturl"); getSinglePostContent(id, datatypeid, action, url, true); }); $(document).on('click', '.p-area .p-area-post-dropdown a', function(e){ e.preventDefault(); }); $(document).on('click', '.btn-header-date-picker', function(e){ e.preventDefault(); $('body').toggleClass("show-header-date-picker"); }); $(document).on('click', '.no-credit-transfer-button', function(e) { e.preventDefault(); noMoveReasonDialog("credit-no-transfers"); }); $(document).on('click', '.btn-selectize-add', function(e){ // open selectize dropdown button e.preventDefault(); var target = $(this).parent().find('input.selectized'); if(target[0].selectize){ target[0].selectize.open(); } }); $(document).on('click', '.btn-animate-to', function(e){ clickAnimateToElement($(this)); }); var urlformid = getUrlParameter('f'); if(urlformid){ stableOpenWaiver = parseInt(urlformid); } //logging("stableOpenWaiver: "+stableOpenWaiver); $(document).on('click', '.btn-add-waiver, .edit-waiver', function(e){ var waiverId = $(this).data("waiverid"); waiverEdit(waiverId); }); $(document).on('click', '.btn-sign-waiver', function(e){ e.preventDefault(); var waiverId = $(this).data("waiverid"); var stableId = $(this).data("stableid"); var action = $(this).data("action"); waiverSign(waiverId, stableId, action); }); $(document).on('click', '.btn-open-signed-waiver', function(e){ e.preventDefault(); var waiverId = $(this).data("waiverid"); waiverOpenSignedWaiver(waiverId); }); $(document).on('click', '.btn-invalidate-client-waiver', function(e){ e.preventDefault(); var waiverId = $(this).data("waiverid"); waiverInvalidate(waiverId); }); $(document).on('click', '.waiver-filtering-buttons .btn', function(e){ $('.waiver-filtering-buttons .btn').removeClass("active"); var section = $(this).data("section"); $('.waiver-filtering-buttons .btn[data-section="'+section+'"]').not('.btn-sign-waiver').addClass("active"); $(document).find('[data-show-section').addClass("hidden"); $(document).find('[data-show-section="'+section+'"]').removeClass("hidden"); if(section == "waivers"){ initStableWaiverTypes(stableWaiverTypes); } }); $(document).on('click', '.waiver-summary-link', function(e){ e.preventDefault(); var waiverTypeId = $(this).data("waivertypeid"); showStableWaiverSummary(waiverTypeId); }); $(document).on('click', '.waiver-status-note .btn', function(e){ e.preventDefault(); var waiverId = $(this).data("waiverid"); $('#contentAreaWaivers').find('.clusterize-row').removeClass("attentionblink-3"); setTimeout(function(){ $('#contentAreaWaivers').find('.clusterize-row[data-waiverid="'+waiverId+'"]').addClass("attentionblink-3"); }, 500); }); // var searchTimeout; $(".common-search input").keyup(function(){ // clearTimeout(searchTimeout); var searchval = $(this).val(); if(searchval.length > 0){ $(this).parent().find('.searchclear').show(); } else { $(this).parent().find('.searchclear').hide(); } }); // clear search field, reset page $(".common-search .searchclear").click(function(){ $(this).hide(); $(this).parent().find('input').val("").change(); }); $(document).on('click', '.btn-change-account', function(e){ e.preventDefault(); var urltarget = $(this).data("target"); var helpText = $(this).data("helptext"); var mode = $(this).data("mode"); var modeData = $(this).data("modedata"); changeAccountDialog(urltarget, helpText, mode, modeData); }); $(document).on('click', '.show-beta-alert', function(e){ // open selectize dropdown button commonHelpDialog(' Feature under development','The feature is under development. Unfortunately, the functionality is not yet in use.',"DANGER"); e.preventDefault(); }); // ! *** CLICKS everyone ends *** // ! *** CLICKS Logged in users starts *** // ! *** CLICKS for Super admin starts *** // ! *** CLICKS for Super admin ends *** });