· 4 years ago · Apr 05, 2021, 03:30 PM
1// selectize for category and location selects
2$(function(){
3
4 // create 1st category select
5 category_select = createCategorySelect();
6 // remove d-none class
7 $('#category-chained .select-category[data-level="0"]').parent('div').removeClass('d-none');
8
9 // load options for 1st category select
10 category_select.load(function(callback) {
11 $.ajax({
12 url: $('#category-chained').data('apiurl'),
13 type: 'GET',
14 data: {
15 "id_category_parent": 1,
16 "sort": 'order',
17 },
18 success: function(results) {
19 callback(results.categories);
20 },
21 error: function() {
22 callback();
23 }
24 });
25 });
26 // advertisement location is enabled?
27 if ($('#location-chained').length ) {
28
29 // create 1st location select
30 location_select = createLocationSelect();
31 // remove d-none class
32 $('#location-chained .select-location[data-level="0"]').parent('div').removeClass('d-none');
33
34 // load options for 1st location select
35 location_select.load(function(callback) {
36 $.ajax({
37 url: $('#location-chained').data('apiurl'),
38 type: 'GET',
39 data: {
40 "id_location_parent": 1,
41 "sort": 'order',
42 },
43 success: function(results) {
44 callback(results.locations);
45 if (results.locations.length === 0)
46 $('#location-chained').closest('.form-group').hide();
47 },
48 error: function() {
49 callback();
50 }
51 });
52 });
53 }
54
55 // show custom fields
56 if ($('#category-selected').val().length > 0) {
57 $.ajax({
58 url: $('#category-chained').data('apiurl') + '/' + $('#category-selected').val(),
59 success: function(results) {
60 createCustomFieldsByCategory(results.category.customfields);
61 }
62 });
63 }
64 else {
65 $.ajax({
66 url: $('#category-chained').data('apiurl') + '/' + 1,
67 success: function(results) {
68 createCustomFieldsByCategory(results.category.customfields);
69 }
70 });
71 }
72});
73
74function createCategorySelect () {
75
76 // count how many category selects we have rendered
77 num_category_select = $('#category-chained .select-category[data-level]').length;
78
79 // clone category select from template
80 $('#select-category-template').clone().attr('id', '').insertBefore($('#select-category-template')).find('select').attr('data-level', num_category_select);
81
82 // initialize selectize on created category select
83 category_select = $('.select-category[data-level="'+ num_category_select +'"]').selectize({
84 valueField: 'id_category',
85 labelField: 'translate_name',
86 searchField: 'translate_name',
87 onChange: function (value) {
88
89 if (!value.length) return;
90
91 // get current category level
92 current_level = $('#category-chained .option[data-value="'+ value +'"]').closest('.selectize-control').prev().data('level');
93
94 // is allowed to post on selected category?
95 if ( current_level > 0 || (current_level == 0 && $('#category-chained').is('[data-isparent]')))
96 {
97 // update #category-selected input value
98 $('#category-selected').attr('value', value);
99
100 //get category price
101 $.ajax({
102 url: $('#category-chained').data('apiurl') + '/' + value,
103 success: function(results) {
104 if (decodeHtml(results.category.price) != $('#category-chained').data('price0')) {
105 price_txt = $('#paid-category .help-block').data('title').replace(/%s/g, results.category.name).replace(/%d/g, results.category.price);
106 $('#paid-category').removeClass('d-none').find('.help-block span').text(price_txt);
107 }
108 else {
109 $('#paid-category').addClass('d-none');
110 }
111 // show custom fields for this category
112 createCustomFieldsByCategory(results.category.customfields);
113 }
114 });
115 }
116 else
117 {
118 // set empty value
119 $('#category-selected').attr('value', '');
120 $('#paid-category').addClass('d-none');
121 // show custom fields
122 $.ajax({
123 url: $('#category-chained').data('apiurl') + '/' + 1,
124 success: function(results) {
125 createCustomFieldsByCategory(results.category.customfields);
126 }
127 });
128 }
129
130 // get current category level
131 current_level = $('#category-chained .option[data-value="'+ value +'"]').closest('.selectize-control').prev().data('level');
132
133 destroyCategoryChildSelect(current_level);
134
135 // create category select
136 category_select = createCategorySelect();
137
138 // load options for category select
139 category_select.load(function (callback) {
140 $.ajax({
141 url: $('#category-chained').data('apiurl'),
142 data: {
143 "id_category_parent": value,
144 "sort": 'order',
145 },
146 type: 'GET',
147 success: function (results) {
148 if (results.categories.length > 0)
149 {
150 callback(results.categories);
151 $('#category-chained .select-category[data-level="' + (current_level + 1) + '"]').parent('div').removeClass('d-none');
152 }
153 else
154 {
155 destroyCategoryChildSelect(current_level);
156 }
157 },
158 error: function () {
159 callback();
160 }
161 });
162 });
163 }
164 });
165
166 // return selectize control
167 return category_select[0].selectize;
168}
169
170function createLocationSelect () {
171
172 // count how many location selects we have rendered
173 num_location_select = $('#location-chained .select-location[data-level]').length;
174
175 // clone location select from template
176 $('#select-location-template').clone().attr('id', '').insertBefore($('#select-location-template')).find('select').attr('data-level', num_location_select);
177
178 // initialize selectize on created location select
179 location_select = $('.select-location[data-level="'+ num_location_select +'"]').selectize({
180 valueField: 'id_location',
181 labelField: 'translate_name',
182 searchField: 'translate_name',
183 onChange: function (value) {
184
185 if (!value.length) return;
186
187 // update #location-selected input value
188 $('#location-selected').attr('value', value);
189
190 // get current location level
191 current_level = $('#location-chained .option[data-value="'+ value +'"]').closest('.selectize-control').prev().data('level');
192
193 destroyLocationChildSelect(current_level);
194
195 // create location select
196 location_select = createLocationSelect();
197
198 // load options for location select
199 location_select.load(function (callback) {
200 $.ajax({
201 url: $('#location-chained').data('apiurl'),
202 data: {
203 "id_location_parent": value,
204 "sort": 'order',
205 },
206 type: 'GET',
207 success: function (results) {
208 if (results.locations.length > 0)
209 {
210 callback(results.locations);
211 $('#location-chained .select-location[data-level="' + (current_level + 1) + '"]').parent('div').removeClass('d-none');
212 }
213 else
214 {
215 destroyLocationChildSelect(current_level);
216 }
217 },
218 error: function () {
219 callback();
220 }
221 });
222 });
223 }
224 });
225
226 // return selectize control
227 return location_select[0].selectize;
228}
229
230function destroyCategoryChildSelect (level) {
231 if (level === undefined) return;
232 $('#category-chained .select-category[data-level]').each(function () {
233 if ($(this).data('level') > level) {
234 $(this).parent('div').remove();
235 }
236 });
237}
238
239function destroyLocationChildSelect (level) {
240 if (level === undefined) return;
241 $('#location-chained .select-location[data-level]').each(function () {
242 if ($(this).data('level') > level) {
243 $(this).parent('div').remove();
244 }
245 });
246}
247
248$('#category-edit button').click(function(){
249 $('#category-chained').removeClass('d-none');
250 $('#category-edit').addClass('d-none');
251});
252
253$('#location-edit button').click(function(){
254 $('#location-chained').removeClass('d-none');
255 $('#location-edit').addClass('d-none');
256});
257
258// sceditor
259$('textarea[name=description]:not(.disable-bbcode)').sceditor({
260 format: 'bbcode',
261 plugins: "bbcode,plaintext",
262 toolbar: "bold,italic,underline,strike,|left,center,right,justify|" +
263 "bulletlist,orderedlist|link,unlink,youtube|source",
264 resizeEnabled: "true",
265 emoticonsEnabled: false,
266 width: '90%',
267 rtl: $('meta[name="application-name"]').data('rtl'),
268 style: $('meta[name="application-name"]').data('baseurl') + "themes/default/css/jquery.sceditor.default.min.css",
269});
270
271//sceditor for validation, updates iframe on submit
272$("button[name=submit]").click(function(){
273 $("textarea[name=description]").data("sceditor").updateOriginal();
274});
275
276function initLocationsGMap() {
277 jQuery.ajax({
278 url: ("https:" == document.location.protocol ? "https:" : "http:") + "//cdn.jsdelivr.net/gmaps/0.4.25/gmaps.min.js",
279 dataType: "script",
280 cache: true
281 }).done(function() {
282 locationsGMap();
283 });
284}
285
286function locationsGMap() {
287 // google map set marker on address
288 if($('#map').length !== 0){
289 map = new GMaps({
290 div: '#map',
291 zoom: parseInt($('#map').attr('data-zoom')),
292 lat: $('#map').attr('data-lat'),
293 lng: $('#map').attr('data-lon')
294 });
295 map.setCenter($('#map').attr('data-lat'), $('#map').attr('data-lon'));
296 map.addMarker({
297 lat: $('#map').attr('data-lat'),
298 lng: $('#map').attr('data-lon')
299 });
300 var typingTimer; //timer identifier
301 var doneTypingInterval = 500; //time in ms, 5 second for example
302 //on keyup, start the countdown
303 $('#address').keyup(function () {
304 clearTimeout(typingTimer);
305 if ($(this).val()) {
306 typingTimer = setTimeout(doneTyping, doneTypingInterval);
307 }
308 });
309 //user is "finished typing," refresh map
310 function doneTyping () {
311 GMaps.geocode({
312 address: $('#address').val(),
313 callback: function (results, status) {
314 if (status == 'OK') {
315 var latlng = results[0].geometry.location;
316 map = new GMaps({
317 div: '#map',
318 lat: latlng.lat(),
319 lng: latlng.lng(),
320 });
321 map.setCenter(latlng.lat(), latlng.lng());
322 map.addMarker({
323 lat: latlng.lat(),
324 lng: latlng.lng(),
325 draggable: true,
326 dragend: function(event) {
327 var lat = event.latLng.lat();
328 var lng = event.latLng.lng();
329 GMaps.geocode({
330 lat: lat,
331 lng: lng,
332 callback: function(results, status) {
333 if (status == 'OK') {
334 $("input[name='address']").val(results[0].formatted_address)
335 }
336 }
337 });
338 $('#publish-latitude').val(lat).removeAttr("disabled");
339 $('#publish-longitude').val(lng).removeAttr("disabled");
340 },
341 });
342 $('#publish-latitude').val(latlng.lat()).removeAttr("disabled");
343 $('#publish-longitude').val(latlng.lng()).removeAttr("disabled");
344 }
345 }
346 });
347 }
348 }
349
350 // auto locate user
351 $('.locateme').click(function() {
352 var lat;
353 var lng;
354 GMaps.geolocate({
355 success: function(position) {
356 lat = position.coords.latitude;
357 lng = position.coords.longitude
358 map = new GMaps({
359 div: '#map',
360 lat: lat,
361 lng: lng,
362 });
363 map.setCenter(lat, lng);
364 map.addMarker({
365 lat: lat,
366 lng: lng,
367 });
368 $('#publish-latitude').val(lat).removeAttr("disabled");
369 $('#publish-longitude').val(lng).removeAttr("disabled");
370 GMaps.geocode({
371 lat: lat,
372 lng: lng,
373 callback: function(results, status) {
374 if (status == 'OK') {
375 $("input[name='address']").val(results[0].formatted_address)
376 }
377 }
378 });
379 },
380 error: function(error) {
381 alert('Geolocation failed: '+error.message);
382 },
383 not_supported: function() {
384 alert("Your browser does not support geolocation");
385 },
386 });
387 });
388}
389
390// Dropzone
391
392Dropzone.options.imagesDropzone = {
393 url: $('.edit_ad_photos_form').attr('action'),
394 timeout: 180000,
395 autoProcessQueue: false,
396 uploadMultiple: true,
397 acceptedFiles: 'image/*',
398 addRemoveLinks: true,
399 resizeMimeType: 'image/jpeg',
400 createImageThumbnails: true,
401 maxFilesize: $('.images').data('max-image-size'),
402 maxFiles: $('.images').data('max-files'),
403 parallelUploads: $('.images').data('max-files'),
404 resizeWidth: getResizeValue($('.images').data('image-width')),
405
406 init: function () {
407 dzClosure = this;
408
409 document.getElementById("upload-photos-btn").addEventListener("click", function (e) {
410 if (dzClosure.getQueuedFiles().length > 0) {
411 e.preventDefault();
412 e.stopPropagation();
413
414 $('#processing-modal').on('shown.bs.modal', function () {
415 dzClosure.options.maxFiles++;
416 dzClosure.options.parallelUploads++;
417
418 // Get the queued files
419 var files = dzClosure.getQueuedFiles();
420
421 // Sort theme based on the DOM element index
422 files.sort(function (a, b) {
423 return ($(a.previewElement).index() > $(b.previewElement).index()) ? 1 : -1;
424 })
425
426 // Clear the dropzone queue
427 dzClosure.removeAllFiles();
428
429 // Add the reordered files to the queue
430 dzClosure.handleFiles(files);
431 dzClosure.processQueue();
432 });
433 $('#processing-modal').modal('show');
434 }
435 });
436
437 this.on("sendingmultiple", function (file, xhr, formData) {
438 formData.append('ajax', true);
439 });
440
441 this.on("thumbnail", function (file, dataUrl) {
442 window.loadImage.parseMetaData(file, function (data) {
443 if (data.exif) {
444 var rotation = 1;
445 var rotate = {
446 1: 'rotate(0deg)',
447 2: 'rotate(0deg)',
448 3: 'rotate(180deg)',
449 4: 'rotate(0deg)',
450 5: 'rotate(0deg)',
451 6: 'rotate(90deg)',
452 7: 'rotate(0deg)',
453 8: 'rotate(270deg)'
454 };
455 rotation = data.exif.get('Orientation');
456
457 $(file.previewElement).find('img').css('transform', rotate[rotation]);
458 // Safari fix
459 $(file.previewElement).find('img').css('-webkit-transform', rotate[rotation]);
460 }
461 });
462 });
463
464 this.on("error", function (file, response) {
465 if (response.redirect_url) {
466 window.location = response.redirect_url;
467 }
468 });
469 },
470
471 successmultiple: function (file, response) {
472 console.log(response);
473 window.location = response.redirect_url;
474 }
475}
476
477$("#images-dropzone").sortable({
478 items: '.dz-preview',
479 cursor: 'move',
480 opacity: 0.5,
481 containment: "parent",
482 distance: 20,
483 tolerance: 'pointer'
484});
485
486// VALIDATION with chosen fix
487$(function(){
488 $.validator.addMethod(
489 "regex",
490 function(value, element, regexp) {
491 var re = new RegExp(regexp);
492 return this.optional(element) || re.test(value);
493 }
494 );
495
496 $.validator.addMethod(
497 "required_checkbox_group",
498 function(value, element, idx) {
499 return $('#' + idx + ' :checkbox:checked').length > 0;
500 }
501 );
502
503 var $params = {
504 rules:{},
505 messages:{},
506 errorClass: 'invalid-feedback',
507 errorElement: 'div',
508 errorPlacement: function(error, element) {
509 element.removeClass('invalid-feedback');
510
511 if(element.is(':radio') || element.is(':checkbox')){
512 error.insertBefore(element.closest('label'));
513 } else if (element.is('textarea')) {
514 error.insertAfter(element.closest('textarea'));
515 } else if (element.is('select')) {
516 error.insertAfter(element.closest('select'));
517 } else if (element.is(':hidden')) {
518 checkbox_group = element.parent('.form-check').parent('div[data-type="checkbox_group"]');
519
520 if (checkbox_group && checkbox_group.find('.invalid-feedback').length === 0) {
521 checkbox_group.append(error);
522 }
523 } else {
524 error.insertAfter(element.closest('input'));
525 }
526 },
527 submitHandler: function(form) {
528 $('#processing-modal').on('shown.bs.modal', function() {
529 form.submit();
530 });
531 $('#processing-modal').modal('show');
532 },
533 };
534 $params['rules']['price'] = {regex: "^[0-9]{1,18}([,.]{1}[0-9]{1,8})?$"};
535 $params['rules']['title'] = {maxlength: 145};
536 $params['rules']['address'] = {maxlength: 145};
537 $params['rules']['phone'] = {maxlength: 30};
538 $params['rules']['website'] = {maxlength: 200};
539 $params['messages']['price'] = {"regex" : $('.edit_ad_form :input[name="price"]').data('error')};
540
541 $.validator.setDefaults({ ignore: ":hidden:not(select)" });
542 var $form = $(".edit_ad_form");
543 $form.validate($params);
544
545 //chosen fix
546 var settings = $.data($form[0], 'validator').settings;
547 settings.ignore += ':not(.cf_select_fields)'; // post_new location(any chosen) texarea
548 // settings.ignore += ':not(.sceditor-container)'; // post_new description texarea
549 settings.ignore += ':not(#description)'; // post_new description texarea
550});
551
552function createCustomFieldsByCategory (customfields) {
553 $('#custom-fields > div').not("#custom-field-template").remove();
554 $.each(customfields, function (idx, customfield) {
555 // don't create admin privilege custom fields if user is not moderator or admin
556 if (customfield.admin_privilege && $('#custom-fields').data("admin-privilege") === undefined)
557 return;
558 // clone custom field from template
559 var $template = $('#custom-field-template').clone().attr('id', '').removeClass('d-none').appendTo('#custom-fields');
560 $template.find('div[data-label]').replaceWith($('<label/>').attr({'for' : idx}).html(customfield.translated_label));
561
562 switch (customfield.type) {
563 case 'string':
564 case 'url':
565 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
566 'id' : idx,
567 'name' : idx,
568 'class' : 'form-control',
569 'placeholder' : customfield.translated_label,
570 'data-type' : customfield.type,
571 'data-toggle' : 'tooltip',
572 'title' : customfield.translated_tooltip,
573 'required' : customfield.required,
574 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
575 }));
576 break;
577 case 'textarea':
578 $template.find('div[data-input]').replaceWith($('<textarea/>').attr({ 'id' : idx,
579 'name' : idx,
580 'class' : 'form-control',
581 'placeholder' : customfield.translated_label,
582 'rows' : 10,
583 'cols' : 50,
584 'data-type' : customfield.type,
585 'data-toggle' : 'tooltip',
586 'title' : customfield.translated_tooltip,
587 'required' : customfield.required,
588 }).append($('#custom-fields').data('customfield-values')[customfield.label]));
589 break;
590 case 'textarea_bbcode':
591 $template.find('div[data-input]').replaceWith($('<textarea/>').attr({ 'id' : idx,
592 'name' : idx,
593 'class' : 'form-control',
594 'placeholder' : customfield.translated_label,
595 'rows' : 10,
596 'cols' : 50,
597 'data-type' : customfield.type,
598 'data-toggle' : 'tooltip',
599 'title' : customfield.translated_tooltip,
600 'required' : customfield.required,
601 }).append($('#custom-fields').data('customfield-values')[customfield.label]));
602 $('#custom-fields textarea[name="' + idx + '"]').sceditor({
603 format: 'bbcode',
604 plugins: "bbcode,plaintext",
605 toolbar: "bold,italic,underline,strike,|left,center,right,justify|" +
606 "bulletlist,orderedlist|link,unlink,youtube|source",
607 resizeEnabled: "true",
608 emoticonsEnabled: false,
609 autoUpdate: true,
610 width: '100%',
611 rtl: $('meta[name="application-name"]').data('rtl'),
612 style: $('meta[name="application-name"]').data('baseurl') + "themes/default/css/jquery.sceditor.default.min.css",
613 });
614 break;
615 case 'integer':
616 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
617 'id' : idx,
618 'name' : idx,
619 'class' : 'form-control',
620 'placeholder' : customfield.translated_label,
621 'data-type' : customfield.type,
622 'data-toggle' : 'tooltip',
623 'title' : customfield.translated_tooltip,
624 'required' : customfield.required,
625 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
626 }));
627 $('#custom-fields input[name="' + idx + '"]').rules('add', {
628 regex: '^[0-9]{1,18}([,.]{1}[0-9]{1,3})?$'
629 });
630 break;
631 case 'decimal':
632 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
633 'id' : idx,
634 'name' : idx,
635 'class' : 'form-control',
636 'placeholder' : customfield.translated_label,
637 'data-type' : customfield.type,
638 'data-toggle' : 'tooltip',
639 'title' : customfield.translated_tooltip,
640 'required' : customfield.required,
641 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
642 }));
643 $('#custom-fields input[name="' + idx + '"]').rules('add', {
644 regex: '^[0-9]{1,18}([,.]{1}[0-9]{1,3})?$'
645 });
646 break;
647 case 'range':
648 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
649 'id' : idx,
650 'name' : idx,
651 'class' : 'form-control',
652 'placeholder' : customfield.translated_label,
653 'data-type' : customfield.type,
654 'data-toggle' : 'tooltip',
655 'title' : customfield.translated_tooltip,
656 'required' : customfield.required,
657 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
658 }));
659 $('#custom-fields input[name="' + idx + '"]').rules('add', {
660 regex: '^[0-9]{1,18}([,.]{1}[0-9]{1,3})?$'
661 });
662 break;
663 case 'money':
664 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
665 'id' : idx,
666 'name' : idx,
667 'class' : 'form-control',
668 'placeholder' : customfield.translated_label,
669 'data-type' : customfield.type,
670 'data-toggle' : 'tooltip',
671 'title' : customfield.translated_tooltip,
672 'required' : customfield.required,
673 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
674 }));
675 $('#custom-fields input[name="' + idx + '"]').keyup(function() {
676 if ($('#price').data('decimal_point') == ',')
677 $(this).val($(this).val().replace(/[^\d,]/g, ''));
678 else
679 $(this).val($(this).val().replace(/[^\d.]/g, ''));
680 });
681 break;
682 case 'date':
683 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
684 'id' : idx,
685 'name' : idx,
686 'class' : 'form-control',
687 'placeholder' : customfield.translated_label,
688 'data-type' : customfield.type,
689 'data-toggle' : 'tooltip',
690 'title' : customfield.translated_tooltip,
691 'data-date-format' : 'yyyy-mm-dd',
692 'required' : customfield.required,
693 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
694 }));
695 $('#custom-fields input[name="' + idx + '"]').datepicker()
696 break;
697 case 'email':
698 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'email',
699 'id' : idx,
700 'name' : idx,
701 'class' : 'form-control',
702 'placeholder' : customfield.translated_label,
703 'data-type' : customfield.type,
704 'data-toggle' : 'tooltip',
705 'title' : customfield.tooltip,
706 'required' : customfield.required,
707 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
708 }));
709 break;
710 case 'select':
711 $template.find('div[data-input]').replaceWith($('<select/>').attr({ 'id' : idx,
712 'name' : idx,
713 'class' : 'form-control',
714 'placeholder' : customfield.translated_label,
715 'data-type' : customfield.type,
716 'required' : customfield.required,
717 }));
718 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(' ').html(' '));
719 for (var val in customfield.translated_values) {
720 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(customfield.translated_values[val]).html(customfield.translated_values[val]));
721 }
722 $('#custom-fields select[name="' + idx + '"] option[value="' + $('#custom-fields').data('customfield-values')[customfield.label] +'"]').attr('selected', true);
723 // selectize allowEmptyOption bugfix
724 $('#custom-fields select[name="' + idx + '"]').selectize({
725 allowEmptyOption: 'true',
726 onChange: function(value) {
727 if (value == ' ')
728 $('#custom-fields select[name="' + idx + '"] option[selected]').val(null);
729 }
730 });
731 $('#custom-fields select[name="' + idx + '"] option[value=" "]').val(null);
732 break;
733 case 'country':
734 $template.find('div[data-input]').replaceWith($('<select/>').attr({ 'id' : idx,
735 'name' : idx,
736 'class' : 'form-control',
737 'placeholder' : customfield.translated_label,
738 'data-type' : customfield.type,
739 'required' : customfield.required,
740 }));
741 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(' ').html(' '));
742 for (var val in customfield.translated_values) {
743 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(val).html(customfield.translated_values[val]));
744 }
745 $('#custom-fields select[name="' + idx + '"] option[value="' + $('#custom-fields').data('customfield-values')[customfield.label] +'"]').attr('selected', true);
746 // selectize allowEmptyOption bugfix
747 $('#custom-fields select[name="' + idx + '"]').selectize({
748 allowEmptyOption: 'true',
749 onChange: function(value) {
750 if (value == ' ')
751 $('#custom-fields select[name="' + idx + '"] option[selected]').val(null);
752 }
753 });
754 $('#custom-fields select[name="' + idx + '"] option[value=" "]').val(null);
755 break;
756 case 'file':
757 case 'file_dropbox':
758 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'hidden',
759 'id' : idx,
760 'name' : idx,
761 'class' : 'form-control',
762 'placeholder' : customfield.translated_label,
763 'data-type' : customfield.type,
764 'data-toggle' : 'tooltip',
765 'title' : customfield.translated_tooltip,
766 'required' : customfield.required,
767 'value' : $('#custom-fields').data('customfield-values')[idx],
768 }));
769 $('#custom-fields input[name="' + idx + '"]').after($('<div/>').attr({'id' : idx + '_dropbox',}));
770 options = {
771 success: function(files) {
772 $('#custom-fields input[name="' + idx + '"]').val(files[0].link);
773 },
774 linkType: "preview",
775 multiselect: false,
776 extensions: customfield.translated_values.split(','),
777 };
778 document.getElementById(idx + '_dropbox').appendChild(Dropbox.createChooseButton(options));
779 break;
780 case 'video':
781 var videoAttributes = [];
782
783 if ($('#custom-fields').data('customfield-values')[customfield.label] !== undefined) {
784 videoAttributes = JSON.parse($('#custom-fields').data('customfield-values')[customfield.label]);
785 }
786
787 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'hidden',
788 'id' : idx,
789 'name' : idx,
790 'class' : 'form-control',
791 'placeholder' : customfield.translated_label,
792 'data-type' : customfield.type,
793 'data-toggle' : 'tooltip',
794 'title' : customfield.translated_tooltip,
795 'required' : customfield.required,
796 'value' : $('#custom-fields').data('customfield-values')[customfield.label],
797 }));
798
799 if (videoAttributes.url === undefined) {
800 $('#custom-fields input[name="' + idx + '"]').before($('<br/>'));
801
802 $('#custom-fields input[name="' + idx + '"]').after($('<button/>').attr({'id' : idx + '_cloudinary', 'class' : 'cloudinary-upload-button btn btn-default', 'type' : 'button'}).html('Upload Video'));
803 var cloudinaryWidget = cloudinary.createUploadWidget({
804 buttonClass : 'cloudinary-upload-button',
805 sources: [ 'local'],
806 multiple: false,
807 showAdvancedOptions: false,
808 cloudName: cloudinaryCloudName,
809 uploadPreset: cloudinaryUploadPreset}, (error, result) => {
810 if (!error && result && result.event === "success") {
811 $('#' + idx + '_cloudinary').hide();
812 $('input[data-type="video"]').val(JSON.stringify({ url: result.info.secure_url, public_id: result.info.public_id}));
813 $('#custom-fields input[name="' + idx + '"]').after($('<div/>', {
814 class: '',
815 }).append($('<video />', {
816 class: 'img-responsive thumbnail',
817 src: result.info.secure_url,
818 type: 'video/mp4',
819 controls: true
820 })));
821 }
822 }
823 )
824 document.getElementById(idx + '_cloudinary').addEventListener("click", function(){
825 cloudinaryWidget.open();
826 }, false);
827 }
828 else {
829 $('#custom-fields input[name="' + idx + '"]').after($('<a/>', {
830 class: 'btn btn-danger',
831 href: '?video_delete=' + idx,
832 }).append('Delete Video'));
833 $('#custom-fields input[name="' + idx + '"]').after($('<div/>', {
834 class: '',
835 }).append($('<video />', {
836 class: 'img-responsive thumbnail',
837 src: videoAttributes.url,
838 type: 'video/mp4',
839 controls: true
840 })));
841 }
842 break;
843 case 'file_gpicker':
844 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'hidden',
845 'id' : idx,
846 'name' : idx,
847 'class' : 'form-control',
848 'placeholder' : customfield.translated_label,
849 'data-type' : customfield.type,
850 'data-toggle' : 'tooltip',
851 'title' : customfield.translated_tooltip,
852 'required' : customfield.required,
853 'value' : $('#custom-fields').data('customfield-values')[idx],
854 }));
855 $('#custom-fields input[name="' + idx + '"]')
856 .after($('<div/>')
857 .attr({'id' : idx + '_gpicker',})
858 .append('<a class="gpicker btn btn-sm btn-default" href="#"><i class="fa fa-google fa-fw text-primary" aria-hidden="true"></i> <strong>' + getCFSearchLocalization('upload_file_to_google_drive') + '</strong></a>'));
859 $('.gpicker').click(function() {
860 var id = this.id;
861 var viewId = new google.picker.DocsUploadView();
862 var setOAuthToken = true;
863
864 if (authApiLoaded && ! oauthToken) {
865 viewIdForhandleAuthResult = viewId;
866 window.gapi.auth.authorize(
867 {
868 'client_id': clientId,
869 'scope': scope,
870 'immediate': false
871 },
872 handleAuthResult
873 );
874 } else {
875 createPicker(viewId, setOAuthToken);
876 }
877
878 return false;
879 });
880 break;
881 case 'radio':
882 $.each(customfield.translated_values, function (radioidx, value) {
883 $('<div/>').attr('class', 'radio').append($('<label/>').append($('<input/>').attr({ 'type' : 'radio',
884 'id' : idx,
885 'name' : idx,
886 'data-type' : customfield.type,
887 'data-toggle' : 'tooltip',
888 'title' : customfield.translated_tooltip,
889 'required' : customfield.required,
890 'value' : radioidx + 1,
891 'checked' : (value == $('#custom-fields').data('customfield-values')[customfield.label]) ? true:false,
892 })).append(value)).insertBefore($template.find('div[data-input]'));
893 });
894 $template.find('div[data-input]').remove();
895 break;
896 case 'checkbox':
897 $template.find('div[data-input]').wrap('<div class="checkbox"></div>').wrap('<label></label>');
898 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'checkbox',
899 'id' : idx,
900 'name' : idx,
901 'data-type' : customfield.type,
902 'data-toggle' : 'tooltip',
903 'title' : customfield.translated_tooltip,
904 'required' : customfield.required,
905 'checked' : $('#custom-fields').data('customfield-values')[customfield.label],
906 }));
907 $('#custom-fields input[name="' + idx + '"]').before($('<input/>').attr({ 'type' : 'hidden',
908 'name' : idx,
909 'value' : 0,
910 }));
911 break;
912 case 'checkbox_group':
913 $template.find('div[data-input]').replaceWith($('<div/>').attr({
914 'id': idx,
915 'data-type': customfield.type,
916 }));
917
918 for (var key in customfield.grouped_values) {
919 var name = 'cf_' + key;
920 var label = customfield.grouped_values[key];
921
922 $('#custom-fields div[id="' + idx + '"]').append($('<input/>').attr({
923 'type': 'checkbox',
924 'id': name,
925 'name': name,
926 'data-type': customfield.type,
927 'data-toggle': 'tooltip',
928 'title': customfield.tooltip,
929 'class': 'form-check-input',
930 'checked': $('#custom-fields').data('customfield-values')[label],
931 }));
932
933 $('input[name="' + name + '"]').wrap('<div class="form-check"></div>').after($('<label class="form-check-label"></label>').text(label));
934
935 $('input[name="' + name + '"]').before($('<input/>').attr({
936 'type': 'hidden',
937 'name': name,
938 'value': 0,
939 }));
940
941 if (customfield.required) {
942 $('input[name="' + name + '"]').rules('add', {
943 required_checkbox_group: idx
944 });
945 }
946 }
947 break;
948 case 'json':
949 if (idx === 'cf_openinghours') {
950 $template.find('div:first').removeClass('col-sm-4').addClass('col-sm-8').find('div[data-input]').replaceWith($('#opening-hours-form-group').clone().attr({'id' : idx}).removeClass('d-none').append($('#custom-fields').data('customfield-values')[idx]));
951 $template.find('select').select2({ width: '100%' });
952
953 $('input[class*=dayopen]').on('change', function () {
954 if ($(this).val() == '1') //open
955 {
956 $(this).closest('.form-group').find('.openninghours').removeClass('d-none');
957 $(this).closest('.form-group').find('select').select2({
958 width: '100%'
959 });
960 }
961 else //closed
962 {
963 $(this).closest('.form-group').find('.openninghours').addClass('d-none');
964 }
965 });
966 } else {
967 $template.find('div[data-input]').replaceWith($('<textarea/>').attr({ 'id' : idx,
968 'name' : idx,
969 'class' : 'form-control',
970 'placeholder' : customfield.translated_label,
971 'rows' : 10,
972 'cols' : 50,
973 'data-type' : customfield.type,
974 'data-toggle' : 'tooltip',
975 'title' : customfield.translated_tooltip,
976 'required' : customfield.required,
977 }).append($('#custom-fields').data('customfield-values')[idx]));
978 }
979
980 break;
981 }
982 });
983
984 $('input[data-toggle=tooltip]').tooltip({
985 placement: "right",
986 trigger: "focus"
987 });
988
989 if (typeof CarQuery !== 'undefined' && $.isFunction(CarQuery) && customfields['cf_make'] != undefined && customfields['cf_model'] != undefined && customfields['cf_year'] != undefined) {
990 $('select#cf_make')[0].selectize.destroy();
991 $('select#cf_model')[0].selectize.destroy();
992 $('select#cf_year')[0].selectize.destroy();
993
994 var carquery = new CarQuery();
995 carquery.init(
996 $('#custom-fields').data('customfield-values')[customfields['cf_year'].label],
997 $('#custom-fields').data('customfield-values')[customfields['cf_make'].label],
998 $('#custom-fields').data('customfield-values')[customfields['cf_model'].label]
999 );
1000 carquery.initYearMakeModelTrim('cf_year', 'cf_make', 'cf_model');
1001 }
1002
1003 if (customfields['cf_brand'] != undefined && customfields['cf_model'] != undefined && customfields['cf_generation'] != undefined) {
1004 autoDataAPI(customfields, 'select#cf_brand', 'select#cf_model', 'select#cf_generation')
1005 }
1006}
1007
1008$(function(){
1009 $(".img-delete").click(function (e) {
1010 var button = $(this);
1011 var href = $(this).attr('href');
1012 var title = $(this).data('title');
1013 var text = $(this).data('text');
1014 var img_id = $(this).attr('value');
1015 var confirmButtonText = $(this).data('btnoklabel');
1016 var cancelButtonText = $(this).data('btncancellabel');
1017 e.preventDefault();
1018 swal({
1019 title: title,
1020 text: text,
1021 type: "info",
1022 showCancelButton: true,
1023 confirmButtonColor: "#DD6B55",
1024 confirmButtonText: confirmButtonText,
1025 cancelButtonText: cancelButtonText,
1026 allowOutsideClick: true,
1027 },
1028 function () {
1029 $('#processing-modal').modal('show');
1030 $('<input>').attr({
1031 type: 'hidden',
1032 name: 'img_delete',
1033 value: img_id,
1034 }).appendTo('.edit_ad_photos_form, .edit_ad_form');
1035 $('.edit_ad_photos_form').submit();
1036 });
1037 });
1038
1039 $(".img-primary").click(function (e) {
1040 e.preventDefault();
1041 var button = $(this);
1042 var href = $(this).attr('href');
1043 var title = $(this).data('title');
1044 var text = $(this).data('text');
1045 var img_id = $(this).attr('value');
1046
1047 $('#processing-modal').modal('show');
1048 $('<input>').attr({
1049 type: 'hidden',
1050 name: 'primary_image',
1051 value: img_id,
1052 }).appendTo('.edit_ad_photos_form, .edit_ad_form');
1053 $('.edit_ad_photos_form').submit();
1054 });
1055});
1056
1057$("#price").keyup(function() {
1058 if ($(this).data('decimal_point') == ',')
1059 $(this).val($(this).val().replace(/[^\d,]/g, ''));
1060 else
1061 $(this).val($(this).val().replace(/[^\d.]/g, ''));
1062});
1063
1064function onApiLoad() {
1065 gapi.load('auth', {'callback': onAuthApiLoad});
1066 gapi.load('picker', {'callback': onPickerApiLoad});
1067}
1068
1069function onAuthApiLoad() {
1070 authApiLoaded = true;
1071}
1072
1073function onPickerApiLoad() {
1074 pickerApiLoaded = true;
1075}
1076
1077function handleAuthResult(authResult) {
1078 if (authResult && ! authResult.error) {
1079 oauthToken = authResult.access_token;
1080 createPicker(viewIdForhandleAuthResult, true);
1081 }
1082}
1083
1084function createPicker(viewId, setOAuthToken) {
1085 if (authApiLoaded && pickerApiLoaded) {
1086 var picker;
1087
1088 if (authApiLoaded && oauthToken && setOAuthToken) {
1089 picker = new google.picker.PickerBuilder().
1090 addView(viewId).
1091 setOAuthToken(oauthToken).
1092 setDeveloperKey(developerKey).
1093 setCallback(pickerCallback).
1094 build();
1095 } else {
1096 picker = new google.picker.PickerBuilder().
1097 addView(viewId).
1098 setDeveloperKey(developerKey).
1099 setCallback(pickerCallback).
1100 build();
1101 }
1102
1103 picker.setVisible(true);
1104 }
1105}
1106
1107function pickerCallback(data) {
1108 if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
1109 doc = data[google.picker.Response.DOCUMENTS][0];
1110 $('input[data-type="file"]').val(doc.downloadUrl);
1111 }
1112}
1113