$(function () {
    "use strict";
    // wyświetlanie newsów
    $('.selectCategory').change(function () {
        $('#selectCategoryForm').submit();
    });
    //wysyłanie formularza paginacji
    $('select[name=per_page]').change(function () {
        $(this).parent().submit();
    })

    //walidacja formularza dodawanie i edycja newsa
    $('#newsNew').submit(function () {
        if($('.chosen-search-input').val()=="Select Some Options"){
            $('#contentValidationCat').css('display', 'block');
            return false;
        }
    });

    // 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');
        }
    });

    // Włącza dodawanie tagów
    $('.addTag').on('click', function () {
        $('.formAddTags').removeClass('hide');
        $(this).addClass('hide');
    });

    // Włączenie selec2 i obsługa wyboru tagów
    if($('.tagsSelect').length > 0) {
        $('.tagsSelect').select2({
            tags: true,
            tokenSeparators: [','],
        });

        $('.tagsSelect').on('select2:selecting', function (e) {
            //console.log(e.params.args.data);
            var id = e.params.args.data.id;
            var name = e.params.args.data.text;
            if (id == name) {
                //console.log(id);
                $.ajax({
                    url: Routing.generate('wi_admin_tag_new'),
                    data: {
                        tagName: name,
                    },
                    type: 'GET',
                    success: function (response) {
                         if ($('.tagsSelect option[value="' + response + '"]').length > 0){
                             $('.tagsSelect option[value="' + name + '"]').remove();
                             $('.tagsSelect option[value="' + response + '"]').prop("selected","selected");
                         } else {
                             $('.tagsSelect option[value="' + name + '"]').remove();
                             var newOption = new Option(name, response, true, true);
                             $('.tagsSelect').append(newOption).trigger('change');
                         }
                    },
                    error: function () {
                        $('.tagsSelect option[value="' + name + '"]').remove();
                    }
                });
            }
        });
    }
});

$(function () {
    "use strict";
    if($('.tooltipster-top').length>0){
        $('.tooltipster-top').tooltipster({
            position: "top"
        });
    }
});

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

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

$(function () {
    "use strict";
    // usuwanie newsa
    $('#deleteNews').change(function () {
        if (this.checked) {
            $('#NewsDeleteInput').removeAttr('disabled');
        } else {
            $('#NewsDeleteInput').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"});
        }
    });
});

// Chosen
$(function () {
    "use strict";
    // Włączenie chosen - dodawanie i edycja newsa - wybór kategorii
    if($('.chosenSelectCategory').length>0){
        $('.chosenSelectCategory').select2();
    }

    var $select2 = $('.select2');

    if ($select2.length > 0) {
        $select2.select2({
            containerCssClass: function (element) {
                return element[0].className.replace(element[0].className.replace(/is-invalid-input/, ''), '');
            },
        });
    }
});

// Date time picker
$(function () {
    "use strict";
    if($('.datePicker').length>0){
        $('.datePicker').datetimepicker({
            timepicker:true,
            format:'d-m-Y H:i',
            closeOnDateSelect:true,
            scrollInput: false
        });
    }
});


// Cropper
$(function () {
    "use strict";
    if($('#cropperImage').length>0){
        var image = document.getElementById('cropperImage');
        var paramWidth = $('#imageDataFromParameter').attr('cropper-width');
        var paramHeight = $('#imageDataFromParameter').attr('cropper-height');


        var originalImageURL = image.src;
        var uploadedImageURL;
        var cropper = new Cropper(image);

        //var inputImage = document.getElementById('appbundle_photo_file');
        var inputImage = document.getElementById('wi_admin_newsbundle_news_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;
                                // $('#appbundle_photo_crop_x').val(x);
                                // $('#appbundle_photo_crop_y').val(y);
                                // $('#appbundle_photo_crop_width').val(width);
                                // $('#appbundle_photo_crop_height').val(height);
                                $('#wi_admin_newsbundle_news_crop_x').val(x);
                                $('#wi_admin_newsbundle_news_crop_y').val(y);
                                $('#wi_admin_newsbundle_news_crop_width').val(width);
                                $('#wi_admin_newsbundle_news_crop_height').val(height);
                            }
                        });

                        // inputImage.value = inputImage;
                    } 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.getElementsByName("file")[0].setAttribute("name", varDataUrl);

             document.getElementById('cropperPreview').setAttribute("src", varDataUrl);
            // $('#appbundle_photo_cropSave').val(true);
            $('#wi_admin_newsbundle_news_cropSave').val(true);
            //$('.previewImage').removeClass('notImageAdded');
            $('#cropperPreview').attr('data-open', 'windowModalCropper');

            // $('#image-upload-form').submit();
        }
    }
});
