var order_id = '0';
//all globals should go here
var FS_APP_VERSION = "2.1";
var company_name = 'Bibliopolis';
var old_type = ''; //used for old_type of cc in validation
var modals = {}; //global of all modals used in a site
var pkd_loc = { httppath: "https://www.bibliopolis.com/", locale: "en_US", currency_loc: "en-US", currency: "USD" };
//paypal vars
var paypal_currency = 'USD';
//cc globals
var pay_type = '', is_valid = false, $cc_num = '';
//allowed data variables through ajax template
var allowed_tpl_ajax_data = ['sku', 'order_item_id', 'tpl'];
var pkd_gateway = "Authorize.net";
var currency = 'USD';
//cart errors/messages
var general_cart_error = "Oops, something went wrong. Please try again.";
var general_ajax_error = "Oops, there was an error with the page request.";
var ajax_error = "We’re having trouble connecting. Please try again.";
var ajax_template_error = "There was a problem loading the content. Please try again.";
var payment_form_error = "There was an issue loading the payment form%msg%Please reload the page.";
var delete_confirm_msg = "Are you sure you want to remove this item?";
var general_liability_error = "We are unable to process your credit card. Please try again or enter a different payment method.";
var credit_card_expired_error = "Credit card has expired.";
var credit_card_select_error = "Please select a credit card.";
var credit_card_required_error = "Please complete all credit card fields.";
var gift_card_required_error = "Please select a gift card or enter a gift card number.";
var missing_address_id_error = "Please select an existing address or add a new address.";
var cart_cvv_amex_error = "Please enter a valid CVV. The CVV code is the four-digit code on the front of your card.";
var cart_cvv_error = "Please enter a valid CVV. The CVV code is the three-digit code on the back of your card.";
var cart_item_label = "%d";
var cart_item_label_plural = "%d";
var valid_amount_error = "Please enter a valid amount.";
var valid_credit_card_error = "Please enter a valid credit card.";
var paypal_signin_required_error = "You must sign into PayPal for payment.";
var gw_default_edit_label = "Edit gift options";
var gw_default_label = "Make it a Gift";
var profile_delete_confirm = "Are you sure you want to delete this profile?";
var square_verify_error = "Please verify that your card information is correct. If you continue to have problems, please contact us.";
var square_verify_gift_error = "Please verify that your gift card information is correct.";
var cart_hide_label = "Hide Cart";
var cart_show_label = "Show Cart";
var purchase_order_num_error = "Please enter a purchase order number.";
var paypal_general_error = "There was an error communicating with PayPal. Please try again, or contact us if you continue to have problems.";
var expires_text = "Expires";
var cart_cc_ending_in_text = "ending in";
var po_number_text = "Purchase Order Number";
var payment_form_confirm = "You are about to submit a payment in the amount of %s. Are you sure?";
var saved_items_empty = "You have no saved items.";
//general labels, errors, messages
var required_fields_error = "Please fill in all required fields.";
var wish_remove_confirm = "Are you sure you want to remove this item?";
var close_label = "Close";
var loading_label = "Loading...";
var previous_label = "Previous";
var next_label = "Next";
var primary_label = "Primary";
var secondary_label = "Secondary";
var sidebar_primary_label = "Primary Sidebar";
var sidebar_secondary_label = "Secondary Sidebar";
var sidebar_label = "Sidebar";
var slider_next_label = "Show Next Slide";
var slider_prev_label = "Show Previous Slide";
var gallery_view_image_alt = "Image %1$d of %2$d for %3$s";
var gallery_view_image_aria = "View Image %1$d of %2$d for %3$s";
var show_all_label = "Show All";
var wizard_finish_label = "Save and Close";
var google_recaptcha_response = "Google ReCaptcha Response";
//custom lightbox stuff
//used with custom lightbox code
var last_max_height = 0; //this is used for adding the inline max-height back onto image after it has been shrunk
var enlarge_enabled = false; //will check on open if the enlarge/shrink toggle is enabled
var boxed_enabled = false; //will check on open of the popup is boxed
var custom_title_src = 'title'; //should be an attribute on the element selecting or a custom function
//magnific popup language
var magnific_popup_config = {
tClose: close_label,
tLoading: loading_label,
gallery: {
tPrev: previous_label,
tNext: next_label,
tCounter: "%curr% of %total%"
},
image: {
tError: "The image could not be loaded."
},
ajax: {
tError: "The content could not be loaded."
}}
//bootbox
bootbox_confirm_label = 'Confirm';
bootbox_cancel_label = 'Cancel';
function ajax_handler_app(params, args, data_dir, callback, debug = false) {
//console.log("ajax_handler_app called");
if(typeof params !== 'undefined') {
args = (typeof args !== 'undefined' ? args : '');
callback = callback || function (data, debug) {
var response = JSON.parse(data);
if(debug) console.log('Response:', response);
if (response.success) {
if(debug) console.log('Request successful:', response);
} else {
if(debug) console.log('Request failed:', response.msg);
}
};
args = json_to_args(args);
// Send AJAX request
$.ajax({
type: "POST",
url: "/manager/include/ajax_call.php", // Actual path to your ajax_call.php
data: {
a_func: 'ajax_handler_app', // The PHP function to call
a_params: params + '|' + args, // Base64-encoded args, concatenated with the type
data_dir: data_dir // Pass the data_dir as a separate parameter
},
success: callback,
error: function(xhr, status, error) {
console.error('Error occurred:', error);
}
});
}
}
function json_to_args(json) {
let args = JSON.stringify(json);
//encode ~ specifically because they break JSON strings
//reserved for pointers in JSON
let args_encoded = args.replace('~', '~');
//base64 encode
return encodeUnicode( args_encoded );
}
function encodeUnicode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function query_string_to_json() {
var pairs = location.search.slice(1).split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return JSON.parse(JSON.stringify(result));
}
function uniqid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
/**
* Replace Url Param or add it on if not there
* @param string url The url to replace the param in
* @param string paramName The name of the param to replace
* @param string paramValue The value to replace the param with
* @return string The new url
**/
function replaceUrlParam(url, paramName, paramValue) {
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
if (url.search(pattern)>=0) {
return url.replace(pattern,'$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/,'');
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}
function append_tn_modal(callback) {
if($('#topic-notification-list-wrap').length == 0) {
$.ajax({
url: "/modal-topic-notification.php",
success: function (data) {
$('#lyr-topic .modal-body').remove();
$('#lyr-topic .modal-content').append(data);
if ( $.isFunction(callback) ) {
callback.call({
data:data
});
}
},
dataType: 'html'
});
} else {
if ( $.isFunction(callback) ) {
callback.call();
}
}
}
function pkd_init_card_validator() {
if($('#fld_cardNumber').length > 0) {
$cc_num = $('#fld_cardNumber');
var validateCCCallback = function (result) {
$(this).parent().removeClass('valid not-valid ' + old_type);
old_type = (result.card_type == null ? '' : result.card_type.name);
$('.card-number-validator').data('type', old_type);
is_valid = (result.valid && result.length_valid && result.luhn_valid);
$(this).parent().addClass((result.card_type == null ? '' : result.card_type.name) + (is_valid ? ' valid' : ' not-valid'));
if($("#cc_type").length > 0 && result.card_type != null) {
$("#cc_type").val(result.card_type.name);
}
};
$('#fld_cardNumber').validateCreditCard(validateCCCallback);
}
}
//extended jquery functions always in use globally
$.fn.extend({
/**********************************************************
* Placeholder replacement for older browsers
* TODO: Remove this when we drop support for IE8
* @return void
**********************************************************/
placeholder: function() {
$(this).find('input[type="text"], input[type="password"], textarea').each(function(ev){
var placeholder = $(this).attr("placeholder");
var is_textarea = $(this).is("textarea");
if(typeof placeholder !== "undefined" && placeholder != "" && ($(this).val() == "") || (is_textarea && $(this).text() == "")) {
$t = $(this);
$t.addClass('hasPlaceholder');
$t.attr("value", placeholder);
$t.bind("focus", function(){
if( this.value == placeholder )
this.value = "";
});
$t.bind("blur", function(){
if( this.value == "" )
this.value = placeholder;
});
$(this).parents("form:first").submit(function(){
var _t = $(this).find('.hasPlaceholder');
if( _t.val() == placeholder )
_t.val("");
});
}
});
},
/**********************************************************
* Clear form of all data
* TODO: Remove need for global.js clearForm()
* @return void
**********************************************************/
clearForm: function(){
this.each(function() {
$(this).click(function() {
var form = this;
while (form.nodeName != "FORM" && form.parentNode) {
form = form.parentNode;
}
clearForm(form);
with(form){
if(typeof recordsLength !== 'undefined')
recordsLength.selectedIndex = 1;
if(typeof kwconj !== 'undefined')
kwconj[0].checked = true;
}
$(form).parent().find('.alert').remove();
});
});
},
/**********************************************************
* Allow alerts to show/hide depending on user cookie
* @param string key The key to use for the cookie
* @return void
**********************************************************/
alert_cookie: function(key) {
this.each(function() {
//if key is not passed we'll just use default global message
key = key || 'global_message';
//setup cookie if this is first time for user
if(typeof $.cookie(key) == "undefined")
$.cookie(key,'open',{path:'/'});
//when we close the alert, set the cookie to closed for other interactions
$alert = $(this).find('.alert');
if (key === 'global_message') {
$('body').on('closed.bs.alert', '#global-message', function() {
$.cookie(key, 'closed', { path: '/' });
});
} else {
$alert.bind('closed.bs.alert', function () {
$.cookie(key, 'closed', {path: '/'});
});
}
});
},
/**********************************************************
* Gets the natural width and height for an image
* @return object Has two keys width and height
**********************************************************/
real_size: function() {
var $img = $(this);
if ($img.prop('naturalWidth') == undefined) {
var $tmpImg = $('
').attr('src', $img.attr('src'));
$img.prop('naturalWidth', $tmpImg[0].width);
$img.prop('naturalHeight', $tmpImg[0].height);
}
return { width: $img.prop('naturalWidth'), height: $img.prop('naturalHeight') };
},
ajax_template: function(data, callback, callbackError) {
var $_this = $(this);
data = data || null;
callback = callback || null;
callbackError = callbackError || null;
if(data !== null) {
//only get parameters allowed by our application
var params = JSON.stringify(data, allowed_tpl_ajax_data);
//encode the parameters
var encoded_params = btoa(data.tpl+"|"+params);
data.tpl_action = data.tpl_action || 'html';
$.ajax({
type: "POST",
url: "/manager/include/ajax_call.php",
data: "a_func=pkd_get_template&a_params="+encoded_params,
success: function (response) {
switch(data.tpl_action) {
case 'append':
$_this.append(response);
break;
case 'prepend':
$_this.prepend(response);
break;
default:
$_this.html(response);
}
//setup callback for finished request
if ( $.isFunction(callback) ) {
callback.call({
data:data,
target: $_this
});
}
},
error: function(jqXHR, textStatus, errorThrown) {
let statuscode = jqXHR.status || '000';
if ( window.console && console.log )
console.log('[ajax_template] [' + statuscode + '] '+(errorThrown != '' ? '['+errorThrown+'] ' : '') + ajax_template_error);
let data_tpl = (typeof data !== 'undefined' && 'tpl' in data ? data.tpl : 'no_tpl');
let _params = btoa(JSON.stringify({action:'ajax_template_'+data_tpl}));
$.ajax({type: "POST",
url: "/manager/include/ajax_cart.php",
data: "a_func=update_connection_error&a_params="+_params});
let error = `
${ajax_template_error} Error code:A${statuscode}
`;
if ( $.isFunction(callbackError) ) {
callbackError(error, $_this);
} else {
$_this.html(error);
}
}
});
} else {
//setup callback for finished request
if ( $.isFunction(callback) ) {
callback.call();
}
}
},
//Counts down the number of remaining characters left
countCharValidation: function (num, selector) {
this.each(function () {
var
chars = "",
charCount = 0;
$(selector).text(num);
chars = $(this).val();
var $remaining_chars = $(this).parent().find(selector);
$(this).keyup(function () {
chars = $(this).val();
$.fn.countChar(chars, num, $remaining_chars);
});
$.fn.countChar(chars, num, $remaining_chars);
});
},
countChar: function (str, num, selector) {
str = $.trim(str);
var charCount = (str == "" ? 0 : str.length);
var remaing = num - parseInt(charCount);
$(selector).text(remaing);
}
,ajax_cc_step_wizard: function() {
if($(this).length > 0) {
var $wizard_form = $(".cim-form");
var $wizard_feedback = $wizard_form.find('.modal-feedback');
$("#card-wizard").steps({
headerTag: "h3",
labels: {
finish: wizard_finish_label
},
onInit: function() {},
onStepChanging: function(event, currentIndex, newIndex){
var errors_html = '';
var errors = [];
var is_next = (currentIndex < newIndex);
$('.current .reqfld').each(function(idx, obj) {
//reset validation states
$(obj).removeClass('error success info warning');
if(is_next) {
//check for empty field errors
if($(obj).val() == '') {
errors.push($(this));
errors_html = ''+required_fields_error+'
';
}
}
});
/* Apparently everything is all set -- Let's check the last day of the month */
var year = parseInt($("#fld_exp_year").val());
var month = parseInt($("#fld_exp_month").val());
if(checkDateBeforeToday(new Date(year, month, 0))) {
//date is before today, throw error
errors.push($("#fld_exp_year"));
errors.push($("#fld_exp_month"));
errors_html += ''+credit_card_expired_error+'
';
}
//if the errors array has elements then proceed to error case
if(errors.length > 0) {
$.each(errors, function(idx,obj) {
$(this).addClass('error');
});
$wizard_feedback.html('').append(''+errors_html+'
');
return false;
}
return true;
},
onStepChanged: function( event, currentIndex, newIndex ) {
$wizard_feedback.html('');
switch(currentIndex) {
case 0:
break;
case 1:
break;
}
},
onFinishing: function( event, currentIndex ) {
var errors_html = '';
var errors = [];
//copy address fields to form fields for submitting
var $active_address_card = $('.address-card').find('.active');
$active_address_card.find('input').each(function(){
var fld_id = $(this).attr("name").substring(5);
$("#"+fld_id).val($(this).val());
});
$('.current .reqfld').each(function(idx, obj) {
//reset validation states
$(obj).removeClass('error success info warning').parent().parent().removeClass('has-error');
if($(obj).val() == '') {
errors.push($(this));
errors_html = missing_address_id_error;
}
});
//if the errors array has elements then proceed to error case
if(errors.length > 0) {
$.each(errors, function(idx,obj) {
$(this).addClass('error').parent().parent().addClass("has-error");
$(this).addClass('error');
});
$wizard_feedback.html('').append(''+errors_html+'
');
return false;
}
return true;
},
onFinished: function( event, currentIndex ) {
if($(this).parent().attr('id') == 'formCIMCheckout') {
event.preventDefault();
var save_payment = true; //$('#save-payment-profile').is(":checked");
let cart = $("#cart-summary").pkdcart();
var callback = function () {
//hide modal
modals.manage_payment.modal('hide');
//refresh the shipping address panel
var $panel_reload = $("#payment").find('.panel-update');
$panel_reload.ajax_template({
'tpl': $panel_reload.data('tpl-reload')
}, function () {
checkRadio($('input:radio[name=paymentType]:checked').val());
});
};
if(save_payment) {
var data = $wizard_form.serialize();
var request = ["pass_thru", 'foobar&' + data, callback];
} else {
var data = $wizard_form.serializeArray();
var cc_type = $('.card-number-validator').data('type');
data.push({'name':'cc_type','value':cc_type});
var request = ["add_temporary_profile", data, callback];
}
cart.pkdcart('request', request);
} else {
$wizard_form.attr('action', cim_refresh_url).submit();
}
return true;
}
});
pkd_init_card_validator();
if($('.cim-select-address').length > 0) {
$('.cim-new-address').hide();
$(document).on('click', '.address-card .btn', function(e){
e.stopImmediatePropagation();
$('.address-card .well').removeClass('active');
$(this).parent().addClass('active');
$('.cim-new-address').slideUp();
});
$(document).on('click', '.open-new-address', function(e){
e.stopImmediatePropagation();
$('.address-card .well').removeClass('active');
$('.cim-new-address').slideToggle();
});
}
}
}
});
function escapeHtml(str){
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
return String(str).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
/**
* Intl.NumberFormat as currencyFormatter
* Creates a proper price out of the entered amount.
*
*/
const currencyFormatter = new Intl.NumberFormat(pkd_loc.currency_loc, {
style: 'currency',
currency: pkd_loc.currency,
minimumFractionDigits: 2
});
/**
* Number.prototype.truncateToDecimals(dec)
* Truncates a number to only two decimal places without rounding
* Should do validation before using this function
*
* @param integer dec: length of decimal
*
*/
Number.prototype.truncateToDecimals = function(dec) {
var dec = dec || 2;
var regex = /\./g;
var num_str = this.toString();
if(num_str.match(regex)) {
// we have a number with a decimal
const calcDec = Math.pow(10, dec);
return Math.trunc(this * calcDec) / calcDec;
} else {
return this.toFixed(dec);
}
};
const populate_wishlist_items = function(records){
//console.log(typeof ajax_handler_app); // Should log 'function'
console.log('Records to filter for wishlist:', records); // Logs the returned SKUs
ajax_handler_app(
'wishlist|filter_records', // Params: Corresponds to the PHP file and action
{ records: records }, // Arguments: Pass the records array
'search', // Data directory: Specify 'search' or any other directory
function(data, debug) { // Callback to handle success
let response = $.parseJSON(data);
if(debug) console.log('Response:', response); // Logs the returned SKUs
if (response.success) {
//if(debug)
console.log('Filtered records:', response.records); // Logs the returned SKUs
response.records.forEach(function(id) {
let wishlisthtml = 'Added to Wish List';
if($('.wish-link[data-sku="' + id + '"] .wishlink-active-html').length > 0) {
wishlisthtml = $('.wish-link[data-sku="' + id + '"] .wishlink-active-html').html();
}
let resethtml = 'Add to Wish List';
$('.wish-link[data-sku="' + id + '"]').attr('href', '/cart.php').attr('aria-label', 'Added to Wish List').data('reset-html', resethtml).removeClass('wish-link-add').addClass('wish-link-added').html(wishlisthtml);
});
} else {
console.log('Error:', response.msg);
}
}
);
}
$(function(){
//bootstrap
$.fn.button.Constructor.DEFAULTS = {
loadingText: 'Loading...'
}
//disable right click on anything marked with nocontextmenu
let nocontexters = document.getElementsByClassName('nocontextmenu');
if(nocontexters.length > 0) {
for (let i = 0; i < nocontexters.length; i++) {
nocontexters[i].oncontextmenu = function(event) {
event.preventDefault(); // Prevent default context menu
};
}
}
//disable right click on all parents of anything marked with nocontextmenu-parent
let parentnocontexters = document.getElementsByClassName('nocontextmenu-parent');
if(parentnocontexters.length > 0) {
for (let i = 0; i < parentnocontexters.length; i++) {
let ele = parentnocontexters[i].parentNode; //get the parent node
ele.oncontextmenu = function(event) {
event.preventDefault(); // Prevent default context menu
};
}
}
if (!("placeholder" in document.createElement("input")))
$("form").placeholder();
if($('#pkd_locale').length > 0) {
$('#pkd_locale').selectpicker({style: 'btn-link'});
$('#pkd_locale').on('change', function (e) {
var url = $(this).find("option:selected").data('target') || '';
if(url != '') {
try {
window.location.replace(url);
} catch (e) {
window.location = url;
}
}
});
}
//setup lightbox in gallery mode
magnific_popup_config.type = 'image';
magnific_popup_config.zoom = {
enabled: true,
opener: function(openerElement) {
//if the opener element is an image than use that to zoom
//else if there is no image inside the openerElement than find the image up a couple parents(used for detail page)
return (openerElement.is('img') ? openerElement : (openerElement.find('img').length > 0 ? openerElement.find('img') : openerElement.parent().parent().find('img')));
}
};
magnific_popup_config.gallery = {
enabled:true
};
magnific_popup_config.image.markup = '';
magnific_popup_config.image.titleSrc = custom_title_src;
magnific_popup_config.callbacks = {
open: function() {
$self = this;
if($self.wrap.find('.mfp-figure').css('position') != 'static') {
boxed_enabled = true;
}
$self.wrap.on('click', '.mfp-enlarge-link', function() {
let $img_ele = $(this).parent().parent().find('.mfp-img');
$self.wrap.toggleClass('mfp-enlarged');
if($self.wrap.hasClass('mfp-enlarged')) {
last_max_height = $img_ele.css('max-height');
$img_ele.css('max-height', 'none');
} else {
$img_ele.css('max-height', last_max_height);
}
});
},
beforeClose: function() {
if(enlarge_enabled) {
this.wrap.off('click', '.mfp-enlarge-link');
this.wrap.removeClass('mfp-enlarged');
}
},
change: function() {
if(boxed_enabled) {
$.magnificPopup.instance.resizeImage.call(this);
}
},
imageLoadComplete: function() {
$self = this;
if(boxed_enabled) {
$.magnificPopup.instance.resizeImage.call(this);
}
if($self.wrap.find('.mfp-enlarge').is(':visible')) {
enlarge_enabled = true;
}
let img_id = 'mfp-img-'+uniqid();
let $img_ele = $self.wrap.find('.mfp-img');
$img_ele.attr('id', img_id);
$self.wrap.removeClass('mfp-enlarged');
var img_size = $img_ele.real_size();
if(img_size.width <= $img_ele.width() ) {
$self.wrap.find(".mfp-enlarge").hide();
} else {
$self.wrap.find(".mfp-enlarge").show();
}
if(disable_right_click) {
let theimg = document.getElementById(img_id);
theimg.oncontextmenu = function (event) {
event.preventDefault(); // Prevent default context menu
};
}
}
};
$('.lightbox').magnificPopup(magnific_popup_config);
$.magnificPopup.instance.resizeImage = function() {
var mfp = $.magnificPopup.instance;
var item = mfp.currItem;
if(!item || !item.img) return;
if(mfp.st.image.verticalFit) {
var decr = 0;
// fix box-sizing in ie7/8
if(mfp.isLowIE) {
decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'),10);
}
var maxHeight = (mfp.wH-decr);
if(boxed_enabled) {
var bottomBarHeight = ( $('.mfp-title').outerHeight(true) + ($('.mfp-bottom-bar').outerHeight(true) - $('.mfp-bottom-bar').height() ) );
var mfpFigure = $('.mfp-figure');
maxHeight = maxHeight - ( ( (mfpFigure.outerHeight(true) - mfpFigure.height() ) + bottomBarHeight ) );
}
item.img.css('max-height', maxHeight);
}
};
//setup sharing tooltips
$('.share-icon').tooltip();
$('.st_sharethis span').tooltip();
//toggle login layer
$(".topic-notification-login").on('click', function(){
$_tn_login_ele = $('.topic-notification-list-login-hide');
$_tn_login_ele.parent().toggleClass('open');
$_tn_login_ele.slideToggle();
});
//setup popovers for shipping links on order detail
if($(".ship-link-popover").length > 0 ) {
$(".ship-link-popover").each(function(){
var popover_html = $(this).next().html();
var options = {
html:true,
content:popover_html,
placement:'auto'
};
$(this).popover(options);
});
}
$('a[rel="external"]').on('click', function(e) {
e.preventDefault();
window.open( $(this).attr('href') );
});
if( $(".clearForm").length > 0 ) {
$(".clearForm").clearForm();
}
// see if referrer is a page within site
if($("#backHistory").length > 0) {
if(document.referrer.indexOf(window.location.hostname) != -1)
$('#backHistory').show();
else
$('#backHistory').hide();
}
//setup global namespace for modals
if($('#coupon_rules_modal').length > 0) modals.coupon = $('#coupon_rules_modal');
if($('#cvv_modal').length > 0) modals.cvv = $('#cvv_modal');
if($('#print_modal').length > 0) modals.print = $('#print_modal');
if($('#order_history_modal').length > 0) {
modals.orderhistory = $('#order_history_modal');
modals.orderhistory.on('hide.bs.modal', function () {
$(this).removeData('bs.modal');
});
}
if($('#lang_modal').length > 0) {
modals.lang = $('#lang_modal');
modals.lang.on('hide.bs.modal', function () {
$('#modal-response-lang').html('');
});
$('#pkd_locale_preferred').selectpicker();
$('.pkd-locale-preferred-dropdown .btn').append('');
$("#pkd_locale_preferred").on('change', function(e){
var val = $(this).val();
//only get parameters allowed by our application
if(val != '') {
var $icon = $(".pkd-locale-preferred-dropdown").find('.fa');
var $response = $('#modal-response-lang');
$icon.css('display', 'inline-block');
$(this).prop('disabled', true);
$.ajax({
type: "POST",
url: "/manager/include/ajax_call.php",
data: "a_func="+ajax_registered_calls.setpreferredlocale+"&a_params="+val+"|",
success: function (response) {
$response.html(response);
},
error: function(jqXHR, textStatus, error) {
if ( window.console && console.log )
console.log('[set_preferred_locale] [' + textStatus + '] '+(error != '' ? '['+error+'] ' : '') + general_ajax_error);
$response.html(''+general_ajax_error+'
');
},
complete: function(){
$("#pkd_locale_preferred").prop('disabled', false);
$icon.css('display', 'none');
}
});
}
});
}
/* Setup Topic Notification */
if($('#lyr-topic').length > 0) {
modals.topics = $('#lyr-topic');
modals.topics.on('hide.bs.modal', function (e) {
window.location.hash = "";
});
}
$('.topic-notification-link').on('click', function(e){
$opener = $(this);
append_tn_modal();
e.preventDefault();
if( $opener.hasClass("mobile") && $opener.data('mobile') != '' ) {
window.location = $opener.data('mobile');
} else if( ! $.isEmptyObject(modals.topics) ) {
modals.topics.modal('show');
//set hash to topics
if(!window.location.hash) {
window.location.hash = "topics";
}
if($(".widget_el_email_wrap_loggedin").length > 0) {
var url = $(".widget_el_email_wrap_loggedin a").attr("href");
if(url.indexOf("topics") == "-1")
$(".widget_el_email_wrap_loggedin a").attr("href", url+"#topics");
}
}
});
//if we have a hash tag
if(window.location.hash)
{
switch(window.location.hash)
{
//when hash is topics then open topic modal
case "#topics":
append_tn_modal();
if( ! $.isEmptyObject(modals.topics) )
{
modals.topics.modal('show');
}
break;
}
}
$('.want-link-remove').on('click', function(e){
e.preventDefault();
if(confirm(wish_remove_confirm)){
window.location=$(this).attr('href');
}
});
$(document).on('click', '.mock-anchor', function(e) {
var url = $(this).data('url') || '';
var target = $(this).data('url-target') || '';
if($.trim(url) != '') {
if($.trim(target) == '') {
window.location = url;
} else {
window.open(url,target);
}
}
});
if($('.flex-form').length > 0) {
$(".flex-form-link").on('click', function(e){
e.preventDefault();
var target = $(this).attr('href');
//show flex form layer
$(target).addClass('display-flex');
//flex layer no longer hidden to user
$(target).attr('aria-hidden', 'false');
//keyup event for closing the popup once opened
$(document).keyup(function(e) {
// esc to close flex form
if (e.keyCode === 27) $(target).trigger('click');
});
//wait a short very brief moment to show the form
setTimeout(function(){
//make form active and visible
$(target).find('.flex-form-inner').addClass('active');
//focus on first element
var $form = $(target).find('form');
$form.find("input[type!='hidden'],select,textarea").first().focus();
}, 50);
});
$('.flex-form').on('click', function(e) {
//hide the form and form layer
$(this).removeClass('display-flex').attr('aria-hidden', 'true');
$(this).find(".flex-form-inner").removeClass('active');
//unbind esc keyup event
$(document).off('keyup');
});
$(".flex-form form").each(function(idx,obj){
$(this).addClass('is-flex');
$(this).on('click', function(e){
//allow you to click inside the form without closing the layer
e.stopPropagation();
});
});
}
/* Fix for Accessibilty */
$('.btn-group-fix .btn').on('click', function(){
$parent = $(this).parent();
$parent.find('input').prop('checked', false);
$(this).next().prop('checked',true);
$(this).closest('form').submit();
});
/* Load cached content */
// Define the mapping array
const cacheMap = [
{ cacheFile: '/cache.site_message.php', target: '#global-message', classToAdd: (typeof $.cookie('global_message') == "undefined" ? 'open' : $.cookie('global_message')) },
{ cacheFile: '/cache.vacation.php', target: '#vacation-message' },
];
// Function to load content via AJAX
function loadCacheContent(cacheFile, target, classToAdd) {
$.ajax({
url: cacheFile, // The cache file URL
method: 'GET',
success: function (response) {
//console.log('Raw response:', response); // Log the response to see exactly what we're getting
// Wrap the response in a jQuery object
const $responseHTML = $(response);
// Check if the response contains the target element directly
const $content = $responseHTML.is(target) ? $responseHTML : $responseHTML.find(target);
if ($content.length) {
// Inject content into the page
$(target).html($content.html());
// Check if classToAdd is provided and add the class if needed
if (classToAdd) {
$(target).addClass(classToAdd);
}
// Remove the display:none inline style if it exists
$(target).css('display', ''); // Reset to default (removes inline display setting)
} /* else {
console.error('Target not found in the response');
} */
},
error: function () {
console.error('Failed to load content from ' + cacheFile);
}
});
}
// Loop through the mapping array and load content if the target is found on the page
cacheMap.forEach(function (item) {
if ($(item.target).length) { // Check if the target exists on the page
loadCacheContent(item.cacheFile, item.target, item.classToAdd);
}
});
$('.wish-link').remove();
$('.booklisting-wishlist').remove();
if($('#utils-wishlist').next('span').length > 0) {
$('#utils-wishlist').next('span').remove();
} else {
$('#utils-wishlist').before('span').remove();
}
$('#utils-wishlist').remove();
$('.tpl-load').each(function(){
var $this = $(this);
$this.ajax_template({
'tpl': $this.data('tpl')
}, function(){
cart = $("#utils-cart").pkdcart('update_values');
if($('#pkd_locale').length > 0) {
$('#pkd_locale').selectpicker({style: 'btn-link'});
$('#pkd_locale').on('change', function (e) {
var url = $(this).find("option:selected").data('target') || '';
if(url != '') {
try {
window.location.replace(url);
} catch (e) {
window.location = url;
}
}
});
}
});
});
// Display the cookie consent banner if enabled
});
function modal_error_callback(error, target) {
console.log(error);
console.log(target);
$(target).html(``);
target.modal('show');
}