PluginProbe
WPPizza – A Restaurant Plugin / 3.20
WPPizza – A Restaurant Plugin v3.20
trunk 2.16.11.28 3.19 3.19.1 3.19.2 3.19.3 3.19.4 3.19.5 3.19.6 3.19.7 3.19.7.1 3.19.7.2 3.19.7.3 3.19.7.4 3.19.8 3.19.8.1 3.19.8.2 3.19.8.3 3.19.9 3.20 3.20.1
wppizza / js / scripts.source.js

scripts.source.js in WPPizza – A Restaurant Plugin 3.20, at js/scripts.source.js

3,282 lines 102.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var wppizzaCartJson = {}; /* globally available object of whatever is currently in the cart */
2 var wppizzaOnCartInit = function(){};/* runs set functions on initializing cart */
3 var wppizzaUpdateCart = function(){};/* update cart by running this function */
4 var wppizzaTotalsBefore = function(){};/* executed just before the ajax call that will update the cart */
5 var wppizzaTotals = function(){};/* executed whenever there's an update to the cart */
6 var wppizzaRestoreOrder = function(){};/* can be used to remove loading div and re-enable order button */
7 var wppizzaPrepareOrder = function(){};/* modal overlay payment windows. prepare order */
8 var wppizzaPrettifyJsAlerts = function(){};/* replace js alerts with modal overlays if enabled*/
9 var wppizzaGatewayCss = {};//capture css dynamically loaded when changing gateways by ajax do remove again when re-changing (so to speak)
10 var wppizzaGatewayJs = {};//capture js dynamically loaded when changing gateways by ajax do remove again when re-changing (so to speak)
11 var wppizzaGetCheckout = function(){};/* get the checkout form via ajax, reinitializing any css/js as required - also used when changing gateways */
12
13 jQuery(document).ready(function($){
14
15 /***************************
16 class slug prefix
17 ***************************/
18 var pluginSlug = 'wppizza' ;
19
20
21 /***************************
22 set some globals
23 ***************************/
24 wppizza.shopOpen = -1 ;/* initializes as undefined */
25 var usingCache = (typeof wppizza.usingCache ==='undefined') ? false : true;
26
27 /***************************
28 not using cache, check for wppizza-open class
29 else we override as carts are loaded
30 ***************************/
31 if(!usingCache){
32 wppizza.shopOpen = ($('.'+pluginSlug+'-open').length > 0) ? true : false;
33 }
34
35 /****************************************************
36 * set current cart object as json
37 * in a globally available variable
38 * called on page load, and whenever the cart gets updated via ajax
39 *****************************************************/
40 var set_cart_json = function(event_type){
41 /***************************
42 get initial cart content
43 if it exists (if pages are not cached)
44 also make sure to remove on empty
45 or distinctly set by cart parameter
46 ***************************/
47 if($('#'+pluginSlug+'-cart-json').length > 0 ){
48 wppizzaCartJson = JSON.parse($('#'+pluginSlug+'-cart-json').val());
49 }else{
50 wppizzaCartJson = {};
51 }
52
53 /*
54 event listener 3rd party plugins can listen for by adding 'wppizza_event' as a class to their element and do something when the event gets triggered
55 */
56 $('.'+pluginSlug+'_event').trigger(event_type);
57
58 }
59 //set on page load too
60 set_cart_json('ini');
61
62 /********************************************
63 set to has cart if using
64 main cart,
65 hidden cart (orderpage),
66 or gettotals shortcode
67 ********************************************/
68 var hasCart = ($('.'+pluginSlug+'-cart').length > 0 || $('.'+pluginSlug+'-cart-novis').length > 0 || $('.'+pluginSlug+'-totals').length > 0 || $('#'+pluginSlug+'-minicart').length > 0) ? true : false;
69 var hasLoginForm = ($('.'+pluginSlug+'-login-form').length > 0) ? true : false;
70 var isCheckout = (typeof wppizza.isCheckout!=='undefined') ? true : false; //checkout page (including cancel and confirmation)
71 var use_confirmation_form = (typeof wppizza.cfrm!=='undefined') ? true : false;
72 var is_page_reload = false;/* flag that gets set to true if whole page gets reloaded to not remove any loading divs */
73 var prettify_js_alerts = (typeof wppizza.pjsa!=='undefined') ? true : false;
74 var force_pickup_toggle = (typeof wppizza.fpt!=='undefined') ? true : false;//bypass isopen check when pickup toggles have forcefully been made visible even if closed and we are toggeling
75 var run_refresh_on_ajaxstop = false;/* ini flag to run (or not) any functions that should run on cart refresh */
76 var send_order_form_id = 'wppizza-send-order';
77 var reinit_minicart_spinner = false;/* a flag that only re-inits the spinner in minicart (if enabled) after any updates as opposed to on page load (at which point this was done already */
78 var gateway_selected_init = '';
79 //for old / legacy gateways we must still reload the checkout page when changing gateways
80 var gateway_compat_page_reload = (typeof wppizza['compat'] !== 'undefined' && typeof wppizza['compat'].gwChg !== 'undefined' ) ? true : false;
81 //for some old/legacy gateways, we must run wppizza_gateway_init on load from here
82 var gateway_compat_init = (typeof wppizza['compat'] !== 'undefined' && typeof wppizza['compat'].gwInit !== 'undefined' ) ? true : false;
83 //init accordion on category/menu items
84 var useAccordion = (typeof wppizza['acc'] !== 'undefined' ) ? true : false;
85
86
87 /******************************
88 * all ajax start function
89 * must be before spinner
90 *******************************/
91 var ajaxStartCount = 0;
92 $( document ).ajaxStart(function() {
93 ajaxStartCount++;
94 });
95
96 /******************************
97 * all ajax complete function
98 * runs BEFORE AJAX STOP
99 *******************************/
100 $( document ).ajaxComplete(function(event, xhr, settings) {
101 wppizza_validator();/*(re)initializes validator - order page only */
102 });
103 /******************************
104 * all ajax requests that error out
105 *******************************/
106 $( document ).ajaxError(function(event, xhr, textStatus, errorThrown) {
107 console.log('error :');
108 console.log(errorThrown);
109 console.log(textStatus);
110 console.log(xhr.responseText);
111 removeLoadingDiv();
112 });
113
114 /******************************
115 * after all ajax stop
116 *******************************/
117 var ajaxStopCount = 0;
118 var forceAjaxStopRefresh = false;
119 var spinnerCount = 0;
120 $(document).ajaxStop(function() {
121
122 ajaxStopCount++;
123
124 if(spinnerCount == 0){
125 wppizza_spinner('complete');/* re-ini spinner when all ajax is said and done */
126 }
127
128 /*
129 if we are *not* reloading the page anyway,
130 remove all loading divs
131 */
132 if(!is_page_reload){
133 removeLoadingDiv();
134 }
135
136 if(ajaxStopCount == 1 || forceAjaxStopRefresh ){
137
138 wppizzaCartRefreshed(wppizza.funcCartRefr, run_refresh_on_ajaxstop);/**also run any cart refreshed functions**/
139 /*
140 always reset back to false after run
141 */
142 run_refresh_on_ajaxstop = false;
143
144 /*
145 always reset back to false after run
146 */
147 forceAjaxStopRefresh = false;
148
149 }
150 });
151
152
153 /****************************************************
154 *
155 * somewhat "prettify" js alerts, provided it's enabled in wppizza->layout
156 * (will not do anything for "confirms" as it's simply not really doable without jumping through 1000 hoops and would only be a hack)
157 *
158 *****************************************************/
159 /* open modal window instead of native js */
160 wppizzaPrettifyJsAlerts = function(txt, alert_type){
161
162 /* make sure we decode entities in title */
163 var modal_title = new DOMParser().parseFromString(wppizza.pjsa.h1, 'text/html');
164 modal_title = modal_title.documentElement.textContent;
165
166 /*set ok / confirm buttons */
167 var button_ok = wppizza.pjsa.ok;
168
169 d = document;
170
171 if(d.getElementById('wppizzaJsAlert')) return;
172
173 mObj = d.getElementsByTagName('body')[0].appendChild(d.createElement('div'));
174 mObj.id = 'wppizzaJsAlert';
175 mObj.style.height = d.documentElement.scrollHeight + 'px';
176
177 alertObj = mObj.appendChild(d.createElement('div'));
178 alertObj.id = 'wppizzaAlertBox';
179 if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + 'px';
180 alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + 'px';
181 alertObj.style.visiblity='visible';
182
183 /* title */
184 h1 = alertObj.appendChild(d.createElement('div'));
185 h1.id = 'wppizzaAlertTitle';
186 h1.appendChild(d.createTextNode(modal_title));
187
188 /* message */
189 msg = alertObj.appendChild(d.createElement('p'));
190 msg.innerHTML = txt;
191
192 /* buttons */
193 btn_wrap = alertObj.appendChild(d.createElement('div'));
194 btn_wrap.id = 'btnWrap';
195
196 btn_ok = btn_wrap.appendChild(d.createElement('button'));
197 btn_ok.id = 'wppizzaAlertOk';
198 btn_ok.innerHTML = button_ok;
199
200 /* clicking ok */
201 btn_ok.onclick = function() {
202 removePrettifyJsAlerts(true);
203 return false;
204 }
205
206 alertObj.style.display = 'block';
207 return ;
208 }
209
210 /*
211 remove modal window again
212 */
213 var removePrettifyJsAlerts = function(e){
214 document.getElementsByTagName('body')[0].removeChild(document.getElementById('wppizzaJsAlert'));
215 }
216
217 /****************************
218 prepare order, saving
219 all user data to db
220 mainly for overlay gateways
221 ****************************/
222 wppizzaPrepareOrder = function(gateway_selected){
223
224 var data = $('#'+pluginSlug+'-send-order').serialize();
225 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json', vars:{'type':'prepareorder','gateway_selected':gateway_selected, 'data': data}, ext : wppizza.extend }, function(r){
226
227 /* alert any errors */
228 if(typeof r.error!=='undefined'){
229 var error_id = [] ;
230 var error_message = [] ;
231 /* set errors to implode */
232 $.each(r.error,function(e,v){
233 error_id[e] = v.error_id;
234 error_message[e] = v.error_message;
235 });
236
237 /* set error div*/
238 var error_info = 'ERROR: '+error_id.join('|')+'\n';
239 error_info += ''+error_message.join('\n')+'';
240
241 if(prettify_js_alerts){//using prettified alerts
242 wppizzaPrettifyJsAlerts(error_info, 'alert');
243 }else{
244 alert(error_info);
245 }
246
247 return;
248 }
249
250 run_refresh_on_ajaxstop = false;
251
252 },'json');
253 };
254
255 /****************************
256 remove all loading divs
257 and reenable order button
258 mainly for overlay gateways
259 ****************************/
260 wppizzaRestoreOrder = function(){
261 removeLoadingDiv();
262 $('.'+pluginSlug+'-ordernow, #'+pluginSlug+'-ordernow').attr('disabled', false);//re enable send order button(s)
263 };
264
265
266 /********************************************************************************
267 *
268 * instanciating some functions we need before all other
269 *
270 ********************************************************************************/
271 /****************************
272 add loading gifs
273 to all instances
274 ****************************/
275 var addLoadingDiv = function(element, loading_class){
276
277 /* IE doesnt like setting defaults in function parameters , so we have to do the following */
278 if(element === undefined) {
279 element = false;
280 }
281 if(loading_class === undefined) {
282 loading_class = false;
283 }
284
285 /**if on orderpage, cover whole page**/
286 if(isCheckout){
287 if(!element){
288 $('html').css({'position':'relative'});/*stretch html to make loading cover whole page*/
289 $('body').prepend('<div class="wppizza-loading"></div>');
290 $('.'+pluginSlug+'-ordernow').attr('disabled', 'true');//disable send order button
291 }
292 }else{
293 /* add specific loading class */
294 if(element && loading_class){
295 element.prepend('<div class="'+loading_class+'"></div>');
296 }else{
297 /*will also cover any buttons so no need to disable those specifically */
298 $('.'+pluginSlug+'-cart').prepend('<div class="wppizza-loading"></div>');
299 }
300 }
301 };
302 /****************************
303 remove loading gifs
304 from all instances
305 ****************************/
306 var removeLoadingDiv = function(element, loading_class){
307
308 /* IE doesnt like setting defaults in function parameters , so we have to do the following */
309 if(element === undefined) {
310 element = false;
311 }
312 if(loading_class === undefined) {
313 loading_class = false;
314 }
315
316
317 /* only from specific element */
318 if(element && loading_class){
319 element.find('.'+loading_class+'').remove();
320 }else{
321
322 var loadingDivs=$('.'+pluginSlug+'-loading');
323 if(loadingDivs.length>0){
324 $.each(loadingDivs,function(e,v){
325 $(this).remove();
326 });
327 }
328 }
329 };
330
331 /******************************
332 * get currently selected gateway
333 * should be called on checkout only
334 *******************************/
335 var wppizza_get_gateway_selected = function(set_gateway){
336
337 /*
338 specifically setting a gateway
339 (on change) , forcing lowercase
340 */
341 if(typeof set_gateway !=='undefined' && set_gateway !== false){
342 gateway_selected = set_gateway.toLowerCase();
343 return gateway_selected;
344 }
345
346
347 /*
348 selected gateway ident
349 depending on if we are using dropdown, radio or hidden
350 */
351 var gateway_as_hidden_input = $('input[type="hidden"][name="wppizza_gateway_selected"]');
352 var gateway_as_radio_input = $('input[type="radio"][name="wppizza_gateway_selected"]:checked');
353 var gateway_as_select = $('select[name="wppizza_gateway_selected"] option:selected');
354
355 var gateway_selected = '';
356 //from hidden input
357 if(gateway_as_hidden_input.length > 0){
358 gateway_selected = gateway_as_hidden_input.val().toLowerCase();
359 }
360 //from radio input
361 else if(gateway_as_radio_input.length > 0){
362 gateway_selected = gateway_as_radio_input.val().toLowerCase();
363 }
364 //from dropdown
365 else if(gateway_as_select.length > 0){
366 gateway_selected = gateway_as_select.val().toLowerCase();
367 }
368
369 return gateway_selected;
370 }
371 /*
372 the gateway set on (order/confirmation)page (re)load to compare against when submitting the order
373 to ensure the html is not being tampered with directly pretending an order was prepaid/cc when in fact it's COD
374 */
375 gateway_selected_init = wppizza_get_gateway_selected(false);
376
377
378 /****************************
379 alert or skip
380 if shop is not open or yet
381 unknown
382
383 after ajax request called with a little timeout to let html() do it's thing first before showing alert
384 otherwise alerts interrupt the html replacement .
385 if someone finds a way to reliably chain this (i.e html('bla') first, alert('bla') second ), let me know
386 ****************************/
387 var checkShopOpen = function(){
388 if (wppizza.shopOpen === -1){
389 return false;
390 }
391 if (!wppizza.shopOpen && hasCart){
392 if(prettify_js_alerts){//using prettified alerts
393 wppizzaPrettifyJsAlerts(wppizza.msg.closed, 'alert');
394 }else{
395 alert(wppizza.msg.closed);
396 }
397 return false;
398 }
399 return true;
400 };
401 /*
402 set cache buster on checkout page for people that backpage
403 after changing order (or after COD) order
404 */
405 if(isCheckout){
406 if (!!window.performance && window.performance.navigation.type === 2) {
407 addLoadingDiv();
408 // value 2 means "The page was accessed by navigating into the history"
409 window.location.reload(true); // reload whole page
410 return;
411 }
412 }
413 /**************************************************************************************************************************************************************************
414 *
415 *
416 *
417 * [the main funtionalities af it all really]
418 * [add to cart, remove from cart, refresh cart, force refresh cart, increment cart , empty cart]
419 *
420 *
421 *
422 **************************************************************************************************************************************************************************/
423
424 /**
425 (re)-load cart - available to 3rd party plugin
426 if markup != '' , run update cart with passed markup
427 else run another ajax request
428 **/
429 wppizzaUpdateCart = function(obj){
430
431 /*
432 add loading div
433 */
434 addLoadingDiv();
435
436 /*
437 if we are passing on full object
438 run associated functions without ajax
439 */
440 if(typeof obj !== 'undefined' && typeof obj.markup !== 'undefined' && typeof obj.is_open !== 'undefined' && typeof obj.is_pickup !== 'undefined'&& typeof obj.cart !== 'undefined'){
441 load_cart_set_height(obj.markup);
442 set_pickup_elements_toggle(null, obj.is_pickup);//set pickup/delivery toggles as required
443 wppizza.shopOpen = obj.is_open;
444 run_refresh_on_ajaxstop = obj.cart;
445 forceAjaxStopRefresh = true;
446 return;
447 }
448
449 /*
450 run full ajax if obj is not defined / false
451 */
452 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'loadcart', 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
453 load_cart_set_height(response.markup);
454 set_pickup_elements_toggle(null, response.is_pickup);//set pickup/delivery toggles as required
455 wppizza.shopOpen = response.is_open;
456 run_refresh_on_ajaxstop = response.cart;
457 forceAjaxStopRefresh = true;
458 set_cart_json('loadcart');//update wppizzaCartJson from hidden input vars
459 },'json');
460
461 return;
462 };
463
464
465 /**
466 (re)-load cart
467 **/
468 var update_cart = function(e){
469 /*show loading*/
470 if(e == 'refresh'){
471 addLoadingDiv();
472 }
473 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'loadcart', 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
474 load_cart_set_height(response.markup);
475 wppizza.shopOpen = response.is_open;
476 run_refresh_on_ajaxstop = response.cart;
477 forceAjaxStopRefresh = true;
478 set_cart_json('update_cart');//update wppizzaCartJson from hidden input vars
479 shop_status(response, 'debug3');
480 },'json');
481 };
482
483
484 /****************************
485 if there are several carts on a page - for some reasosn -
486 and / or the carts had specific heights set, we
487 loop through all carts and set height for each as
488 we cannot know beforehand the size it is going to be
489 when carts get loaded by ajax
490 ****************************/
491 var load_cart_set_height = function(cart_markup){
492
493 var all_carts = $('.'+pluginSlug+'-cart');
494
495 /* display cart after setting hight for each */
496 $.each(all_carts,function(e,v){
497 var this_cart = $(this);
498 var cart_id = this_cart.attr('id');
499 var cart_height_from_id = cart_id.split('-').pop(-1);
500 /*
501 height not set, simply show markup
502 else set height on itemised table body
503 */
504 if(cart_height_from_id <= 0 || cart_height_from_id==''){
505 $(this).html(cart_markup);
506 }else{
507 $(this).html(cart_markup);
508 var cart_set_itemised_tbody_height = $('#'+cart_id+' .'+pluginSlug+'-order-itemised > tbody').css({'height' : ''+cart_height_from_id+'px', 'min-height' : ''+cart_height_from_id+'px', 'max-height' : ''+cart_height_from_id+'px'});
509 }
510 });
511 return;
512 };
513
514
515
516 /****************************
517 * load cart dynamically on page load
518 * if using cache
519 * alternatively trigger update by .wppizza-cart-refresh
520 ****************************/
521 if(hasCart){
522 if(usingCache){
523 update_cart('load');
524 }
525 $(document).on('click', '.'+pluginSlug+'-cart-refresh', function(e){
526 /*show loading*/
527 //addLoadingDiv();
528 update_cart('refresh');
529 });
530 }
531
532
533 /**
534 run defined functions before
535 each cart refresh/update ajax call
536 **/
537 var wppizzaCartRefreshedBefore = (function(functionArray, res) {
538 if(functionArray.length>0){
539 for(i=0;i<functionArray.length;i++){
540 var func = new Function('term', 'return ' + functionArray[i] + '(term);');
541 func(res);
542 }
543 }
544 });
545
546 /**
547 run defined functions after
548 each cart refresh/update
549 **/
550 var wppizzaCartRefreshed = (function(functionArray, res) {
551 //skip if not using cache and undefined event (or it might run multiple times)
552 if(!usingCache && typeof res['event'] === 'undefined'){
553 return;
554 }
555 if(functionArray.length>0){
556 for(i=0;i<functionArray.length;i++){
557 var func = new Function('term', 'return ' + functionArray[i] + '(term);');
558 func(res);
559 }
560 }
561 wppizza_spinner('refresh');
562
563 spinnerCount++;/* counter to not reinit spinner again on completed ajax requests */
564 });
565 /***********************************************
566 *
567 * [using totals shortcode or minicart,load via js]
568 *
569 ***********************************************/
570 if ($('.'+pluginSlug+'-totals-container').length > 0){
571
572 /* toggle shortcode type=totals cart visibility */
573 var element_view_cart=$('.'+pluginSlug+'-totals-viewcart, .'+pluginSlug+'-totals-viewcart-button');
574 var element_cart=$('.'+pluginSlug+'-totals-cart');
575
576 if (element_view_cart.length > 0){
577
578 /* show this particular cart (minicart or totals) on click of dashicon */
579 $(document).on('click', '.'+pluginSlug+'-totals-container>.dashicons-cart, .'+pluginSlug+'-totals-viewcart-button', function(e){
580 var self=$(this);
581 self.closest('div').find('.'+pluginSlug+'-totals-cart').fadeToggle();
582 });
583 /* if clicking anywhere else, hide cart details*/
584 $('html').click(function (event) {
585
586 /* if clicked dashicon has it's cart shown skip, but DO hide carts of all other shortcodes (in case there's more than one) */
587 var target_element=$(event.target);
588
589 //skip if we select the spinner element or spinner up/downs in the minicart (provided it's enabled there in the first place)
590 if(target_element.is('#'+pluginSlug+'-minicart .ui-spinner-input, #'+pluginSlug+'-minicart .ui-spinner-button, #'+pluginSlug+'-minicart .ui-icon')){
591 return;
592 }
593
594 if(target_element.is('.'+pluginSlug+'-totals-container>.dashicons-cart, .'+pluginSlug+'-totals-viewcart-button>input')){
595 var self_cart = target_element.closest('div').find('.'+pluginSlug+'-totals-cart');
596 if(self_cart.is(':visible')){
597 return;
598 }
599 }
600
601 if(element_cart.is(':visible')){
602 element_cart.fadeOut();
603 }
604
605 });
606 }
607
608 /*add small loading gif - but skip when loading page */
609 wppizzaTotalsBefore = function(page_load){
610
611 /* IE doesnt like setting defaults in function parameters , so we have to do the following */
612 if(page_load === undefined) {
613 page_load = false;
614 }
615
616 var element_totals_container=$('.'+pluginSlug+'-totals-container');
617 if(page_load !== true){
618 addLoadingDiv(element_totals_container, 'wppizza-loading-small');
619 }
620 };
621 wppizzaTotalsBefore(true);
622
623 wppizzaTotals = function(page_load){
624
625 /* IE doesnt like setting defaults in function parameters , so we have to do the following */
626 if(page_load === undefined) {
627 page_load = false;
628 }
629 var element_totals_container=$('.'+pluginSlug+'-totals-container');
630 var element_total_order=$('.'+pluginSlug+'-totals-order');
631 var element_total_items=$('.'+pluginSlug+'-totals-items');
632 var element_itemcount=$('.'+pluginSlug+'-totals-itemcount');
633 var element_checkout_button=$('.'+pluginSlug+'-totals-checkout-button');
634 var element_view_cart=$('.'+pluginSlug+'-totals-viewcart');
635 var element_view_cart_button=$('.'+pluginSlug+'-totals-viewcart-button');
636 var element_emptycart_button=$('.'+pluginSlug+'-totals-emptycart-button');
637 var element_cart=$('.'+pluginSlug+'-totals-cart');
638 var element_cart_items=$('.'+pluginSlug+'-totals-cart-items');
639 var element_cart_summary=$('.'+pluginSlug+'-totals-cart-summary');
640
641 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'gettotals'}, ext : wppizza.extend}, function(res) {
642 /*
643 adding hidden input for wppizzaCartJson
644 - skip if there's a main cart on page
645 - skip if there's a NO mini cart on page
646 - skip if get_cart_json is not in the results set anyway
647
648 if the cart is being emptied, the #wppizza-cart-json will always be removed
649 by the set_cart_json function called
650 */
651 if (mainCartElm.length <= 0 && miniCartElm.length > 0 ){
652
653
654 if(typeof res.get_cart_json !== 'undefined'){
655
656 /*
657 if it already exists in the minicart replace , else prepend
658 */
659 if($('#'+pluginSlug+'-minicart > #'+pluginSlug+'-cart-json').length > 0 ){
660
661 $('#'+pluginSlug+'-minicart > #'+pluginSlug+'-cart-json').replaceWith(res.get_cart_json);
662
663 /* update cart json with updated values */
664 set_cart_json('minicart-update');
665
666 }else{
667 miniCartElm.prepend(res.get_cart_json);
668
669 /* update cart json with initial values */
670 set_cart_json('minicart-ini');
671 }
672 }
673
674 else{
675 /* remove hidden element and */
676 $('#'+pluginSlug+'-minicart > #'+pluginSlug+'-cart-json').empty().remove();
677 /* update cart json */
678 set_cart_json('minicart-empty');
679 }
680
681 }
682
683
684 /* add /remove empty|not empty class to surrounding parent div */
685 if (res.no_of_items > 0){
686 element_totals_container.removeClass('wppizza-totals-no-items');
687 element_totals_container.addClass('wppizza-totals-has-items');
688 }else{
689 element_totals_container.removeClass('wppizza-totals-has-items');
690 element_totals_container.addClass('wppizza-totals-no-items');
691 }
692
693 /** add view cart dashicons if items in cart and view cart is enabled**/
694 if (element_cart.length > 0 ){
695
696 /* totals shortcode: adding classes if not exist already */
697 if(element_view_cart.length > 0){
698 /* add if not exists already */
699 if (!element_view_cart.hasClass('dashicons-cart')) {
700 element_view_cart.addClass('dashicons dashicons-cart');
701 }
702
703 /* totals shortcode: simply hide icon if empty cart */
704 if(res.cart_empty!=''){
705 element_view_cart.hide();
706 }else{
707 element_view_cart.show();
708 }
709 }
710 }
711
712 /** add is open hiddden input - if open**/
713 if(res.is_open){
714 wppizza.shopOpen = true;
715 }
716
717 /** order total **/
718 if (element_view_cart_button.length > 0){
719 element_view_cart_button.html(res.view_cart_button);
720 }
721
722 /** order total **/
723 if (element_total_order.length > 0){
724 element_total_order.html(res.total);
725 }
726 /** items only total **/
727 if (element_total_items.length > 0){
728 element_total_items.html(res.total_price_items);
729 }
730 /** number of items **/
731 if (element_itemcount.length > 0){
732 element_itemcount.html(res.itemcount);
733 }
734 /** checkout button **/
735 if (element_checkout_button.length > 0){
736 element_checkout_button.html(res.checkout_button);
737 }
738 /** emptycart **/
739 if (element_itemcount.length > 0){
740 element_emptycart_button.html(res.emptycart_button);
741 }
742
743 /* set cart markup */
744 if (element_cart.length > 0){
745
746 /* loop through each totals as they might have different summary/itemised settings */
747 $.each(element_cart,function(e,v){
748
749 /* selected totals element */
750 var selected_totals = $(this);
751
752 /** get cart markup **/
753 var cart_markup = '';
754
755 /* itemised */
756 if(selected_totals.hasClass('wppizza-totals-cart-items')){
757 cart_markup += res.items;
758 }
759
760 /* summary */
761 if(selected_totals.hasClass('wppizza-totals-cart-summary')){
762 cart_markup += res.summary;
763 }
764
765 /* min order info - will actually be an empty str if min order has been reached */
766 if(typeof res.minimum_order !=='undefined'){
767 cart_markup += res.minimum_order;
768 }
769
770 /* set cart markup for this shortcode element */
771 selected_totals.html(cart_markup);
772
773 /* only reinit minicart/gettotals spinner after cart changes not on pageload (as that's already happened) */
774 if(reinit_minicart_spinner){
775 wppizza_spinner('minicart-cart_markup');
776 }
777 });
778 }
779 /* nothing to remove when loading page */
780 if(page_load !== true){
781 removeLoadingDiv(element_totals_container, 'wppizza-loading-small');
782 }
783
784
785 run_refresh_on_ajaxstop = false;
786
787 /* once the initial page load was completed, we need to reinit the spinner when the (mini)cart changes */
788 reinit_minicart_spinner = true;
789
790 },'json');
791 }
792 wppizzaTotals(true);
793 }
794
795
796 /***********************************************
797 *
798 * [minicart behaviour]
799 *
800 ***********************************************/
801 var miniCartElm=$('#'+pluginSlug+'-minicart');
802 var mainCartElm=$('.'+pluginSlug+'-cart');
803 if(miniCartElm.length>0){
804
805 var wppizzaMiniCart = function(){
806
807 /********************************
808 add to id.class instead of body if set
809 ********************************/
810 if(typeof wppizza.crt.mElm !=='undefined'){
811 miniCartElm.prependTo(''+wppizza.crt.mElm+'');
812 }
813 var addElmPaddingTop=wppizza.crt.mCartPadTop;
814 /********************************
815 set padding (if set) to body or distinct element
816 ********************************/
817 if(typeof wppizza.crt.mPadTop !=='undefined' && wppizza.crt.mPadTop>0){
818
819 var addElmPaddingTop=wppizza.crt.mPadTop;
820
821 /**add padding to set elements**/
822 if(typeof wppizza.crt.mPadElm !== 'undefined'){
823 var elmToPad=$(''+wppizza.crt.mPadElm+'');
824 }else{
825 var elmToPad=$('body');
826 }
827 /* add css padding */
828 elmToPad.css({'padding-top': '+='+wppizza.crt.mPadTop+'px'});
829 }
830
831 /*********************************
832 if set to always show skip everything after
833 *********************************/
834 if(typeof wppizza.crt.mStatic!=='undefined'){
835 return;
836 }
837
838 /*********************************
839 scrolling behaviour if not static
840 *********************************/
841 /**current window**/
842 var currentWindow = $(window);
843 var miniCartIni=true;
844
845 /**on initial load**/
846 setTimeout(function(){
847 wppizzaMiniCartDo(currentWindow, miniCartElm, mainCartElm, addElmPaddingTop, elmToPad);
848 miniCartIni=false;
849 },500);
850
851 /**on scroll**/
852 var showMiniCart;
853 currentWindow.scroll(function () {
854 /**only on subsequent scrolls not when page is already scrolled on load*/
855 if(!miniCartIni){
856 clearTimeout(showMiniCart);
857 showMiniCart=setTimeout(function(){
858 wppizzaMiniCartDo(currentWindow, miniCartElm, mainCartElm,addElmPaddingTop, elmToPad);
859 },300);
860 }
861 });
862 /**on resize**/
863 currentWindow.resize(function() {
864 /**only on subsequent scrolls not when page is already scrolled on load*/
865 if(!miniCartIni){
866 clearTimeout(showMiniCart);
867 showMiniCart=setTimeout(function(){
868 wppizzaMiniCartDo(currentWindow, miniCartElm, mainCartElm,addElmPaddingTop, elmToPad);
869 },300);
870 }
871 });
872
873 }
874 wppizzaMiniCart();
875
876 var wppizzaMiniCartDo = function(currentWindow, miniCartElm, mainCartElm, addElmPaddingTop, elmToPad){
877
878 /*get width**/
879 var docViewWidth = currentWindow.width();
880
881 /*
882 max browser width up to which we display the minicart,
883 though that would be a bit silly to set if no maincart exists in the first place
884 */
885 if(typeof wppizza.crt.mMaxWidth !=='undefined'){
886 var docWidthLimit=wppizza.crt.mMaxWidth;
887 }
888
889 /**skip if wider than max width set or on oderpage**/
890 if((typeof docWidthLimit !=='undefined' && docViewWidth>docWidthLimit) || typeof wppizza.isCheckout!=='undefined'){
891 /*in case its still visible*/
892 if(miniCartElm.is(':visible')){
893 miniCartElm.fadeOut(250);
894 }
895 return;
896 }
897
898
899 /**
900 only needed if there is actually a main cart on page in the first place,
901 else just set to not in view
902 **/
903 if(mainCartElm.length>0){
904 var docViewTop = currentWindow.scrollTop();
905 var docViewBottom = docViewTop + currentWindow.height();
906 var elemTop = mainCartElm.offset().top;
907 var elemBottom = elemTop + mainCartElm.height();
908 var notInView = (elemBottom<=docViewTop || elemTop>=docViewBottom);
909 }else{
910 var notInView = true;
911 }
912
913 /*fade in minicart if needed**/
914 if(notInView && miniCartElm.is(':hidden')){
915 /*add padding if set **/
916 if(typeof elmToPad !=='undefined'){
917 elmToPad.animate({'padding-top': '+='+addElmPaddingTop+'px'},250);
918 }
919 miniCartElm.fadeIn(250);
920 }
921
922 if(!notInView && miniCartElm.is(':visible')){
923 /*reset padding if required **/
924 if(typeof elmToPad !=='undefined'){
925 elmToPad.animate({'padding-top': '-='+addElmPaddingTop+'px'},250);
926 }
927 miniCartElm.fadeOut(250);
928 }
929 };
930 }
931
932 /****************************
933
934 repurchase previous order
935 [adding to cart]
936
937 ****************************/
938 $(document).on('click', '.'+pluginSlug+'-reorder-purchase', function(e){
939 e.preventDefault();
940 e.stopPropagation();
941
942 /*
943 let's find out if we know yet if shop is open
944 (as on pageload carts might get loaded by ajax)
945 */
946 var is_open = checkShopOpen();
947 if(!is_open){
948 return;
949 }
950
951 /*
952 only if open and cart on page
953 */
954 if(hasCart){
955
956 /*show loading*/
957 addLoadingDiv();
958
959 /**get the id**/
960 var self=$(this);
961 var selfId=self.attr('id');
962
963
964 wppizzaCartRefreshedBefore(wppizza.funcBeforeCartRefr,e);/**run function before ajax cart update**/
965 /******************************
966 make the ajax request
967 ******************************/
968 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'reorder', 'id':selfId, 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
969 /**error, invalid - display error code in console **/
970 if(typeof response.invalid!=='undefined'){
971 console.log(response.invalid);
972 }
973 /*replace cart contents*/
974 if(typeof response.markup!=='undefined'){
975 load_cart_set_height(response.markup);
976 }
977 run_refresh_on_ajaxstop = response.cart;
978 forceAjaxStopRefresh = true;
979 set_cart_json('update-cart');//update wppizzaCartJson from hidden input vars
980
981 },'json');
982 return;
983 }
984
985 });
986 /****************************
987
988 adding item
989 to cart
990
991 ****************************/
992 $(document).on('click', '.'+pluginSlug+'-add-to-cart, .'+pluginSlug+'-add-to-cart-select', function(e){
993 e.preventDefault();
994 e.stopPropagation();
995 /*
996 let's find out if we know yet if shop is open
997 (as on pageload carts might get - slowly - loaded by ajax)
998 */
999 var is_open = checkShopOpen();
1000 if(!is_open){
1001 return false;
1002 }
1003
1004 /*
1005 only if open and cart on page
1006 */
1007 if(hasCart){
1008
1009 /*show loading*/
1010 addLoadingDiv();
1011
1012 /**get the id**/
1013 var self=$(this);
1014 var selfId=self.attr('id');
1015
1016
1017 /**feedback on item add enabled ? - always skip if triggered from add_to_cart_button shortcode*/
1018 if(typeof wppizza.itm!=='undefined' && typeof wppizza.itm.fbatc!=='undefined' && !self.hasClass('wppizza-add-to-cart-btn')){
1019 var add_remove_class = true;
1020 var currentHtml=self.html();
1021 var target = self;
1022 /* when reordering, replace inner td */
1023 if(self.hasClass('wppizza-do-reorder')){
1024 target = self.closest('td');
1025 currentHtml=target.html();
1026 add_remove_class = false;
1027 }
1028 if(add_remove_class){
1029 self.removeClass('wppizza-add-to-cart');/* stop excessive double clicks */
1030 }
1031
1032 self.fadeOut(100, function(){
1033 target.html( '<div class="wppizza-item-added-feedback">'+wppizza.itm.fbatc+'</div>' ).fadeIn(400).delay(wppizza.itm.fbatcms).fadeOut(400,function(){
1034 target.html(currentHtml).fadeIn(100);
1035 if(add_remove_class){
1036 self.addClass('wppizza-add-to-cart');/* re add class */
1037 }
1038 });
1039 });
1040 }
1041
1042 /*
1043 if using shortcode "add to cart button" with select dropdown
1044 */
1045 if(self.hasClass('wppizza-add-to-cart-select')){
1046 var selected_base = selfId.split('_').pop(-1);
1047 var selected_option = self.closest('span').find('select').val() ;
1048 /* set/override id */
1049 selfId = selected_base + '-' + selected_option;
1050 }
1051
1052 wppizzaCartRefreshedBefore(wppizza.funcBeforeCartRefr,e);/**run function before ajax cart update**/
1053 /******************************
1054 make the ajax request
1055 ******************************/
1056 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'add', 'id':selfId, 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
1057
1058 /**error, invalid - display error code in console **/
1059 if(typeof response.invalid!=='undefined'){
1060 console.log(response.invalid);
1061 }
1062 /*replace cart contents*/
1063 if(typeof response.markup!=='undefined'){
1064 load_cart_set_height(response.markup);
1065 wppizza.shopOpen = response.is_open;
1066 setTimeout(checkShopOpen, 10);/* timeout to finish html() */
1067 }
1068 /*replace order page contents (if there's an orderpage widget on the page)*/
1069 if(isCheckout && typeof response.page_markup!=='undefined'){
1070 $('.'+pluginSlug+'-order-wrap').replaceWith(response.page_markup);
1071 }
1072 run_refresh_on_ajaxstop = response.cart;
1073 forceAjaxStopRefresh = true;
1074 set_cart_json('add');//update wppizzaCartJson from hidden input vars
1075
1076 },'json');
1077 return;
1078 }
1079 });
1080
1081
1082 /****************************
1083
1084 remove from cart = simple click on [x]
1085 modify cart using input number text field
1086
1087 ****************************/
1088 $(document).on('click', '.'+pluginSlug+'-remove-from-cart, .'+pluginSlug+'-delete-from-cart', function(e){//, .wppizza-cart-modify old, using spinner
1089 e.preventDefault();e.stopPropagation();
1090
1091 /*show loading*/
1092 addLoadingDiv();
1093
1094 /**get the id**/
1095 var self=$(this);
1096 var selected_id=self.attr('id');
1097 var key=selected_id.split('-').pop(-1);
1098 /** delete entire quantity of this item when spinner enabled and clicked on delete button */
1099 if(self.hasClass('wppizza-delete-from-cart')){
1100 var quantity = 0;
1101 }else{
1102 /* -1 to just remove one from existing*/
1103 var quantity = -1;
1104 }
1105
1106 wppizzaCartRefreshedBefore(wppizza.funcBeforeCartRefr,e);/**run function before ajax cart update**/
1107 /******************************
1108 make the ajax request
1109 ******************************/
1110 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json', vars:{'type':'modify', 'id': selected_id, 'quantity': quantity, 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response){
1111
1112 /**error, invalid - display error code in console **/
1113 if(typeof response.invalid!=='undefined'){
1114 console.log(response.invalid);
1115 }
1116 /*replace cart contents*/
1117 if(typeof response.cart_markup!=='undefined'){
1118 load_cart_set_height(response.cart_markup);
1119 wppizza.shopOpen = response.is_open;
1120 setTimeout(checkShopOpen, 10);/* timeout to finish html() */
1121 }
1122 /*replace order page contents*/
1123 if(isCheckout && typeof response.page_markup!=='undefined'){
1124 $('.'+pluginSlug+'-order-wrap').replaceWith(response.page_markup);
1125 /* make sure to remove loading div */
1126 removeLoadingDiv();
1127 }
1128
1129 run_refresh_on_ajaxstop = response.cart;
1130 forceAjaxStopRefresh = true;
1131 set_cart_json('modify');//update wppizzaCartJson from hidden input vars
1132
1133 },'json');
1134 return;
1135 });
1136
1137 /*
1138 only allow integers in cart increase/decrease - although it's set to type=number min=0
1139 it still allows for negatives ...
1140 trigger click on enter too
1141 */
1142 $(document).on('keyup', '.'+pluginSlug+'-cart-mod, .'+pluginSlug+'-item-qupdate', function(e){
1143 this.value = this.value.replace(/[^0-9]/g,'');
1144 });
1145 /*
1146 get value on focus,
1147 to trigger click on blur too if value has changed
1148 */
1149 var wppizza_current_item_count_val='';
1150 /**get current value for cart increase/decrease first**/
1151 $(document).on('focus', '.'+pluginSlug+'-cart-mod, .'+pluginSlug+'-item-qupdate', function(e){
1152 wppizza_current_item_count_val = this.value.replace(/[^0-9]/g,'');
1153 });
1154 /*
1155 execute/trigger on blur too if value is different
1156 */
1157 $(document).on('blur', '.'+pluginSlug+'-cart-mod, .'+pluginSlug+'-item-qupdate', function(e){
1158 this.value = this.value.replace(/[^0-9]/g,'');
1159 });
1160
1161
1162 /***********************************************
1163 *
1164 * [if we are trying to add to cart by clicking on the title
1165 * but there's more than one size to choose from, display alert]
1166 * [provided there's a cart on page and we are open]
1167 ***********************************************/
1168 /*more than one size->choose alert*/
1169 $(document).on('click', '.'+pluginSlug+'-trigger-choose', function(e){
1170 if (wppizza.shopOpen && hasCart){
1171 if(prettify_js_alerts){//using prettified alerts
1172 wppizzaPrettifyJsAlerts(wppizza.msg.choosesize, 'alert');
1173 }else{
1174 alert(wppizza.msg.choosesize);
1175 }
1176 }
1177 });
1178 /*only one size, trigger click*/
1179 $(document).on('click', '.'+pluginSlug+'-trigger-click', function(e){
1180 if (wppizza.shopOpen && hasCart){
1181
1182 /*just loose wppizza-article- from id*/
1183 var ArticleId=this.id.split('-');
1184 ArticleId=ArticleId.splice(2);
1185 ArticleId = ArticleId.join('-');
1186 /**make target id*/
1187 target=$('#'+pluginSlug+'-'+ArticleId+'');
1188 /*trigger*/
1189 target.trigger('click');
1190 }
1191 });
1192
1193 /****************************
1194
1195 empty cart entirely
1196
1197 ****************************/
1198 $(document).on('click', '.'+pluginSlug+'-empty-cart-button', function(e){
1199
1200
1201 e.preventDefault();
1202 e.stopPropagation();
1203 /*show loading*/
1204 addLoadingDiv();
1205
1206 wppizzaCartRefreshedBefore(wppizza.funcBeforeCartRefr,e);/**run function before ajax cart update**/
1207 /******************************
1208 make the ajax request
1209 ******************************/
1210 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'empty', 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
1211
1212 /**error, invalid - display error code in console **/
1213 if(typeof response.invalid!=='undefined'){
1214 console.log(response.invalid);
1215 }
1216
1217 /*replace cart contents*/
1218 if(typeof response.cart_markup!=='undefined'){
1219 load_cart_set_height(response.cart_markup);
1220 wppizza.shopOpen = response.is_open;
1221 setTimeout(checkShopOpen, 10);/* timeout to finish html() */
1222 }
1223 /*replace order page contents*/
1224 if(isCheckout && typeof response.page_markup!=='undefined'){
1225 $('.'+pluginSlug+'-order-wrap').replaceWith(response.page_markup);
1226 }
1227
1228 run_refresh_on_ajaxstop = response.cart;
1229 forceAjaxStopRefresh = true;
1230 set_cart_json('empty');//update wppizzaCartJson from hidden input vars
1231
1232 },'json');
1233 });
1234
1235
1236 /***********************************************
1237 * [customer selects self pickup , session gets set via ajax
1238 * reload page to reflect delivery charges....
1239 * only relevant if there's a shoppingcart or orderpage on page]
1240 ***********************************************/
1241 var set_pickup_elements_toggle = function(disable_elemnts, pickup_toggle){
1242
1243 /* get all pickup checkboxes and radios in case there are more than one */
1244 var all_pickup_checkboxes=$('input[type="checkbox"][name="wppizza-order-pickup"]');//checkbox
1245 var all_pickup_toggles=$('.'+pluginSlug+'-toggle-pickup');//radio
1246 var all_delivery_toggles=$('.'+pluginSlug+'-toggle-delivery');//radio
1247 var all_pickup_toggle_labels = all_pickup_toggles.closest('label');
1248 var all_delivery_toggle_labels = all_delivery_toggles.closest('label');
1249
1250
1251 if(disable_elemnts === true){
1252 /* disable all checkboxes/radios */
1253 all_pickup_checkboxes.attr('disabled', true);/*disable checkbox to give ajax time to do things*/
1254 all_pickup_toggles.attr('disabled', true);/*disable radios to give ajax time to do things*/
1255 all_delivery_toggles.attr('disabled', true);/*disable radios to give ajax time to do things*/
1256 }
1257
1258 if(disable_elemnts === false){
1259 /* enable all checkboxes/radios */
1260 all_pickup_checkboxes.attr('disabled', false);/*disable checkbox to give ajax time to do things*/
1261 all_pickup_toggles.attr('disabled', false);/*disable radios to give ajax time to do things*/
1262 all_delivery_toggles.attr('disabled', false);/*disable radios to give ajax time to do things*/
1263 }
1264
1265 if(pickup_toggle === true){
1266 /* set to true what needs to be true*/
1267 all_pickup_checkboxes.prop('checked',true);
1268 all_pickup_toggles.prop('checked',true);
1269 all_delivery_toggles.prop('checked',false);
1270 all_pickup_toggle_labels.addClass('wppizza-pickup-toggle-selected');
1271 all_delivery_toggle_labels.removeClass('wppizza-pickup-toggle-selected');
1272
1273 }
1274 if(pickup_toggle === false){
1275 all_pickup_checkboxes.prop('checked',false);
1276 all_pickup_toggles.prop('checked',false);
1277 all_delivery_toggles.prop('checked',true);
1278 all_pickup_toggle_labels.removeClass('wppizza-pickup-toggle-selected');
1279 all_delivery_toggle_labels.addClass('wppizza-pickup-toggle-selected');
1280 }
1281
1282 }
1283 //var alert_run = false;
1284 $(document).on('change', '.'+pluginSlug+'-order-pickup', function(e){
1285
1286 /*
1287 let's find out if we know yet if shop is open
1288 (as on pageload carts might get loaded by ajax)
1289 bypass if toggle has forced visibility to show even when closed
1290 */
1291 if(!force_pickup_toggle){
1292
1293 var is_open = checkShopOpen();
1294
1295
1296 if(!is_open){
1297
1298 var elm = $(this);
1299 var elmType = elm.attr('type');
1300 var elmVal = elm.val();
1301
1302 /*
1303 revert back to what it was
1304 */
1305 if(elmType == 'checkbox'){
1306 $('.'+pluginSlug+'-order-pickup').each(function(){
1307 $(this).checked = ! $(this).checked
1308 });
1309 }
1310
1311 if(elmType == 'radio'){
1312
1313 $('.'+pluginSlug+'-order-pickup').each(function(){
1314 var thisRadioElm = $(this) ;
1315 /*
1316 for radios , we only need to re-check the "other one"
1317 */
1318 if(thisRadioElm.val() != elmVal ){
1319 thisRadioElm.prop('checked', true);
1320 }
1321
1322 });
1323 }
1324
1325
1326 return;
1327 }
1328 }
1329
1330 if (hasCart || force_pickup_toggle){
1331
1332 var self=$(this);
1333 /*
1334 serialize the data before we mess around with
1335 states of pickup toggles / checkbox
1336 */
1337 var data = $('#'+pluginSlug+'-send-order').serialize();
1338
1339 /**
1340 as the default for checkbox can change to be pickup,
1341 instead of delivery find out whats what
1342 **/
1343 var default_is_pickup = (typeof wppizza.opt !=='undefined' && typeof wppizza.opt.puDef !== 'undefined') ? true : false;
1344
1345 /** is radio toggle or checkbox */
1346 if (self.is(':radio')) {
1347 var is_pickup =(self.val()==1 ) ? true : false;
1348
1349 }else{
1350 var is_pickup = (self.is(':checked')) ? true : false;
1351 /* overwrite if default is set to be pickup */
1352 if(default_is_pickup){
1353 is_pickup = (self.is(':checked')) ? false : true;
1354 }
1355 }
1356 /**
1357 changed from default to show (right) alerts
1358 **/
1359 var changed_from_default = false ;
1360 if(default_is_pickup !== is_pickup){
1361 changed_from_default = true ;
1362 }
1363
1364 /* disable all checkboxes/radios */
1365 set_pickup_elements_toggle(true, null);
1366 /*
1367 default is set to pickup or delivery, checkbox is UN-checked , and labelled for appropriat selection
1368 */
1369 if(is_pickup){
1370 set_pickup_elements_toggle(null, true);
1371 }else{
1372 set_pickup_elements_toggle(null, false);
1373 }
1374
1375 /*js alert if enabled and switching to opposite of default - only runs the first time*/
1376 if(typeof wppizza.opt!=='undefined' && typeof wppizza.opt.puAlrt!=='undefined'){
1377 /* only run if changing non default (i.e the opposite to the unchecked default) */
1378 if(changed_from_default == true){
1379 /*
1380 alert only
1381 */
1382 if(wppizza.opt.puAlrt == 1){
1383 if(prettify_js_alerts){//using prettified alerts
1384 wppizzaPrettifyJsAlerts(wppizza.msg.pickup, 'alert');
1385 }else{
1386 alert(wppizza.msg.pickup);
1387 }
1388 }
1389
1390 /*
1391 confirm
1392 */
1393 if(wppizza.opt.puAlrt == 2){
1394 if(confirm(wppizza.msg.pickup)){
1395 //just continue
1396 }else{
1397 /* reset checkboxes / radios*/
1398 if((default_is_pickup && is_pickup) || (!default_is_pickup && is_pickup)){
1399 set_pickup_elements_toggle(null, false);
1400 }else{
1401 set_pickup_elements_toggle(null, true);
1402 }
1403 /* make all selectable again */
1404 set_pickup_elements_toggle(false, null);
1405 return;
1406 }
1407 }
1408 }
1409 }
1410
1411 /**run function before ajax cart update**/
1412 wppizzaCartRefreshedBefore(wppizza.funcBeforeCartRefr,e);
1413
1414 /*show loading*/
1415 addLoadingDiv();
1416
1417 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'order-pickup', 'value': is_pickup, 'data': data, 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
1418
1419 /*
1420 conditionally still reloading page entirely
1421 on change of pickup to delivery (on checkout page)
1422 if not yet using updated plugins
1423 */
1424 if(typeof wppizza['compat'] !== 'undefined' && typeof wppizza['compat'].puDel !== 'undefined' ){
1425 if(isCheckout){
1426 window.location.reload(true);
1427 is_page_reload = true;
1428 return;
1429 }
1430 }
1431
1432 /*
1433 distinctly set flag here
1434 to make sure to remove any loading divs
1435 after change
1436 */
1437 is_page_reload = false;
1438
1439
1440 /*
1441 replace cart contents
1442 */
1443 if(typeof response.cart_markup!=='undefined'){
1444 load_cart_set_height(response.cart_markup);
1445 wppizza.shopOpen = response.is_open;
1446 if(!force_pickup_toggle){
1447 setTimeout(checkShopOpen, 10);/* timeout to finish html() - not ideal but will do for now*/
1448 }
1449 }
1450 /*
1451 replace order page contents
1452 */
1453 if(isCheckout && typeof response.page_markup!=='undefined'){
1454 $('.'+pluginSlug+'-order-wrap').replaceWith(response.page_markup);
1455 }
1456
1457 /*
1458 replace pickup choice contents
1459 */
1460 $('.'+pluginSlug+'-orders-pickup-choice').replaceWith(response.cart_pickup_select);
1461
1462 /*
1463 replace opening hours contents (as pickup/delivery tiimes may be filtered and therefore different)
1464 */
1465 $('.'+pluginSlug+'-opening-hours').html(response.opening_hours);//
1466
1467 /*
1468 make radios/checkboxes selectable again - irrelevant as html actually gets replaced
1469 */
1470 run_refresh_on_ajaxstop = response.cart;
1471
1472 forceAjaxStopRefresh = true;
1473
1474 set_cart_json('pickup-toggle');//update wppizzaCartJson from hidden input vars
1475
1476 },'json');
1477 }
1478 });
1479
1480
1481 /**************************************************************************************************************************************************************************
1482 *
1483 *
1484 *
1485 * [spinner]
1486 *
1487 *
1488 *
1489 **************************************************************************************************************************************************************************/
1490 /*******************************************************
1491 * [order form , initialize spinner for increase/decrease of items if enabled]
1492 * as function to allow re-initializing on ajax complete
1493 *******************************************************/
1494 var wppizza_spinner_blur_count = 0;
1495 var wppizza_spinner = function(action){
1496
1497 /**
1498 only on wppizza checkout
1499 check isCheckout and wppizza.ofqc here too as it gets re-initialized
1500 on ajaxComplete !
1501 **/
1502 if(typeof wppizza.ofqc!=='undefined'){
1503
1504 var spinnerElements = '';
1505 if(isCheckout){
1506 spinnerElements += '.'+pluginSlug+'-item-qupdate, ';
1507 }
1508 spinnerElements += '.'+pluginSlug+'-cart-mod';
1509
1510
1511 var spinnerElm=$( spinnerElements );
1512
1513 /*
1514 set min var
1515 */
1516 spinnerElm.spinner({
1517 min: 0
1518 });
1519
1520 /*
1521 capture original spinner value on focus
1522 */
1523 var spinner_value;
1524 var spinner_update_value;
1525 var spinner_element;
1526
1527
1528 /*
1529 stop submitting if we are hitting enter
1530 after changing quantities
1531 and update checkout page instead if needed
1532 */
1533 /*
1534 lets make sure to not re-initialize blur/keydown 2x
1535 spinner gets initialized from ajax complete.
1536 however, if no ajax (orderpage) ajaxStart_count will be 0
1537 */
1538 //if(action=='load' && wppizza.ajaxStart_count > 0)
1539 if(action=='load' && ajaxStartCount > 0){
1540 return false;
1541 }
1542
1543 spinnerElm.focus(function(event) {
1544 event.preventDefault();
1545 wppizza_spinner_blur_count = 0;//reset count on focus
1546 spinner_value = $(this).val();
1547 spinner_element_id = $(this).attr('id').split('-').pop(-1);
1548
1549 /*
1550 only enable mousewheel on focus
1551 */
1552 $(this).on( 'DOMMouseScroll mousewheel', function ( event ) {
1553 /*restrict scrollwheel to be >=0*/
1554 if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
1555 // down
1556 if (parseInt(this.value) > 0) {
1557 this.value = parseInt(this.value, 10) - 1;
1558 }
1559 } else {
1560 // up
1561 this.value = parseInt(this.value, 10) + 1;
1562 }
1563
1564 //prevent page from scrolling
1565 return false;
1566 });
1567
1568 return false;
1569 });
1570
1571 /*
1572 simply trigger blur event
1573 on enter keydown
1574 */
1575 spinnerElm.keydown(function(event) {
1576 spinner_update_value = $(this).val();
1577 /* simply trigger blur event */
1578 if(event.which == 13 || event.which == 35){
1579 $(this).blur();
1580 return false;
1581 }
1582 });
1583
1584 /*
1585 after changing quantities on blur
1586 update checkout page if needed
1587 */
1588 spinnerElm.blur(function(event) {
1589 spinner_update_value = $(this).val();
1590 event.preventDefault();
1591 event.stopPropagation();
1592
1593
1594 if(wppizza_spinner_blur_count == 0 ){//make sure only the first blur will call the update function
1595
1596 /*
1597 only bother with this if the vlues have actually changed
1598 */
1599 if(spinner_value != spinner_update_value){
1600 /*
1601 make it behave like an onchange event
1602 by triggering change event
1603 */
1604 $(this).change();
1605 }
1606
1607 wppizza_spinner_blur_count++;
1608 }
1609 return false;
1610 });
1611 }
1612 };
1613
1614
1615 /*
1616 spinner change event
1617 (esentially this is forced from the blur event when the value has in fact changed)
1618 */
1619 $(document).on('change', '.'+pluginSlug+'-cart-mod, .'+pluginSlug+'-item-qupdate', function(e){
1620 e.preventDefault();
1621 e.stopPropagation();
1622
1623 var self = $(this);
1624 var selfId = self.attr('id');
1625 var spinner_id = selfId.split('-').pop(-1);
1626 var spinner_value = self.val();
1627
1628 /*
1629 update the order
1630 */
1631 wppizza_update_order(spinner_value, spinner_id);
1632
1633 })
1634
1635 /*
1636 if clicking on spinner arrows, immediately update cart by simply triggering the blur event on the input
1637 (as - by the nature of arrows - they increment by one anyway)
1638 */
1639 $(document).on('click', '.'+pluginSlug+'-item-row > td > span > a.ui-spinner-up, .'+pluginSlug+'-item-row > td > span > a.ui-spinner-down', function(e){
1640 e.preventDefault();
1641 e.stopPropagation();
1642 $(this).closest('span').find('.ui-spinner-input').blur();
1643 });
1644
1645
1646
1647 /**************************************************************************************************************************************************************************
1648 *
1649 *
1650 *
1651 * [Accordion]
1652 *
1653 *
1654 *
1655 **************************************************************************************************************************************************************************/
1656 var initAccordion = function(){
1657 //console.log(wppizza['acc']);
1658 $( ""+wppizza['acc'].elm+"" ).accordion(wppizza['acc'].opt);
1659 }
1660 if(useAccordion){
1661 initAccordion();
1662 }
1663
1664 /**************************************************************************************************************************************************************************
1665 *
1666 *
1667 *
1668 * [submit order - including validation]
1669 *
1670 *
1671 *
1672 **************************************************************************************************************************************************************************/
1673
1674 /*******************************************
1675 * [validate order form - in function
1676 * to allow re-initializing on ajax complete]
1677 *******************************************/
1678 var wppizza_validator = function(){
1679
1680 /**
1681 only on wppizza checkout
1682 check isCheckout here too as it gets re-initialized
1683 on ajaxComplete !
1684 **/
1685 if(isCheckout){
1686 $('#'+send_order_form_id+'').validate({
1687
1688 rules: wppizza.validate.rules,
1689
1690 errorElement : 'div',
1691
1692 errorClass:'wppizza-validation-error error',
1693
1694 ignore: ':hidden, :disabled, .'+pluginSlug+'-ignore, .ignore',
1695
1696 errorPlacement: function(error, element) {
1697 /* append to parent div */
1698 var parent = element.closest('div');
1699 error.appendTo(parent);
1700
1701 },
1702
1703 invalidHandler: function(form, validator) {
1704 if (!validator.numberOfInvalids()){
1705 return;
1706 }
1707
1708 /**check if element is in view and scrollto if not*/
1709 var errorElem = $(validator.errorList[0].element);
1710 var currentWindow = $(window);
1711
1712 var docViewTop = currentWindow.scrollTop();
1713 var docViewBottom = docViewTop + currentWindow.height();
1714
1715 var elemTop = errorElem.offset().top;
1716 var elemBottom = elemTop + errorElem.height();
1717
1718 var inView= ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
1719
1720 /**scroll into view if needed*/
1721 if(!inView){
1722 $('html, body').animate({
1723 scrollTop: errorElem.offset().top-50
1724 }, 300);
1725 }
1726 },
1727
1728 submitHandler: function(form, event) {
1729
1730 /*
1731 stop double clicks, add spinner - just for good measure.
1732 loading will cover all anyway
1733 */
1734 var submit_button = $('#'+pluginSlug+'-ordernow');
1735 submit_button.attr('disabled', 'true');//.addClass('wppizza-ordernow-spinner');
1736
1737 /*
1738 show loading
1739 */
1740 addLoadingDiv();
1741
1742 /*
1743 submit
1744 */
1745 wppizza_submit_order();
1746
1747 return false;/* dont submit form, we'll do that via wppizza_submit_order */
1748 }
1749 });
1750 };
1751 };
1752 /******************************
1753 initialize spinner on load
1754 ******************************/
1755 wppizza_spinner('load');
1756 /******************************
1757 * update order page modules via ajax instead of reload
1758 *******************************/
1759 var wppizza_update_order = function(current_value, element_id, force_reload){
1760
1761 /*
1762 forcing reload of page regardless making sure not to cache
1763 not really in use anywhere from what i can tell....
1764 but lets keep it for now
1765 */
1766 if(typeof force_reload !== 'undefined' && force_reload === true){
1767 window.location.reload(true);
1768 is_page_reload = true;
1769 return;
1770 }
1771 // just stop if there's no element id to begin with
1772 if(typeof element_id === 'undefined'){
1773 return;
1774 }
1775
1776 /* cover page with loading gif before running ajax*/
1777 addLoadingDiv();
1778 var element_totals_container=$('.'+pluginSlug+'-totals-container');
1779 addLoadingDiv(element_totals_container, 'wppizza-loading-small');
1780
1781 /* when changing quantities on checkout page make sure we keep any newly entered/changed customer data */
1782 var data = '';
1783 if(isCheckout){
1784 data = $('#'+pluginSlug+'-send-order').serialize();
1785 }
1786
1787
1788 /** run function before ajax cart update **/
1789 wppizzaCartRefreshedBefore(wppizza.funcBeforeCartRefr,'update');
1790
1791 /**now send ajax to update**/
1792 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json', vars:{'type':'update-order', 'id': element_id, 'quantity': current_value, 'isCheckout': isCheckout, 'data': data}, ext : wppizza.extend}, function(response) {
1793
1794 /**error, invalid - display error code in console **/
1795 if(typeof response.invalid!=='undefined'){
1796 console.log(response.invalid);
1797 }
1798 /*replace cart contents*/
1799 if(typeof response.cart_markup!=='undefined'){
1800 load_cart_set_height(response.cart_markup);
1801 wppizza.shopOpen = response.is_open;
1802 setTimeout(checkShopOpen, 10);/* timeout to finish html() */
1803 }
1804 /*replace page contents*/
1805 if(typeof response.page_markup!=='undefined'){
1806 $('.'+pluginSlug+'-order-wrap').replaceWith(response.page_markup);
1807 /* make sure to remove loading div */
1808 removeLoadingDiv();
1809 }
1810
1811 run_refresh_on_ajaxstop = response.cart;
1812
1813 forceAjaxStopRefresh = true;
1814
1815 set_cart_json('update-order');//update wppizzaCartJson from hidden input vars
1816
1817 return;
1818 },'json');
1819 }
1820
1821
1822
1823 /********************************************
1824 *
1825 * orderpage only
1826 *
1827 ********************************************/
1828 if(isCheckout){
1829
1830 /******************************
1831 make sure page gets reloaded/changed
1832 to avoid possible "cannot find order by hash"
1833 when simply backpaging from payment gateway pages
1834 without having canceled or done anything further
1835
1836 strangly enough, simply adding a class to the 'body'
1837 seems to make this work without having to reload
1838 the order page
1839 ******************************/
1840 if($('body').hasClass('wppizza-checkout')){
1841 }else{
1842 $('body').addClass('wppizza-checkout');
1843 }
1844 /******************************
1845 initialize validator on load
1846 ******************************/
1847 wppizza_validator();
1848
1849 /******************************
1850 * validation - set error messages
1851 *******************************/
1852 jQuery.extend(jQuery.validator.messages, {
1853 required: wppizza.validate.error.required,
1854 email: wppizza.validate.error.email,
1855 decimal: wppizza.validate.error.decimal,
1856 })
1857 /******************************
1858 validation - add method - decimals (for tips)
1859 ******************************/
1860 $.validator.methods.decimal = function (value, element) {
1861 return this.optional(element) || /^(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
1862 }
1863
1864 /*******************************
1865 * [apply percentage tips if enabled]
1866 *******************************/
1867 $(document).on('change', '#ctips_pc', function(e){
1868
1869 /*
1870 take the total, minus current tips and calculate new tips
1871 */
1872 var total_before_tips = 0;
1873 // current total
1874 if(typeof wppizzaCartJson['summary']['total'].total !== 'undefined'){
1875 total_before_tips = wppizzaCartJson['summary']['total'].total;
1876 }
1877 // deduct current tips
1878 if(typeof wppizzaCartJson['summary']['tips'].tips !== 'undefined' && total_before_tips > 0){
1879 total_before_tips -= wppizzaCartJson['summary']['tips'].tips;
1880 }
1881
1882 // currency decimals - defaults to 2
1883 var decimals = (typeof wppizzaCartJson['currency'].decimals !== 'undefined') ? wppizzaCartJson['currency'].decimals : 2 ;
1884
1885
1886 //percentage or value
1887 var tipType = $(this).find(':selected').data('type');
1888
1889
1890 /*
1891 init -- option
1892 */
1893 if(tipType == 'init' ){
1894 var new_tip = 0;
1895 }
1896 /*
1897 percentage option
1898 */
1899 else if(tipType == 'pc' ){
1900 // calc tip based on total before tip, 2 decimals max
1901 var new_tip = ($(this).val() == '' || $(this).val() == 0 ) ? 0 : total_before_tips * ($(this).val() / 100 );
1902 }
1903 /*
1904 absolute option
1905 */
1906 else if(tipType == 'val' ){
1907 // calc tip based on total before tip, 2 decimals max
1908 var new_tip = parseFloat($(this).val());
1909 }
1910 /*
1911 invalid -> set to 0
1912 */
1913 else{
1914 var new_tip = 0;
1915 }
1916 new_tip = new_tip.toFixed(decimals);
1917
1918 /*
1919 apply tip and trigger update
1920 */
1921 $('#ctips').val(new_tip).trigger('blur');
1922
1923 return;
1924 });
1925
1926 /*******************************
1927 * [validate tips/gratuities]
1928 * remove any utter nonsense on keyup first
1929 *******************************/
1930 $(document).on('keyup', '#ctips', function(e){
1931 /* ignore arrows/home/end/backspacing*/
1932 if(e.which==8 || (e.which>=35 && e.which<=40)){
1933 return;
1934 }
1935
1936 var self = $(this);
1937 var value = self.val();
1938 validate = value.replace(/[^0-9\.,]+/g, '');
1939 //validate = parseFloat(validate)
1940 //num = validate.toFixed(2);
1941 self.val(validate);
1942 });
1943
1944 /*******************************
1945 * get current tip value set
1946 *******************************/
1947 var tips_input=$('#ctips');
1948 var tips_percent_select = $('#ctips_pc');
1949 var current_tips=tips_input.val();
1950
1951 /*******************************
1952 * get current tip value set on focus
1953 *******************************/
1954 $(document).on('focus', '#ctips, #ctips_pc', function(e){
1955 current_tips=$(this).val();
1956
1957 /*
1958 if we focus on the tips input to enter the value manually
1959 unset the dropdown tips percentage
1960 */
1961 if(tips_percent_select.length > 0 ){
1962 $('#ctips_pc').val('');
1963 }
1964 });
1965 /*******************************
1966 * stop submitting form if we are hitting enter on tip field ...
1967 *******************************/
1968 $(document).on('keydown', '#ctips', function(e){
1969 if(event.which == 13 || event.which == 35){
1970 event.preventDefault();
1971 $(this).blur();
1972 //apply_tips(current_tips);
1973 return false;
1974 }
1975 });
1976 /*******************************
1977 * .....and just apply tip by triggering "blur" button
1978 *******************************/
1979 $(document).on('blur', '#ctips', function(e){
1980 apply_tips(current_tips);
1981 return false;
1982 });
1983 }
1984
1985
1986
1987
1988 /*******************************
1989 * apply tip set
1990 *******************************/
1991 var apply_tips = function(current_tips){
1992
1993 var self = $(this);
1994 var entered_tips=$('#ctips').val();
1995 //percentage(pc) or value(val) - sanitised. defaults to value(val) if not set
1996 var tipType = $('#ctips_pc').find(':selected').data('type');
1997 tipType = typeof tipType !== 'undefined' ? tipType.toLowerCase().replace(/[^a-z]/g, '') : 'val' ;
1998
1999 /**
2000 only update/refresh if the value has actually changed
2001 **/
2002 if( current_tips != entered_tips ){
2003 var data = $('#'+pluginSlug+'-send-order').serialize();
2004 //add tip type
2005 data +='&ctips_type='+tipType;
2006 /*stop double clicks*/
2007 self.attr('disabled', 'true');
2008 /*show loading*/
2009 addLoadingDiv();
2010 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'addtips','data':data, 'tipType':tipType, 'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
2011
2012 /*replace cart contents*/
2013 if(typeof response.cart_markup!=='undefined'){
2014 load_cart_set_height(response.cart_markup);
2015 wppizza.shopOpen = response.is_open;
2016 setTimeout(checkShopOpen, 10);/* timeout to finish html() */
2017 }
2018 /*replace order page contents*/
2019 if(isCheckout && typeof response.page_markup!=='undefined'){
2020 $('.'+pluginSlug+'-order-wrap').replaceWith(response.page_markup);
2021 /* make sure to remove loading div */
2022 removeLoadingDiv();
2023 }
2024
2025 run_refresh_on_ajaxstop = response.cart;
2026 forceAjaxStopRefresh = true;
2027 set_cart_json('tips');//update wppizzaCartJson from hidden input vars
2028
2029 },'json');
2030 }
2031 };
2032
2033 /**************************************************************************************************************************************************************************
2034 *
2035 *
2036 *
2037 * [submit order - end validation]
2038 *
2039 *
2040 *
2041 ****************************************************************************************************************************************************************************
2042
2043
2044 /******************************
2045 * ini selected wppizza_'+gateway_selected+'_init
2046 * js function if it was ddefined by currently selected
2047 * gateway -> on load
2048 *******************************/
2049 var wppizza_gateway_init=function(){
2050
2051 /*
2052 get selected gateway
2053 */
2054 var gateway_selected = wppizza_get_gateway_selected(false);
2055 if(gateway_selected == '' ){
2056 return;
2057 }
2058 /*
2059 check if gateway provides it's own init function
2060 to perhaps mount some fields or similar
2061 */
2062 var gateway_function_name = 'wppizza_'+gateway_selected+'_init'/* the function name to look for */
2063 gateway_function_name = window[gateway_function_name];
2064 if(typeof gateway_function_name === 'function'){
2065 /*
2066 run defined ini function
2067 */
2068 gateway_function_name();
2069 }
2070 }
2071 /*
2072 only run above init function on load of checkout page
2073 if no confirmation form is being used and only
2074 for some old/legacy gateway implementations
2075 (only affects non-redirects / inline gateways)
2076 */
2077 if(gateway_compat_init){
2078 if(!use_confirmation_form){
2079 wppizza_gateway_init();
2080 }
2081 }
2082
2083
2084
2085 /******************************
2086 * submit_order
2087 *******************************/
2088 var wppizza_submit_order=function(){
2089 /*
2090 dont use jQuery here to get the form to keep it
2091 consistent with "form", "form.id" etc returned by the validator
2092 */
2093 var form = document.getElementById(send_order_form_id);
2094
2095 /*
2096 already on confirmation page, override must_confirm
2097 */
2098 var must_confirm = use_confirmation_form;
2099 if($('#'+form.id+'').hasClass('wppizza-order-confirmed')){
2100 must_confirm = false;
2101 }
2102
2103 /*
2104 are we on checkout or confirmation page
2105 */
2106 var is_confirmation_page = $('#'+form.id+'').hasClass('wppizza-order-confirmed') ? true : false
2107
2108
2109 /*
2110 serialized input data
2111 */
2112 var data = $(form).serialize();
2113
2114
2115 /**************************************************************************************************
2116 Allow the execution to be interrupted AFTER the submit button was clicked
2117 by running functions defined in 'fnBeforeOrderSubmit'
2118
2119 run any js functions that interjects before submitting order.
2120 if any of these do NOT return true, stop execution , reloading the page
2121 it is the called functions responsibility to display alerts, confirms etc
2122 as appropriate before page reload
2123 **************************************************************************************************/
2124 if(typeof wppizza.fnBeforeOrderSubmit !== 'undefined' && wppizza.fnBeforeOrderSubmit.length>0){
2125
2126 /*
2127 set to true here to
2128 stop removing loading div early
2129 */
2130 is_page_reload = true;
2131
2132 /*
2133 by default, we always continue, unless some function
2134 set in fnBeforeOrderSubmit is set to interrupt the process
2135 by distinctly returning
2136
2137 res.responseJSON['continue'] = false;
2138
2139 (can be either ajax or non-ajax)
2140 */
2141 var continue_execution = true;
2142
2143
2144 /*
2145 list of functions to execute (as they are most likely ajax calls)
2146 we have to wait for all of their results before deciding to either interrupt
2147 the checkout process or continue
2148 */
2149 var promiseList = [];
2150 for(i=0; i < wppizza.fnBeforeOrderSubmit.length; i++){
2151 var fn = new Function('formid, data, must_confirm, is_confirmation_page', 'return ' + wppizza.fnBeforeOrderSubmit[i] + '(formid, data, must_confirm, is_confirmation_page);');
2152 var fnResult = fn(form.id, data, must_confirm, is_confirmation_page);
2153 /*
2154 add the function to the list pf promises
2155 */
2156 promiseList.push(fnResult);
2157
2158 }
2159
2160 /*
2161 loop through the promises list and set continue_execution to false
2162 if *any* of the functions return continue = false in the responseJSON
2163
2164 (if function is not using ajax, it still needs to return the same responseJSON.continue = false just like ajax calls)
2165 */
2166 $.when.apply($, promiseList).then(function(results){
2167 $.each(promiseList,function(idx,res){
2168
2169
2170 // set continue_execution to false if defined as such
2171 if(typeof res.responseJSON['_wppizza_verify_on_submit'] !== 'undefined' && typeof res.responseJSON['_wppizza_verify_on_submit']['continue'] !== 'undefined' && res.responseJSON['_wppizza_verify_on_submit']['continue'] === false){
2172
2173 /*
2174 set flags to not continue execution
2175 including elemnt id and alert mssage (if defined)
2176 */
2177 continue_execution = res.responseJSON['_wppizza_verify_on_submit'];
2178
2179 /*
2180 if even only one is false, stop the each loop
2181 */
2182 return false;
2183 }
2184 });
2185
2186 return continue_execution;
2187
2188 }).done(function(order_continue){
2189
2190 /*
2191 continue submitting the order
2192 (or not as the case may be if order_continue === false)
2193 */
2194 on_before_order_continue(order_continue, data, form, must_confirm, is_confirmation_page);
2195
2196 return;
2197
2198 });
2199
2200 /*
2201 always return here if we have defined fnBeforeOrderSubmit functions
2202 */
2203 return;
2204 }
2205
2206 /***********************************************************
2207 continue execution as normal if no
2208 fnBeforeOrderSubmit is set to interrupt the process
2209 ***********************************************************/
2210 on_before_order_continue(true, data, form, must_confirm, is_confirmation_page);
2211
2212 return;
2213 }
2214
2215 /**************************************************************************************************************************************
2216 * a helper to allow for fnVerifyOnOrderSubmit added in 3.13.5
2217 * for a better way (we can check multiple results in *one* ajax call)
2218 * to verify things before submitting
2219 * @since 3.13.5+
2220 ***************************************************************************************************************************************/
2221 var on_before_order_continue = function(order_continue, data, form, must_confirm, is_confirmation_page){
2222
2223
2224 /* fnVerifyOnOrderSubmit not defined, or order_continue == false already */
2225 if(typeof wppizza['fnVerifyOnOrderSubmit'] === 'undefined' || order_continue === false ){
2226 submit_order_continue(order_continue, data, form, must_confirm, is_confirmation_page);
2227 }
2228 /*
2229 3rd party plugins can check for whatever they need to check for , before an order gets submitted
2230 plugins should return bool "true" or an error message
2231 */
2232 else{
2233 var param = {};
2234 param['post_data'] = data;
2235 //param['form'] = form;
2236
2237 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'before_order_continue', 'param' : param }, ext : wppizza.extend}, function(response) {
2238
2239
2240 if(typeof response['errors'] !== 'undefined' ){
2241
2242 /*
2243 aid debugging
2244 */
2245 console.log('ERROR - OBOC');
2246 console.log(response);
2247
2248 /*
2249 if there's a function defined, run that, passing on any args set , else just alert the error
2250 */
2251 var showOrderContinueAlert = true;
2252
2253 if(typeof response['errors']['func'] !== 'undefined' && response['errors']['func'] != '' ){
2254
2255 /*
2256 define as function
2257 */
2258 var fn_error_on_order_continue = window[response['errors']['func']];
2259 /*
2260 run function
2261 */
2262 if(typeof fn_error_on_order_continue === 'function'){
2263 /*
2264 as there is a corresponding function
2265 we don't alert but let it do what it
2266 wants to do
2267 */
2268 showOrderContinueAlert = false;
2269
2270 /*
2271 the function called here really should exist!
2272 */
2273 fn_error_on_order_continue(response['errors'].args);
2274 }
2275 }
2276
2277 /*
2278 restore page visibility / re-enable submit button again
2279 (let's do this before we show the actual error alert)
2280 */
2281 wppizzaRestoreOrder();
2282
2283 /*
2284 just alert error if necessary
2285 */
2286 if(showOrderContinueAlert){
2287 //set error message
2288 var alert_txt = response['errors'].message;
2289 /* prettify alert */
2290 if(prettify_js_alerts){
2291 alert_txt = '<center>'+alert_txt.replace(/[\r\n]+/g,'<br>')+'</center>';
2292 wppizzaPrettifyJsAlerts(alert_txt, 'interrupt before continue');
2293 }
2294 /* regular alert */
2295 else{
2296 alert(alert_txt);
2297 }
2298 }
2299 }else{
2300 submit_order_continue(order_continue, data, form, must_confirm, is_confirmation_page);
2301 }
2302
2303 return;
2304 },'json');
2305 }
2306
2307 return;
2308 }
2309
2310 /**************************************************************************************************************************************
2311 * get checkout form via ajax
2312 * made globally available for other plugins to use
2313 * @since 3.13+
2314 ***************************************************************************************************************************************/
2315 wppizzaGetCheckout = function(gatewayChanged){
2316
2317 /**
2318 show loading div
2319 **/
2320 addLoadingDiv();
2321
2322 /**
2323 get form data too so we set
2324 session to not loose already entered info
2325 **/
2326 var data = $('#'+pluginSlug+'-send-order').serialize();
2327
2328 /**
2329 get the now selected gateway value
2330 when changing gateways
2331 **/
2332 if(typeof gatewayChanged !== 'undefined'){
2333 /*
2334 id of gateway we have now changed to
2335 */
2336 var gateway_selected = gatewayChanged.val();
2337 /*######################################################################
2338 # the gateway now set to compare against when submitting the order
2339 # to ensure the html is not being tampered with directly pretending
2340 # an order was prepaid/cc when in fact it's COD (etc)
2341 ######################################################################*/
2342 gateway_selected_init = wppizza_get_gateway_selected(gateway_selected);
2343
2344 }
2345 /**
2346 if we are not chaging gateways specifically
2347 just use the gateway value we have set previously
2348 **/
2349 else{
2350 var gateway_selected = gateway_selected_init;
2351 }
2352
2353 /************************************************************************************************
2354 Run the AJAX request
2355 even if we are not in fact chaging gateways by calling wppizzaGetCheckout() directly
2356 we need to run this ajax call here to replace and recalculate what needs replacing and recalculating
2357 ************************************************************************************************/
2358 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'changegateway','data': data,'gateway_selected':gateway_selected, 'isCheckout': isCheckout, 'pageReload': gateway_compat_page_reload}, ext : wppizza.extend}, function(response) {
2359
2360 /*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*
2361 # GATEWAY LEGACY / COMPATIBILITY
2362 # conditionally still reloading page entirely
2363 # on change of gateway to delivery if not yet using updated inline payment gateways
2364 *\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*/
2365 if(gateway_compat_page_reload){
2366 window.location.reload(true);
2367 is_page_reload = true;
2368 return;
2369 }
2370 /*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*
2371 # END GATEWAY LEGACY / COMPATIBILITY
2372 *\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*/
2373
2374
2375 /*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*
2376 #
2377 # PAGE / FORM / SCRIPTS / CSS -> (RE-)LOAD BY AJAX
2378 #
2379 *\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*\/*/
2380
2381
2382 /*######################################################################
2383 #
2384 # replace ORDER FORM contents
2385 #
2386 ######################################################################*/
2387 if(isCheckout && typeof response.page_markup!=='undefined'){
2388 $('.'+pluginSlug+'-order-wrap').replaceWith(response.page_markup);
2389 }
2390
2391 /*######################################################################
2392 #
2393 #
2394 # GATEWAY CSS
2395 #
2396 #
2397 ######################################################################*/
2398 /*******************************************************
2399 remove any previously dynamically loaded css again
2400 when changing gateways
2401 *******************************************************/
2402 $.each(wppizzaGatewayCss,function(idx, handle){
2403 // remove stylesheet and reference by idx/handle
2404 // (they are the same here)
2405 $('#'+idx).remove();
2406 delete wppizzaGatewayCss[idx];
2407 });
2408 /*******************************************************
2409 load any gateway css
2410 *******************************************************/
2411 if(typeof response.gwAjax['styles'] !=='undefined'){
2412 $.each(response.gwAjax['styles'],function(handle,param){
2413
2414 /*
2415 capture added css id in variable
2416 (to remove it again, if we change gateway)
2417 */
2418 var cssId = handle+'-css';
2419 wppizzaGatewayCss[cssId] = cssId;
2420
2421 /*
2422 construct css url with version no
2423 */
2424 var cssUrl = param.src;
2425 if(param.ver !='' ){
2426 cssUrl += '?ver='+param.ver;
2427 }
2428 /*
2429 add stylesheet to Dom
2430 */
2431 if(document.createStyleSheet) {
2432 try { document.createStyleSheet(cssUrl); } catch (e) { }
2433 }else {
2434 var cssElm;
2435 cssElm = document.createElement('link');
2436 cssElm.rel = 'stylesheet';
2437 cssElm.id = cssId;
2438 cssElm.href = cssUrl;
2439 cssElm.type = 'text/css';
2440 cssElm.media = 'all';
2441 /*
2442 unless specifically defined to be dependent of a specific element,
2443 we simply append to 'head'
2444 */
2445 if(typeof param.deps !== 'undefined' && param.deps != '' ){
2446 $('#'+param.deps).after(cssElm);
2447 }else{
2448 $('head').append(cssElm);
2449 }
2450 }
2451 });
2452 }
2453
2454 /*######################################################################
2455 #
2456 # UPDATING MAIN WPPIZZA JS INLINE PARAMETERS
2457 # COULD - IN THEORY - ALSO REPLACE/ADD SOME OTHER GATEWAY SPECIFIC
2458 # INLINE PARAMETERS ONE DAY IF NECESSARY
2459 #
2460 ######################################################################*/
2461 if(typeof response.gwAjax['inline'] !=='undefined'){
2462 $.each(response.gwAjax['inline'],function(handle,param){
2463
2464 //inline script id to replace
2465 var jsInlineId = ''+handle+'-js-extra';
2466 var jsScriptId = ''+handle+'-js';
2467
2468 //inline script data
2469 var jsInlineData = '/* <![CDATA[ */';
2470 jsInlineData += param.data;
2471 jsInlineData += '/* ]]> */';
2472
2473 //inline script element
2474 var jsInlineElm;
2475 jsInlineElm = document.createElement('script');
2476 jsInlineElm.type = 'text/javascript';
2477 jsInlineElm.id = jsInlineId;
2478 jsInlineElm.innerText = jsInlineData;
2479
2480 //replace current if exists,
2481 /* (this should always be the case as wppizza js really need to exist for anything to work at all !!) */
2482 if($('#'+jsInlineId+'').length > 0 ){
2483 $('#'+jsInlineId+'').replaceWith(jsInlineElm);
2484 }
2485 //else, add before wppizza src script
2486 /* (this should never actually need to be done !!!) */
2487 else{
2488 $('#'+jsScriptId+'').before(jsInlineElm);
2489 }
2490 });
2491 }
2492
2493
2494 /*######################################################################
2495 #
2496 #
2497 # LOAD GATEWAY JS SOURCE FILES (i.e URLs)
2498 # AND ASSOCIATED INLINE PARAMETERS (if any)
2499 #
2500 #
2501 ######################################################################*/
2502 /*******************************************************
2503 remove any previously dynamically loaded js
2504 src or inline again when changing gateways
2505 *******************************************************/
2506 $.each(wppizzaGatewayJs,function(idx, handle){
2507 // remove stylesheet and reference by idx/handle
2508 // (they are the same here)
2509 $('#'+idx).remove();
2510 delete wppizzaGatewayJs[idx];
2511 });
2512
2513 /*******************************************************
2514 load any gateway js
2515 *******************************************************/
2516 if(typeof response.gwAjax['scripts'] !=='undefined'){
2517
2518 $.each(response.gwAjax['scripts'],function(handle,param){
2519
2520 /******************
2521 # JS SRC SCRIPT
2522 ******************/
2523 if(typeof param.src !=='undefined' && param.src !=''){
2524
2525 /* set id's / handle */
2526 var jsId = handle+'-js';
2527 wppizzaGatewayJs[jsId] = jsId;//(capture added js id in variable to remove it again, if we change gateway)
2528
2529 /* check if theres some inline js data associated with the script and whether to add or replace*/
2530 var hasInlineData = (typeof param.data !=='undefined' && param.data !='' ) ? true : false ;
2531 var addInlineData = true;
2532 /*
2533 if there's also inline data associated with it
2534 add this first
2535 */
2536 if(hasInlineData){
2537
2538 //inline script id to add/replace
2539 var jsInlineId = ''+handle+'-js-extra';
2540
2541 //inline script data
2542 var jsInlineData = '/* <![CDATA[ */';
2543 jsInlineData += param.data;
2544 jsInlineData += '/* ]]> */';
2545
2546 //inline script element
2547 var jsInlineElm;
2548 jsInlineElm = document.createElement('script');
2549 jsInlineElm.type = 'text/javascript';
2550 jsInlineElm.id = jsInlineId;
2551 jsInlineElm.innerText = jsInlineData;
2552
2553
2554 //replace current if exists and set flag, not to add it again
2555 if($('#'+jsInlineId+'').length > 0 ){
2556 /* replace existing */
2557 $('#'+jsInlineId+'').replaceWith(jsInlineElm);
2558 /* set flag it exists already */
2559 addInlineData = false;
2560
2561 }
2562 }
2563
2564
2565
2566 //construct js url with version no
2567 var jsUrl = param.src;
2568 if(typeof param.src !=='undefined' && param.ver !='' ){
2569 jsUrl += '?ver='+param.ver;
2570 }
2571
2572 /*
2573 if for some reason it still exists, remove it here
2574 (some gateways are very particular about this)
2575 to make sure any init/load functions run
2576 */
2577 var scriptExists = document.getElementById(jsId);
2578 if (scriptExists) {
2579 $('#'+jsId).remove();
2580 }
2581
2582 //create element
2583 var jsElm;
2584 jsElm = document.createElement('script');
2585 jsElm.type = 'text/javascript';
2586 jsElm.src = jsUrl;
2587 jsElm.id = jsId;
2588 //defer if definded
2589 if(typeof param.strategy !=='undefined' && param.strategy == 'defer' ){
2590 jsElm.defer = true;
2591 }
2592 //async if defined
2593 else{
2594 jsElm.async = true;
2595 }
2596
2597 /*
2598 unless specifically defined to be dependent of a specific element,
2599 or to footer somwhere we simply append to 'head'
2600 */
2601 if(typeof param.deps === 'undefined' || param.deps == ''){
2602
2603 //add inline data - if any and previous data was not already replaced - first
2604 if(hasInlineData && addInlineData){
2605 $('head').append(jsInlineElm);
2606 }
2607 //add the js script itself
2608 $('head').append(jsElm);
2609
2610 }else{
2611
2612 //add inline data - if any and previous data was not already replaced - first
2613 if(hasInlineData && addInlineData){
2614 $('#'+param.deps+'').after(jsInlineElm);//inline vars
2615 $('#'+jsInlineId).after(jsElm);//script, after inline
2616 }else{
2617 $('#'+param.deps).after(jsElm);
2618 }
2619 }
2620
2621 }
2622 });
2623 }
2624
2625
2626
2627 /*######################################################################
2628 #
2629 # set shop open (or not) parameter - appending to
2630 # the now updated / reinitialize MAIN WPPIZZA JS INLINE PARAMETERS
2631 #
2632 ######################################################################*/
2633 wppizza.shopOpen = response.is_open;
2634
2635
2636 /*######################################################################
2637 distinctly set flag here to make sure to
2638 remove any loading divs after change
2639 ######################################################################*/
2640 is_page_reload = false;
2641
2642
2643 /*######################################################################
2644 needed to reinit and gw scripts on ajaxstop (and a couple of other refresh functions like spinner init etc) !!!
2645 ######################################################################*/
2646 run_refresh_on_ajaxstop = response.cart;
2647
2648 forceAjaxStopRefresh = true;
2649 /*######################################################################
2650 update wppizzaCartJson from hidden input vars as they will have changed when chaging gateways
2651 must run after page/cart markup is replaced
2652 ######################################################################*/
2653 set_cart_json('change-gateway');
2654
2655 return;
2656
2657 },'json');
2658
2659 return;
2660 }
2661 /**************************************************************************************************************************************
2662 * submit_order_continue
2663 * continue with order execution
2664 * if it was not interrupted by
2665 * some functions
2666 ***************************************************************************************************************************************/
2667 var submit_order_continue = function(order_continue, data, form, must_confirm, is_confirmation_page){
2668
2669 /*
2670 make sure to re-get the form wrapper here
2671 as the form might have been dynamically added and may
2672 not yet exists on page-load !!
2673 */
2674 var target_replace = $('.'+pluginSlug+'-order-wrap');/* form element */
2675
2676
2677 /*****************************************************************
2678 # [INTERRUPT EXECUTION]
2679 #
2680 # stop right here if set that way by some 3rd party plugin
2681 # and simply reload the page, but making sure we updated
2682 # whatever was already entered by the customer
2683 *****************************************************************/
2684 /*
2685 just to be save, dont just simply check
2686 for !true (though should work just as well)
2687 */
2688 if(typeof order_continue !== 'undefined' && typeof order_continue['continue'] !== 'undefined' && order_continue['continue'] === false ){
2689
2690
2691 /*
2692 is there an alert message defined ?
2693 */
2694 var alert_txt = (typeof order_continue['alert'] !== 'undefined' && order_continue['alert'] != '' ) ? order_continue['alert'] : false ;
2695
2696 /*
2697 is there an element to scroll to ?
2698 */
2699 var anchor_element = (typeof order_continue['element_id'] !== 'undefined' && order_continue['element_id'] != '' ) ? order_continue['element_id'] : false ;
2700
2701
2702 /*
2703 Regular checkout page (not confirmation page)
2704 scroll to anchor if we are on the checkout page using prettified or standard alert
2705 */
2706 if(!is_confirmation_page){
2707
2708
2709 /*
2710 alert, if any
2711 */
2712 if(alert_txt !== false){
2713
2714 /* prettify alert */
2715 if(prettify_js_alerts){
2716 alert_txt = '<center>'+alert_txt.replace(/[\r\n]+/g,'<br>')+'</center>';
2717 wppizzaPrettifyJsAlerts(alert_txt, 'invalid');
2718 }
2719 /* regular alert */
2720 else{
2721 alert(alert_txt);
2722 }
2723
2724 }
2725
2726 /*
2727 scroll to element
2728 */
2729 if(anchor_element !== false){
2730 scroll_to_anchor(anchor_element)
2731 }
2732
2733 /*
2734 remove any loading divs
2735 and re-enable button
2736 */
2737 wppizzaRestoreOrder()
2738
2739 return;
2740 }
2741
2742 /*
2743 on confirmation page
2744 reload with anchor in hash after calling standard (blocking) alert
2745 */
2746 if(is_confirmation_page){
2747
2748 /*
2749 change class name of loading div to not
2750 remove it on ajax stop before actually reloading
2751 */
2752 $('.'+pluginSlug+'-loading').addClass('wppizza-load-redirect').removeClass('wppizza-loading');
2753
2754 /*
2755 alert, if any
2756 (blocking, so people can actually read the message before being redirected
2757 */
2758 if(alert_txt !== false){
2759 //alert_txt = ''+alert_txt.replace(/[\r\n]+/gm,'\n')+'';
2760 alert(alert_txt);
2761 }
2762
2763 /*
2764 add anchor element to url if set to make
2765 scroll_to_anchor() scroll to it when the page we are redirecting
2766 to , i.e the order page , gets loaded
2767 (always remove any previously existing anchors)
2768 */
2769 var url = location.href.replace(location.hash,'')
2770 if(anchor_element !== false){
2771 url +='#'+ anchor_element;
2772 }
2773
2774 window.location.href = url;
2775 window.location.reload(true);//must force reload
2776 return;
2777 }
2778
2779 return;
2780 }
2781
2782
2783 /*****************************************************************
2784 #
2785 # [CONTINUE EXECUTION]
2786 #
2787 *****************************************************************/
2788
2789 /*******************************
2790 confirmation page enabled,
2791 show that first
2792 ********************************/
2793 if(must_confirm){
2794
2795 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'confirmorder','data':data,'isCheckout': isCheckout}, ext : wppizza.extend}, function(response) {
2796
2797 /**
2798 replace the whole div with the confirmation page form
2799 and if selected gateway has an init function, run it
2800 **/
2801 target_replace.replaceWith(response.markup).promise().done(function(elem) {
2802
2803 set_cart_json('confirmation_page');
2804
2805 wppizza_gateway_init();
2806 });
2807
2808 //scroll to a bit higher than top of form
2809 var form_top = $('#'+pluginSlug+'-send-order').offset().top;
2810 $('html, body').animate({ scrollTop: form_top - 100 }, 300);
2811
2812 run_refresh_on_ajaxstop = false;
2813
2814 removeLoadingDiv();
2815
2816 },'json');
2817 return;
2818 }
2819
2820
2821
2822 /*********************************
2823 confirmation page not enabled
2824 or already on confirmation page
2825 **********************************/
2826 if(!must_confirm){
2827
2828 /*
2829 get selected gateway
2830 */
2831 var gateway_selected = wppizza_get_gateway_selected(false);
2832
2833 /**
2834 just in case something went wrong and nothing was selected
2835 **/
2836 if(gateway_selected == '' ){
2837 console.log('No payment method selected');
2838 return false;
2839 }
2840
2841 /**
2842 if payment method that was set on page load was altered directly in the html
2843 setting another radio for example to be checked bypassing page reload - i.e hacking around somewhere
2844 to execute COD payments pretending to be cc/prepaid for example, stop right here with console log notice
2845
2846 **/
2847 if(gateway_selected != gateway_selected_init ){
2848 console.log('Payment method mismatch ['+gateway_selected+'#'+gateway_selected_init+']');
2849 return false;
2850 }
2851
2852 /*
2853 run gateways own payment function
2854
2855 check if gateway provides it's own function (mainly for overlays / inline payments)
2856 if so, submit order will be halted and script used instead
2857 should result in redirect to thank you page
2858 */
2859 var gateway_function_name = 'wppizza_'+gateway_selected+'_payment'/* the function name to look for */
2860 gateway_function_name = window[gateway_function_name];
2861 if(typeof gateway_function_name === 'function'){
2862 /*
2863 firefox does - for some reason - return event as undefined, so lets account for that
2864 (not even sure stopPropagation is needed here anyway, but lets keep it for now)
2865 */
2866 if(typeof event !== 'undefined'){
2867 event.stopPropagation();
2868 }
2869
2870 is_page_reload = true;
2871 gateway_function_name(form.id, data, event );
2872
2873 return false;
2874 }
2875
2876
2877 /*
2878 run ajax
2879 */
2880 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'submitorder','gateway_selected':gateway_selected, 'wppizza_data':data}, ext : wppizza.extend}, function(response){
2881
2882 /** if we have errors , display those , replacing page */
2883 /** if we have no errors , redirect to thank you / results */
2884 if(typeof response.error!=='undefined'){
2885 var error_id = [] ;
2886 var error_message = [] ;
2887 /* set errors to implode */
2888 $.each(response.error,function(e,v){
2889 error_id[e] = v.error_id;
2890 error_message[e] = v.error_message;
2891 });
2892
2893 /* set error div*/
2894 var error_info = '<div id="wppizza-order-error" class="wppizza-error">ERROR: '+error_id.join('|')+'<br /><br /></div>';
2895 error_info += '<div id="wppizza-order-error-details" class="wppizza-error-details"><ul><li>'+error_message.join('</li><li>')+'</li></ul></div>';
2896
2897 /* replace with error */
2898 target_replace.replaceWith(error_info);
2899
2900 /* scroll to top of page */
2901 $('html,body').animate({scrollTop:0},300);
2902
2903 /* remove loading div */
2904 removeLoadingDiv();
2905
2906 return;
2907 }
2908 /**
2909 show email output - if enabled via DEV constant
2910 **/
2911 if(typeof response.output!=='undefined'){
2912
2913 console.log(response);
2914
2915 /* replace with output */
2916 target_replace.replaceWith(response.output);
2917 return;
2918 }
2919
2920 /**
2921 if we have no errors and selected gateway
2922 needs to redirect, do this here now
2923 **/
2924 if(typeof response.gateway !=='undefined'){
2925 /* if posting form*/
2926 if(typeof response.gateway.form !=='undefined'){
2927 is_page_reload = true;/* do not clear loading div */
2928 $(response.gateway.form).appendTo('body').submit();
2929 return;
2930 }
2931 /* redirect by url */
2932 if(typeof response.gateway.redirect !=='undefined'){
2933 is_page_reload = true;/* do not clear loading div */
2934 window.location.href=response.gateway.redirect;
2935 return;
2936 }
2937 return;
2938 }
2939
2940 /**
2941 if we have no errors , and no previous redirect
2942 redirect to thank you (COD)
2943 **/
2944 if(typeof response.redirect_url!=='undefined'){
2945 is_page_reload = true;/* do not clear loading div */
2946 window.location.href=response.redirect_url;
2947 return;
2948 }
2949
2950 run_refresh_on_ajaxstop = false;
2951
2952 },'json');
2953
2954 }
2955 return;
2956 }
2957
2958 /******************************************************
2959 * [changing gateways, re-calculate handling charges
2960 * and reload - if necessary]
2961 ******************************************************/
2962 $(document).on('change', 'input[name="wppizza_gateway_selected"]:radio, select[name="wppizza_gateway_selected"]', function(e){
2963 var self = $(this);
2964 //do not try to load standard checkout via ajax if using a custom checkout implementation
2965 if(self.hasClass('wppizza-custom-checkout')){
2966 return;
2967 }
2968 wppizzaGetCheckout($(this));
2969 });
2970
2971
2972 /***********************************************
2973 *
2974 * [order form: scroll to anchor if there is one]
2975 *
2976 ***********************************************/
2977 var scroll_to_anchor = function(elm_id){
2978 if(isCheckout){
2979 /*
2980 on page load take from page url hass as id
2981 if called directly, use elm_id (must be an id)
2982 */
2983 var anchor_elm = !elm_id ? window.location.hash.substring(1) : elm_id;
2984
2985 if(anchor_elm !='' && $('#'+anchor_elm).length > 0){
2986 $('html, body').animate(
2987 {scrollTop: $('#'+anchor_elm).offset().top-100},
2988 1000);
2989 }
2990 }
2991 }
2992 scroll_to_anchor(false);
2993 /***********************************************
2994 *
2995 * [order form: toggle info "create account" / "continue as guest"]
2996 *
2997 ***********************************************/
2998 $(document).on('change', '.'+pluginSlug+'_account', function(e){
2999 $('#'+pluginSlug+'-user-register-info' ).toggle(200);
3000 });
3001
3002 /*******************************************
3003 * [user login (order form | orderhistory): show login input fields]
3004 *******************************************/
3005 $(document).on('click', '.'+pluginSlug+'-login-show, .'+pluginSlug+'-login-cancel', function(e){
3006 e.preventDefault(); e.stopPropagation();
3007 $('.'+pluginSlug+'-login-fieldset').slideToggle(300);
3008 $('.'+pluginSlug+'-login-option>a').toggle();
3009 });
3010 /*******************************************
3011 * [user login (order form | orderhistory): validation login]
3012 *******************************************/
3013 if(hasLoginForm){
3014 $('.'+pluginSlug+'-login-form > form ').validate({
3015 rules: {
3016 log: {
3017 required: true
3018 },
3019 pwd: {
3020 required: true
3021 },
3022 },
3023 errorElement : 'div',
3024 errorClass:'wppizza-validation-error error',
3025 errorPlacement: function(error, element) {
3026 /* append to parent div */
3027 var parent = element.closest('p');
3028 error.appendTo(parent);
3029 }
3030 });
3031 };
3032 /*******************************************
3033 * [user login (order form | orderhistory): logging in or error]
3034 *******************************************/
3035 $(document).on('click', '.'+pluginSlug+'-login-form #wp-submit', function(e){
3036 e.preventDefault(); e.stopPropagation();
3037 var self = $(this);
3038 var form = self.closest('form');
3039 if (form.valid()) {
3040
3041
3042 var data = form.serialize();
3043 var setWidth=self.css('width');
3044 var setHeight=self.css('height');
3045 var info_div = $('.'+pluginSlug+'-login-info');
3046 self.attr('disabled', 'true').val('').addClass('wppizza-wait').css({'width':setWidth,'height':setHeight});
3047 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'user-login','data':data}, ext : wppizza.extend}, function(response) {
3048
3049 /* successful login, -> reload */
3050 if(typeof response.error ==='undefined'){
3051 /* just reload after login */
3052 window.location.reload(true);
3053 is_page_reload = true;/* do not clear loading div */
3054 return;
3055 }
3056
3057 /* error login, -> show info for a few seconds */
3058 if(typeof response.error !=='undefined'){
3059 /* show error, fadeout, remove again */
3060 info_div.append(''+response.error+'').slideDown(250).delay(3500).slideUp(1000,function(){info_div.empty()});
3061 /* reenable button */
3062 self.removeAttr('disabled').val(response.button_value).removeClass('wppizza-wait');
3063 return;
3064 }
3065
3066 run_refresh_on_ajaxstop = false;
3067
3068 },'json');
3069
3070 }
3071 });
3072
3073 /*******************************************
3074 * [USER - orderhistory: toggle transaction/order details]
3075 *******************************************/
3076 $(document).on('click', '.'+pluginSlug+'-transaction-details-orderhistory > legend', function(e){
3077 var self = $(this);
3078 var order_details = self.closest('fieldset').find('.'+pluginSlug+'-order-details');
3079 var transaction_details = self.closest('fieldset').find('.'+pluginSlug+'-transaction-details');
3080
3081 if(order_details.is(':visible')){
3082 order_details.hide();
3083 transaction_details.fadeIn();
3084 }else{
3085 transaction_details.hide();
3086 order_details.fadeIn();
3087 }
3088 });
3089
3090 /***********************************************
3091 *
3092 * [navigation widget as dropdown - redirect on change]
3093 *
3094 ***********************************************/
3095 $(document).on('change', '.'+pluginSlug+'-dd-categories > select', function(e){
3096 e.preventDefault(); e.stopPropagation();
3097 var url = $(this).val();
3098 if(url <=0 ){/* placeholder */
3099 return;
3100 }
3101 window.location.href = url;/*make sure page gets loaded without confirm*/
3102 return;
3103 });
3104
3105
3106 /**********************************************************************************
3107 #
3108 # SHOP STATUS CHANGE
3109 # DO THINGS WHENTHE SHOP CHANGES FROM BEING OPEN TO BEING CLOSED OR VICE VERSA
3110 # @since 3.13.2
3111 #
3112 ***********************************************************************************/
3113
3114
3115 /**************************************************************************
3116 * get and pass on parameters / values to some defined fuctions
3117 * either on page load or directly from first ajax call when loading
3118 * the cart if caching function will get called whenever the status
3119 * of the shop changes (open -> close and vice versa)
3120 **************************************************************************/
3121 var shop_status_init = true;//bool true on pageload
3122 var shop_status_interval = null;//set interval to update status
3123 var shop_status = function(results, debug){
3124
3125 /*
3126 initially turned off and will only run
3127 if a plugin adds some function that needs to
3128 be called by adding it to the 'funcSetSts' array
3129 with wppizza_filter_js_set_status_functions
3130 */
3131 if(typeof wppizza['funcSetSts'] === 'undefined'){
3132 return;
3133 }
3134
3135 /*
3136 if not caching pages, run ajax on load.
3137 also called when status changes from open to closed
3138 (or reverse) at end of countdown to get current values
3139 */
3140 if(results === false){
3141
3142 jQuery.post(wppizza.ajaxurl , {action :'wppizza_json',vars:{'type':'loadcart', 'isCheckout': isCheckout}, ext : wppizza.extend}, function(results){
3143 /*
3144 seconds until status change
3145 */
3146 var seconds_remaining = results['shop_status']['next']['remaining']['sec'];
3147
3148 /*
3149 run that functions defined when status changes
3150 */
3151 exec_shop_status(shop_status_init, results, seconds_remaining, 'A=>cache OFF');
3152
3153 shop_status_init = false;
3154
3155 },'json');
3156
3157 }
3158 /*
3159 if pages caching enabled function will be run when
3160 cart loading by ajax with the relevant parameters
3161 returned already
3162 */
3163 else{
3164 /*
3165 seconds until status change
3166 */
3167 var seconds_remaining = results['shop_status']['next']['remaining']['sec'];
3168 /*
3169 run that functions defined when status changes
3170 */
3171 exec_shop_status(shop_status_init, results, seconds_remaining, 'B=>cache on');
3172
3173 shop_status_init = false;
3174
3175
3176 }
3177 }
3178 /**********************************************************
3179 if we are not caching pages, run "shop_status" on page load
3180 as opposed to it being triggered when cart is being loaded by ajax
3181 **********************************************************/
3182 if(!usingCache){
3183 shop_status(false, 'debug1');
3184 }
3185
3186 /*********************************************************
3187 run attached functions on shop status set as required
3188 *********************************************************/
3189 var exec_shop_status = function(shop_status_init, results, seconds_remaining, debug){
3190
3191 /*
3192 run on page load
3193 */
3194 on_status_set(shop_status_init, results, seconds_remaining);
3195
3196 /*
3197 1 second interval countdown to status change
3198 based on seconds_remaining until that event
3199 */
3200 shop_status_interval = setInterval(function () {
3201 /*
3202 countdown to zero
3203 to next status change
3204 */
3205 seconds_remaining--;
3206
3207 /*
3208 run any fn's and
3209 reinit countdown at zero
3210 */
3211 if(seconds_remaining == 0){
3212
3213 /*
3214 clear the interval
3215 */
3216 clearInterval(shop_status_interval);
3217
3218 /*
3219 force update cart when shop status changes (at end of countdown)
3220 but allow for a second grace for the moment
3221 */
3222 setTimeout(function(){
3223
3224 //on checkout
3225 if(typeof wppizza['isCheckout'] !== 'undefined'){
3226 wppizzaGetCheckout();
3227 }
3228 //on NON checkout where there's a cart
3229 else{
3230 wppizzaUpdateCart();
3231 }
3232
3233
3234 },1000);
3235
3236
3237 /*
3238 give it 3 secs before re-running itself
3239 it doesnt need to be that manic
3240 */
3241 setTimeout(function(){
3242 shop_status(false, 'debug2');
3243 },3000);
3244
3245
3246 return;
3247 }
3248
3249 }, 1000);
3250 }
3251
3252 /**************************************************************************************************************************
3253 * run some functions when status (open/close) is set or changes
3254 * @param - init will be true or false (tru on page load, false on update/status change
3255 * @param - json object of values
3256 * @param - integer seconds until next closing/opening
3257 * Note: depending on what needs to be executed , one might not want to execute any defined functions if
3258 * is_init == true and seconds_remaining <=3 (or so) as the defined function(s) will run again when the
3259 * "seconds_remaining" reaches 0 !! (just a suggestion)
3260 * i.e fn(a,b,c){if (c <= 3){return;} else{//do stuff }}; or some such
3261 ***************************************************************************************************************************/
3262 var on_status_set = function(is_init, values, seconds_remaining){
3263
3264 /*
3265 check if we have any functions defined that need to run
3266 and if so , do
3267 */
3268 if(typeof wppizza.funcSetSts === 'undefined'){
3269 return;
3270 }
3271 var functionArray = wppizza.funcSetSts;
3272 if(functionArray.length>0){
3273 for(i=0;i<functionArray.length;i++){
3274 var func = new Function('is_init, values, seconds_remaining', 'return ' + functionArray[i] + '(is_init, values, seconds_remaining);');
3275 //run the function
3276 func(is_init, values, seconds_remaining);
3277 }
3278 }
3279 return false;
3280 }
3281
3282 });