var ImageCrop = (function() {

    var removeActiveClassElement = function() {
        $('[data-action="crop"]', ImageCrop.selectorContext).removeClass('active');
    };

    var activeElement = function(elem) {
        removeActiveClassElement();
        elem.addClass('active');
    }

    var initialize = function() {
        $('[data-action="crop"]', ImageCrop.selectorContext).on('click', function(e){
            e.preventDefault();
            var ratio  = $(this).attr('data-ratio');
            var cords  = $(this).attr('data-cords').split(',');
            var cropId = $(this).attr('data-crop-id');

            activeElement($(this));

            initCrop(ratio, cords, cropId);
        });

        $('#tab_crop', ImageCrop.selectorContext).on('click', function(e){
            if($(e.target).is('button') === false && $(e.target).is('input') === false) {
                removeCrop();
            }
        });

        $('#apply-crop', ImageCrop.selectorContext).on('click', function(e){
            e.preventDefault();
            applyCrop();
        });
    };

    var initCrop = function(aspectRatio, cords, cropId) {

        if (!ImageCrop.jcropApi) {
            $('#crop-target', ImageCrop.selectorContext).Jcrop({
                bgFade: true,
                bgOpacity: .2,
                setSelect: cords,
                aspectRatio: aspectRatio,
                trueSize: ImageCrop.trueSize
            }, function () {
                ImageCrop.jcropApi = this;
            });
        } else {
            animateHandler(aspectRatio, cords);
        }

        ImageCrop.cropSelected = cropId;

        toogleApplyButton();
    };

    var animateHandler = function(aspectRatio, cords) {

        ImageCrop.jcropApi.setOptions({
            aspectRatio: aspectRatio
        });

        ImageCrop.jcropApi.animateTo(cords);

        return false;
    };

    var removeCrop = function() {
        if (ImageCrop.jcropApi) {
            ImageCrop.jcropApi.destroy();
            ImageCrop.jcropApi = null;
            ImageCrop.cropSelected = null;
        }

        removeActiveClassElement();
        toogleApplyButton();

    };

    var checkWatermarksApplied = function () {
        $('#c-crops__content--info', ImageCrop.selectorContext).addClass("loading");
        unCheckWatermarks();

        $.ajax({
            url: Routing.generate('designer_asset_crop_watermarks', { assetId: ImageCrop.asset, cropId: ImageCrop.cropSelected}),
            success: function (response) {
                triggerWatermarks(response.watermarks);
            },
            complete: function () {
                $('#c-crops__content--info', ImageCrop.selectorContext).removeClass("loading");
            }
        });
    };

    var unCheckWatermarks = function () {
        var $element = $("input[name='watermark[]']", ImageCrop.selectorContext);

        $element.parent().removeClass("checked");
        $element.attr("checked", false);
    };

    var triggerWatermarks = function (watermarks) {
        $("input[name='watermark[]']", ImageCrop.selectorContext).each(function () {
            var $watermark = $(this);

            if (watermarks.indexOf(parseInt($watermark.val())) !== -1) {
                $watermark.parent().addClass("checked");
                $watermark.attr("checked", true);
            }
        });
    };

    var toogleApplyButton = function() {
        $('#apply-crop', ImageCrop.selectorContext).prop('disabled', ImageCrop.cropSelected ? false : true);
        checkWatermarksApplied()
    };

    var applyCrop = function() {
        if (ImageCrop.cropSelected && ImageCrop.jcropApi) {

            $('.cs-module-spinner', ImageCrop.selectorContext).show();
            $("[data-crops-results]", ImageCrop.selectorContext).addClass("loading")

            var watermarks = [];
            $("input[name='watermark[]']:checked", ImageCrop.selectorContext).each(function (i) {
                watermarks[i] = $(this).val();
            });

            $.ajax({
                url: Routing.generate('designer_asset_crops_create', { assetId: ImageCrop.asset, cropId: ImageCrop.cropSelected}),
                data: {cords:ImageCrop.jcropApi.tellSelect(), watermarks: watermarks},
                method: 'POST',
                success: function(response) {
                    if (response) {
                        $("[data-crops-results]", ImageCrop.selectorContext).html(response);
                    }

                    $("[data-crops-results]", ImageCrop.selectorContext).removeClass("loading");
                },
                error: function() {
                    showToastrNotification('error',Translator.trans( 'cs_assets.messages.crop.create_error'));
                },
                complete: function() {
                    $('.cs-module-spinner', ImageCrop.selectorContext).hide();
                }
            });
        }
    };

    var displayResizeBlock = function(isPrivate) {
        $.ajax({
            url: Routing.generate('admin_image_resize_blocks', { asset: ImageCrop.asset}),
            method: 'POST',
            success: function(response) {
                var wrapper = $('#resize-blocks', ImageCrop.selectorContext);
                var parent = wrapper.parent();
                if (wrapper.length > 0) {
                    wrapper.remove();
                    //wrapper.replaceWith(response);
                    parent.append(response);

                    parent.find("img").each(function(k,v){
                        var d = new Date(),
                            src = $(v).attr("src");

                        if (isPrivate !== true) {
                            src = src + "?" + d.getTime();
                        }

                        $(v).attr("src", src);
                    });

                    // Remove scroll effect
                    //$('body').animate({
                    //    scrollTop: $('#resize-blocks').offset().top
                    //}, 1000);
                }
            }
        });
    };


    var initForm = function() {
        bindCollectionsEvents();
        preSubmitActions();
    };

    var bindCollectionsEvents = function() {

        var options = {
            'addElement' : '[data-add="crop"]',
            'deleteElement' : '[data-delete="crop"]'
        };

        options[SimpleFormCollection.AFTER_ADD] = function(element) {

            // Remove empty message if exists
            $('[role="alert"]', ImageCrop.selectorContext).remove();

            if (!$(element).data("persisted")) {
                initSelect2(element);
            }

            $(element).find("[data-collection]").sortable({
                placeholder: 'portlet-sortable-placeholder',
                forcePlaceholderSize: true
            });

            initCollapseEvents(element);
            initInlineEditableFields(element);
            initSpinners(element);
            initCheckbox(element);
            bindQuestionItemsCollection(element);

        };

        options[SimpleFormCollection.REMOVE] = function(element) {
            var _this = this;

            var modal = window.bootstrap.modal.show(
                Translator.trans("imageCrop.modal.crop.title"),
                Translator.trans("imageCrop.modal.crop.message"),
                Translator.trans("cs_core.action.accept")
            );


            modal
                .find('[data-btn-type="save"]')
                .on("click", function () {
                    _this.removeElement(element);
                    modal.modal('hide');
                })
                .end();
        };

        $('[data-collection="content-crop"]').SimpleFormCollection(options);

    };

    var fixResizeValues = function (element) {
        $(element).find('.gf-spinner').on("change", function(){
            var value  = $(this).spinner("value");
            var container = $(this).parentsUntil(".item");
            var resizeContainer = $(this).parents(".resize-item");
            var cropWidth  = container.find('[data-type-crop-width]').val();
            var cropHeight = container.find('[data-type-crop-height]').val();

            var isWidth = $(this).has('[id$="width"]').length == 1;
            var isHeight = $(this).has('[id$="height"]').length == 1;

            if (cropWidth && cropHeight) {
                var ratio = cropWidth > cropHeight ? cropWidth/cropHeight : cropHeight/cropWidth ;

                if (isWidth) {
                    if (value >= cropWidth) {
                        value = cropWidth;
                    }

                    var h = cropWidth > cropHeight ? Math.round(value/ratio) : Math.round(value*ratio);

                    resizeContainer.find('.gf-spinner.height').spinner("value", h);
                } else if(isHeight) {
                    if (value >= cropHeight) {
                        value = cropHeight;
                    }

                    var w = cropWidth > cropHeight ? Math.round(value*ratio) : Math.round(value/ratio);

                    resizeContainer.find('.gf-spinner.width').spinner("value", w);
                }
            }

            $(this).spinner("value", value);

        });
    };

    /**
     * Bind pre-submit actions.
     */
    var preSubmitActions = function(){
        $('form').on('submit', function(e) {

            var success = false;
            var countDefaults = 0;

            $('[id$="position"][data-type="crop-position"]', $(this)).each(function(k){
                $(this).val(k+1);
            });

            $('[data-collection="content-crop"] .item').each(function(){
                $('[id$="position"][data-type="resize-position"]', $(this)).each(function(k){
                    $(this).val(k+1);
                });
            });


            if ($('[type="checkbox"]').length) {
                $('[type="checkbox"]').each(function(){
                    var state = $(this).bootstrapSwitch("state");

                    if (state === true) {
                        success = true;
                        countDefaults++;
                    }
                });

                if (countDefaults > 1) {
                    success = false;
                    showToastrNotification('error', Translator.trans('imageCrop.messages.error.maxDefaultCrops'));
                } else if (success === false) {
                    showToastrNotification('error', Translator.trans('imageCrop.messages.error.noDefaultCrops'));
                }
            } else {
                success = true;
            }

            return success;
        });
    };

    var initCollapseEvents = function(element) {
        $(element).find('i[data-toggle="collapse"]').on("click", function(){
            $(this).parents(".item").toggleClass("portlet-sortable portlet-sortable-empty");
        });
    };

    var bindQuestionItemsCollection = function(element) {

        var options = {
            'addElement' : '[data-add="resize"]',
            'deleteElement' : '[data-delete="resize"]',
            'context' : element,
            'prototypeFieldName' : '__NAME_OPTION__'
        };

        options[SimpleFormCollection.AFTER_ADD] = function(element) {
            initSpinners(element);
            //fixResizeValues(element);
            //checkOption(element, this);
        };

        options[SimpleFormCollection.REMOVE] = function(element) {
            var _this = this;

            var modal = window.bootstrap.modal.show(
                Translator.trans("imageCrop.modal.resize.title"),
                Translator.trans("imageCrop.modal.resize.message"),
                Translator.trans("cs_core.action.accept")
            );

            modal
                .find('[data-btn-type="save"]')
                .on("click", function () {
                    _this.removeElement(element);
                    modal.modal('hide');
                })
                .end();
        };

        $('[data-collection="content-resize-items"]', element).SimpleFormCollection(options);
    };

    var initInlineEditableFields = function(element) {
        $(element)
            .find('.groupname, .fieldname').editable({
                validate: function (value) {
                    if ($.trim(value) == '') {
                        return Translator.trans('cs_common_base.form.messages.errors.required');
                    }
                    else{
                        $('#'+$(this).data('for')).val(value);
                    }
                },
                mode: 'inline'
            })
            .on('click', function(){
                $('.editable-input :first-child').select().addClass('form-control');
            })
        ;
    };

    var initSelect2 = function(element) {
        $(element).find('select').each(function(){
            $(this).select2();
        });
    };

    var initCheckbox = function(element) {
        $(element).find('[type="checkbox"]').each(function(){
            $(this)
                .bootstrapSwitch()
                .on('switchChange.bootstrapSwitch', function(event, state) {
                    console.log(this); // DOM element
                    console.log(event); // jQuery event
                    console.log(state); // true | false
            });
        });
    };

    var initSpinners = function(element) {
        $(element).find('.gf-spinner').each(function(){
            $(this).spinner({max:9999});
        });
    };

    return {
        init: function(trueSize, assetId, selectorContext) {
            this.trueSize = trueSize;
            this.asset = assetId;
            this.selectorContext = selectorContext;
            initialize();
        },
        initForm: function() {
            initForm();
        },
        jcropApi: null,
        cropSelected: null,
        asset: null,
        trueSize: [],
        selectorContext: null
    };
})();
