
//**************************show images gallery**********************************************
$(document).ready(function(){
    $('.upload-widget').on('click', '.deleteGallary', function(e){
        e.preventDefault();
        $(this).closest(".DeleteImages").remove();
    });

});
var FileUploader = (function() {

    function FileUploader(options) {
        options = options || {};

        this.widget = document.querySelector(options.className);
        this.dropZone = this.widget.querySelector('.dropZone');
        this.input = this.widget.querySelector('.files');
        this.output = this.widget.querySelector('.list');
    };


    FileUploader.prototype.init = function() {
        var self = this;

        self.dropZone.addEventListener('drop', function(e) {self.handleFile(e, self);}, false);
        self.input.addEventListener('change', function(e) {self.handleFile(e, self);}, false);
        self.dropZone.addEventListener('dragover', self.handleDragOver, false);
    };

    //
    FileUploader.prototype.handleFile = function(evt, that) {
        var self = that;
        var files;

        evt.stopPropagation();
        evt.preventDefault();

        if (evt.type === 'change') {
            files = evt.target.files;
        } else if (evt.type === 'drop') {
            files = evt.dataTransfer.files;
        }

        self.selectLogic(files, self);
    };


    FileUploader.prototype.handleDragOver = function(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        evt.dataTransfer.dropEffect = 'link';
    };


    FileUploader.prototype.selectLogic = function(files, that) {
        var self = that;
        var reader;

        for (var i = 0, file; file = files[i]; i++) {

            reader = new FileReader();
            reader.onload = (function(theFile) {
                return function(e) {
                    var
                        div = document.createElement('div'),
                        canvas = document.createElement('canvas'),
                        ctx = canvas.getContext('2d'),
                        image = new Image(),
                        ratio,
                        thumb;
                    div.className = 'b';
                    image.src = e.target.result;
                    //size image
                    image.onload = function() {
                        ratio = 150/image.width;
                        ratio = 150/image.height;


                        canvas.width = image.width * ratio;
                        canvas.height = image.height * ratio;
                        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

                        // Gallery Description Input Fields
                        thumb = canvas.toDataURL(theFile.type);

                        div.innerHTML = '<div class="DeleteImages">' +
                            '<a href="" class="deleteGallary btn btn-danger pull-right position-absolute"> ' +
                            '<i class="icon fa fa-close"></i>' +
                            '</a>' +
                            '<img class="thumb img-thumbnail" style="width: 200px; height: 150px;" src="' + thumb + '" title="' + escape(theFile.name) + '">' +
                            '<span class="form-input py-3 md-form" style="display: block;"> ' +
                            '<label for="description">توضیحات: </label>' +
                            '<input type="text" class="form-control" name="descriptionGallery[]">\n' +
                            '<label for="caption">عنوان: </label>' +
                            '<input type="text" class="form-control" name="captionGallery[]">' +
                            '</span>' +
                            '</div>';
                    }



                    self.output.insertBefore(div, null);
                }
            })(file)
            reader.readAsDataURL(file);
        }
    }
    return FileUploader;
})();

var test = new FileUploader({className: '.test'});
test.init();

//***************FEATURE IMAGES***************************************
$(document).ready(function () {
    $('[data-toggle="tooltip"]').tooltip({
        html: true
    });
    $('.media').addClass('hide-element');
    $('#imagesUploadForm').submit(function (evt) {
        evt.preventDefault();
    });
    $('#edit').click(function () {
        console.log('click detected inside circl-o of edit');
        $('#edit').toggleClass('fa-circle-o').toggleClass('fa-check-circle');
        if ($('#edit').hasClass('fa-check-circle')) {
            $('#captionForImage').toggleClass('hide-element');
        } else {
            $('#captionForImage').toggleClass('hide-element');
        }
    });
    //Delete features Image
    $(document).ready(function(){
        $('#previewImages').on('click', '#delete', function(e){
            e.preventDefault();
            $(this).closest(".media").remove();
        });
    });
    //namespace variable to determine whether to continue or not
    var proceed = false;
    //Ensure that FILE API is supported by the browser to proceed
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        if (window.webkitURL || window.URL) {
            $('#errorMessaage').removeClass('hide-element').addClass(
                '').html('');
            proceed = true;
        } else {
            $('#errorMessaage').removeClass('hide-element').addClass(
                'alert-warning').html('');
        }

    } else {
        $('#errorMessaage').removeClass('hide-element').addClass(
            'alert-warning').html('');
    }
    if (proceed) {
        var input = "";
        var formData = new FormData();
        $('input[name=featured_image]').on("change", function (e) {
            var counter = 0;
            var modalPreviewItems = "";
            input = this.files;
            $($(this)[0].files).each(function (i, file) {
                formData.append("file[]", file);
            });
            $('#previewImages').removeClass('hide-element');
            $('#imagesUpload').removeClass('disabled');
            var successUpload = 0;
            var failedUpload = 0;
            var extraFiles = 0;
            var size = input.length;
            $(input).each(function () {
                var reader = new FileReader();
                var uploadImage = this;
                console.log(this);
                reader.readAsArrayBuffer(this);
                reader.onload = function (e) {
                    var magicNumbers = validateImage.magicNumbersForExtension(e);
                    var fileSize = validateImage.isUploadedFileSizeValid(uploadImage);
                    var extension = validateImage.uploadFileExtension(uploadImage);
                    var isValidImage = validateImage.validateExtensionToMagicNumbers(magicNumbers);
                    var thumbnail = validateImage.generateThumbnail(uploadImage);
                    if (fileSize && isValidImage) {
                        $('#' + counter).parents('.media').removeClass('hide-element');
                        $('#' + counter).attr('src', thumbnail).height('200');
                        $('#uploadDataInfo').removeClass('hide-element').addClass('alert-success');
                        successUpload++;
                        modalPreviewItems += carouselInsideModal.createItemsForSlider(thumbnail, counter);

                    } else {
                        $('#uploadDataInfo').removeClass('hide-element alert-success').addClass('alert-warning');
                        failedUpload++;
                    }
                    counter++;
                    if (counter === size) {
                        $('#myCarousel').append(carouselInsideModal.createIndicators(successUpload, "myCarousel"));
                        $('#previewItems').append(modalPreviewItems);
                        $('#previewItems .item').first().addClass('active');
                        $('#carouselIndicators > li').first().addClass('active');
                        $('#myCarousel').carousel({
                            interval: 2000,
                            cycle: true
                        });
                        if (size > 4) {
                            $('#toManyFilesUploaded').html("Only files displayed below will be uploaded");
                            extraFiles = size - 4;
                        }

                        $('#filesCount').html(successUpload + " files are ready to upload");
                        if (failedUpload !== 0 || extraFiles !== 0) {
                            failedUpload === 0 ? "" : failedUpload;
                            extraFiles === 0 ? "" : extraFiles;
                            $('#filesUnsupported').html(failedUpload + extraFiles + " files were not selected for upload");
                        }

                    }
                };
            });

        });

        var toBeDeleted = [];
        var eachImageValues = [];
        $('.media').each(function (index) {
            var imagePresent = "";
            $("body").on("click", "#delete" + index, function () {
                imagePresent = $("#" + index).attr('src');
                $("#undo" + index).removeClass('hide-element');
                $("#" + index).attr('src', './img/200x200.gif');
                $("#delete" + index).addClass('hide-element');
                toBeDeleted.push(index);

            });
            $("body").on("click", "#undo" + index, function () {
                $("#" + index).attr('src', imagePresent);
                $("#undo" + index).addClass('hide-element');
                $("#delete" + index).removeClass('hide-element');
                var indexToDelete = toBeDeleted.indexOf(index);
                if (indexToDelete > -1) {
                    toBeDeleted.splice(indexToDelete, 1);
                    // console.log(toBeDeleted);
                    $("#delete" + index).parent().find('input[type="text"]').prop('disabled', false).removeClass('disabled');
                }
                if (toBeDeleted.length === 4) {
                    $('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');

                } else {
                    $('#sendImagesToServer').prop('disabled', false).html('Update &amp; Preview');
                }
            });
        });


        var validateImage = {
            magicNumbersForExtension: function (event) {
                var headerArray = (new Uint8Array(event.target.result)).subarray(0, 4);
                var magicNumber = "";
                for (var counter = 0; counter < headerArray.length; counter++) {
                    magicNumber += headerArray[counter].toString(16);
                }
                return magicNumber;
            },
            isUploadedFileSizeValid: function (fileUploaded) {
                var fileSize = fileUploaded.size;
                var maximumSize = 2097125;
                var isValid = "";
                if (fileSize <= maximumSize) {
                    isValid = true;
                } else {
                    isValid = false;
                }
                return isValid;
            },
            uploadFileExtension: function (fileUploaded) {
                var fileExtension = "";
                var imageType = "";
                imageType = fileUploaded.type.toLowerCase();
                fileExtension = imageType.substr((imageType.lastIndexOf('/') + 1));
                return fileExtension;
            },
            validateExtensionToMagicNumbers: function (magicNumbers) {
                var properExtension = "";
                if (magicNumbers.toLowerCase() === "ffd8ffe0" || magicNumbers.toLowerCase() === "ffd8ffe1" ||
                    magicNumbers.toLowerCase() === "ffd8ffe8" ||
                    magicNumbers.toLocaleLowerCase() === "89504e47") {
                    properExtension = true;

                } else {
                    properExtension = false;
                }
                return properExtension;
            },
            generateThumbnail: function (uploadImage) {
                if (window.URL)
                    imageSrc = window.URL.createObjectURL(uploadImage);
                else
                    imageSrc = window.webkitURL.createObjectURL(uploadImage);
                return imageSrc;
            }
        };
        var carouselInsideModal = {
            createIndicators: function (carouselLength, dataTarget) {
                var carouselIndicators = '<ol class = "carousel-indicators" id="carouselIndicators">';
                for (var counter = 0; counter < carouselLength; counter++) {
                    carouselIndicators += '<li data-target = "#' + dataTarget + '"data-slide-to="' + counter + '"></li>';
                }
                carouselIndicators += "</ol>";
                return carouselIndicators;
            },
            createItemsForSlider: function (imgSrc, counter) {
                var item = '<div class = "item">' + '<img src="' + imgSrc + '" id="preview' + counter + '" /></div>';
                return item;
            }
        };
    }
});

