$(function () {
    var $deleteForm = $('#delete_delete');

    if ($deleteForm.length > 0) {
        $deleteForm.change(function (e) {
            if (this.checked) {
                $('#AdminDeleteInput').removeAttr('disabled');
            } else {
                $('#AdminDeleteInput').attr('disabled', 'disabled');
            }
        });
    }

    $('.item[data-url]').click(function (e) {
        var link = $(this).data('url');
        location.href = link;
    });

    $('.item[data-url] .item-menu').click(function (e) {
        e.stopPropagation();
        var id = $(this).find('span').attr('data-toggle');
        $('#' + id).foundation('toggle');
    });

    // Kadrowanie zdjęcia.
    $('.InputFileHidden').on('change', function (e) {
        $('#windowModalCropper').foundation('open');
    });

    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('wi_admin_gallerybundle_gallery_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;
                                $('#wi_admin_gallerybundle_gallery_crop_x').val(x);
                                $('#wi_admin_gallerybundle_gallery_crop_y').val(y);
                                $('#wi_admin_gallerybundle_gallery_crop_width').val(width);
                                $('#wi_admin_gallerybundle_gallery_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);
            $('#wi_admin_gallerybundle_gallery_cropSave').val(true);

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

    var $prettyPhotoLink = $('a[rel^="prettyPhoto[1]"]');

    if ($prettyPhotoLink.length > 0) {
        $prettyPhotoLink.prettyPhoto({
            theme: 'minimal',
        });
    }

    var $dropArea = $('#gallery-drop-area');

    if ($dropArea.length > 0) {
        var $currentNumber = $('#current-number');
        var $totalNumber = $('#total-number');
        var $uploadProgress = $('#upload-progress');

        $dropArea.on('dragenter', function (e) {
            $(this).addClass('dragover');
        });
        $dropArea.on('dragover', function (e) {
            $(this).addClass('dragover');
        });
        $dropArea.on('dragleave', function (e) {
            $(this).removeClass('dragover');
        });
        $dropArea.on('drop', function (e) {
            $(this).removeClass('dragover');
        });

        var uploader = new plupload.Uploader({
            browse_button: 'gallery-button',
            url: Routing.generate('wi_admin_galleries_photos_upload', { id: $dropArea.data('id') }),
            chunk_size: '200kb',
            max_retries: 3,
            unique_names: false,
            drop_element: 'gallery-drop-area',
            filters: {
                mime_types : [
                    { title : "Image files", extensions : "jpeg,jpg,png" }
                ]
            },
            init: {
                FilesAdded: function (up, files) {
                    $currentNumber.text('0');
                    $totalNumber.text(files.length);
                    uploader.start();
                    $('#upload-progress-wrapper').foundation('open');
                },
                UploadProgress: function (up, file) {
                    $uploadProgress
                        .find('span').width(up.total.percent + '%')
                        .find('p').text(up.total.percent + '%')
                    ;
                    $currentNumber.text(up.total.uploaded);
                },
                UploadComplete: function (up, files) {
                    $uploadProgress
                        .find('span').width(up.total.percent + '%')
                        .find('p').text(up.total.percent + '%')
                    ;
                    $currentNumber.text(up.total.uploaded);
                    location.reload();
                }
            }
        });

        // Inicjalizacja mechanizmu do przesyłania plików.
        uploader.init();
    }

    // Kopiowanie URL.
    $('#copy-to-clipboard').bind('click', function () {
        $('#gallery_url')[0].select();
        document.execCommand('copy');
        $('.infoCopyUrl').css({'opacity': 1, 'z-index': 1}).animate({'opacity': 0, 'z-index': -1}, 3000);
    });

    // Kopiowanie URL.
    $('#copy-to-clipboard-2').bind('click', function () {
        $('#photo_url')[0].select();
        document.execCommand('copy');
        $('.infoCopyUrl').css({'opacity': 1, 'z-index': 1}).animate({'opacity': 0, 'z-index': -1}, 3000);
    });

    // Widok listy.
    $('.gallery-view').click(function (e) {
        if ($(this).data('view') == 'grid') {
            localStorage.setItem('wicms3_gallery_list_view', 0);
        } else {
            localStorage.setItem('wicms3_gallery_list_view', 1);
        }

        changeView();
    });

    function changeView() {
        var $items = $('.gallery-wrapper .items');

        if (parseInt(localStorage.getItem('wicms3_gallery_list_view'))) {
            $items.addClass('list')
        } else {
            $items.removeClass('list')
            localStorage.setItem('wicms3_gallery_list_view', 0);
        }
    }

    changeView();
});
