var order_id = '0';
//all globals should go here
var FS_APP_VERSION = "2.1";
var company_name = 'Tempo Books';
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.tempobookshop.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 = "Square";
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 = `