product.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //**************************show images gallery**********************************************
  2. // $(document).ready(function(){
  3. // $('.upload-widget').on('click', '.deleteGallary', function(e){
  4. // e.preventDefault();
  5. // $(this).closest(".DeleteImages").remove();
  6. // });
  7. // });
  8. var FileUploader = (function() {
  9. function FileUploader(options) {
  10. options = options || {};
  11. this.widget = document.querySelector(options.className);
  12. this.dropZone = this.widget.querySelector('.dropZone');
  13. this.input = this.widget.querySelector('.files');
  14. this.output = this.widget.querySelector('.list');
  15. };
  16. FileUploader.prototype.init = function() {
  17. var self = this;
  18. self.dropZone.addEventListener('drop', function(e) {self.handleFile(e, self);}, false);
  19. self.input.addEventListener('change', function(e) {self.handleFile(e, self);}, false);
  20. self.dropZone.addEventListener('dragover', self.handleDragOver, false);
  21. };
  22. FileUploader.prototype.handleFile = function(evt, that) {
  23. var self = that;
  24. var files;
  25. evt.stopPropagation();
  26. evt.preventDefault();
  27. if (evt.type === 'change') {
  28. files = evt.target.files;
  29. } else if (evt.type === 'drop') {
  30. files = evt.dataTransfer.files;
  31. }
  32. self.selectLogic(files, self);
  33. };
  34. FileUploader.prototype.handleDragOver = function(evt) {
  35. evt.stopPropagation();
  36. evt.preventDefault();
  37. evt.dataTransfer.dropEffect = 'link';
  38. };
  39. FileUploader.prototype.selectLogic = function(files, that) {
  40. var self = that;
  41. var reader;
  42. for (var i = 0, file; file = files[i]; i++) {
  43. reader = new FileReader();
  44. reader.onload = (function(theFile) {
  45. return function(e) {
  46. var
  47. div = document.createElement('div'),
  48. canvas = document.createElement('canvas'),
  49. ctx = canvas.getContext('2d'),
  50. image = new Image(),
  51. ratio,
  52. thumb;
  53. div.className = 'b';
  54. image.src = e.target.result;
  55. //size image
  56. image.onload = function() {
  57. ratio = 150/image.width;
  58. ratio = 150/image.height;
  59. canvas.width = image.width * ratio;
  60. canvas.height = image.height * ratio;
  61. ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
  62. // Gallery Description Input Fields
  63. thumb = canvas.toDataURL(theFile.type);
  64. div.innerHTML = '<div class="DeleteImages">' +
  65. '<a href="" class="deleteGallary btn btn-danger pull-right position-absolute"> ' +
  66. '<i class="icon fa fa-close"></i>' +
  67. '</a>' +
  68. '<img class="thumb img-thumbnail" style="width: 200px; height: 150px;" src="' + thumb + '" title="' + escape(theFile.name) + '">' +
  69. '<span class="form-input py-3 md-form" style="display: block;"> ' +
  70. '<label for="description">توضیحات: </label>' +
  71. '<input type="text" class="form-control" name="descriptionGallery[]">\n' +
  72. '<label for="caption">عنوان: </label>' +
  73. '<input type="text" class="form-control" name="captionGallery[]">' +
  74. '</span>' +
  75. '</div>';
  76. }
  77. self.output.insertBefore(div, null);
  78. }
  79. })(file)
  80. reader.readAsDataURL(file);
  81. }
  82. }
  83. return FileUploader;
  84. })();
  85. if( $('.GalleryImageChoice').length > 0 ){
  86. var GalleryImageChoice = new FileUploader({className: '.GalleryImageChoice'});
  87. GalleryImageChoice.init();
  88. }
  89. //***************FEATURE IMAGES***************************************
  90. $(document).ready(function () {
  91. $('[data-toggle="tooltip"]').tooltip({
  92. html: true
  93. });
  94. $('.media').addClass('hide-element');
  95. $('#imagesUploadForm').submit(function (evt) {
  96. evt.preventDefault();
  97. });
  98. $('#edit').click(function () {
  99. console.log('click detected inside circl-o of edit');
  100. $('#edit').toggleClass('fa-circle-o').toggleClass('fa-check-circle');
  101. if ($('#edit').hasClass('fa-check-circle')) {
  102. $('#captionForImage').toggleClass('hide-element');
  103. } else {
  104. $('#captionForImage').toggleClass('hide-element');
  105. }
  106. });
  107. //Delete features Image
  108. // $(document).ready(function(){
  109. // $('#previewImages').on('click', '#delete', function(e){
  110. // e.preventDefault();
  111. // $(this).closest(".media").remove();
  112. // });
  113. // });
  114. //namespace variable to determine whether to continue or not
  115. var proceed = false;
  116. //Ensure that FILE API is supported by the browser to proceed
  117. if (window.File && window.FileReader && window.FileList && window.Blob) {
  118. if (window.webkitURL || window.URL) {
  119. $('#errorMessaage').removeClass('hide-element').addClass(
  120. '').html('');
  121. proceed = true;
  122. } else {
  123. $('#errorMessaage').removeClass('hide-element').addClass(
  124. 'alert-warning').html('');
  125. }
  126. } else {
  127. $('#errorMessaage').removeClass('hide-element').addClass(
  128. 'alert-warning').html('');
  129. }
  130. if (proceed) {
  131. var input = "";
  132. var formData = new FormData();
  133. $('input[name=featured_image]').on("change", function (e) {
  134. var counter = 0;
  135. var modalPreviewItems = "";
  136. input = this.files;
  137. $($(this)[0].files).each(function (i, file) {
  138. formData.append("file[]", file);
  139. });
  140. $('#previewImages').removeClass('hide-element');
  141. $('#imagesUpload').removeClass('disabled');
  142. var successUpload = 0;
  143. var failedUpload = 0;
  144. var extraFiles = 0;
  145. var size = input.length;
  146. $(input).each(function () {
  147. var reader = new FileReader();
  148. var uploadImage = this;
  149. console.log(this);
  150. reader.readAsArrayBuffer(this);
  151. reader.onload = function (e) {
  152. var magicNumbers = validateImage.magicNumbersForExtension(e);
  153. var fileSize = validateImage.isUploadedFileSizeValid(uploadImage);
  154. var extension = validateImage.uploadFileExtension(uploadImage);
  155. var isValidImage = validateImage.validateExtensionToMagicNumbers(magicNumbers);
  156. var thumbnail = validateImage.generateThumbnail(uploadImage);
  157. if (fileSize && isValidImage) {
  158. $('#' + counter).parents('.media').removeClass('hide-element');
  159. $('#' + counter).attr('src', thumbnail).height('200');
  160. $('#uploadDataInfo').removeClass('hide-element').addClass('alert-success');
  161. successUpload++;
  162. modalPreviewItems += carouselInsideModal.createItemsForSlider(thumbnail, counter);
  163. } else {
  164. $('#uploadDataInfo').removeClass('hide-element alert-success').addClass('alert-warning');
  165. failedUpload++;
  166. }
  167. counter++;
  168. if (counter === size) {
  169. $('#myCarousel').append(carouselInsideModal.createIndicators(successUpload, "myCarousel"));
  170. $('#previewItems').append(modalPreviewItems);
  171. $('#previewItems .item').first().addClass('active');
  172. $('#carouselIndicators > li').first().addClass('active');
  173. $('#myCarousel').carousel({
  174. interval: 2000,
  175. cycle: true
  176. });
  177. if (size > 4) {
  178. $('#toManyFilesUploaded').html("Only files displayed below will be uploaded");
  179. extraFiles = size - 4;
  180. }
  181. $('#filesCount').html(successUpload + " files are ready to upload");
  182. if (failedUpload !== 0 || extraFiles !== 0) {
  183. failedUpload === 0 ? "" : failedUpload;
  184. extraFiles === 0 ? "" : extraFiles;
  185. $('#filesUnsupported').html(failedUpload + extraFiles + " files were not selected for upload");
  186. }
  187. }
  188. };
  189. });
  190. });
  191. var toBeDeleted = [];
  192. var eachImageValues = [];
  193. $('.media').each(function (index) {
  194. var imagePresent = "";
  195. $("body").on("click", "#delete" + index, function () {
  196. imagePresent = $("#" + index).attr('src');
  197. $("#undo" + index).removeClass('hide-element');
  198. $("#" + index).attr('src', './img/200x200.gif');
  199. $("#delete" + index).addClass('hide-element');
  200. toBeDeleted.push(index);
  201. });
  202. $("body").on("click", "#undo" + index, function () {
  203. $("#" + index).attr('src', imagePresent);
  204. $("#undo" + index).addClass('hide-element');
  205. $("#delete" + index).removeClass('hide-element');
  206. var indexToDelete = toBeDeleted.indexOf(index);
  207. if (indexToDelete > -1) {
  208. toBeDeleted.splice(indexToDelete, 1);
  209. // console.log(toBeDeleted);
  210. $("#delete" + index).parent().find('input[type="text"]').prop('disabled', false).removeClass('disabled');
  211. }
  212. if (toBeDeleted.length === 4) {
  213. $('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');
  214. } else {
  215. $('#sendImagesToServer').prop('disabled', false).html('Update &amp; Preview');
  216. }
  217. });
  218. });
  219. var validateImage = {
  220. magicNumbersForExtension: function (event) {
  221. var headerArray = (new Uint8Array(event.target.result)).subarray(0, 4);
  222. var magicNumber = "";
  223. for (var counter = 0; counter < headerArray.length; counter++) {
  224. magicNumber += headerArray[counter].toString(16);
  225. }
  226. return magicNumber;
  227. },
  228. isUploadedFileSizeValid: function (fileUploaded) {
  229. var fileSize = fileUploaded.size;
  230. var maximumSize = 2097125;
  231. var isValid = "";
  232. if (fileSize <= maximumSize) {
  233. isValid = true;
  234. } else {
  235. isValid = false;
  236. }
  237. return isValid;
  238. },
  239. uploadFileExtension: function (fileUploaded) {
  240. var fileExtension = "";
  241. var imageType = "";
  242. imageType = fileUploaded.type.toLowerCase();
  243. fileExtension = imageType.substr((imageType.lastIndexOf('/') + 1));
  244. return fileExtension;
  245. },
  246. validateExtensionToMagicNumbers: function (magicNumbers) {
  247. var properExtension = "";
  248. if (magicNumbers.toLowerCase() === "ffd8ffe0" || magicNumbers.toLowerCase() === "ffd8ffe1" ||
  249. magicNumbers.toLowerCase() === "ffd8ffe8" ||
  250. magicNumbers.toLocaleLowerCase() === "89504e47") {
  251. properExtension = true;
  252. } else {
  253. properExtension = false;
  254. }
  255. return properExtension;
  256. },
  257. generateThumbnail: function (uploadImage) {
  258. if (window.URL)
  259. imageSrc = window.URL.createObjectURL(uploadImage);
  260. else
  261. imageSrc = window.webkitURL.createObjectURL(uploadImage);
  262. return imageSrc;
  263. }
  264. };
  265. var carouselInsideModal = {
  266. createIndicators: function (carouselLength, dataTarget) {
  267. var carouselIndicators = '<ol class = "carousel-indicators" id="carouselIndicators">';
  268. for (var counter = 0; counter < carouselLength; counter++) {
  269. carouselIndicators += '<li data-target = "#' + dataTarget + '"data-slide-to="' + counter + '"></li>';
  270. }
  271. carouselIndicators += "</ol>";
  272. return carouselIndicators;
  273. },
  274. createItemsForSlider: function (imgSrc, counter) {
  275. var item = '<div class = "item">' + '<img src="' + imgSrc + '" id="preview' + counter + '" /></div>';
  276. return item;
  277. }
  278. };
  279. }
  280. });
  281. // ********************File Attachment featured_image*******************
  282. $(document).ready(function(){
  283. $(".attachment_upload").on('change',function(){
  284. var loc = window.location;
  285. var base_url = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "");
  286. var uploader = $('input[name="featured_image"]');
  287. var data = new FormData();
  288. // var uploader = $('.attachment_upload[name="featured_image"]');
  289. uploader.each(function(){
  290. data.append('featured_image', $(this).prop('files')[0]);
  291. data.append('featureDescription', $('#featureDescription').val());
  292. data.append('featureCaption', $('#featureCaption').val());
  293. })
  294. data.append('_token', $('[name="csrf-token"]').attr('content'));
  295. $.ajax({
  296. url: base_url + "/panel/product_uploads/FeaturedImage",
  297. method: 'POST',
  298. data: data,
  299. processData: false,
  300. contentType: false,
  301. success: function(data) {
  302. }
  303. });
  304. });
  305. });
  306. //****************
  307. $(document).ready(function(){
  308. $(".attachment_upload_gallery").on('change',function(){
  309. var loc = window.location;
  310. var base_url = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "");
  311. for( let i=0; i<$(this).prop('files').length; i++ ){
  312. var uploader = $('.attachment_upload_gallery[name="gallery_image[]"]');
  313. var data = new FormData();
  314. uploader.each(function(){
  315. data.append('gallery_image[]', $(this).prop('files')[i]);
  316. data.append('descriptionGallery[]', $('#descriptionGallery').val());
  317. data.append('captionGallery[]', $('#captionGallery').val());
  318. })
  319. data.append('_token', $('[name="csrf-token"]').attr('content'));
  320. $.ajax({
  321. url: base_url + "/panel/product_uploads/GalleryImage",
  322. method: 'POST',
  323. data: data,
  324. processData: false,
  325. contentType: false,
  326. success: function(data) {
  327. }
  328. });
  329. };
  330. });
  331. });
  332. //delete
  333. // $('#previewImages').on('click', '#delete', function(){
  334. // var loc = window.location;
  335. // var base_url = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "");
  336. // var target = $(this).closest('.attachment_file_upload ');
  337. // Swal.fire({
  338. // title: 'آیا اطمینان دارید؟',
  339. // text: 'در صورت تایید فایل آپلود شده حذف خواهد شد.',
  340. // type: 'warning',
  341. // customClass: {
  342. // icon: 'swal2-arabic-question-mark'
  343. // },
  344. // showCancelButton: true,
  345. // confirmButtonColor: '#e3342f',
  346. // cancelButtonColor: '#38c172',
  347. // cancelButtonText: 'انصراف',
  348. // confirmButtonText: 'تایید و حذف'
  349. // }).then((result) => {
  350. // if(result.value){
  351. // Swal.fire({
  352. // title: 'در حال اجرای درخواست',
  353. // type: 'info',
  354. // allowEscapeKey: false,
  355. // allowOutsideClick: false,
  356. // onOpen: () => {
  357. // Swal.showLoading();
  358. // }
  359. // });
  360. //
  361. // $.ajax({
  362. // type: 'post',
  363. // url: base_url + "/panel/uploads/{upload}",
  364. // dataType: 'json',
  365. // data: data,
  366. // success: function(response){
  367. // target.remove();
  368. // Swal.fire({
  369. // title: 'عملیات موفق',
  370. // text: 'فایل با موفقیت حذف شد.',
  371. // type: 'info'
  372. // });
  373. // },
  374. // error: function(response){
  375. // if( response.status == 404 ){
  376. // var response_text = $.parseJSON( response.responseText )
  377. // Swal.fire({
  378. // title: 'خطا در حذف فایل',
  379. // html: response_text.errors.file[0],
  380. // type: 'error',
  381. // customClass: {
  382. // icon: 'swal2-arabic-question-mark'
  383. // },
  384. // confirmButtonText: 'تایید'
  385. // })
  386. // }
  387. // }
  388. // });
  389. // }
  390. // });
  391. // });
  392. //***************************************