var windowHeight = 0; var windowWidth = 0; var postMade = false; var DEBUG = false; window.onhashchange = function(e) { if(site.isSmallOrMediumDevice()) { var oldHash = e.oldURL.split('#')[1]; var newHash = e.newURL.split('#')[1]; if (oldHash == 'confirm') { e.preventDefault(); trainingCard.showConfirm(false); return false; } else if (oldHash == 'summary') { } } } $(document).ready(function () { if(!$("#base_summary").hasClass('v2')){ $("#base_summary").addClass('v2'); } if(!$("body").hasClass('v2')){ $("body").addClass('v2'); } //force remove old campaign code for backward compatibility, if was added as translate in training card v1 to info text. campaign code input is now in summary $('#tc_sp_info #campaign_code').remove(); $('#tc_sp_info #btn_tc_campaign_code').remove(); if($('#tc_customer_details').length){ return trainingCard.customerDetails.init(); } trainingCard.initSwiper(); trainingCard.setEventHandlers(); trainingCard.init(); $(window).resize(function () { ResizeHandler(); }); var selectedProduct = trainingCard.product.get(); //to avoid summary being fetched multiple times on page load ResizeHandler(selectedProduct ? false : true); }); function ResizeHandler(getSummary) { if(typeof getSummary == 'undefined') { //if not set, default is true getSummary = true; } /*If width has changed*/ if (windowWidth != $(window).width()) { if(getSummary) { trainingCard.summary.show(); } trainingCard.initSwiper(); } SaveWindowResolution(); } function SaveWindowResolution () { windowHeight = $(window).height(); windowWidth = $(window).width(); } var trainingCard = new function () { this.swiperInstances = []; this.initSwiper = function(){ if(site.isSmallOrMediumDevice()) { $(".swiper-container").each(function(index, element){ //some-slider-wrap-in var $this = $(this); $this.addClass('instance').addClass("instance-" + index); //instance need to be unique (ex: some-slider) $this.parent().find(".swiper-pagination").addClass("pagination-" + index); $this.parent().find(".swiper-button-prev").addClass("prev-" + index); //prev must be unique (ex: some-slider-prev) $this.parent().find(".swiper-button-next").addClass("next-" + index); //next must be unique (ex: some-slider-next) trainingCard.swiperInstances[index] = new Swiper(".instance-" + index, { //instance need to be unique (ex: some-slider) /* slidesPerView: 'auto', freeMode: true, */ direction: 'horizontal', /*spaceBetween: 20,*/ loop: true, pagination: { el: '.pagination-' + index, type: 'bullets', clickable: true }, // Navigation arrows navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, /*setWrapperSize:false,*/ slidesPerView: 'auto', /*freeMode: true, freeModeMomentum:true, freeModeMomentumRatio: 1, freeModeMomentumBounce:true, freeModeMomentumBounceRatio: 1, freeModeMomentumVelocityRatio: 1, freeModeSticky:false, freeModeMinimumVelocity: 0.05, */ observer: true, observeParents: true, }); }); /* setTimeout(function() { $('.swiper-slide').css('width', '100%'); },500); */ } }; this.init = function(){ //set default values var stepInto = 'tc_select_location'; if(!$('#select_location .list-group-item.active').length){ $('#select_location .list-group-item').first().addClass('active'); } if($('#tc_select_location.centers').length){ $('#select_location .list-group-item.active').click(); } $('#select_location button').html($('#select_location .list-group-item.active').data('name') + ' '); trainingCard.showSection(stepInto); if(($('#select_location .list-group-item.active').data('value') || !$('#id_ask_rr_location').length) && !$('#tc_select_location.centers').length){ trainingCard.showSection('tc_select_product'); } //select product from cookie if(trainingCard.product.get()){ var productCard = $('.product_card[data-product="'+trainingCard.product.get()+'"]'); if($(productCard).length) { stepInto = 'tc_select_product'; trainingCard.showSection(stepInto); trainingCard.product.select($(productCard), false, false); if(trainingCard.swiperInstances.length) { var prodIndex = 0; $('.product_card[data-product-type="contract_product"],.product_card[data-product-type="single_card"],.product_card[data-product-type="campaign"]').each(function(){ if($(this).data('product') == trainingCard.product.get()) { trainingCard.swiperInstances[0].slideTo(prodIndex, false,false); } prodIndex++; }); } } if($('section[data-name="tc_select_options"]').length) { //select options from cookie if (trainingCard.option.get()) { stepInto = 'tc_select_options'; trainingCard.showSection(stepInto); var arrOptions = trainingCard.option.get().split('|'); for (var option in arrOptions) { var productCard = $('.product_card[data-product="' + arrOptions[option] + '"]'); if ($(productCard).length) { trainingCard.option.select($(productCard), false, false); } } } } //to avoid summary being fetched multiple times if both product and option is found in cookie, fetch summary once trainingCard.summary.show(); if(site.isSmallOrMediumDevice()){ summary.hide(); } /* //select payment type from cookie if(trainingCard.paymentType.get()){ var productCard = $('button.payment_type[data-type="'+trainingCard.paymentType.get()+'"]'); if($(productCard).length) { stepInto = 'tc_select_payment_type'; trainingCard.showSection(stepInto); trainingCard.paymentType.select($(productCard, false)); } } */ } site.calculateProductCardMaxHeight('#contract_products_v2', 55, true, true); //site.calculateProductCardMaxHeight('#options', 55, true, true); //todo! doesn't work if options are hidden if($('#auto_select').length > 0 && $("[data-role=filter]").length){ if($('input[name="web_groups[]"],select[name="web_groups[]"]').length) { trainingCard.filter.setLinkedContracts(); } trainingCard.filter.execute(true); //select first visible product trainingCard.product.select($('.product_card:visible').first(), false); } trainingCard.stepInto(stepInto, false); }; this.setEventHandlers = function(){ $('.tc_product_list_v2 .product_card .product_select button.btn').on('click', function(){ if($(this).closest('.product_card').data('product-type') == 'option'){ trainingCard.option.select($(this).closest('.product_card'), true); } else { trainingCard.product.select($(this).closest('.product_card'), true); } }); $('.tc_product_list_v2 .product_card .product_select select').on('change', function(){ if($(this).closest('.product_card').data('product-type') == 'option'){ trainingCard.option.select($(this).closest('.product_card'), true); } }); //prevent menu from closing when scrolling up/down in mobile $('#select_location .dropdown').on({ "shown.bs.dropdown": function() { this.closable = true; }, "click": function(e) { var target = $(e.target); if(target.hasClass("scroll")) this.closable = false; else this.closable = true; }, "hide.bs.dropdown": function() { return this.closable; } }); $('#payment_type .payment_type[data-product-type="payment_type"] .product_select .btn').on('click', function(){ trainingCard.paymentType.select($(this).closest('.payment_type')); }); $('section[data-name="tc_select_options"] a.remove').on('click', function(){ trainingCard.option.removeAll(); }); $('body.training_card .tc_btn_continue').on('click', function(){ if(site.isSmallOrMediumDevice()){ if(!$('#tc_summary_mobile').hasClass('confirm')){ //show confirm //add location hash, for browser back navigation window.location.hash = 'confirm'; trainingCard.showConfirm(true); } else { if ($('body.training_card.v2 #campaign_code').val()) { //user filled in campaign code but did not press submit button if (!$('#id_frm_training_card #campaign_code').length) { var inp = $('', { name: 'campaign_code', id: 'campaign_code', type: 'hidden', value: $('body.training_card.v2 #campaign_code').val() }); $('#id_frm_training_card').append(inp); } trainingCard.post('#id_frm_training_card'); //delete input, in case something went wrong $('#id_frm_training_card #campaign_code').remove(); } else { trainingCard.post('#id_frm_training_card'); } } } else { trainingCard.post('#id_frm_training_card'); } }); //filters $("[data-role=filter]").each(function(){ try { if ($(this).prop('name') == 'locations[]') { $(this).change(function () { //unselect all others (grouped by city) var selectedValue = $(this).val(); $('input[name="locations[]"]').each(function(){ if($(this).val() !== selectedValue){ $(this).is(':checked', false); $(this).closest('label').removeClass('active'); } }); //trainingCard.filter.setLinkedContracts(); //trainingCard.filter.execute(true); }); } if ($(this).prop('name') == 'web_groups[]') { $(this).change(function () { trainingCard.filter.setLinkedContracts(); trainingCard.filter.execute(true); }); } else { $(this).change(function () { trainingCard.filter.execute(true); }) } } catch (e){ console.log('Error in document.ready filter events: '+ e.message); } }); }; this.showConfirm = function(show){ if(show){ summary.maximize(); //hide all except continue button $('#training_card_v2').addClass('no-show'); $('#tc_summary_mobile').addClass('maximized').addClass('confirm'); $('body.training_card .tc_btn_continue').addClass('confirm'); $('body.training_card .tc_btn_continue').find('#tc_btn_continue_navigation').html('2/4'); $('body.training_card .tc_btn_back').addClass('confirm'); $('#powered_by').hide(); } else { summary.minimize(); $('#training_card_v2').removeClass('no-show'); $('#tc_summary_mobile').removeClass('maximized').removeClass('confirm'); $('body.training_card .tc_btn_continue').removeClass('confirm'); $('body.training_card .tc_btn_continue').find('#tc_btn_continue_navigation').html('1/4'); $('body.training_card .tc_btn_back').removeClass('confirm'); } }; /*trainingCard.stepInto*/ this.stepInto = function(step, scrollToNext){ if(DEBUG) { console.log('trainingCard.stepInto ' + step); } var progressbarStep = step; if(step == 'tc_select_location'){ progressbarStep = 'tc_select_product'; } if(step == 'checkout' || step == 'tc_select_options'){ progressbarStep = 'tc_select_payment_type'; } progressbar.set(progressbarStep); trainingCard.showSection(step); if($('section[data-name="' + step + '"]').length) { if (scrollToNext) { $('html, body').animate({ scrollTop: $('section[data-name="' + step + '"]').offset().top - 50 }, 500); } } }; /*trainingCard.showSection*/ this.showSection = function(name){ if(DEBUG) { console.log('trainingCard.showSection ' + name); } $('#training_card_v2 section').each(function(){ if($(this).data('name') == name){ return false; } else { $(this).closest('li').addClass('is-done'); } }); $('section[data-name="'+name+'"]').show(); $('section[data-name="'+name+'"]').closest('li').show(); }; /*trainingCard.hideSection*/ this.hideSection = function(name){ if(DEBUG) { console.log('trainingCard.hideSection ' + name); } $('#training_card_v2 section').each(function(){ if($(this).data('name') == name){ return false; } else { $(this).closest('li').removeClass('is-done'); } }); $('section[data-name="'+name+'"]').hide(); $('section[data-name="'+name+'"]').closest('li').hide(); }; this.showMore = function(card){ var html = { title: $(card).find('.product_name').text(), body: $(card).find('.product_notes').html(), buttons: {accept: 'Sulje', reject: 'Takaisin'} }; showConfirmation(null, html); //piilotetaan cancel nappi $('#dialog-confirmation .user-reject').hide(); }; /*trainingCard.post*/ this.post = function(formId){ try { if(DEBUG) { console.log('trainingCard.post'); } if (postMade) { return false; } if(formId == '#id_frm_training_card') { if(!trainingCard.product.get() && $('section[data-name="tc_select_product"]').length) { showUserNotification('danger', 'Asiakkuutta ei ole vielä valittu.'); return; } } postMade = true; ShowPageLoading(); hideUserNotification(); ScrollTo("#img_loading"); var url = 'index.php?func=tc_post'; var currentLocation = document.location; if (currentLocation.toString().indexOf('inframe=1') > -1) { url += '&inframe=1'; } if (currentLocation.toString().indexOf('iframe=0') > -1) { url += '&iframe=0'; } if (site.isSmallOrMediumDevice()) { url += '&mobile=1'; } for(var i in trainingCard.option.values.personalTrainers.values){ var inp = $('', {name: 'personal_trainers[]', type: 'hidden', value: trainingCard.option.values.personalTrainers.values[i]}); $(formId).append(inp); } for(var i in trainingCard.option.values.rows.values){ var inp = $('', {name: 'ms_pt[]', type: 'hidden', value: trainingCard.option.values.rows.values[i]}); $(formId).append(inp); } $.post(url, $(formId).serialize(), function(data) { }) .done(function(redirectUrl) { window.location = redirectUrl; }) .fail(function(data) { postMade = false; //Allow to submit again var errorMsg = ''; if (data && data.responseJSON && data.responseJSON.errors) { for (errorCode in data.responseJSON.errors) { errorMsg = errorMsg + "

" + data.responseJSON.errors[errorCode] + "

"; } } else { //something went really wrong errorMsg = errorMsg + "

" + 'Toiminto epäonnistui. Ole hyvä yritä hetken kuluttua uudelleen' + "

"; } showUserNotification('danger', errorMsg); HidePageLoading(); }); } catch (e){ console.log('Error in trainingCard.post: '+ e.message); } }; this.reset = function(){ trainingCard.product.set(''); trainingCard.option.removeAll(); trainingCard.option.values = { 'personalTrainers': {'dataName': 'personal_trainer', 'values': []}, 'rows': {'dataName': 'row', 'values': []}, }; trainingCard.stepInto('tc_select_product', false); if($('section[data-name="tc_select_product"]').length) { //there may or may not be products for sale, or just options trainingCard.hideSection(('checkout')); } // prevent getting empty summary again if ($('#tc_summary').data('product-code')) { trainingCard.summary.show(); } //$('.tc_btn_continue').hide(); //commented out, caused problems, button is not set visible again when selecting another center and product }; /*trainingCard.product*/ this.product = new function() { /*trainingCard.product.get*/ this.get = function () { //Get product code from cookie. return Cookie.get('tc_selected_product'); }; /*trainingCard.product.set*/ this.set = function (productCode) { if (productCode) { //Set to form $("#id_rcr_product").val(productCode); //Save product code to cookie. return Cookie.set('tc_selected_product', productCode); }else{ //Remove from form $("#id_rcr_product").val(''); $('.product_card[data-product-type="contract_product"],.product_card[data-product-type="campaign"],.product_card[data-product-type="single_card"]').removeClass('selected'); $('.product_card[data-product-type="contract_product"],.product_card[data-product-type="campaign"],.product_card[data-product-type="single_card"]').find('.btn_buy').html('Valitse'); //Remove saved product code from cookie return Cookie.remove('tc_selected_product'); } }; /*trainingCard.product.select*/ this.select = function(card, scrollToNext, getSummary) { if(DEBUG) { console.log('trainingCard.product.select'); } if(typeof getSummary == 'undefined') { //if not set, default is true getSummary = true; } var productCode = card.data('product'); trainingCard.product.set(productCode); $('#contract_products_v2 .product_card:not([data-product-type="option"])').removeClass('selected'); $('#contract_products_v2 .product_card:not([data-product-type="option"]) .btn_buy').html('Valitse'); $(card).find('.btn_buy').html(''); $(card).addClass('selected'); if($(card).data('is-drop-in')){ //hide options trainingCard.hideSection('tc_select_options'); } else { if($('#user_input_required').length){ //reset flags trainingCard.userConfirmation.shown = false; trainingCard.userConfirmation.handled = false; //show user confirmations (modal lightbox) trainingCard.userConfirmation.show(); } trainingCard.stepInto('tc_select_options', scrollToNext); } //trainingCard.showSection('tc_select_payment_type'); trainingCard.stepInto('checkout', scrollToNext); if(getSummary) { trainingCard.summary.show(); } }; }; /*trainingCard.option*/ this.option = new function () { this.values = { 'personalTrainers': {'dataName': 'personal_trainer', 'values': []}, 'rows': {'dataName': 'row', 'values': []}, }; /*trainingCard.option.get*/ this.get = function () { //Get product codes from cookie. return Cookie.get('tc_selected_options'); //string, values separated with | }; /*trainingCard.option.select*/ this.select = function(card, scrollToNext, getSummary){ if(DEBUG) { console.log('trainingCard.option.select'); } if(typeof getSummary == 'undefined') { //if not set, default is true getSummary = true; } if($(card).hasClass('selected')){ //unselect option if ($(card).find('select.btn_buy').length){ if ($(card).find('select.btn_buy').val() == ''){ $(card).removeClass('selected'); } } else if ($(card).find('button.btn_buy').length) { $(card).find('button.btn_buy').html('Valitse'); $(card).removeClass('selected'); } } else { if ($(card).find('button.btn_buy').length) { $(card).find('button.btn_buy').html(''); } $(card).addClass('selected'); } if($('#id_option_select_multiple').val() == '0'){ //toggle option. unselect all others $('.tc_product_list_v2 .product_card[data-product-type="option"]').each(function(){ if($(this).data('product') !== $(card).data('product')) { $(this).removeClass('selected'); if ($(this).find('select.btn_buy').length){ $(this).find('select.btn_buy').val(''); } else if($(this).find('button.btn_buy').length) { $(this).find('button.btn_buy').html('Valitse'); } } }); } //reset selected options trainingCard.option.values = { 'personalTrainers': {'dataName': 'personal_trainer', 'values': []}, 'rows': {'dataName': 'row', 'values': []}, }; $('.product_card[data-product-type="option"].selected').each(function(){ var productCode = $(this).data('product'); if($(this).data('option-type') == 'ms_pt'){ if ($(this).find('select.btn_buy').length){ productCode += 'QTY*' + $(this).find('select.btn_buy').val().toString(); //add quantity as trailing number productCodeQTY*2 } trainingCard.option.values.rows.values.push(productCode); } else { trainingCard.option.values.personalTrainers.values.push(productCode); } }); //Save options to cookie var options = trainingCard.option.values.personalTrainers.values.concat(trainingCard.option.values.rows.values); Cookie.set('tc_selected_options', options.join('|')); if($('.product_card[data-product-type="option"].selected').length) { $('section[data-name="tc_select_options"] a.remove').show(); } else { $('section[data-name="tc_select_options"] a.remove').hide(); } trainingCard.stepInto('checkout', true); if(getSummary) { trainingCard.summary.show(); } }; this.remove = function(product){ $('.product_card[data-product-type="option"].selected').each(function(){ if($(this).data('product') == product){ $(this).removeClass('selected'); $(this).find('.btn_buy').html('Valitse'); } }); trainingCard.option.values = { 'personalTrainers': {'dataName': 'personal_trainer', 'values': []}, 'rows': {'dataName': 'row', 'values': []}, }; //Read filter values if ($('.product_card[data-product-type="option"]').length) { $('.product_card[data-product-type="option"].selected').each(function(){ var productCode = $(this).data('product'); if($(this).data('option-type') == 'ms_pt'){ if ($(this).find('select.btn_buy').length){ productCode += 'QTY#' + $(this).find('select.btn_buy').val().toString(); //add quantity as trailing number productCodeQTY#2 } trainingCard.option.values.rows.values.push(productCode); } else { trainingCard.option.values.personalTrainers.values.push(productCode); } }); } var options = trainingCard.option.values.personalTrainers.values.concat(trainingCard.option.values.rows.values); Cookie.set('tc_selected_options', options.join('|')); if($('.product_card[data-product-type="option"].selected').length) { $('section[data-name="tc_select_options"] a.remove').hide(); } trainingCard.summary.show(); }; this.removeAll = function(){ $('.product_card[data-product-type="option"].selected').each(function(){ trainingCard.option.remove($(this).data('product')); $(this).removeClass('selected'); $(this).find('.btn_buy').html('Valitse'); }); $('section[data-name="tc_select_options"] a.remove').hide(); trainingCard.stepInto('tc_select_options', false); }; }; this.paymentType = new function(){ /*trainingCard.paymentType.get*/ this.get = function () { //Get payment_type from cookie. return Cookie.get('tc_selected_payment_type'); }; /*trainingCard.paymentType.select*/ this.select = function(card, scrollToNext) { var type = card.data('type'); $('#payment_type .payment_type').removeClass('selected'); $(card).addClass('selected'); $('.payment_type .btn_buy').removeClass('disabled'); $('.payment_type .btn_buy').html('Valitse'); $(card).find('.btn_buy').addClass('disabled'); $(card).find('.btn_buy').html(''); $('#payment_type .product_details').hide(); $('#payment_type .product_details[data-type="'+ type +'"]').show(); Cookie.set('tc_selected_payment_type', type); $('#id_payment_type').val(type); trainingCard.stepInto('checkout', scrollToNext); trainingCard.summary.show(); }; }; /*trainingCard.customerDetails*/ this.customerDetails = new function(){ this.init = function() { if(site.isSmallOrMediumDevice()) { summary.show(); } else { if($('#tc_cd_login_container #login_form').length){ summary.hide(); } else { summary.show(); $('#tc_cd_container').removeClass('col-lg-5').addClass('col-lg-8'); $('#shopping_cart_cont').hide(); } } //fix login form $('#tc_cd_login_container #login_form').removeClass('col-sm-8 col-md-6 col-lg-4').addClass('col-lg-6'); $('#login_form_btns .btn[type="submit"]').closest('div').addClass('col-lg-8'); //$('#tc_cd_login_container #login_form input[name="txt_login"]').attr('placeholder', ''); //$('#tc_cd_login_container #login_form input[name="psw_password"]').attr('placeholder', ''); var labelLogin = $('label[for="id_first_name"]').clone(); $(labelLogin).attr('for', 'txt_login'); $(labelLogin).html($('#tc_cd_login_container #login_form input[name="txt_login"]').attr('placeholder')); $(labelLogin).insertBefore($('#tc_cd_login_container #login_form input[name="txt_login"]')); var labelLogin2 = $('label[for="id_first_name"]').clone(); $(labelLogin2).attr('for', 'psw_password'); $(labelLogin2).html('Salasana'); $(labelLogin2).insertBefore($('#tc_cd_login_container #login_form input[name="psw_password"]')); var fp_link = $('#login_form_fp').attr('href'); fp_link +='&show=login'; $('#login_form_fp').attr('href', fp_link); $('#id_frm_tc_cd_login h1').first().html('Olen palaava asiakas'); $('#btn_register_form').remove(); /*Read input values*/ $("#tc_customer_details input").each(function () { try { if ($(this).attr('type') != 'radio') { $(this).val(trainingCard.input.get($(this).prop('name'))); } /*Validate input values*/ if ($(this).val()) { trainingCard.input.set($(this)); } $(this).blur(function() { trainingCard.input.set($(this)); }); } catch (e) { console.log('Error in customerdetails read input values: ' + e.message); } }); $('body.tc_customer_details .tc_cd_btn_continue').on('click', function(){ if (trainingCard.input.showErrors()) { //Errors in form return false; } trainingCard.post('#id_frm_tc_customer_details'); }); if(site.isSmallOrMediumDevice()){ if($('#tc_cd_choose').data('show')){ $('.tc_cd_btn_type').hide(); //hide buttons $('.tc_cd_container_type:not([data-name="'+$('#tc_cd_choose').data('show')+'"])').hide(); } else { $('.tc_cd_container_type').hide(); } } $('.tc_cd_btn_type').on('click', function(){ $('.tc_cd_btn_type').hide(); //hide buttons $('.tc_cd_container_type[data-name="'+$(this).data('show')+'"]').show(); }); // Hide campaign code input on customer details page. It doesn't work. // Should have to recalculate summary prices if added, because we don't want to redirect back to first page after submitting campaign code, that would break the user's process. $('body.training_card.v2 #campaign_code').closest('.row').hide(); }; this.reset = function () { $("#tc_customer_details input, #tc_customer_details select").each(function () { try { //reset input and cookie value if ($(this).attr('type') != 'radio') { $(this).val(''); //reset cookie value Cookie.set('tc_input_'+ $(this).prop('name'), ''); } } catch (e){ console.log('Error in customerdetails reset: '+ e.message); } }); }; this.post = function() { var inp = $('', {name: 'rcr_product', type: 'hidden', value: Cookie.get('tc_selected_product')}); $("#id_frm_tc_customer_details").append(inp); if(Cookie.get('tc_selected_options')) { var options = Cookie.get('tc_selected_options').split('|'); for (var i in options) { var inp = $('', {name: 'personal_trainers[]', type: 'hidden', value: options[i]}); $("#id_frm_tc_customer_details").append(inp); } } }; }; /*trainingCard.filter*/ this.filter = new function (readFilterInputs) { this.values = { /*'productTypes': {'dataName': 'product-type', 'values': []}, 'sc_types': {'dataName': 'sc_type', 'values': []}, 'products': {'dataName': 'product', 'values': []},*/ 'commitMonths': {'dataName': 'commit-month', 'values': []}, 'frequencies': {'dataName': 'frequency', 'values': []}, 'contracts': {'dataName': 'contract', 'values': []}, 'webGroups': {'dataName': 'web-group', 'values': []}, 'locations': {'dataName': 'location', 'values': []}, 'centers': {'dataName': 'center', 'values': []}, }; this.linkedContractCount = 0; this.selectedContractIndex = 0; this.previousLinkedContractCount = 0; this.previousSelectedWebGroupIndex = null; this.previousLinkedContracts = ''; /*trainingCard.filter.hideRow*/ this.hideRow = function (value, filterValues) { if (filterValues.length > 0) { if (filterValues[0] == '') { return false; } if (typeof(value) === 'string' && value.includes(',')) { var values = value.split(','); var match = false; for (var i in values) { /* console.log('productcard has values ' + values); console.log('productcard contains ' + values[i]); console.log('searching for ' + filterValues); */ if (InArray(values[i], filterValues) || values[i] == NOT_SET) { //NOT_SET is used as wildcard match = true; } } if (!match) { return true; } } else { if (!InArray(value, filterValues) && value !== NOT_SET) { return true; } } } return false; }; /*trainingCard.filter.execute*/ this.execute = function (readFilterInputs) { try { if(DEBUG) { console.log('trainingCard.filter.execute'); } //remove selected product and options when filtering trainingCard.reset(); if (readFilterInputs) { this.readInputs(); } //Loop products //$('.product_card[data-product-type="contract_product"],.product_card[data-product-type="single_card"]').each(function () { $('.product_card[data-product-type="contract_product"],.product_card[data-product-type="campaign"],.product_card[data-product-type="single_card"],.product_card[data-product-type="option"][data-option-type="ms_pt"]').each(function () { $(this).show(); if(site.isSmallOrMediumDevice()) { $(this).closest('.swiper-slide').show(); } for (var filter in trainingCard.filter.values) { if($('#tc_select_location.centers').length){ if(filter=='locations'){ continue; } if($(this).data('product-type')=='option' && filter !== 'centers') { //only filter options by center continue; } $('#id_center').val(trainingCard.filter.values[filter]['values']); } var value = $(this).data(trainingCard.filter.values[filter]['dataName']); //Ex data-commit-month if (trainingCard.filter.hideRow(value, trainingCard.filter.values[filter]['values'])) { $(this).hide(); if(site.isSmallOrMediumDevice()) { $(this).closest('.swiper-slide').hide(); } break; } } }); if(site.isSmallOrMediumDevice()) { trainingCard.swiperInstances[0].update(); } } catch (e){ console.log('Error in trainingCard.filter.execute: '+ e.message); } }; /*trainingCard.filter.readInputs*/ this.readInputs = function () { try { if(DEBUG) { console.log('trainingCard.filter.readInputs'); } /*trainingCard.filter.values.productTypes.values = []; trainingCard.filter.values.sc_types.values = []; trainingCard.filter.values.products.values = [];*/ trainingCard.filter.values.commitMonths.values = []; trainingCard.filter.values.frequencies.values = []; trainingCard.filter.values.contracts.values = []; trainingCard.filter.values.webGroups.values = []; trainingCard.filter.values.locations.values = []; trainingCard.filter.values.centers.values = []; //Read filter values $('input[name="commit_months[]"]').each(function () { if ($(this).prop('checked')) { trainingCard.filter.values.commitMonths.values.push($(this).val()); } }); $('input[name="frequencies[]"]').each(function () { if ($(this).prop('checked')) { trainingCard.filter.values.frequencies.values.push($(this).val()); } }); $('input[name="contracts[]"]').each(function () { if ($(this).prop('checked')) { trainingCard.filter.values.contracts.values.push($(this).val()); } }); if ($('input[name="web_groups[]"]').length) { $('input[name="web_groups[]"]').each(function () { if ($(this).prop('checked')) { trainingCard.filter.values.webGroups.values.push($(this).val()); } }); } if ($('select[name="web_groups[]"]').length) { if($('select[name="web_groups[]"]').val()){ trainingCard.filter.values.webGroups.values.push($('select[name="web_groups[]"]').val()); } } $('input[name="locations[]"]').each(function () { if ($(this).prop('checked')) { trainingCard.filter.values.locations.values.push($(this).val()); } }); if($('#select_location[data-role-filter="1"]').length){ trainingCard.filter.values.locations.values.push($('#select_location[data-role-filter="1"] .list-group-item.active').data('value')); trainingCard.filter.values.centers.values.push($('#select_location[data-role-filter="1"] .list-group-item.active').data('value')); } } catch (e){ console.log('Error in trainingCard.filter.readInputs: '+ e.message); } }; /*trainingCard.filter.setLinkedContracts*/ this.setLinkedContracts = function () { if(DEBUG) { console.log('trainingCard.filter.setLinkedContracts'); } try { //show contract options according to web group //hide all if (($('input[name="web_groups[]"]').length > 0 || $('select[name="web_groups[]"]').length > 0) && $('input[name="contracts[]"]').length > 0) { $('.contracts_area').show(); var linkedContracts = new Array(); var webGroup; var selectedWebGroupIndex = 0; var newSelectedIndex = 0; //get selected web group $('input[name="web_groups[]"]').each(function (index) { if ($(this).is(':checked')) { webGroup = $(this).val(); selectedWebGroupIndex = index; } }); if($('select[name="web_groups[]"]').length > 0){ webGroup = $('select[name="web_groups[]"]').val(); selectedWebGroupIndex = $('select[name="web_groups[]"] option:selected').index(); } if(trainingCard.filter.previousSelectedWebGroupIndex == null){ trainingCard.filter.previousSelectedWebGroupIndex = selectedWebGroupIndex; } if(trainingCard.filter.previousSelectedWebGroupIndex == null){ trainingCard.filter.previousSelectedWebGroupIndex = 0; } $('input[name="contracts[]"]').each(function (index) { if($(this).prop('checked')){ trainingCard.filter.selectedContractIndex = index; } //hide all contracts $(this).hide(); //radio $(this).prop('checked', false); $(this).prop('disabled', true); //for slider $(this).parent().hide(); //label $(this).parent().removeClass('active'); }); //Loop products if ($('.centers_area').length) { var selectedCenter = $('.select_location.v2 a.list-group-item.active').data('value'); $('.center_contracts[data-name="'+ selectedCenter +'"]').each(function(ci){ if ($(this).data('value')) { var contracts = $(this).data('value').toString().split(','); $(contracts).each(function(cx) { linkedContracts.push(contracts[cx]); }); } }); } else { $('.product_card[data-product-type="contract_product"],.product_card[data-product-type="single_card"],.product_card[data-product-type="campaign"]').each(function () { if (InArray(webGroup, $(this).data('web-group').split(',')) || !webGroup) { if (linkedContracts.indexOf($(this).data('contract')) == -1) { linkedContracts.push($(this).data('contract').split(',')); } } }); } if(DEBUG) { /* console.log('previously selected index:: ' + trainingCard.filter.selectedContractIndex); console.log('number of previous linkedContracts:: ' + trainingCard.filter.previousLinkedContractCount); console.log('number of linkedContracts:: ' + linkedContracts.length); console.log('linkedContracts:: ' + linkedContracts); */ } if((linkedContracts.length <= trainingCard.filter.previousLinkedContractCount || trainingCard.filter.previousLinkedContractCount == 0)){ //try to maintain same selected option index even if contract options/indexes have changed //get new selected index var idX = linkedContracts.length; if(selectedWebGroupIndex > trainingCard.filter.previousSelectedWebGroupIndex) { //changed level up, add //how many levels? if(trainingCard.filter.previousLinkedContractCount == linkedContracts.length) { var levels = selectedWebGroupIndex - trainingCard.filter.previousSelectedWebGroupIndex; newSelectedIndex = trainingCard.filter.selectedContractIndex + (idX * levels); } } if(selectedWebGroupIndex < trainingCard.filter.previousSelectedWebGroupIndex){ //changed level down, subtract //how many levels? if(trainingCard.filter.previousLinkedContractCount == linkedContracts.length) { var levels = trainingCard.filter.previousSelectedWebGroupIndex - selectedWebGroupIndex; newSelectedIndex = trainingCard.filter.selectedContractIndex - (idX * levels); if (newSelectedIndex < 0 && trainingCard.filter.selectedContractIndex < idX) { //keep index newSelectedIndex = trainingCard.filter.selectedContractIndex; } } } if(selectedWebGroupIndex == trainingCard.filter.previousSelectedWebGroupIndex) { newSelectedIndex = trainingCard.filter.selectedContractIndex; } if(trainingCard.filter.previousLinkedContractCount == linkedContracts.length){ //keep index newSelectedIndex = trainingCard.filter.selectedContractIndex; } if(DEBUG) { console.log('new index:: ' + newSelectedIndex); } } $('input[name="contracts[]"]').each(function (i) { var contract = $(this).val().toString(); var contractElement = $(this); $.each(linkedContracts, function (index, value) { if (value.toString() == contract) { $(contractElement).show(); $(contractElement).prop('disabled', false); //for slider if(!$(contractElement).prop('checked')){ $(contractElement).parent().removeClass('active'); } $(contractElement).parent().show(); if((linkedContracts.length <= trainingCard.filter.previousLinkedContractCount || trainingCard.filter.previousLinkedContractCount == 0)){ if(i == newSelectedIndex){ if(DEBUG) { console.log('selecting index:: ' + (index+i)); } $(contractElement).prop('checked', true); $(contractElement).parent().addClass('active'); } } else { if(newSelectedIndex == 0 && !$('#contract_show_all').length) { //select first visible option if (index == 0) { if (DEBUG) { console.log('selecting index:: ' + index); } $(contractElement).prop('checked', true); $(contractElement).parent().addClass('active'); } } } } }); }); trainingCard.filter.selectedContractIndex = newSelectedIndex; trainingCard.filter.previousLinkedContractCount = linkedContracts.length; trainingCard.filter.previousSelectedWebGroupIndex = selectedWebGroupIndex; trainingCard.filter.previousLinkedContracts = linkedContracts; if ($('input[name="contracts[]"]:visible').length == 0){ //no contracs are visible, hide heading if(DEBUG) { console.log('no contracts visible'); } $('.sp_sub_header_contracts').hide(); } else { $('.sp_sub_header_contracts').show(); if(!webGroup && $('#contract_show_all').length) { $('#contract_show_all').closest('.btn').click(); } } if ($('.centers_area').length) { if ($('input[name="contracts[]"]:visible').length <= 0) { //25.3.2019 if contracts 1 or less, contract filter not visible #19570 $('.contracts_area').hide(); } else { //select first visible contract $('input[name="contracts[]"]:visible').first().prop('checked', true); $('input[name="contracts[]"]:visible').first().parent().addClass('active'); } } else { if ($('input[name="contracts[]"]:visible').length <= 1) { //25.3.2019 if contracts 1 or less, contract filter not visible #19570 $('.contracts_area').hide(); } } } } catch (e){ console.log('Error in trainingCard.filter.setLinkedContracts: '+ e.message); } }; }; /*trainingCard.input*/ this.input = new function () { /*trainingCard.input.get*/ this.get = function (name, index) { var val = Cookie.get('tc_input_'+name); if(name == 'birthday[]'){ if(index != undefined && val != '') { if(DATEFMT == 'd.m.Y') { var tmp = val.split('.'); } else { var tmp = val.split('-'); } val = tmp[index]; } } return val; }; /*trainingCard.input.getErrorMessage*/ this.getErrorMessage = function (jQInput) { console.log('Virhe kentässä: '); return 'Virhe kentässä: ' + jQInput.attr('placeholder') + "
"; }; /*trainingCard.input.integer*/ this.getInteger = function (str) { str = str.replace(/[^0-9.]/g, ''); str = str.replace(/(\..*)\./g, '$1'); return str; }; /*trainingCard.input.set*/ this.set = function (jQInput) { try { var str = jQInput.val(); //Set to uppercase if (jQInput.attr('type') == 'text') { str = str.substring(0, 1).toLocaleUpperCase() + str.substring(1); } //Trim str = str.trim(); /*Data fetch*/ switch (jQInput.prop('name')) { case 'zip': case 'bill_addr_zip': str = this.getInteger(str); $.getJSON("index.php?func=tc_search&case=city&zip=" + str, function (data) { if (data) { if (jQInput.prop('name') == 'bill_addr_zip') { $('#id_bill_addr_city').val(data); } else { $('#id_city').val(data); } } }); break; } /*Validation*/ if (!jQInput.attr('required') && str == '') { jQInput.get(0).setCustomValidity(''); } else { switch (jQInput.prop('name')) { case 'social_sec_no': case 'bill_social_sec_no': if ($('#tc_guardian').length && jQInput.prop('name') !== 'bill_social_sec_no') { $('#tc_guardian').hide(); $('#tc_guardian input').each(function(){ document.getElementById($(this).attr('id')).required = false; }); } //set last character to uppercase var lastChar = str.substring(str.length-1).toLocaleUpperCase(); str = str.substring(0, str.length-1)+lastChar; if (validator.isValid.socialSecNo($("input[name=country_code]").val(), str)) { jQInput.get(0).setCustomValidity(''); $.getJSON("index.php?func=tc_search&case=isunderage&social_sec_no=" + str+'&source='+jQInput.prop('name'), function (data) { if (data) { if (jQInput.prop('name') !== 'bill_social_sec_no') { $('#tc_guardian').show(); $('#tc_guardian input').each(function(){ document.getElementById($(this).attr('id')).required = true; }); } else { jQInput.get(0).setCustomValidity('Virheellinen henkilötunnus'); jQInput.addClass('invalid'); jQInput.closest('.form-group').find('.control-label').addClass('invalid'); } } }); } else { jQInput.get(0).setCustomValidity('Virheellinen henkilötunnus'); } break; case 'birthday[]': var obj = $('[name="birthday[]"]'); var tmp = ''; var d = DATEFMT == 'd.m.Y' ? $(obj[0]).val() : $(obj[2]).val(); var m = $(obj[1]).val(); var y = DATEFMT == 'd.m.Y' ? $(obj[2]).val() : $(obj[0]).val(); //check if all values are selected if (d != '' && $.isNumeric(d) && m != '' && $.isNumeric(m) && y != '' && $.isNumeric(y)) { if(DATEFMT == 'd.m.Y'){ var strVal = d + '.' + m + '.' + y; } else { var strVal = y + '-' + m + '-' + d; } //pad day and month if (d.length == 1) { d = '0' + d; } if (m.length == 1) { m = '0' + m; } tmp = y + '-' + m + '-' + d; } if(DEBUG) { console.log(tmp); } if (tmp != '') { if (validator.isValid.date(tmp)) { jQInput.get(0).setCustomValidity(''); $.getJSON("index.php?func=tc_search&case=isunderage&birthday=" + tmp, function (data) { if (data) { $('#tc_guardian').show(); } }); } else { jQInput.get(0).setCustomValidity('Virheellinen syntymäaika'); } } else { jQInput.get(0).setCustomValidity(''); } break; case 'email_confirm': if($('input[name="email"]').length){ if($('input[name="email"]').val() != $('input[name="email_confirm"]').val()){ jQInput.get(0).setCustomValidity('Sähköpostiosoitteet eivät täsmää. Ole hyvä ja tarkasta antamasi osoitteet.'); } else { jQInput.get(0).setCustomValidity(''); } } break; } } if (jQInput[0].checkValidity()) { jQInput.removeClass('invalid'); jQInput.closest('.form-group').find('.control-label').removeClass('invalid'); if(jQInput.prop('name') == 'birthday[]'){ if(strVal){ Cookie.set('tc_input_' + jQInput.prop('name'), strVal); } } else { if(jQInput.prop('name') !== 'social_sec_no' && jQInput.prop('name') !== 'bill_social_sec_no' && jQInput.prop('name') !== 'password' && jQInput.prop('name') !== 'password_confirm') { //do not store sensitive information in cookie #24444 Cookie.set('tc_input_' + jQInput.prop('name'), jQInput.val()); } } } else { jQInput.addClass('invalid'); jQInput.closest('.form-group').find('.control-label').addClass('invalid'); } jQInput.val(str); } catch (e){ console.log('Error in trainingCard.input.set: '+ e.message); } }; this.showErrors = function () { var errorMsg = ''; $("#tc_customer_details input").each(function (){ $(this).removeClass('invalid'); $(this).closest('.form-group').find('.control-label').removeClass('invalid'); }); $("#tc_customer_details select").each(function (){ $(this).removeClass('invalid'); $(this).closest('.form-group').find('.control-label').removeClass('invalid'); }); $("#tc_customer_details input:invalid").each(function (){ errorMsg = errorMsg + trainingCard.input.getErrorMessage($(this)); $(this).addClass('invalid'); $(this).closest('.form-group').find('.control-label').addClass('invalid'); }); $("#tc_customer_details select:invalid").each(function (){ errorMsg = errorMsg + trainingCard.input.getErrorMessage($(this)); $(this).addClass('invalid'); $(this).closest('.form-group').find('.control-label').addClass('invalid'); }); if (errorMsg) { showUserNotification ('danger', errorMsg); $('#tc_customer_details .tc_cd_required_fields').addClass('invalid'); return true; }else{ hideUserNotification(); $('#tc_customer_details .tc_cd_required_fields').removeClass('invalid'); return false; } }; }; /*trainingCard.summary*/ this.summary = new function () { /*trainingCard.summary.show*/ this.show = function() { try { if(DEBUG) { console.log('trainingCard.summary.show'); } var productCode = trainingCard.product.get(); var productType = $("div[data-product='" + productCode + "']").data('product-type'); var url = 'index.php?func=tc_summary&products[' + productType + ']=' + productCode; if($('#id_center').length){ if($('#id_center').val()){ url += '¢er=' + $('#id_center').val(); } } if($('input[name="web_groups[]"]:checked').length){ url += '&web_groups=' + $('input[name="web_groups[]"]:checked').val(); } if($('input[name="frequencies[]"]:checked').length){ url += '&frequencies=' + $('input[name="frequencies[]"]:checked').val(); } if($('input[name="contracts[]"]:checked').length){ url += '&contracts=' + $('input[name="contracts[]"]:checked').val(); } if($('input[name="commit_months[]"]:checked').length){ url += '&commit_months=' + $('input[name="commit_months[]"]:checked').val(); } if (site.isSmallOrMediumDevice()){ if(productCode == ''){ summary.hide(); return false; } } //options for (var option in trainingCard.option.values) { var dataName = trainingCard.option.values[option]['dataName']; var values = trainingCard.option.values[option]['values']; if (values.length > 0) { for (var val in values) { url += '&options[' + dataName + '][]=' + values[val]; } } } //start date url += '&start_date=' + $('#id_date_saved').val(); //save card number if($('#id_save_card_no').length) { url += '&save_card_no=' + $('#id_save_card_no').val(); } //location //url += '&rr_location=' + $('#select_location .list-group-item.active').data('value'); if($('#payment_type .payment_type.selected').length){ url += '&payment_type=' + $('#payment_type .payment_type.selected').data('type'); } if(site.isSmallOrMediumDevice()){ url += '&mobile=1'; } //get product details $.getJSON(url, function (html) { //prevent fetching new summary while in mobile confirm if($('#tc_summary_mobile').hasClass('confirm')){ return; } //Show summary summary.show(); $("#base_summary_content").html(html); if($('#btn_tc_campaign_code').length){ $('#btn_tc_campaign_code').on('click', function(){ if($('body.training_card.v2 #campaign_code').val()) { if (site.isSmallOrMediumDevice() && trainingCard.product.get()) { if (!$('#id_frm_training_card #campaign_code').length) { var inp = $('', {name: 'campaign_code', id: 'campaign_code', type: 'hidden', value: $('body.training_card.v2 #campaign_code').val()}); $('#id_frm_training_card').append(inp); } trainingCard.post('#id_frm_training_card'); //delete input, in case something went wrong $('#id_frm_training_card #campaign_code').remove(); } else { var url = 'index.php?func=training_card&campaign_code=' + $('body.training_card.v2 #campaign_code').val(); //todo! easyfit has 2 campaign code fields, one is hidden. should trigger only the :visible field //location //url += '&rr_location=' + $('#select_location .list-group-item.active').data('value'); window.location = url; } } }); $('body.training_card.v2 #campaign_code').on('keydown', function(e){ if (e.keyCode == 13) { $('#btn_tc_campaign_code').click(); } }); if($('#campaign_code_in_use').length){ $('body.training_card.v2 #campaign_code').closest('.row').hide(); } } //remove the options header in summary if there are none options if(!$('section[data-name="tc_select_options"]').length) { $('#tc_summary li[data-name="tc_select_options"]').remove(); } //overridable function trainingCard.summary.fetchReady(); }); } catch (e){ console.log('Error in trainingCard.summary.show: '+ e.message); } }; this.fetchReady = function(){ //overridable function }; }; /*trainingCard.confirm*/ this.confirm = function(status) { if($('#user_input_required').length){ if(trainingCard.userConfirmation.shown){ if(!trainingCard.userConfirmation.handled){ //user input filled in trainingCard.userConfirmation.confirm(status); return; } } else { //show user confirmations (modal lightbox) trainingCard.userConfirmation.show(); return; } } }; /*trainingCard.userConfirmation*/ this.userConfirmation = new function () { this.shown = false; this.handled = false; /*trainingCard.userConfirmation.confirm*/ this.confirm = function(status) { if(DEBUG) { console.log('trainingCard.userConfirmation.confirm'); } try { if (status) { //ok pressed //check required fields var err=''; if($('#start_date').val()){ //validate date var inp_date = $('#start_date').val(); if(DATEFMT == 'd.m.Y'){ var tmp = inp_date.split('.'); var day = tmp[0]; var month = tmp[1]; var year = tmp[2]; d = new Date(year, month, day, 23, 59, 59); } else { var tmp = inp_date.split('-'); var day = tmp[2]; var month = tmp[1]; var year = tmp[0]; d = new Date(year, month, day, 23, 59, 59); } if(d < Date.now() || isNaN(d)){ err += 'Virhe kentässä: Valitse aloituspvm'; } else { $('#id_date_saved').val($('#start_date').val()); } } //favorite location if($('#id_select_location').length) { if ($('#id_select_location').val()) { $('#id_frm_training_card #id_favorite_location').val($('#id_select_location').val()); } else { if(err != ''){ err += '
'; } err += 'Virhe kentässä: Valitse sijainti'; } } //confirm save card no if($('#save_card_no').length) { if($('#save_card_no').val()){ $('#id_frm_training_card #id_save_card_no').val($('#save_card_no').val()); } else{ if (err != '') { err += '
'; } err += 'Ole hyvä valitse jos sinulla on tallessa vanha jäsenkorttisi.'; } } if(err){ this.show(err); } else { //continue this.continue(); } } else { //cancel pressed //reset flag trainingCard.userConfirmation.shown = false; } } catch (e){ console.log('Error in trainingCard.userConfirmation.confirm: '+ e.message); } } /*trainingCard.userConfirmation.show*/ this.show = function (errorMsg) { if(DEBUG) { console.log('trainingCard.userConfirmation.show'); } try { //check if there is any user input required. var userInputRequired = false; var productCode = trainingCard.product.get(); var selectedProductType = $(".product_card[data-product='" + productCode + "']").data('product-type'); if ($("#userConfirmation ." + selectedProductType).length && $("#userConfirmation ." + selectedProductType).html().trim() != '') { userInputRequired = true; } //allow overriding the ask rr location dialog, set custom css visibility: hidden if ($("#userConfirmation .general #select_location").length) { if ($("#userConfirmation .general #select_location").css('visibility') == 'hidden') { $("#userConfirmation .general #select_location").remove(); } } if ($("#userConfirmation .general").length && $("#userConfirmation .general").html().trim() != '') { userInputRequired = true; } if(!userInputRequired){ //exit function this.continue(); return; } //reset flag trainingCard.userConfirmation.shown = true; /* modal lightbox */ var html = { title: 'Valitse seuraavat tiedot', body: $("#userConfirmation").html(), buttons: {accept: 'Jatka', reject: 'Takaisin'} }; showConfirmation(trainingCard.confirm, html); //set start date max date if($('#start_date_max_days_ahead').val() && $('#start_date').length){ $('.start_date.datepicker') .datepicker('setEndDate', '+'+$('#start_date_max_days_ahead').val()+'d') .datepicker('update'); } if(errorMsg){ var errorElement = $('#dialog-confirmation #userConfirmationErr'); //cloned element $(errorElement).html(errorMsg); $(errorElement).show(); } } catch (e){ console.log('Error in trainingCard.userConfirmation.show: '+ e.message); } } /*trainingCard.userConfirmation.continue*/ this.continue = function (errorMsg) { if(DEBUG) { console.log('trainingCard.userConfirmation.continue'); } this.handled = true; var productCode = trainingCard.product.get(); //trainingCard.product.next(productCode); trainingCard.summary.show(); return; } } };