· 7 years ago · Apr 09, 2018, 03:56 PM
1// selectize for category and location selects
2$(function(){
3
4 // create 1st category select
5 category_select = createCategorySelect();
6 // remove hidden class
7 $('#category-chained .select-category[data-level="0"]').parent('div').removeClass('hidden');
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
27 // advertisement location is enabled?
28 if ($('#location-chained').length ) {
29
30 // create 1st location select
31 location_select = createLocationSelect();
32 // remove hidden class
33 $('#location-chained .select-location[data-level="0"]').parent('div').removeClass('hidden');
34
35 // load options for 1st location select
36 location_select.load(function(callback) {
37 $.ajax({
38 url: $('#location-chained').data('apiurl'),
39 type: 'GET',
40 data: {
41 "id_location_parent": 1,
42 "sort": 'order',
43 },
44 success: function(results) {
45 callback(results.locations);
46 if (results.locations.length === 0)
47 $('#location-chained').closest('.form-group').remove();
48 },
49 error: function() {
50 callback();
51 }
52 });
53 });
54 }
55
56 // show custom fields
57 if ($('#category-selected').val().length > 0) {
58 $.ajax({
59 url: $('#category-chained').data('apiurl') + '/' + $('#category-selected').val(),
60 success: function(results) {
61 createCustomFieldsByCategory(results.category.customfields);
62 }
63 });
64 }
65 else {
66 $.ajax({
67 url: $('#category-chained').data('apiurl') + '/' + 1,
68 success: function(results) {
69 createCustomFieldsByCategory(results.category.customfields);
70 }
71 });
72 }
73});
74
75function createCategorySelect () {
76
77 // count how many category selects we have rendered
78 num_category_select = $('#category-chained .select-category[data-level]').length;
79
80 // clone category select from template
81 $('#select-category-template').clone().attr('id', '').insertBefore($('#select-category-template')).find('select').attr('data-level', num_category_select);
82
83 // initialize selectize on created category select
84 category_select = $('.select-category[data-level="'+ num_category_select +'"]').selectize({
85 valueField: 'id_category',
86 labelField: 'name',
87 searchField: 'name',
88 onChange: function (value) {
89
90 if (!value.length) return;
91
92 // get current category level
93 current_level = $('#category-chained .option[data-value="'+ value +'"]').closest('.selectize-control').prev().data('level');
94
95 // is allowed to post on selected category?
96 if ( current_level > 0 || (current_level == 0 && $('#category-chained').is('[data-isparent]')))
97 {
98 // update #category-selected input value
99 $('#category-selected').attr('value', value);
100
101 //get category price
102 $.ajax({
103 url: $('#category-chained').data('apiurl') + '/' + value,
104 success: function(results) {
105 if (decodeHtml(results.category.price) != $('#category-chained').data('price0')) {
106 price_txt = $('#paid-category .help-block').data('title').replace(/%s/g, results.category.name).replace(/%d/g, decodeHtml(results.category.price));
107 $('#paid-category').removeClass('hidden').find('.help-block span').text(price_txt);
108 }
109 else {
110 $('#paid-category').addClass('hidden');
111 }
112 // show custom fields for this category
113 createCustomFieldsByCategory(results.category.customfields);
114 }
115 });
116 }
117 else
118 {
119 // set empty value
120 $('#category-selected').attr('value', '');
121 $('#paid-category').addClass('hidden');
122 // show custom fields
123 $.ajax({
124 url: $('#category-chained').data('apiurl') + '/' + 1,
125 success: function(results) {
126 createCustomFieldsByCategory(results.category.customfields);
127 }
128 });
129 }
130
131 // get current category level
132 current_level = $('#category-chained .option[data-value="'+ value +'"]').closest('.selectize-control').prev().data('level');
133
134 destroyCategoryChildSelect(current_level);
135
136 // create category select
137 category_select = createCategorySelect();
138
139 // load options for category select
140 category_select.load(function (callback) {
141 $.ajax({
142 url: $('#category-chained').data('apiurl'),
143 data: {
144 "id_category_parent": value,
145 "sort": 'order',
146 },
147 type: 'GET',
148 success: function (results) {
149 if (results.categories.length > 0)
150 {
151 callback(results.categories);
152 $('#category-chained .select-category[data-level="' + (current_level + 1) + '"]').parent('div').removeClass('hidden');
153 }
154 else
155 {
156 destroyCategoryChildSelect(current_level);
157 }
158 },
159 error: function () {
160 callback();
161 }
162 });
163 });
164 }
165 });
166
167 // return selectize control
168 return category_select[0].selectize;
169}
170
171function createLocationSelect () {
172
173 // count how many location selects we have rendered
174 num_location_select = $('#location-chained .select-location[data-level]').length;
175
176 // clone location select from template
177 $('#select-location-template').clone().attr('id', '').insertBefore($('#select-location-template')).find('select').attr('data-level', num_location_select);
178
179 // initialize selectize on created location select
180 location_select = $('.select-location[data-level="'+ num_location_select +'"]').selectize({
181 valueField: 'id_location',
182 labelField: 'name',
183 searchField: 'name',
184 onChange: function (value) {
185
186 if (!value.length) return;
187
188 // update #location-selected input value
189 $('#location-selected').attr('value', value);
190
191 // get current location level
192 current_level = $('#location-chained .option[data-value="'+ value +'"]').closest('.selectize-control').prev().data('level');
193
194 destroyLocationChildSelect(current_level);
195
196 // create location select
197 location_select = createLocationSelect();
198
199 // load options for location select
200 location_select.load(function (callback) {
201 $.ajax({
202 url: $('#location-chained').data('apiurl'),
203 data: {
204 "id_location_parent": value,
205 "sort": 'order',
206 },
207 type: 'GET',
208 success: function (results) {
209 if (results.locations.length > 0)
210 {
211 callback(results.locations);
212 $('#location-chained .select-location[data-level="' + (current_level + 1) + '"]').parent('div').removeClass('hidden');
213 }
214 else
215 {
216 destroyLocationChildSelect(current_level);
217 }
218 },
219 error: function () {
220 callback();
221 }
222 });
223 });
224 }
225 });
226
227 // return selectize control
228 return location_select[0].selectize;
229}
230
231function destroyCategoryChildSelect (level) {
232 if (level === undefined) return;
233 $('#category-chained .select-category[data-level]').each(function () {
234 if ($(this).data('level') > level) {
235 $(this).parent('div').remove();
236 }
237 });
238}
239
240function destroyLocationChildSelect (level) {
241 if (level === undefined) return;
242 $('#location-chained .select-location[data-level]').each(function () {
243 if ($(this).data('level') > level) {
244 $(this).parent('div').remove();
245 }
246 });
247}
248
249$('#category-edit button').click(function(){
250 $('#category-chained').removeClass('hidden');
251 $('#category-edit').addClass('hidden');
252});
253
254$('#location-edit button').click(function(){
255 $('#location-chained').removeClass('hidden');
256 $('#location-edit').addClass('hidden');
257});
258
259// sceditor
260$('textarea[name=description]:not(.disable-bbcode)').sceditor({
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 autoUpdate: true,
267 width: '100%',
268 height: "300px",
269 rtl: $('meta[name="application-name"]').data('rtl'),
270 style: $('meta[name="application-name"]').data('baseurl') + "themes/default/css/jquery.sceditor.default.min.css",
271});
272
273$('textarea[name=description]').prop('required',true);
274
275//sceditor for validation, updates iframe on submit
276$("button[name=submit]").click(function(){
277 $("textarea[name=description]").data("sceditor").updateOriginal();
278});
279
280function initLocationsGMap() {
281 jQuery.ajax({
282 url: ("https:" == document.location.protocol ? "https:" : "http:") + "//cdn.jsdelivr.net/gmaps/0.4.15/gmaps.min.js",
283 dataType: "script",
284 cache: true
285 }).done(function() {
286 locationsGMap();
287 });
288}
289
290function locationsGMap() {
291 // google map set marker on address
292 if ($('#map').length !== 0){
293 var typingTimer; //timer identifier
294 var doneTypingInterval = 500; //time in ms, 5 second for example
295 //on keyup, start the countdown
296 $('#address').keyup(function () {
297 clearTimeout(typingTimer);
298 if ($(this).val()) {
299 typingTimer = setTimeout(doneTyping, doneTypingInterval);
300 }
301 });
302 //user is "finished typing," refresh map
303 function doneTyping () {
304 GMaps.geocode({
305 address: $('#address').val(),
306 callback: function (results, status) {
307 if (status == 'OK') {
308 var latlng = results[0].geometry.location;
309 map = new GMaps({
310 div: '#map',
311 lat: latlng.lat(),
312 lng: latlng.lng(),
313 });
314 map.setCenter(latlng.lat(), latlng.lng());
315 map.addMarker({
316 lat: latlng.lat(),
317 lng: latlng.lng(),
318 draggable: true,
319 dragend: function(event) {
320 var lat = event.latLng.lat();
321 var lng = event.latLng.lng();
322 GMaps.geocode({
323 lat: lat,
324 lng: lng,
325 callback: function(results, status) {
326 if (status == 'OK') {
327 $("input[name='address']").val(results[0].formatted_address)
328 }
329 }
330 });
331 $('#publish-latitude').val(lat).removeAttr("disabled");
332 $('#publish-longitude').val(lng).removeAttr("disabled");
333 },
334 });
335 $('#publish-latitude').val(latlng.lat()).removeAttr("disabled");
336 $('#publish-longitude').val(latlng.lng()).removeAttr("disabled");
337 }
338 }
339 });
340 }
341
342 $('a[href="#complete"]').on('shown.bs.tab', function (e) {
343 // google map set marker on address
344 map = new GMaps({
345 div: '#map',
346 zoom: parseInt($('#map').attr('data-zoom')),
347 lat: $('#map').attr('data-lat'),
348 lng: $('#map').attr('data-lon')
349 });
350 map.refresh();
351 });
352 }
353
354 // auto locate user
355 $('.locateme').click(function() {
356 var lat;
357 var lng;
358 GMaps.geolocate({
359 success: function(position) {
360 lat = position.coords.latitude;
361 lng = position.coords.longitude
362 map = new GMaps({
363 div: '#map',
364 lat: lat,
365 lng: lng,
366 });
367 map.setCenter(lat, lng);
368 map.addMarker({
369 lat: lat,
370 lng: lng,
371 });
372 $('#publish-latitude').val(lat).removeAttr("disabled");
373 $('#publish-longitude').val(lng).removeAttr("disabled");
374 GMaps.geocode({
375 lat: lat,
376 lng: lng,
377 callback: function(results, status) {
378 if (status == 'OK') {
379 $("input[name='address']").val(results[0].formatted_address)
380 }
381 }
382 });
383 },
384 error: function(error) {
385 alert('Geolocation failed: '+error.message);
386 },
387 not_supported: function() {
388 alert("Your browser does not support geolocation");
389 },
390 });
391 });
392}
393
394$('.fileinput').on('change.bs.fileinput', function() {
395
396 //check whether browser fully supports all File API
397 if (FileApiSupported())
398 {
399 //get the file size and file type from file input field
400 var $input = $(this).find('input[name^="image"]');
401 var image = $input[0].files[0];
402 var max_size = $('.images').data('max-image-size')*1048576 // max size in bites
403 var $closestFileInput = $(this).closest('.fileinput');
404
405 //resize image
406 canvasResize(image, {
407 width: getResizeValue($('.images').data('image-width')),
408 height: getResizeValue($('.images').data('image-height')),
409 crop: false,
410 quality: $('.images').data('image-quality'),
411 callback: function(data, width, height) {
412
413 var base64Image = new Image();
414 base64Image.src = data;
415
416 if (base64Image.size > max_size)
417 {
418 swal({
419 title: '',
420 text: $('.images').data('swaltext'),
421 type: "warning",
422 allowOutsideClick: true
423 });
424
425 $closestFileInput.fileinput('clear');
426 }
427 else
428 {
429 $('<input>').attr({
430 type: 'hidden',
431 name: 'base64_' + $input.attr('name'),
432 value: data
433 }).appendTo('#publish-new');
434 }
435 }
436 });
437
438 // Fixes exif orientation on thumbnail
439 var thumbnail = $(this).find('.thumbnail > img');
440 var rotation = 1;
441 var rotate = {
442 1: 'rotate(0deg)',
443 2: 'rotate(0deg)',
444 3: 'rotate(180deg)',
445 4: 'rotate(0deg)',
446 5: 'rotate(0deg)',
447 6: 'rotate(90deg)',
448 7: 'rotate(0deg)',
449 8: 'rotate(270deg)'
450 };
451
452 loadImage.parseMetaData(
453 image,
454 function (data) {
455 if (data.exif) {
456 rotation = data.exif.get('Orientation');
457 thumbnail.css('transform', rotate[rotation]);
458 }
459 }
460 );
461 }
462
463 //unhide next box image after selecting first
464 $(this).next('.fileinput').removeClass('hidden');
465
466 //hide image url button
467 $(this).find('.fileinput-url').addClass('hidden');
468});
469
470$('.fileinput').on('clear.bs.fileinput', function() {
471 var $input = $(this).find('input[name^="image"]');
472 $('input[name="base64_' + $input.attr('name') + '"]').remove();
473
474 //unhide image url button
475 $(this).find('.fileinput-url').removeClass('hidden');
476});
477
478function convertFunction(url, callback) {
479 var xhr = new XMLHttpRequest();
480 xhr.onload = function() {
481 var reader = new FileReader();
482 reader.onloadend = function() {
483 callback(reader.result);
484 }
485 reader.readAsDataURL(xhr.response);
486 };
487 xhr.open('GET', url);
488 xhr.responseType = 'blob';
489 xhr.onerror = function() {
490 alert("The image could not be loaded")
491 }
492 xhr.send();
493}
494
495$('.imageURL').submit(function(event) {
496 var $input = $(this).find('[name^="image"]');
497 var $fileInput = $('.fileinput [name="' + $input.attr('name') + '"]').closest('.fileinput');
498 var $fileInputPreview = $fileInput.find('.fileinput-preview');
499
500 convertFunction($input.val(), function(base64Img) {
501 $('<input>').attr({
502 type: 'hidden',
503 name: 'base64_' + $input.attr('name'),
504 value: base64Img
505 }).appendTo('#publish-new');
506 $('<img>').attr({
507 src: base64Img
508 }).appendTo($fileInputPreview);
509 $fileInput.removeClass('fileinput-new').addClass('fileinput-exists');
510 $fileInput.find('.fileinput-url').addClass('hidden');
511 $('#urlInput' + $input.attr('name')).modal('hide');
512
513 //unhide next box image after selecting first
514 $fileInput.next('.fileinput').removeClass('hidden');
515 });
516
517 event.preventDefault();
518});
519
520// VALIDATION with chosen fix
521$(function(){
522 $.validator.addMethod(
523 "regex",
524 function(value, element, regexp) {
525 var re = new RegExp(regexp);
526 return this.optional(element) || re.test(value);
527 }
528 );
529
530 var $params = {
531 rules:{},
532 messages:{},
533 focusInvalid: false,
534 onkeyup: false,
535 ignore: 'input[type="text"]:hidden',
536 errorPlacement: function(error, element) {
537 if(element.is(':radio') || element.is(':checkbox')){
538 error.insertBefore(element.closest('label'));
539 } else if (element.is('textarea')) {
540 error.insertAfter(element.closest('textarea'));
541 } else {
542 error.insertAfter(element.closest('input'));
543 }
544 },
545 submitHandler: function(form) {
546 $('#processing-modal').on('shown.bs.modal', function() {
547 if (FileApiSupported())
548 $.when(clearFileInput($('input[name^="image"]'))).then(form.submit());
549 else
550 form.submit()
551 });
552 $('#processing-modal').modal('show');
553 },
554 invalidHandler: function(form, validator) {
555 if (!validator.numberOfInvalids())
556 return;
557 }
558 };
559 $params['rules']['price'] = {regex: "^[0-9]{1,18}([,.]{1}[0-9]{1,8})?$"};
560 $params['rules']['title'] = {maxlength: 145};
561 $params['rules']['address'] = {maxlength: 145};
562 $params['rules']['phone'] = {maxlength: 30};
563 $params['rules']['website'] = {maxlength: 200};
564 $params['rules']['captcha'] = {
565 "remote" :
566 {
567 url: $(".post_new").attr('action'),
568 type: "post",
569 data:
570 {
571 ajaxValidateCaptcha: true
572 }
573 }
574 };
575 $params['rules']['email'] = {emaildomain: $('.post_new :input[name="email"]').data('domain')};
576 $params['rules']['description'] = {nobannedwords: $('.post_new :input[name="description"]').data('bannedwords')};
577 $params['messages']['email'] = {"emaildomain" : $('.post_new :input[name="email"]').data('error')};
578 $params['messages']['description'] = {"nobannedwords" : $('.post_new :input[name="description"]').data('error')};
579 $params['messages']['price'] = {"regex" : $('.post_new :input[name="price"]').data('error')};
580 $params['messages']['captcha'] = {"remote" : $('.post_new :input[name="captcha"]').data('error')};
581
582 $.validator.setDefaults({ ignore: ":hidden:not(select)" });
583 var $form = $(".post_new");
584 $form.validate($params
585 // {
586 // errorLabelContainer: $(".post_new div.error"),
587 // wrapper: 'div',
588 // rules: {
589 // title: {minlength:2},
590 // price: {regex:"^[0-9]{1,18}([,.]{1}[0-9]{1,3})?$"}
591 // },
592 // messages: {
593 // price:{regex: "Format is incorect"}
594 // }
595 // }
596 );
597
598 //chosen fix
599 var settings = $.data($form[0], 'validator').settings;
600 settings.ignore += ':not(.cf_select_fields)'; // post_new location(any chosen) texarea
601 // settings.ignore += ':not(.sceditor-container)'; // post_new description texarea
602 settings.ignore += ':not(#description)'; // post_new description texarea
603});
604
605// sure you want to leave alert and processing modal
606$(function(){
607 if ($('input[name=leave_alert]').length === 0) {
608 var _ouibounce = ouibounce(false, {
609 aggressive: true,
610 callback: function() {
611 swal({
612 title: $('#publish-new-btn').data('swaltitle'),
613 text: $('#publish-new-btn').data('swaltext'),
614 type: "warning",
615 allowOutsideClick: true
616 });
617 }
618 });
619 }
620});
621
622function createCustomFieldsByCategory (customfields) {
623 $('#custom-fields > div').not("#custom-field-template").remove();
624 $.each(customfields, function (idx, customfield) {
625 // don't create admin privilege custom fields
626 if (customfield.admin_privilege)
627 return;
628 // clone custom field from template
629 var $template = $('#custom-field-template').clone().attr('id', '').removeClass('hidden').appendTo('#custom-fields');
630 if (customfield.required)
631 $template.addClass('required');
632 $template.find('div[data-label]').replaceWith($('<label/>').attr({'for' : idx}).html(customfield.label));
633
634 switch (customfield.type) {
635 case 'string':
636 case 'url':
637 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
638 'id' : idx,
639 'name' : idx,
640 'class' : 'form-control',
641 'placeholder' : customfield.label,
642 'data-type' : customfield.type,
643 'data-toggle' : 'tooltip',
644 'title' : customfield.tooltip,
645 'required' : customfield.required,
646 'value' : $('#custom-fields').data('customfield-values')[idx],
647 }));
648 break;
649 case 'textarea':
650 $template.find('div[data-input]').replaceWith($('<textarea/>').attr({ 'id' : idx,
651 'name' : idx,
652 'class' : 'form-control',
653 'placeholder' : customfield.label,
654 'rows' : 10,
655 'cols' : 50,
656 'data-type' : customfield.type,
657 'data-toggle' : 'tooltip',
658 'title' : customfield.tooltip,
659 'required' : customfield.required,
660 }).append($('#custom-fields').data('customfield-values')[idx]));
661 break;
662 case 'integer':
663 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
664 'id' : idx,
665 'name' : idx,
666 'class' : 'form-control',
667 'placeholder' : customfield.label,
668 'data-type' : customfield.type,
669 'data-toggle' : 'tooltip',
670 'title' : customfield.tooltip,
671 'required' : customfield.required,
672 'value' : $('#custom-fields').data('customfield-values')[idx],
673 }));
674 $('#custom-fields input[name="' + idx + '"]').rules('add', {
675 regex: '^[0-9]{1,18}([,.]{1}[0-9]{1,3})?$'
676 });
677 break;
678 case 'decimal':
679 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
680 'id' : idx,
681 'name' : idx,
682 'class' : 'form-control',
683 'placeholder' : customfield.label,
684 'data-type' : customfield.type,
685 'data-toggle' : 'tooltip',
686 'title' : customfield.tooltip,
687 'required' : customfield.required,
688 'value' : $('#custom-fields').data('customfield-values')[idx],
689 }));
690 $('#custom-fields input[name="' + idx + '"]').rules('add', {
691 regex: '^[0-9]{1,18}([,.]{1}[0-9]{1,3})?$'
692 });
693 break;
694 case 'range':
695 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
696 'id' : idx,
697 'name' : idx,
698 'class' : 'form-control',
699 'placeholder' : customfield.label,
700 'data-type' : customfield.type,
701 'data-toggle' : 'tooltip',
702 'title' : customfield.tooltip,
703 'required' : customfield.required,
704 'value' : $('#custom-fields').data('customfield-values')[idx],
705 }));
706 $('#custom-fields input[name="' + idx + '"]').rules('add', {
707 regex: '^[0-9]{1,18}([,.]{1}[0-9]{1,3})?$'
708 });
709 break;
710 case 'date':
711 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'text',
712 'id' : idx,
713 'name' : idx,
714 'class' : 'form-control',
715 'placeholder' : customfield.label,
716 'data-type' : customfield.type,
717 'data-toggle' : 'tooltip',
718 'title' : customfield.tooltip,
719 'data-date-format' : 'yyyy-mm-dd',
720 'required' : customfield.required,
721 'value' : $('#custom-fields').data('customfield-values')[idx],
722 }));
723 $('#custom-fields input[name="' + idx + '"]').datepicker({
724 autoclose: true
725 })
726 break;
727 case 'email':
728 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'email',
729 'id' : idx,
730 'name' : idx,
731 'class' : 'form-control',
732 'placeholder' : customfield.label,
733 'data-type' : customfield.type,
734 'data-toggle' : 'tooltip',
735 'title' : customfield.tooltip,
736 'required' : customfield.required,
737 'value' : $('#custom-fields').data('customfield-values')[idx],
738 }));
739 break;
740 case 'select':
741 $template.find('div[data-input]').replaceWith($('<select/>').attr({ 'id' : idx,
742 'name' : idx,
743 'class' : 'form-control',
744 'placeholder' : customfield.label,
745 'data-type' : customfield.type,
746 'data-toggle' : 'tooltip',
747 'title' : customfield.tooltip,
748 'required' : customfield.required,
749 }));
750 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(''));
751 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(' ').html(' '));
752 $('#custom-fields select[name="' + idx + '"]').after($('<span class="help-block">' + customfield.tooltip + '</span>'));
753 for (var val in customfield.values) {
754 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(customfield.values[val]).html(customfield.values[val]));
755 }
756 $('#custom-fields select[name="' + idx + '"] option[value="' + $('#custom-fields').data('customfield-values')[idx] +'"]').attr('selected', true);
757 $('#custom-fields select[name="' + idx + '"]').selectize({
758 onChange: function(value) {
759 if (value == ' ')
760 $('#custom-fields select[name="' + idx + '"] option[selected]').val(null);
761 }
762 });
763 $('#custom-fields select[name="' + idx + '"] option[value=" "]').val(null);
764 break;
765 case 'country':
766 $template.find('div[data-input]').replaceWith($('<select/>').attr({ 'id' : idx,
767 'name' : idx,
768 'class' : 'form-control',
769 'placeholder' : customfield.label,
770 'data-type' : customfield.type,
771 'data-toggle' : 'tooltip',
772 'title' : customfield.tooltip,
773 'required' : customfield.required,
774 }));
775 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(''));
776 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(' ').html(' '));
777 $('#custom-fields select[name="' + idx + '"]').after($('<span class="help-block">' + customfield.tooltip + '</span>'));
778 for (var val in customfield.values) {
779 $('#custom-fields select[name="' + idx + '"]').append($('<option/>').val(val).html(customfield.values[val]));
780 }
781 $('#custom-fields select[name="' + idx + '"] option[value="' + $('#custom-fields').data('customfield-values')[idx] +'"]').attr('selected', true);
782 $('#custom-fields select[name="' + idx + '"]').selectize({
783 onChange: function(value) {
784 if (value == ' ')
785 $('#custom-fields select[name="' + idx + '"] option[selected]').val(null);
786 }
787 });
788 $('#custom-fields select[name="' + idx + '"] option[value=" "]').val(null);
789 break;
790 case 'file':
791 case 'file_dropbox':
792 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'hidden',
793 'id' : idx,
794 'name' : idx,
795 'class' : 'form-control',
796 'placeholder' : customfield.label,
797 'data-type' : customfield.type,
798 'data-toggle' : 'tooltip',
799 'title' : customfield.tooltip,
800 'required' : customfield.required,
801 'value' : $('#custom-fields').data('customfield-values')[idx],
802 }));
803 $('#custom-fields input[name="' + idx + '"]').after($('<div/>').attr({'id' : idx + '_dropbox',}));
804 options = {
805 success: function(files) {
806 $('#custom-fields input[name="' + idx + '"]').val(files[0].link);
807 },
808 linkType: "preview",
809 multiselect: false,
810 extensions: customfield.values.split(','),
811 };
812 document.getElementById(idx + '_dropbox').appendChild(Dropbox.createChooseButton(options));
813 break;
814 case 'file_gpicker':
815 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'hidden',
816 'id' : idx,
817 'name' : idx,
818 'class' : 'form-control',
819 'placeholder' : customfield.label,
820 'data-type' : customfield.type,
821 'data-toggle' : 'tooltip',
822 'title' : customfield.tooltip,
823 'required' : customfield.required,
824 'value' : $('#custom-fields').data('customfield-values')[idx],
825 }));
826 $('#custom-fields input[name="' + idx + '"]')
827 .after($('<div/>')
828 .attr({'id' : idx + '_gpicker',})
829 .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>'));
830 $('.gpicker').click(function() {
831 var id = this.id;
832 var viewId = new google.picker.DocsUploadView();
833 var setOAuthToken = true;
834
835 if (authApiLoaded && ! oauthToken) {
836 viewIdForhandleAuthResult = viewId;
837 window.gapi.auth.authorize(
838 {
839 'client_id': clientId,
840 'scope': scope,
841 'immediate': false
842 },
843 handleAuthResult
844 );
845 } else {
846 createPicker(viewId, setOAuthToken);
847 }
848
849 return false;
850 });
851 break;
852 case 'radio':
853 $.each(customfield.values, function (radioidx, value) {
854 $('<div/>').attr('class', 'radio').append($('<label/>').append($('<input/>').attr({ 'type' : 'radio',
855 'id' : idx,
856 'name' : idx,
857 'data-type' : customfield.type,
858 'data-toggle' : 'tooltip',
859 'title' : customfield.tooltip,
860 'required' : customfield.required,
861 'value' : radioidx + 1,
862 'checked' : ((radioidx + 1) == $('#custom-fields').data('customfield-values')[idx]) ? true:false,
863 })).append(value)).insertBefore($template.find('div[data-input]'));
864 });
865 $template.find('div[data-input]').remove();
866 break;
867 case 'checkbox':
868 $template.find('div[data-input]').wrap('<div class="checkbox"></div>').wrap('<label></label>');
869 $template.find('div[data-input]').replaceWith($('<input/>').attr({ 'type' : 'checkbox',
870 'id' : idx,
871 'name' : idx,
872 'data-type' : customfield.type,
873 'data-toggle' : 'tooltip',
874 'title' : customfield.tooltip,
875 'required' : customfield.required,
876 'checked' : $('#custom-fields').data('customfield-values')[idx],
877 }));
878 break;
879 }
880 });
881
882 $('input[data-toggle=tooltip]').tooltip({
883 placement: "right",
884 trigger: "focus"
885 });
886
887 if (typeof CarQuery !== 'undefined' && $.isFunction(CarQuery) && customfields['cf_make'] != undefined && customfields['cf_model'] != undefined && customfields['cf_year'] != undefined) {
888 $('select#cf_make')[0].selectize.destroy();
889 $('select#cf_model')[0].selectize.destroy();
890 $('select#cf_year')[0].selectize.destroy();
891
892 var carquery = new CarQuery();
893 carquery.init('', '', '');
894 carquery.initYearMakeModelTrim('cf_year', 'cf_make', 'cf_model');
895 }
896}
897
898function clearFileInput($input) {
899 if ($input.val() == '') {
900 return;
901 }
902 // Fix for IE ver < 11, that does not clear file inputs
903 if (/MSIE/.test(navigator.userAgent)) {
904 var $frm1 = $input.closest('form');
905 if ($frm1.length) {
906 $input.wrap('<form>');
907 var $frm2 = $input.closest('form'),
908 $tmpEl = $(document.createElement('div'));
909 $frm2.before($tmpEl).after($frm1).trigger('reset');
910 $input.unwrap().appendTo($tmpEl).unwrap();
911 } else {
912 $input.wrap('<form>').closest('form').trigger('reset').unwrap();
913 }
914 } else if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
915 $input.replaceWith($input.clone());
916 } else {
917 $input.val('');
918 }
919}
920
921// check whether browser fully supports all File API
922function FileApiSupported() {
923 if (window.File && window.FileReader && window.FileList && window.Blob)
924 return true;
925
926 return false;
927}
928
929$("#price").keyup(function() {
930 if ($(this).data('decimal_point') == ',')
931 $(this).val($(this).val().replace(/[^\d,]/g, ''));
932 else
933 $(this).val($(this).val().replace(/[^\d.]/g, ''));
934});
935
936// Step by step process publish new
937$(function(){
938 //Initialize tooltips
939 $('.nav-tabs > li a[title]').tooltip();
940
941 //Wizard
942 $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
943
944 var $target = $(e.target);
945
946 if ($target.parent().hasClass('disabled')) {
947 return false;
948 }
949 });
950
951 $(".next-step").click(function (e) {
952 var $active = $('.wizard .nav-tabs li.active');
953 var $inputFields = $($active.find('a').attr('href') + ' :input');
954 var isInvalid = false;
955
956 //sceditor for validation, updates iframe
957 $("#description").sceditor('instance').updateOriginal();
958
959 $inputFields.each(function () {
960 if ( ! $(this).valid())
961 isInvalid = true;
962 });
963
964 if (isInvalid)
965 return false;
966
967 $active.next().removeClass('disabled');
968 nextTab($active);
969
970 });
971
972 $(".prev-step").click(function (e) {
973
974 var $active = $('.wizard .nav-tabs li.active');
975 prevTab($active);
976
977 });
978});
979
980$(function(){
981 $(".next-step").click(function() {
982 $('html, body').animate({
983 scrollTop: $(".wizard-inner").offset().top
984 }, 500);
985 });
986 $(".prev-step").click(function() {
987 $('html, body').animate({
988 scrollTop: $(".wizard-inner").offset().top
989 }, 500);
990 });
991});
992
993function nextTab(elem) {
994 $(elem).next().find('a[data-toggle="tab"]').click();
995}
996function prevTab(elem) {
997 $(elem).prev().find('a[data-toggle="tab"]').click();
998}
999
1000function onApiLoad() {
1001 gapi.load('auth', {'callback': onAuthApiLoad});
1002 gapi.load('picker', {'callback': onPickerApiLoad});
1003}
1004
1005function onAuthApiLoad() {
1006 authApiLoaded = true;
1007}
1008
1009function onPickerApiLoad() {
1010 pickerApiLoaded = true;
1011}
1012
1013function handleAuthResult(authResult) {
1014 if (authResult && ! authResult.error) {
1015 oauthToken = authResult.access_token;
1016 createPicker(viewIdForhandleAuthResult, true);
1017 }
1018}
1019
1020function createPicker(viewId, setOAuthToken) {
1021 if (authApiLoaded && pickerApiLoaded) {
1022 var picker;
1023
1024 if (authApiLoaded && oauthToken && setOAuthToken) {
1025 picker = new google.picker.PickerBuilder().
1026 addView(viewId).
1027 setOAuthToken(oauthToken).
1028 setDeveloperKey(developerKey).
1029 setCallback(pickerCallback).
1030 build();
1031 } else {
1032 picker = new google.picker.PickerBuilder().
1033 addView(viewId).
1034 setDeveloperKey(developerKey).
1035 setCallback(pickerCallback).
1036 build();
1037 }
1038
1039 picker.setVisible(true);
1040 }
1041}
1042
1043function pickerCallback(data) {
1044 if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
1045 doc = data[google.picker.Response.DOCUMENTS][0];
1046 $('input[data-type="file"]').val(doc.downloadUrl)
1047 }
1048}
1049
1050if ($('#phone').length) {
1051 $("#phone").intlTelInput({
1052 formatOnDisplay: false,
1053 initialCountry: $('#phone').data('country')
1054 });
1055}