$(function () {
    var $productList = $('#productList');
    var $catList = $('#catList');

    if ($productList.length > 0) {
        $productList.dataTable({
            ordering: false,
            searching: false,
            paging: false,
            info: false,
            "order": [
                [0, "desc"]
            ],
            "dom": '<f<t><"bottom"ilp>><"clear">',
            language: {
                url: language,
            }
        });
    }

    if ($catList.length > 0) {
        $catList.dataTable({
            ordering: false,
            searching: false,
            paging: false,
            info: false,
            dom: '<f<t><"bottom"ilp>><"clear">',
            language: {
                url: language,
            }
        });
    }

    // Wysyłanie formularza paginacji.
    $('select[name=per_page]').change(function () {
        $(this).parent().submit();
    });

    if ($('.select2').length > 0) {
        $('.select2').select2();
    }
    // Zablokowanie wysłania formularza jeśli zdjęcie jest za duże
    var fileInput = $('.InputFileHidden');
    var maxSize = fileInput.data('max-size');
    $('#newsNew').submit(function(e){
        $('.komunikatBleduImage').addClass('hide');
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                $('.komunikatBleduImage').removeClass('hide');
                return false;
            }
        }

    });

    // Sprawdza czy zdjęcie zostało dodane, jeśli nie to zamyka cropper
    $('.InputFileHidden').on("change", function(ev) {
        var $windowModalCropper = $('#windowModalCropper');

        if ($windowModalCropper.length > 0) {
            $windowModalCropper.foundation('open');
        }
    });
});

// Cropper
$(function () {
    "use strict";

    if($('#cropperImage').length>0){
        var prefix = $('#cropperImage').data('prefix');
        var image = document.getElementById('cropperImage');
        var paramWidth = $('#imageDataFromParameter').attr('cropper-width');
        var paramHeight = $('#imageDataFromParameter').attr('cropper-height');
        var uploadedImageURL;
        var cropper = new Cropper(image);
        var inputImage = document.getElementById(prefix+'_file');

        if (URL) {
            inputImage.onchange = function () {
                var files = this.files;
                var file;

                if (cropper && files && files.length) {
                    file = files[0];

                    if (/^image\/\w+/.test(file.type)) {
                        if (uploadedImageURL) {
                            URL.revokeObjectURL(uploadedImageURL);
                        }

                        image.src = uploadedImageURL = URL.createObjectURL(file);
                        cropper.destroy();
                        cropper = new Cropper(image, {
                            aspectRatio: paramWidth / paramHeight,
                            maxCanvasWidth: paramWidth,
                            maxCanvasHeight: paramHeight,
                            responsive: false,
                            autoCropArea: 0.9,
                            scalable: false,
                            cropBoxResizable: true,
                            dragMode: 'move',
                            rotatable: false,
                            toggleDragModeOnDblclick: true,
                            viewMode: 1,
                            crop: function(e) {
                                var x = e.detail.x;
                                var y = e.detail.y;
                                var width = e.detail.width;
                                var height = e.detail.height;
                                $('#'+prefix+'_crop_x').val(x);
                                $('#'+prefix+'_crop_y').val(y);
                                $('#'+prefix+'_crop_width').val(width);
                                $('#'+prefix+'_crop_height').val(height);
                            }
                        });
                    } else {
                        window.alert('Please choose an image file.');
                    }
                }
            };
        } else {
            inputImage.disabled = true;
            inputImage.parentNode.className += ' disabled';
        }
        document.getElementById('Wyslijfoto').onclick = function () {
            var varDataUrl = cropper.getCroppedCanvas().toDataURL('image/jpeg');
            document.getElementById('cropperPreview').setAttribute("src", varDataUrl);
            $('#admin_ecommerce_category_cropSave').val(true);
            $('#cropperPreview').attr('data-open', 'windowModalCropper');
        }
    }
});

// Cropper edit.
$(function () {
    "use strict";

    var $windowModalEditCropper = $('#windowModalEditCropper');
    var $editCropperImage = $('#editCropperImage');
    var $editImageDataFromParameter = $('#editImageDataFromParameter');

    if ($windowModalEditCropper.length > 0) {
        $('.InputFileHidden').on('change', function(e) {
            $('.komunikatBleduImage').addClass('hide');
            if ($windowModalEditCropper.length > 0) {
                $windowModalEditCropper.foundation('open');
            }
        });
    }

    if($editCropperImage.length>0){
        var image = $editCropperImage[0];
        var paramWidth = $editImageDataFromParameter.attr('cropper-width');
        var paramHeight = $editImageDataFromParameter.attr('cropper-height');
        var originalImageURL = image.src;
        var uploadedImageURL;
        var cropper = new Cropper(image);
        var inputImage = $('#file_photo')[0];
        var file;

        if (URL) {
            inputImage.onchange = function () {
                var files = this.files;

                if (cropper && files && files.length) {
                    file = files[0];

                    if (/^image\/\w+/.test(file.type)) {
                        if (uploadedImageURL) {
                            URL.revokeObjectURL(uploadedImageURL);
                        }

                        image.src = uploadedImageURL = URL.createObjectURL(file);
                        cropper.destroy();
                        cropper = new Cropper(image, {
                            aspectRatio: paramWidth / paramHeight,
                            maxCanvasWidth: paramWidth,
                            maxCanvasHeight: paramHeight,
                            responsive: false,
                            autoCropArea: 0.9,
                            scalable: false,
                            cropBoxResizable: true,
                            dragMode: 'move',
                            rotatable: false,
                            toggleDragModeOnDblclick: true,
                            viewMode: 1,
                            crop: function(e) {
                                var x = e.detail.x;
                                var y = e.detail.y;
                                var width = e.detail.width;
                                var height = e.detail.height;
                                $('#crop_x').val(x);
                                $('#crop_y').val(y);
                                $('#crop_width').val(width);
                                $('#crop_height').val(height);
                            }
                        });
                    } else {
                        window.alert('Please choose an image file.');
                    }
                }
            };
        } else {
            inputImage.disabled = true;
            inputImage.parentNode.className += ' disabled';
        }

        $('#save_photo').click(function (e) {
            var varDataUrl = cropper.getCroppedCanvas().toDataURL('image/jpeg');

            $('#editCropperPreview').attr('src', varDataUrl);
            $('#cropSave').val(true);
            $('#editCropperPreview').attr('data-open', 'windowModalEditCropper');

            var formData = new FormData();
            formData.append('file', file, file.name);
            formData.append('x', $('#crop_x').val());
            formData.append('y', $('#crop_y').val());
            formData.append('width', $('#crop_width').val());
            formData.append('height', $('#crop_height').val());
            formData.append('cropSave', $('#cropSave').val());

            var fileInput = $('.InputFileHiddenEdit');
            var maxSize = fileInput.data('max-size');

            if(file.size > maxSize){
                $('.komunikatBleduImage').removeClass('hide');
            } else {
                $.ajax({
                    type: 'POST',
                    dataType: 'JSON',
                    data: formData,
                    processData: false,
                    contentType: false,
                    url: $('#editCropperImage').data('save-url'),
                    success: function (response) {
                        var imageUrl = $('#image-wrapper').data('image-url');
                        var $ul = $('#image-wrapper .image-list');

                        var $li = '<li data-id="'+response.id+'">' +
                            '<img src="'+imageUrl+response.name+'">' +
                            '<a href="'+response.delete_link+'" class="remove-image">Usuń</a>' +
                            '</li>';
                        $ul.append($li);
                        $editCropperImage.attr('src', originalImageURL);
                        $('#editCropperPreview').attr('src', originalImageURL);
                        uploadedImageURL = originalImageURL;
                    }
                });
            }
        });
    }

    $('#image-wrapper').on('click', '.remove-image', function (e) {
        e.preventDefault();
        var $li = $(this).parent();

        $.get($(this).attr('href'), function (response) {
            $li.remove();
        });
    });

    // Usuwanie.
    $('#delete_delete').change(function () {
        if (this.checked) {
            $('#AdminDeleteInput').removeAttr('disabled');
        } else {
            $('#AdminDeleteInput').attr('disabled', 'disabled');
        }
    });

    // usuwanie kategorii newsów
    $('#deleteCategory').change(function () {
        if(this.checked && $("#countNews").attr("wartosc")==0 && $("#countChildren").attr("wartosc")==0){
            $('#CatDeleteInput').removeAttr('disabled');
            $('#confirmDelete').css({opacity: "1", filter: "alpha(opacity=100)", "pointer-events": "all"});
        } else if(this.checked) {
            $('#confirmDelete').css({opacity: "1", filter: "alpha(opacity=100)", "pointer-events": "all"});
        } else {
            $('#confirmDelete').css({opacity: "0.3", filter: "alpha(opacity30)", "pointer-events": "none"});

        }
    });
    $('#deleteAll').change(function () {
        if(this.checked){
            $('#CatDeleteInput').removeAttr('disabled');
            $('#confirmDeleteSubcategories').css({opacity: "0.3", filter: "alpha(opacity=30)", "pointer-events": "none"});
            $('#selectCategories').css({opacity: "0.3", filter: "alpha(opacity=30)", "pointer-events": "none"});
        } else {
            $('#confirmDeleteSubcategories').css({opacity: "1", filter: "alpha(opacity=100)", "pointer-events": "all"});
            if($('input[name=noDeleteNews]').checked){
                $('#CatDeleteInput').removeAttr('disabled');
                if($('input[name=noDeleteNews]:checked').val()=="changeCat") {
                    $('#selectCategories').css({opacity: "1", filter: "alpha(opacity=100)", "pointer-events": "all"});
                }
            } else {
                $('#CatDeleteInput').attr('disabled', 'disabled');
            }
        }
    });
    $('input[name="noDeleteNews"]').change(function () {
        $('#CatDeleteInput').removeAttr('disabled');
        if($('input[name=noDeleteNews]:checked').val()=="changeCat"){
            $('#selectCategories').css({opacity: "1", filter: "alpha(opacity=100)", "pointer-events": "all"});
        } else {
            $('#selectCategories').css({opacity: "0.3", filter: "alpha(opacity=30)", "pointer-events": "none"});
        }
    });
});
