PluginProbe
Cooked – Recipe Management / 1.9.1
Cooked – Recipe Management v1.9.1
1.16.1 1.16.0 1.15.0 trunk 1.10.0 1.11.0 1.11.1 1.11.2 1.11.3 1.11.4 1.12.0 1.13.0 1.14.0 1.7.10 1.7.11 1.7.12 1.7.13 1.7.15.1 1.7.15.3 1.7.15.4 1.8.0 1.8.1 1.8.2 1.8.3 1.8.4 All 37 releases
cooked / assets / admin / js / cooked-functions.js

cooked-functions.js in Cooked – Recipe Management 1.9.1, at assets/admin/js/cooked-functions.js

960 lines 43.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var $_CookedConditionalTimeout = false;
2
3 (function( $ ) {
4
5 $(document).ready(function() {
6
7 var $_CookedColorPickers = $('.cooked-color-field'),
8 $_CookedSelectFields = $('#cooked_recipe_settings').find('select'),
9 $_CookedRecipeTabs = $('#cooked-recipe-tabs'),
10 $_CookedRecipeSettingsWrap = $('#cooked-settings-wrap'),
11 $_CookedRecipeSettings = $('#cooked_recipe_settings'),
12 $_CookedRecipeSettingsSubmit = $_CookedRecipeSettings.find( 'input#submit' )
13 $_CookedTooltips = $('.cooked-tooltip'),
14 $_CookedConditionals = $('.cooked-conditional-hidden'),
15 $_CookedSortable = $('.cooked-sortable'),
16 $_CookedRecipeSaveDefault = $('.cooked-layout-save-default'),
17 $_CookedShortcodeField = $('.cooked-shortcode-field'),
18 $_CookedIngredientBuilder = $('#cooked-ingredients-builder'),
19 $_CookedAutoNutritionButton = $('.cooked-auto-nutrition-button'),
20 $_CookedDirectionBuilder = $('#cooked-directions-builder'),
21 $_CookedRecipeGallery = $('#cooked-recipe-image-gallery'),
22 $_CookedNutritionFactsTab = $('#cooked-recipe-tab-content-nutrition'),
23 $_CookedSettingsPanel = $('#cooked-settings-panel'),
24 $_CookedSettingsTabs = $('#cooked-settings-tabs');
25
26 // Cooked Color Pickers
27 if ($_CookedColorPickers.length) {
28 $_CookedColorPickers.wpColorPicker();
29 }
30
31 // Cooked Sortables
32 if ($_CookedSortable.length) {
33 if ($_CookedSortable.find('.cooked-icon-drag')) {
34 $_CookedSortable.sortable({
35 stop: function(event, ui) {
36 let textarea = ui.item.find('textarea');
37 let textareaName = textarea.attr('name');
38 let fieldID = textarea.attr('id');
39
40 wp.editor.remove(fieldID);
41 wp.editor.initialize(fieldID, {
42 tinymce: {
43 wpautop: false,
44 toolbar1: 'bold,italic,underline,blockquote,strikethrough,bullist,numlist,alignleft,aligncenter,alignright,undo,redo,wp_link_advanced,unlink,fullscreen',
45 toolbar2: '',
46 toolbar3: '',
47 toolbar4: '',
48 height: 100,
49 textarea_name: textareaName,
50 plugins: 'link lists fullscreen wordpress wplink',
51 setup: function(editor) {
52 // @TODO: Inline Link editor does not work.
53 // editor.on('init', function() {
54 // if (typeof wpLink !== 'undefined') {
55 // editor.addCommand('WP_Link', function() {
56 // window.wpActiveEditor = editor.id;
57 // wpLink.open(editor.id);
58 // return false;
59 // });
60 // }
61 // });
62 }
63 },
64 quicktags: true,
65 mediaButtons: false
66 });
67 }
68 });
69 } else {
70 $_CookedSortable.sortable();
71 }
72 }
73
74 // Save as Default
75 if ($_CookedRecipeSaveDefault.length) {
76 var saveDefaultTooltip = $_CookedRecipeSaveDefault.tooltipster({
77 theme : ['tooltipster-light', 'tooltipster-sideTip-cooked'],
78 trigger : 'click',
79 animation : 'grow',
80 delay : 0,
81 speed : 200,
82 maxWidth : 275,
83 contentAsHTML : true,
84 interactive : true,
85 functionReady: function(instance, helper) {
86 $('.cooked-save-default-all').on('click', function(e) {
87 e.preventDefault();
88
89 var thisButton = $(this),
90 cooked_save_default_nonce = thisButton.data('nonce'),
91 cooked_save_default_bulk_nonce = thisButton.data('bulk-nonce'),
92 thisContainer = thisButton.parent(),
93 confirm_save = confirm(cooked_js_vars.i18n_confirm_save_default_all),
94 recipe_editor_textarea = $( "#_recipe_settings_content" ),
95 recipe_editor = tinymce.get('_recipe_settings_content');
96
97 if (recipe_editor === null) {
98 var recipe_editor_content = recipe_editor_textarea.val();
99 } else {
100 var recipe_editor_content = recipe_editor.getContent();
101 }
102
103 if (confirm_save && !thisButton.hasClass('disabled')) {
104 thisContainer.find('.button, .button-primary').addClass('disabled');
105
106 var ajax__save_default_new = $.post(
107 cooked_js_vars.ajax_url,
108 {
109 action: 'cooked_save_default',
110 'default_content': recipe_editor_content,
111 nonce: cooked_save_default_nonce
112 },
113 function(result) {
114 var ajax__save_default_all = $.post(
115 cooked_js_vars.ajax_url,
116 {
117 action: 'cooked_get_recipe_ids',
118 nonce: cooked_save_default_bulk_nonce
119 },
120 function(json_recipe_ids) {
121 thisButton.removeClass("button-primary").addClass("button");
122
123 if (json_recipe_ids) {
124 var recipe_ids = JSON.parse(json_recipe_ids),
125 total_recipes = Object.keys(recipe_ids).length;
126
127 if (total_recipes > 0) {
128 cooked_set_default_template(json_recipe_ids, total_recipes, recipe_editor_content, cooked_save_default_bulk_nonce, instance);
129 }
130 }
131 }
132 );
133 }
134 );
135 }
136 });
137
138 $('.cooked-save-default-new').on('click', function(e) {
139 e.preventDefault();
140 var thisButton = $(this),
141 nonce = thisButton.data('nonce'),
142 thisContainer = thisButton.parent(),
143 recipe_editor_textarea = $("#_recipe_settings_content"),
144 recipe_editor = tinymce.get('_recipe_settings_content');
145
146 if (recipe_editor === null) {
147 var recipe_editor_content = recipe_editor_textarea.val();
148 } else {
149 var recipe_editor_content = recipe_editor.getContent();
150 }
151
152 if (!thisButton.hasClass('disabled')) {
153 thisContainer.find('.button, .button-primary').addClass('disabled');
154 var ajax__save_default_new = $.post(
155 cooked_js_vars.ajax_url,
156 {
157 action: 'cooked_save_default',
158 'default_content': recipe_editor_content,
159 nonce: nonce
160 },
161 function(result) {
162 thisButton.text( cooked_js_vars.i18n_saved );
163 thisContainer.find('.button-primary').removeClass('disabled');
164 }
165 ).fail(function(result) {
166 //console.log( 'Error: ' + result );
167 });
168 }
169 });
170 }
171 });
172
173 $('.cooked-layout-load-default').on('click', function(e) {
174 e.preventDefault();
175
176 var thisButton = $(this),
177 thisContainer = thisButton.parent(),
178 confirm_load = confirm( cooked_js_vars.i18n_confirm_load_default ),
179 recipe_editor_textarea = $( "#_recipe_settings_content" ),
180 recipe_editor = tinymce.get('_recipe_settings_content');
181
182 if (confirm_load && !thisButton.hasClass('disabled')) {
183 thisContainer.find('.button, .button-primary').addClass('disabled');
184 var ajax__save_default_all = $.post(
185 cooked_js_vars.ajax_url,
186 {
187 action: 'cooked_load_default'
188 },
189 function (result) {
190 if ( recipe_editor === null ) {
191 recipe_editor_textarea.val( result );
192 } else {
193 recipe_editor_textarea.val( result );
194 recipe_editor.setContent( result );
195 }
196
197 thisContainer.find('.button, .button-primary').removeClass('disabled');
198 }).fail(function(result) {
199 thisContainer.find('.button, .button-primary').removeClass('disabled');
200 });
201 }
202 });
203 }
204
205 // Cooked Select Wrappers
206 if ($_CookedSelectFields.length) {
207 $_CookedSelectFields.each(function() {
208 $(this).wrap('<div class="cooked-select-wrapper" />');
209 });
210 }
211
212 // Cooked Tooltips
213 if ($_CookedTooltips.length){
214 $_CookedTooltips.tooltipster({
215 theme : ['tooltipster-light', 'tooltipster-sideTip-cooked'],
216 animation : 'grow',
217 delay : 100,
218 speed : 200,
219 maxWidth : 275,
220 contentAsHTML : true,
221 interactive : true
222 });
223 }
224
225 // Cooked Shortcode Fields
226 if ($_CookedShortcodeField.length) {
227 $_CookedShortcodeField.on('click',function(e) {
228 $(this).select();
229 });
230 }
231
232 // Conditional Fields (Recipes and Settings Pages)
233 if ($_CookedConditionals.length) {
234 var conditionalFields = [];
235 $_CookedConditionals.each(function() {
236 var thisBlock = $(this),
237 thisBlockType,
238 thisID = $(this).data('condition'),
239 thisVal = $(this).data('value'),
240 thisField = $('#'+thisID);
241
242 if (thisVal){
243 thisVal = thisVal.split(' ');
244 } else {
245 thisVal = false;
246 }
247
248 if ( thisBlock.is('li') || thisBlock.is('span') ) {
249 thisBlockType = 'inline-block';
250 } else {
251 thisBlockType = 'block';
252 }
253
254 if (thisField.is(":checkbox") && thisField.is(":checked") || thisField.is(":radio") && thisField.is(":checked")) {
255 thisBlock.css({'display':thisBlockType});
256 } else if (thisField.is(":checkbox") && !thisField.is(":checked") || thisField.is(":radio") && !thisField.is(":checked")) {
257 thisBlock.hide();
258 } else if (!thisField.is(":checkbox") && !thisVal && thisField.val() || !thisField.is(":checkbox") && thisVal && $.inArray(thisField.val(),thisVal) > -1){
259 thisBlock.css({'display':thisBlockType});
260 } else if (!thisField.is(":radio") && !thisVal && thisField.val() || !thisField.is(":radio") && thisVal && $.inArray(thisField.val(),thisVal) > -1){
261 thisBlock.css({'display':thisBlockType});
262 } else {
263 thisBlock.hide();
264 }
265
266 if ($.inArray(thisID,conditionalFields) == -1){
267 conditionalFields.push(thisID);
268 }
269
270 var conditionalsLength = conditionalFields.length;
271 for (var i = 0; i < conditionalsLength; i++) {
272 cooked_init_conditional_field(thisID);
273 }
274
275 });
276 }
277
278 // Recipe Tabs
279 if ($_CookedRecipeTabs.length) {
280 var $_CookedRecipeTab = $_CookedRecipeTabs.find('li'),
281 $_CookedRecipeTabsOffset = $_CookedRecipeTabs.offset().top - 32; // 32px for the admin bar
282
283 $(window).on('load scroll',function() {
284 var scroll = $(window).scrollTop();
285 if (scroll >= $_CookedRecipeTabsOffset) {
286 $_CookedRecipeSettings.addClass("stuck");
287 } else {
288 $_CookedRecipeSettings.removeClass("stuck");
289 }
290 });
291
292 $_CookedRecipeTab.on('click', function(e) {
293 e.preventDefault();
294 $_CookedRecipeTab.removeClass('active');
295 window.scrollTo(0, 0);
296
297 var thisTab = $(this),
298 thisTabID = thisTab.attr('id').split('cooked-recipe-tab-')[1];
299
300 $('.cooked-recipe-tab-content').hide();
301 var $newTab = $('#cooked-recipe-tab-content-' + thisTabID);
302 $newTab.show();
303
304 thisTab.addClass('active');
305 });
306 }
307
308 // Checkboxes
309 if ( $_CookedSettingsTabs.length || $_CookedRecipeTabs.length ) {
310 var greenSwitches = Array.prototype.slice.call(document.querySelectorAll('.cooked-switch'));
311 var redSwitches = Array.prototype.slice.call(document.querySelectorAll('.cooked-switch-red'));
312 var yellowSwitches = Array.prototype.slice.call(document.querySelectorAll('.cooked-switch-yellow'));
313 var graySwitches = Array.prototype.slice.call(document.querySelectorAll('.cooked-switch-gray'));
314
315 greenSwitches.forEach(function( html ) {
316 var greenSwitchery = new Switchery( html, { color: '#00c086', size: 'small' } );
317 });
318
319 redSwitches.forEach(function( html ) {
320 var redSwitchery = new Switchery( html, { color: '#d44d1f', size: 'small' } );
321 });
322
323 yellowSwitches.forEach(function( html ) {
324 var yellowSwitchery = new Switchery( html, { color: '#ffad18', size: 'small' } );
325 });
326
327 graySwitches.forEach(function( html ) {
328 var graySwitchery = new Switchery( html, { color: '#aaaaaa', size: 'small' } );
329 });
330 }
331
332 // Settings Tabs
333 if ($_CookedSettingsTabs.length) {
334 var CookedSettingsTabHash = window.location.hash;
335 var $_CookedSettingsTab = $_CookedSettingsTabs.find('li'),
336 $_CookedSettingsTabOffset = $_CookedSettingsTabs.offset().top - 32; // 32px for the admin bar
337
338 $(window).on('load scroll',function() {
339 var scroll = $(window).scrollTop();
340 if (scroll >= $_CookedSettingsTabOffset) {
341 $_CookedSettingsPanel.addClass("stuck");
342 $("#cooked-settings-wrap").addClass("is-stuck");
343 } else {
344 $_CookedSettingsPanel.removeClass("stuck");
345 $("#cooked-settings-wrap").removeClass("is-stuck");
346 }
347 });
348
349 if ( CookedSettingsTabHash ) {
350 var activeTab = CookedSettingsTabHash;
351 activeTab = activeTab.split('#');
352 activeTab = activeTab[1];
353 $_CookedSettingsTabs.find('li').removeClass('active');
354 $_CookedSettingsTabs.find('a[href="'+CookedSettingsTabHash+'"]').parent().addClass('active');
355 if ( activeTab == 'migration' ) {
356 $_CookedRecipeSettingsSubmit.hide();
357 } else {
358 $_CookedRecipeSettingsSubmit.show();
359 }
360 $('.cooked-settings-tab-content').hide();
361 $('#cooked-settings-tab-content-'+activeTab).show();
362 } else {
363 var activeTab = $_CookedSettingsTabs.find('.active > a').attr('href');
364 activeTab = activeTab.split('#');
365 activeTab = activeTab[1];
366 $('.cooked-settings-tab-content').hide();
367 $('#cooked-settings-tab-content-'+activeTab).show();
368 }
369
370 $_CookedSettingsTab.on('click',function(e) {
371 $('.tab-content').hide();
372 var thisTab = $(this).find('a');
373 $_CookedSettingsTabs.find('li').removeClass('active');
374
375 $(this).addClass('active');
376 var activeTab = thisTab.attr('href');
377 activeTab = activeTab.split('#');
378 activeTab = activeTab[1];
379
380 if ( activeTab == 'migration' ) {
381 $_CookedRecipeSettingsSubmit.hide();
382 } else {
383 $_CookedRecipeSettingsSubmit.show();
384 }
385
386 $('.cooked-settings-tab-content').hide();
387 $('#cooked-settings-tab-content-'+activeTab).show();
388
389 if ( $('#cooked-settings-panel').hasClass('stuck') ) {
390 window.scrollTo(0,130);
391 } else {
392 window.scrollTo(0,0);
393 }
394 });
395 }
396
397 if ($_CookedIngredientBuilder.length) {
398 cooked_reset_ingredient_builder();
399
400 $_CookedIngredientBuilder.on('keydown', 'input[data-ingredient-part="name"]', function(e) {
401 if ( e.keyCode === 9 || e.keyCode === 13 ) {
402 if ( $(this).parents('.cooked-ingredient-block').is(':last-child') ) {
403 e.preventDefault();
404 $('#cooked-recipe-tab-content-ingredients').find('.cooked-add-ingredient-button').trigger('click');
405 $_CookedIngredientBuilder.find('.cooked-ingredient-block:last-child input[data-ingredient-part="amount"]').focus();
406 }
407 } else {
408 return;
409 }
410 });
411
412 if ($_CookedAutoNutritionButton.length) {
413 $_CookedIngredientBuilder.on('change', 'input[data-ingredient-part="name"]', function(e) {
414 var ingredient_name_value = false;
415
416 $_CookedIngredientBuilder.find('input[data-ingredient-part="name"]').each(function() {
417 if ($(this).val() != '') {
418 ingredient_name_value = true;
419 return false; // Break the loop
420 }
421 });
422
423 if (ingredient_name_value) {
424 $_CookedAutoNutritionButton.prop('disabled', false);
425 } else {
426 $_CookedAutoNutritionButton.prop('disabled', true);
427 }
428 });
429 }
430
431 $_CookedIngredientBuilder.on('keyup', 'input[data-ingredient-part="url"]', function(e) {
432 var thisVal = $(this).val(),
433 parentBlock = $(this).parents('.recipe-setting-block');
434 if (thisVal){
435 parentBlock.addClass('cooked-has-url');
436 } else {
437 parentBlock.removeClass('cooked-has-url');
438 }
439 });
440
441 $_CookedIngredientBuilder.parent().on('click', '.cooked-add-ingredient-button', function(e) {
442 e.preventDefault();
443 var clonedIngredientTemplate = $_CookedIngredientBuilder.parent().find('.cooked-ingredient-template').clone().removeClass('cooked-template cooked-ingredient-template').addClass('cooked-ingredient-block');
444 $_CookedIngredientBuilder.append(clonedIngredientTemplate);
445 cooked_reset_ingredient_builder();
446 });
447
448 $_CookedIngredientBuilder.parent().on('click','.cooked-add-heading-button',function(e) {
449 e.preventDefault();
450 var clonedHeadingTemplate = $_CookedIngredientBuilder.parent().find('.cooked-heading-template').clone().removeClass('cooked-template cooked-heading-template').addClass('cooked-ingredient-block cooked-ingredient-heading');
451 $_CookedIngredientBuilder.append(clonedHeadingTemplate);
452 cooked_reset_ingredient_builder();
453 });
454
455 $_CookedIngredientBuilder.parent().on('click','.cooked-delete-ingredient',function(e) {
456 e.preventDefault();
457 $(this).parent().remove();
458 cooked_reset_ingredient_builder();
459 });
460 }
461
462 if ($_CookedDirectionBuilder.length) {
463 cooked_reset_direction_builder();
464
465 $_CookedDirectionBuilder.parent().on('click', '.cooked-add-direction-button', function(e) {
466 e.preventDefault();
467 var clonedDirectionTemplate = $_CookedDirectionBuilder.parent().find('.cooked-direction-template').clone().removeClass('cooked-template cooked-direction-template').addClass('cooked-direction-block');
468 $_CookedDirectionBuilder.append(clonedDirectionTemplate);
469 cooked_reset_direction_builder();
470 });
471
472 $_CookedDirectionBuilder.parent().on('click', '.cooked-add-heading-button', function(e) {
473 e.preventDefault();
474 var clonedHeadingTemplate = $_CookedDirectionBuilder.parent().find('.cooked-heading-template').clone().removeClass('cooked-template cooked-heading-template').addClass('cooked-direction-block cooked-direction-heading');
475 $_CookedDirectionBuilder.append(clonedHeadingTemplate);
476 cooked_reset_direction_builder();
477 });
478
479 $_CookedDirectionBuilder.parent().on('click', '.cooked-delete-direction', function(e) {
480 e.preventDefault();
481 $(this).parent().remove();
482 cooked_reset_direction_builder();
483 });
484
485 $_CookedDirectionBuilder.parent().on('click', '.remove-image-button', function(e) {
486 e.preventDefault();
487 $(this).parent().removeClass('cooked-has-image');
488 $(this).parent().find('img').remove();
489 $(this).parent().find('input[data-direction-part="image"]').val('');
490 cooked_reset_direction_builder();
491 });
492
493 // Instantiates the variable that holds the media library frame.
494 var direction_image_frame, directionID;
495
496 $('body').on('click', '.cooked-direction-img-placeholder, .cooked-direction-img', function(e) {
497 e.preventDefault();
498 var thisButton = $(this).parent().find('.direction-image-button');
499 thisButton.trigger('click');
500 });
501
502 // Runs when the image button is clicked.
503 $('body').on('click', '.direction-image-button',function(e) {
504
505 var thisButton = $(this);
506 directionID = thisButton.data('id');
507
508 e.preventDefault();
509
510 // If the frame already exists, re-open it.
511 if ( direction_image_frame ) {
512 direction_image_frame.open();
513 return;
514 }
515
516 // Sets up the media library frame
517 direction_image_frame = wp.media.frames.direction_image_frame = wp.media({
518 title: cooked_js_vars.i18n_image_title,
519 button: { text: cooked_js_vars.i18n_image_button },
520 library: { type: 'image' }
521 });
522
523 // Runs when an image is selected.
524 direction_image_frame.on('select', function() {
525 // Grabs the attachment selection and creates a JSON representation of the model.
526 var media_attachment = direction_image_frame.state().get('selection').first().toJSON();
527
528 // Sends the attachment URL to our custom image input field.
529 $('#direction-'+directionID+'-image-src').attr('src',media_attachment.sizes.thumbnail.url).parent().addClass('cooked-has-image');
530 $('input[name="_recipe_settings[directions]['+directionID+'][image]"]').val( media_attachment.id );
531 $('.direction-image-button[data-id="'+directionID+'"]').prop( 'value', cooked_js_vars.i18n_image_change );
532 });
533
534 // Opens the media library frame.
535 direction_image_frame.open();
536 });
537 }
538
539 if ( $_CookedRecipeGallery.length ) {
540
541 var gallery_images_frame;
542 cooked_init_gallery_sorting();
543
544 // Runs when the Add Images button is clicked in the Gallery tab.
545 $('body').on('click','.cooked-gallery-add-button', function(e) {
546 var thisButton = $(this);
547 e.preventDefault();
548
549 // If the frame already exists, re-open it.
550 if ( gallery_images_frame ) {
551 gallery_images_frame.open();
552 return;
553 }
554
555 // Sets up the media library frame
556 gallery_images_frame = wp.media.frames.gallery_images_frame = wp.media({
557 title: cooked_js_vars.i18n_gallery_image_title,
558 button: { text: cooked_js_vars.i18n_gallery_image_title },
559 library: { type: 'image' },
560 multiple: true
561 });
562
563 // Runs when an image is selected.
564 gallery_images_frame.on('select', function() {
565 // Grabs the attachment selection and creates a JSON representation of the model.
566 var media_attachments = gallery_images_frame.state().get('selection').toJSON();
567 var thisThumbnail;
568
569 for (var media_key in media_attachments) {
570 if (!media_attachments.hasOwnProperty(media_key)) continue;
571 var media_attachment = media_attachments[media_key];
572 thisThumbnail = media_attachment.sizes.thumbnail.url;
573 $('#cooked-recipe-image-gallery').append( '<div data-attachment-id="' + media_attachment.id + '" class="cooked-recipe-gallery-item"><img src="' + thisThumbnail + '" /><span class="cooked-gallery-item-title">' + media_attachment.title + '</span><input type="hidden" name="_recipe_settings[gallery][items][]" value="' + media_attachment.id + '" /><a href="#" data-attachment-id="' + media_attachment.id + '" class="cooked-gallery-edit-button"><i class="cooked-icon cooked-icon-pencil"></i></a><a href="#" class="remove-image-button"><i class="cooked-icon cooked-icon-times"></i></a></div>' );
574 }
575
576 cooked_init_gallery_sorting();
577 });
578
579 // Opens the media library frame.
580 gallery_images_frame.open();
581 });
582
583 $('body').on('click','.cooked-recipe-gallery-item img', function(e) {
584 e.preventDefault();
585 var thisButton = $(this).parent().find('.cooked-gallery-edit-button');
586 thisButton.trigger('click');
587 });
588
589 $('body').on('click','.cooked-gallery-edit-button', function(e) {
590 var thisButton = $(this),
591 attachment_id = thisButton.data('attachment-id');
592
593 e.preventDefault();
594
595 // Sets up the media library frame
596 var image_edit_frame = wp.media.frames.gallery_images_frame = wp.media({
597 title: cooked_js_vars.i18n_edit_image_title,
598 button: { text: cooked_js_vars.i18n_edit_image_button },
599 library: { type: 'image' },
600 multiple: false
601 });
602
603 image_edit_frame.on('open',function() {
604 var selection = image_edit_frame.state().get('selection');
605 attachment = wp.media.attachment(attachment_id);
606 attachment.fetch();
607 selection.add( attachment ? [ attachment ] : [] );
608 });
609
610 // Opens the media library frame.
611 image_edit_frame.open();
612
613 // Runs when an image is selected.
614 image_edit_frame.on('select', function() {
615 // Grabs the attachment selection and creates a JSON representation of the model.
616 var media_attachments = image_edit_frame.state().get('selection').toJSON();
617 var thisThumbnail;
618
619 for (var media_key in media_attachments) {
620 if (!media_attachments.hasOwnProperty(media_key)) continue;
621 var media_attachment = media_attachments[media_key];
622 thisThumbnail = media_attachment.sizes.thumbnail.url;
623 thisButton.parent().replaceWith( '<div data-attachment-id="' + media_attachment.id + '" class="cooked-recipe-gallery-item"><img src="' + thisThumbnail + '" /><span class="cooked-gallery-item-title">' + media_attachment.title + '</span><input type="hidden" name="_recipe_settings[gallery][items][]" value="' + media_attachment.id + '" /><a href="#" data-attachment-id="' + media_attachment.id + '" class="cooked-gallery-edit-button"><i class="cooked-icon cooked-icon-pencil"></i></a><a href="#" class="remove-image-button"><i class="cooked-icon cooked-icon-times"></i></a></div>' );
624 }
625
626 cooked_init_gallery_sorting();
627 });
628 });
629
630 $_CookedRecipeGallery.on('click', '.remove-image-button', function(e) {
631 var thisButton = $(this);
632 directionID = thisButton.data('id');
633 e.preventDefault();
634
635 if ( directionID ) {
636 $('#direction-'+directionID+'-image-src').parent().removeClass('cooked-has-image').prop('src',false);
637 $('input[name="_recipe_settings[directions]['+directionID+'][image]"]').val('');
638 $('.direction-image-button[data-id="'+directionID+'"]').prop( 'value',cooked_js_vars.i18n_image_title );
639 } else {
640 thisButton.parent().remove();
641 }
642 });
643 }
644
645 if ( $_CookedNutritionFactsTab.length ) {
646 init_nutrition_facts( $_CookedNutritionFactsTab );
647
648 $_CookedNutritionFactsTab.on('keyup', 'input', function(e) {
649 init_nutrition_facts( $_CookedNutritionFactsTab );
650 });
651 }
652
653 /**** Time Pickers ****/
654 if ( $('#cooked-prep-time').length ) {
655 $( '#cooked-prep-time,#cooked-cook-time' ).on('change', function() {
656 var prepTimeValue = parseInt( $( '#cooked-prep-time' ).val() ),
657 cookTimeValue = parseInt( $( '#cooked-cook-time' ).val() );
658 cooked_updateTotalTimeValue( prepTimeValue, cookTimeValue );
659 });
660 }
661
662 });
663
664 })( jQuery );
665
666 var cooked_recipe_update_counter = 0;
667
668 function cooked_set_default_template(recipe_ids, total_recipes, content, nonce, instance) {
669 var temp_counter = 0,
670 total_counter = 0,
671 progress_percent = 0;
672
673 if (total_recipes > 0) {
674 var progress = jQuery('#cooked-template-progress');
675 var progress_bar = progress.find('.cooked-progress-bar');
676 var progress_text = jQuery('#cooked-template-progress-text');
677
678 if (!progress.hasClass('cooked-active')) {
679 progress.addClass('cooked-active');
680 progress_text.addClass('cooked-active');
681 progress_bar.css({ "width" : "0%" });
682 instance.reposition();
683 }
684
685 var ajax__bulk_save_default_template = jQuery.post(
686 cooked_js_vars.ajax_url,
687 {
688 action: 'cooked_save_default_bulk',
689 recipe_ids: recipe_ids,
690 default_content: content,
691 nonce: nonce
692 },
693 function(new_recipe_ids) {
694 if (new_recipe_ids && new_recipe_ids != 'false' && new_recipe_ids != false) {
695 var leftover_recipe_ids = JSON.parse(new_recipe_ids),
696 leftover_recipes = Object.keys(leftover_recipe_ids).length;
697
698 cooked_recipe_update_counter = total_recipes - leftover_recipes;
699
700 progress_percent = Math.round((cooked_recipe_update_counter / total_recipes ) * 100);
701 progress_bar.css({ "width" : progress_percent + "%" });
702 progress_text.text(cooked_recipe_update_counter + " / " + total_recipes);
703 cooked_set_default_template(new_recipe_ids, total_recipes, content, nonce, instance);
704 } else {
705 jQuery('.cooked-save-default-all').text(cooked_js_vars.i18n_applied);
706 progress_bar.css({ "width" : "100%" });
707 progress.removeClass('cooked-active');
708 progress_text.removeClass('cooked-active').text("");
709
710 instance.reposition();
711 }
712 }
713 );
714 };
715 }
716
717 function cooked_updateTotalTimeValue( prepTime, cookTime ) {
718 var totalTimeInput = jQuery( '#cooked-total-time' ),
719 totalTime = prepTime + cookTime;
720
721 totalTimeInput.val( totalTime );
722 }
723
724 // Reset the Gallery Builder
725 // Assign a value to the hidden input field.
726 // Init the jQuery UI Sort
727 function cooked_init_gallery_sorting() {
728 jQuery('#cooked-recipe-image-gallery').sortable();
729 }
730
731 function init_nutrition_facts( nutritionTab ) {
732 nutritionTab.find('input').each(function() {
733 var thisInput = jQuery(this),
734 thisID = thisInput.attr('id'),
735 thisVal = thisInput.val(),
736 hasPercent = jQuery('.cooked-nut-percent[data-labeltype="' + thisID + '"]').length;
737
738 if ( jQuery('.cooked-nut-label[data-labeltype="' + thisID + '"]').length ) {
739 if ( thisVal ) {
740 jQuery('.cooked-nut-label[data-labeltype="' + thisID + '"]').text( thisVal );
741 jQuery('.cooked-nut-label[data-labeltype="' + thisID + '"]').parents('li').eq(0).show();
742 jQuery('.cooked-nut-label[data-labeltype="' + thisID + '"]').parents('p').eq(0).show();
743 if ( hasPercent ) {
744 var thisPercentElem = jQuery('.cooked-nut-percent[data-labeltype="' + thisID + '"]'),
745 pvd = thisPercentElem.data('pdv');
746 if ( pvd ) {
747 thisPercent = Math.ceil( ( thisVal / pvd ) * 100 );
748 thisPercentElem.text( thisPercent );
749 }
750 }
751 } else {
752 jQuery('.cooked-nut-label[data-labeltype="' + thisID + '"]').text( '___' );
753 jQuery('.cooked-nut-label[data-labeltype="' + thisID + '"]').parents('li').eq(0).hide();
754 jQuery('.cooked-nut-label[data-labeltype="' + thisID + '"]').parents('p').eq(0).hide();
755 }
756 }
757 });
758 }
759
760 // Reset Time Picker Settings & Names
761 function cooked_reset_ingredient_builder() {
762 var ingredientBlocks = jQuery('.cooked-ingredient-block'),
763 total_ingredients_blocks = 0,
764 total_blocks = 0,
765 ingredientNameValue = false;
766
767 if (ingredientBlocks.length > 0) {
768 ingredientBlocks.each(function() {
769 var randomKeyForInterval = cooked_get_random_int(10000000, 99999999);
770 total_blocks++;
771
772 // Set the input "name" values.
773 var $_this = jQuery(this);
774
775 if (!$_this.hasClass('cooked-ingredient-heading')) {
776 total_ingredients_blocks++;
777 }
778
779 $_this.find("[data-ingredient-part]").each(function() {
780 var thisField = jQuery(this);
781 if (thisField.attr('name') == '') {
782 var ingredientPartName = thisField.data('ingredient-part');
783 thisField.attr('name', '_recipe_settings[ingredients][' + randomKeyForInterval + '][' + ingredientPartName + ']');
784 }
785 });
786 });
787
788 if ($_CookedAutoNutritionButton.length) {
789 jQuery('input[data-ingredient-part="name"]').each(function() {
790 if (jQuery(this).val() != '') {
791 ingredientNameValue = true;
792 return false; // Break the loop
793 }
794 });
795 }
796 }
797
798 if (total_ingredients_blocks) {
799 jQuery('.cooked-ingredient-headers').show();
800 if ($_CookedAutoNutritionButton.length) {
801 if (ingredientNameValue) {
802 $_CookedAutoNutritionButton.prop('disabled', false);
803 } else {
804 $_CookedAutoNutritionButton.prop('disabled', true);
805 }
806 }
807 } else {
808 jQuery('.cooked-ingredient-headers').hide();
809 if ($_CookedAutoNutritionButton.length) $_CookedAutoNutritionButton.prop('disabled', true);
810 }
811
812 if (total_blocks) {
813 jQuery('#cooked-ingredients-builder').css( { 'margin-bottom':'20px' } );
814 } else {
815 jQuery('#cooked-ingredients-builder').css( { 'margin-bottom':'12px' } );
816 }
817 }
818
819 // Reset Time Picker Settings & Names
820 function cooked_reset_direction_builder() {
821 var directionBlocks = jQuery('.cooked-direction-block'),
822 total_blocks = 0;
823
824 directionBlocks.each(function() {
825 var randomKeyForInterval = cooked_get_random_int(10000000, 99999999);
826 total_blocks++;
827
828 // Set the input "name" values.
829 var $_this = jQuery(this);
830
831 $_this.find("[data-direction-part]").each(function() {
832 var thisField = jQuery(this);
833 var directionPartName = thisField.data('direction-part');
834
835 if ( thisField.attr('name') == '') {
836 thisField.attr( 'name', '_recipe_settings[directions][' + randomKeyForInterval + '][' + directionPartName + ']' );
837 }
838
839 if ( thisField.attr('data-id') == '') {
840 thisField.attr( 'data-id', randomKeyForInterval );
841 }
842
843 let theId = thisField.attr('id');
844
845 if ( theId == '' || theId == undefined ) {
846 directionPartName = directionPartName.replace( '_', '-' );
847 var fieldID = 'direction-' + randomKeyForInterval + '-' + directionPartName;
848 thisField.attr('id', fieldID);
849
850 if (directionPartName === 'content' && thisField.is('textarea') && cooked_js_vars.wp_editor_roles_allowed) {
851 // Init the WordPress Editor.
852 wp.editor.initialize(fieldID, {
853 tinymce: {
854 wpautop: false,
855 toolbar1: 'bold,italic,underline,blockquote,strikethrough,bullist,numlist,alignleft,aligncenter,alignright,undo,redo,wp_link_advanced,unlink,fullscreen',
856 toolbar2: '',
857 toolbar3: '',
858 toolbar4: '',
859 height: 100,
860 textarea_name: '_recipe_settings[directions][' + randomKeyForInterval + '][' + directionPartName + ']',
861 plugins: 'link lists fullscreen wordpress wplink',
862 setup: function(editor) {
863 // @TODO: Inline Link editor does not work.
864 // editor.on('init', function() {
865 // if (typeof wpLink !== 'undefined') {
866 // editor.addCommand('WP_Link', function() {
867 // window.wpActiveEditor = editor.id;
868 // wpLink.open(editor.id);
869 // return false;
870 // });
871 // }
872 // });
873 }
874 },
875 quicktags: true,
876 mediaButtons: false
877 });
878 }
879 }
880 });
881 });
882
883 if ( total_blocks ) {
884 jQuery('#cooked-directions-builder').css( { 'margin-bottom': '20px' } );
885 } else {
886 jQuery('#cooked-directions-builder').css( { 'margin-bottom': '12px' } );
887 }
888 }
889
890 // Get random integer for sortable lists (ingredients and directions)
891 function cooked_get_random_int(min, max) {
892 return Math.floor(Math.random() * (max - min)) + min;
893 }
894
895 // Check if value is an integer (for amount field in Ingredients Builder)
896 function cooked_is_int(val) {
897 if (Math.floor(val) == val && $.isNumeric(val)) {
898 return true;
899 } else {
900 return false;
901 }
902 }
903
904 // Cooked Conditional Fields Function
905 function cooked_init_conditional_field(thisID) {
906 var thisField = jQuery('#' + thisID);
907
908 if (thisField.is(':radio')) {
909 jQuery('body').find('input:radio').on('change', function() {
910 if (!thisField.is(':checked')) {
911 jQuery('body').find("[data-condition='" + thisID + "']").each(function() {
912 jQuery(this).hide();
913 });
914 }
915 });
916 }
917
918 thisField.on('change', function() {
919 jQuery('#cooked_recipe_settings').addClass('cooked-loading');
920
921 window.clearTimeout($_CookedConditionalTimeout);
922
923 $_CookedConditionalTimeout = window.setTimeout(function() {
924 jQuery('body').find("[data-condition='" + thisID + "']").each(function() {
925 var thisBlock = jQuery(this),
926 thisBlockType;
927
928 if ( thisBlock.is('li') || thisBlock.is('span') ) {
929 thisBlockType = 'inline-block';
930 } else {
931 thisBlockType = 'block';
932 }
933
934 var thisVal = thisBlock.data('value');
935
936 if (thisVal) {
937 thisVal = thisVal.split(' ');
938 } else {
939 thisVal = false;
940 }
941
942 if (thisField.is(":checkbox") && thisField.is(":checked") || thisField.is(":radio") && thisField.is(":checked")) {
943 thisBlock.css({'display':thisBlockType});
944 } else if (thisField.is(":checkbox") && !thisField.is(":checked")) {
945 thisBlock.hide();
946 } else if (!thisField.is(":checkbox") && !thisVal && thisField.val() || !thisField.is(":checkbox") && thisVal && jQuery.inArray(thisField.val(),thisVal) > -1) {
947 thisBlock.css({'display':thisBlockType});
948 } else if (!thisField.is(":radio") && !thisVal && thisField.val() || !thisField.is(":radio") && thisVal && jQuery.inArray(thisField.val(),thisVal) > -1) {
949 thisBlock.css({'display':thisBlockType});
950 } else {
951 thisBlock.hide();
952 }
953 });
954
955 jQuery('#cooked_recipe_settings').removeClass('cooked-loading');
956
957 }, 25);
958 });
959 }
960