$(function () {

    /**
     * Hide show action bar
     * @type {jQuery}
     */
    /*var contentHegiht  = $('.page-content').height();
    var documentHeight = $(document).height();
    var actionsBar     = $('.form-actions');
    var scrollerEl     = $('.c-container');
    var scroll         = scrollerEl.scrollTop();

    if (contentHegiht <= documentHeight) {
        actionsBar.fadeIn();
    }

    scrollerEl.on("scroll", function(){
        var newScroll = $(this).scrollTop();

        if (newScroll === 0 || newScroll < scroll) {
            actionsBar.fadeOut();
        } else {
            actionsBar.fadeIn();
        }

        scroll = newScroll;
    });*/

    window.$deleteAction = new DeleteContentActivity();

    Metronic.init(); // init metronic core components
    Layout.init(); // init current layout
    QuickSidebar.init(); // init quick sidebar
    Pagination.init();
    Suggest.init();
    ComponentsPickers.init();
    Demo.init(); // init demo features


    //if (typeof FormDropzone != "undefined") FormDropzone.init();
    if (typeof ComponentsCollection != "undefined") ComponentsCollection.init();

    $(document).ajaxComplete(function (event, xhr, settings) {

        if(xhr.status == 0) { // Aborted ajax request
            return;
        }

        try {
            var json = $.parseJSON(xhr.response);
            ErrorHandler.handle(json.status);
        } catch (e) {

            if(xhr.status == 500) {
                ErrorHandler.handle(xhr.status);
            }
        }

    });

    //$('.nav-tabs li.active a[data-toggle="tab"]').tab('show');
    $('.nav-tabs li:not(.active) a[data-toggle="tab"]').each(function () {
        $($(this).attr('href')).removeClass('active');
    });

    //var $ajaxTabs = $('a[data-toggle="tab"][data-load="ajax"]');
    //$(document)
    //    .on('shown.bs.tab', $ajaxTabs, function (e) {
    //        var target = $(e.target);
    //        $(target.attr('href')).load(target.data('url'), function () {
    //
    //        target.trigger('load.bs.tab');
    //    });
    //    })
    //    .on('load.bs.tab', $ajaxTabs, function () {
    //        Pagination.onChange.dispatch();
    //    });

    $('input[data-check-enable], select[data-check-enable]').each(function (i, e) {
        var input = $(e);
        var check = $($(e).data('check-enable'));
        var associatedInputs = check.data('associated');

        if (typeof associatedInputs == 'undefined') {
            associatedInputs = [];
        }
        associatedInputs.push(input);

        var action = function (check, input) {
            if (check.prop('checked')) {
                input.attr('disabled', false);
            } else {
                input.attr('disabled', true);
            }
        };


        $(check).on('change', function () {
            var associatedInputs = $(this).data('associated');

            for (input in associatedInputs) {
                action($(this), associatedInputs[input]);
            }
        });

        for (input in associatedInputs) {
            action($(this), associatedInputs[input]);
        }

        if ('radio' == check.attr('type')) {
            var radioGroup = $('[name="' + check.attr('name') + '"]');

            radioGroup.on('change', function () {
                radioGroup.each(function (i, e) {
                    var el = $(e).data('associated');
                    if (el) {
                        for (input in el) {
                            action($(this), el[input]);
                        }
                    }
                });
            });
        }

        check.data('associated', associatedInputs);

    });

    $('input[type="checkbox"][data-exclusive="true"]').on('change', function () {
        var input = $(this);

        if (input.prop('checked')) {
            var group = $('input[type="checkbox"][data-group="' + input.data('group') + '"]');
            group
                .filter(':checked')
                .not(input)
                .each(function (i, e) {
                    $(e).prop('checked', false);
                    $(e).trigger('change');
                    $(e).parent('span').removeClass('checked');
                });
        }

    });

    $(".tags").each(function(){
        var _this = $(this);

        MultiWordsText.handle({
            width: "auto",
            defaultText: typeof _this.data("text") === "string" ? _this.data("text") : Translator.trans("cs_common_base.common.add_a_tag")
        }, _this);
    });

    $('.cs-module-search form').each(function (i, e) {
        var form = $(e);
        var input = $('input', form);
        form.on('submit', function (e) {
            e.preventDefault();
            input.trigger('keyup');
        });
        input.on('keyup', function (e) {
            if ((e.keyCode || e.which) == KEY_ESCAPE) {
                input.val(null);
            }
            var code = (typeof e.keyCode != 'undefined') ? e.keyCode : e.which;
            if(advancedSearch.exclude.indexOf(code) == -1) {
                return;
            }

            var element = $(this);
            var xhr = element.data('call');
            if(xhr) {
                xhr.abort();
            }
            clearTimeout(element.data('timeout'));
            element.data('timeout', setTimeout(function () {
                var url = form.attr("action");

                if (form.data("extra-url-params")) {
                    var sign = "?";

                    if (/.+\?.+/.test(url)) {
                        sign = '&';
                    }

                    url += sign + form.data("extra-url-params");
                }


                var search = element.val();
                var container = $(element.data("container"));
                if (search.length >= 2 || search.length == 0) {


                    if(!container.find('.pagination-loader').length) {
                        container.append($('<div></div>', { 'class': 'pagination-loader' }));
                    }
                    var formData = form.serialize();
                    var xhr = $.ajax({
                        url: url,
                        data: formData,
                        success: function (data) {
                           container.fadeOut(200, function () {

                               window.history.replaceState({}, "", window.location.pathname+'?'+formData);
                               container.replaceWith(data).fadeIn("slow", function() {
                                   if(contentSelected !== 'undefined') {
                                       contentSelected.reset();
                                       contentSelected.setTotalItems();
                                   }

                                   Pagination.onChange.dispatch();
                               });



                           });
                       }
                    });

                    element.data('call', xhr);
                }
            }, 250));
        });
    });

    $('a[data-dimiss="modal"], button[data-dimiss="modal"]').on('click', function () {
        $(this).parents('.modal').modal('hide');
    });

    $.each($("select"), function (k, v) {
        switch ($(v).children().length) {
            case 0:
                $(v).closest(".form-group ").addClass('no-content');
                break;
        }
    });

    $.unparam = function (value) {
        var
            params = {},
            parts = value.split('&'),
            pair, i, l;

        for (i = 0, l = parts.length; i < l; i++) {
            pair = parts[i].split('=', 2);
            params[decodeURIComponent(pair[0])] = (pair.length == 2 ?
                decodeURIComponent(pair[1].replace(/\+/g, ' ')) : true);
        }

        return params;
    };

    window.showToastrNotification = function (type, text, options, callBack) {

        var default_options = {
            "closeButton": true,
            "debug": false,
            "positionClass": "toast-top-right",
            "onclick": null,
            "showDuration": "5000",
            "hideDuration": "3000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "swing",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut",
            "newestOnTop": true
        };

        toastr.options = $.extend(default_options, options);

        toastr[type](text);

        if (typeof callBack == 'function') {
            callBack.call(this);
        }
    };

    if ( typeof current_section != "undefined") {

        var myMenuCookie = localStorage.getItem("my-menu");
        var displayMenu = true;


        if (myMenuCookie) {
            isFavorite = myMenuCookie.split(",").filter(function(section) {
                return section === current_section;
            })

            if (isFavorite.length > 0) {
                displayMenu = false;
            }
        }

        var menu_option = $('[data-section="' + current_section + '"]');
        menu_option.addClass('active');

        if (displayMenu) {
            var menu_option_parents = menu_option.parentsUntil('.page-sidebar-menu');

            for (var i = 0, menu_option_parents_length = menu_option_parents.length; i < menu_option_parents_length; i++) {

                var element = $(menu_option_parents[i]);

                if (element.is('li')) {
                    element.addClass('open');
                    //element.children(':first').find('span').addClass('open');
                }

                if (element.is('ul')) {
                    //element.show();
                }
            }
        }
    }

    window.$singleDeleteAction = new DeleteContentActivity();

    $singleDeleteAction
        .setSelector('[data-toggle="modal"][data-behaviour="delete"]')
        .setTitle(Translator.trans('cs_core.messages.confirm_delete'))
        .setMessage(Translator.trans('cs_core.messages.confirm_delete'))
        .init();


    /**
     * onConfirm Action
     */
    $singleDeleteAction.on('confirm', function(d, params) {
        //params.message = 'You can change modal title here if your want';
        //params.message = 'You can change modal message here if your want';
        //d.reject(new Error('Entity could not be deleted!'));
        //d.resolve(params); // This will call to the next promixe

    });
    window.$classifiedsDelete = new DeleteContentActivity();

    $classifiedsDelete.on('success', function (params) {

        var container = $(params.element).parents('.pagination-container');

        $('[data-dismiss="modal"]').trigger('click');
        if ($('[data-toggle="modal"][data-behaviour="delete-inline"]').length > 1) {
            Pagination.paginate(Pagination.url, Pagination.page, container);
        }
        else {
            if (Pagination.page !== 1) {
                Pagination.page--;
            }

            Pagination.paginate(Pagination.url, Pagination.page, container);
        }
    });

    $classifiedsDelete
        .setSelector('[data-toggle="modal"][data-behaviour="delete-inline"]')
        .init()
    ;

    //GLOBAL SEARCH FORM
    if ($('[data-action="global-search"]').length === 1) {
        var globalSearch      =  $('[data-action="global-search"]');
        var globalSearchInput = globalSearch.find('input[name="query"]');

        globalSearchInput.autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: Routing.generate('content_search_global_suggest'),
                    dataType: "json",
                    data: {
                        q: request.term
                    },
                    success: function( data ) {
                        response( data );
                    }
                });
            },
            minLength: 3,
            focus: function(event, ui) {
                ui.item.label = ui.item.title;
                ui.item.value = ui.item.title;
            },
            select: function(event, ui) {
                window.location.href = ui.item.redirectUrl;
            },
            create: function() {
                var _$thisAutocomplete = $(this).data("ui-autocomplete");

                _$thisAutocomplete._renderItem = function( ul, item ) {

                    var term = this.term;

                    if (typeof this.term === "string") {
                        term = this.term.replace("*","");
                    }

                    var title = item.title.replace(new RegExp(term, "gi"), "<strong>$&</strong>");

                    return $( "<li>" )
                        .append( '<a href="javascript: void(0);" title="'+ item.title +'"><span class="info-icon"></span><i class="'+ item.icon + '"></i> ' + title +'</a>' )
                        .appendTo( ul );
                };

                _$thisAutocomplete._renderMenu = function( ul, items ) {
                    var $this = this;

                    $.each( items, function( index, item ) {
                        $this._renderItemData( ul, item );
                    });

                    $(ul).addClass('cs_global_search small');
                };

                // Remove helper
                $(this).prev('span').remove();
            }
        });
    }

    //Order select 2 categories
    if($("form").find("select[id$=categories_tags_categories]").length) {
        $("form").on('change', function(e){
            var $this = $(this);
            var selectData = $("form").find("select[id$=categories_tags_categories]").select2('data');
            var select = $("form").find("select[id$=categories_tags_categories]");

            $this.find('[name="c-order[]"]').each(function(k,v){
                $(v).remove();
            });

            $.each(selectData, function(k,v){
                var h = '<input type="hidden" name="c-order[]" value="'+ v.id+'" />';
                $this.append(h);
            });

        });
    }

    if ($('[data-type="external_video_upload"]').length) {
        $('[data-type="external_video_upload"]').on('change', function(){
            if ($(this).val()) {
                $(this).next().find('[data-type="external_video_upload_submit"]').removeClass('disabled');
            } else {
                $(this).next().find('[data-type="external_video_upload_submit"]').addClass('disabled');
            }
        })
    }

    // Global translate tab link
    $('a[href="#translate"]').on('click', function(event){

        var backTab = $('.nav-tabs li.active a').attr('href');
        var _form = $('form');
        var _dataURL = $(this).data("url");
        var matchLocale = _dataURL.match(/orig=([a-zA-Z]{2})/);
        var locale = matchLocale ? matchLocale[1] : null;

        if (_form.valid()) {
            var _modal = window.bootstrap.createModal().show(
                Translator.trans('translate.modal.from_edit.title'),
                Translator.trans('translate.modal.from_edit.message'),
                Translator.trans('translate.modal.from_edit.submit')
            );

            _modal.find('[data-btn-type="cancel"]').on('click', function () {
                $('[href="'+backTab+'"]').trigger('click');
            });

            _modal.find('[data-btn-type="save"]').on('click', function (e) {

                var _submit = $(e.target);
                var _url = ComitiumUtils.addURLParameter(window.location, "goToTranslate" , 1);

                _url = ComitiumUtils.addURLParameter(_url, "dataType" , "json");

                if (locale) {
                    _url = ComitiumUtils.addURLParameter(_url, "entityLocale" , locale);
                }

                _submit.addClass('disabled');

                $.ajax({
                    url: _url,
                    method: _form.attr('method'),
                    dataType: "json",
                    data: _form.serialize(),
                    beforeSend: function() {
                        $('.cs-module-spinner').show();
                    },
                    success: function (response) {
                        window.location.href = response.url;
                    },
                    error: function () {
                        _modal.find('[data-dismiss="modal"]').trigger('click');
                        $('.cs-module-spinner').hide();
                    }
                });

            });
        } else {
            event.stopPropagation();
            event.preventDefault();
        }
    });

    Pagination.onChange.add(function(element, data) {

        if (!data) {
            return;
        }

        var urlComponents = window.location.href.match(/(.+)(?:\?(.*))/, 'g');

        var query = {}, url = window.location.href;

        if(urlComponents) {
            url = urlComponents[1];
            query = $.unparam(urlComponents[2]);
        }

        query.page = data.page;

        window.history.replaceState({}, "", url+'?'+ $.param(query));

    });

    // Global submit and redirect to translate
    $('[data-action="submit-form"]').on('click', function(e){
        e.preventDefault();
        var ignoreReferer = Metronic.getURLParameter("ignoreReferer");
        var form = $('form');
        var currentUrl = window.location;
        var action = ignoreReferer ? currentUrl + '?ignoreReferer=1' : currentUrl;
        form.attr('action', action).trigger('submit');

    });

    $('[data-action="submit-form-redirect"]').on('click', function(e){
        e.preventDefault();
        var form = $('form');
        var url = ComitiumUtils.addURLParameter(form.attr('action'), "goToTranslate", 1);
        form.attr('action', url ).trigger('submit');
    });

    $('[data-action="submit-form-preview"]').on('click', function(e){
        e.preventDefault();
        var form = $('form');
        var url = ComitiumUtils.addURLParameter(form.attr('action'), "goToPreview", 1);

        form.attr('action', url ).trigger('submit');
    });

    if (ComitiumUtils.getURLParameter("previewUrl")) {
        window.open(Metronic.getURLParameter("previewUrl"));
    }

    //$('[data-action="submit-form-preview"]').on('click', function(e){
    //    e.preventDefault();
    //
    //    var _this = $(this);
    //    var _form = $('form');
    //
    //    if (_form.valid()) {
    //        $.ajax({
    //            url: _form.attr('action') + '?goToPreview=1',
    //            method: "post",
    //            data: _form.serialize(),
    //            dataType: "json",
    //            beforeSend: function() {
    //                $('.cs-module-spinner').show();
    //            },
    //            success: function (response) {
    //
    //                formChange.offCheckEvent();
    //
    //                if (response.previewUrl) {
    //                    window.open(response.previewUrl);
    //                }
    //                if (response.editUrl) {
    //                    window.location.href = response.editUrl;
    //                }
    //            },
    //            error: function () {
    //                $('.cs-module-spinner').hide();
    //            }
    //        });
    //    }
    //});

    var currentUrl = window.location.href;
    var patt = new RegExp(/.+\/(edit|translate)\/.+?/g);
    var isEdit = patt.test(currentUrl);

    //Open graph population
    // $('[name$="[metadata][metaTitle]"]').on('change', function(e, options){
    //
    //     options = $.extend({
    //         override:false
    //     }, options);
    //
    //     var openGraphTitle = $('[name$="[openGraph][defaultLang][title]"]');
    //     var facebookTitle  = $('[name$="[facebookIntegration][title]"]');
    //     var twitterTitle  = $('[name$="[twitterIntegration][title]"]');
    //
    //     if (openGraphTitle.val() == '' || isEdit === false || options.override === true) {
    //         openGraphTitle.val($(this).val());
    //     }
    //
    //     if (facebookTitle.val() == '' || isEdit === false || options.override === true) {
    //         facebookTitle.val($(this).val());
    //     }
    //
    //     if (twitterTitle.val() == '' || isEdit === false ||options.override === true) {
    //         twitterTitle.val($(this).val());
    //     }
    //
    // });

    // $('[name$="[metadata][metaDescription]"]').on('change', function(e, options){
    //
    //     options = $.extend({
    //         override:false
    //     }, options);
    //
    //     var openGraphTitle = $('[name$="[openGraph][defaultLang][description]"]');
    //     var facebookTitle  = $('[name$="[facebookIntegration][description]"]');
    //
    //     if (openGraphTitle.val() == '' || isEdit === false || options.override === true) {
    //         openGraphTitle.val($(this).val());
    //     }
    //
    //     if (facebookTitle.val() == '' || isEdit === false || options.override === true) {
    //         facebookTitle.val($(this).val());
    //     }
    // });

    $('[data-action="toogle-social-network-form"]').on('switchChange.bootstrapSwitch', function(e, state){

        e.preventDefault();

        var target = $(this).data('target');
        var overrideImage = $(this).data('override-image');

        if (state === true) {
            $('[data-action="update-social-networks"]')
                .trigger("click", { overrideImage : overrideImage });
            $('[id$="socialNetworkProfiles"]', target).attr("required", true);
            $(target).show();
        } else {
            $('[id$="socialNetworkProfiles"]', target).attr("required", false);
            $(target).hide();
        }
    });

    $('[data-action="twitter-interval"] .gf-spinner').on("change", function(){
        var value  = $(this).spinner("value");
        var target = $(this).find("input").data('target');

        if (value <= 1) {
            $(target).prop("disabled", true);
        } else {
            $(target).prop("disabled", false);
        }
    });

    $('[data-action="update-social-networks"]').on("click",function(e, options){
        e.preventDefault();

        var title = $('[name$="[openGraph][defaultLang][title]"]').val();
        var description = $('[name$="[openGraph][defaultLang][description]"]').val();
        var facebookContainer = $("[id$='facebookIntegration_image_container']");
        var twitterContainer = $("[id$='twitterIntegration_image_container']");

        facebookContainer.find('[data-action="unselect"]').trigger('click');
        twitterContainer.find('[data-action="unselect"]').trigger('click');

        var dropzone  = $("[id$='openGraph_image_container']").data("dropzoneElement");

        if (typeof dropzone !== "undefined" && options.overrideImage ) {
            if (dropzone.data("dropzoneType") === "image") {
                var contentId = dropzone.find("[data-asset]").val();

                if (contentId) {
                    var content = {
                        id: contentId,
                        src: $("#library-asset-" + contentId + "_selected img").attr("src"),
                        title: $("#library-asset-" + contentId + "_selected input:text").val()
                    };

                    AssetsHelper.loadById(facebookContainer, content);
                    //AssetsHelper.loadById(twitterContainer, content);
                }
            }
        }

        ComitiumUtils.populateValueToElements(title, [
            $('[name$="[facebookIntegration][title]"]'),
            $('[name$="[twitterIntegration][title]"]')
        ]);

        ComitiumUtils.populateValueToElements(description, [
            $('[name$="[facebookIntegration][description]"]')
        ]);
    });

    // Clear social network queues
    $('[data-action="remove-queue"]').on("click", function(e){
        e.preventDefault();

        var _this = $(this);
        var entityClass = _this.data("class");
        var entityId    = _this.data("id");
        var container   = _this.data("container");
        var entityType   = _this.data("type");
        var locale   = _this.data("locale");

        var _modal = window.bootstrap.createModal().show(
            Translator.trans('social_network.queue.delete.title'),
            Translator.trans('social_network.queue.delete.message'),
            Translator.trans('common.delete')
        );

        _modal.find('data-btn-type="save"').on('click', function (e) {

            var _submit = $(e.target);

            _submit.addClass('disabled');

            $.ajax({
                url: Routing.generate("cs_core_social_network_integration_clear_queues"),
                data: {
                    "class": entityClass,
                    "id": entityId,
                    "type": entityType,
                    "locale": locale
                },
                method: "post",
                success: function(){
                    _this.parents('[data-container="queue-info-container"]').fadeOut(300, function(){
                        _modal.find('[data-dismiss="modal"]').trigger('click');
                        $(this).remove();
                        $('#'+container).show();
                    });
                },
                error: function(){

                }
            });

        });
    });

    $('[href="#social_network"],[href="#social-network"],[data-tab="social_network"]').on("click", function(){
        initOpenGraph($(this));
    });

    function initOpenGraph(elementScope) {
        // Find asset dropzone
        $('.assets-widget', elementScope).each(function(){
            var dropzone  = $(this).data("dropzoneElement");

            if (dropzone.data("dropzoneType") !== "image") {
                return;
            }

            var contentId = dropzone.find("[data-asset]").val();

            if (contentId) {

                var src   = $("#library-asset-"+contentId+"_selected img").attr("src");
                var title = $("#library-asset-"+contentId+"_selected input:text").val();

                var content = {
                    id: contentId,
                    src: src,
                    title: title
                };

                populateOpenGraph(content);

                return false;
            }
        });

        // Find if any dropzone has been found asset image (edit page)
        var assetImg = $("img[data-asset-id]");

        if (assetImg.length > 0) {
            var content = {
                id: assetImg.data("asset-id"),
                src: assetImg.attr("src"),
                title: assetImg.attr("title")
            };

            populateOpenGraph(content);
        }
    }

    function populateOpenGraph(content) {
        var openGraphWidget = $("[id$='openGraph_image_container']");
        var facebookWidget = $("[id$='facebookIntegration_image_container']");
        var twitterWidget  = $("[id$='twitterIntegration_image_container']");
        var assetId = null;

        if (facebookWidget.length) {
            assetId = facebookWidget.data("dropzoneElement").find("[data-asset]").val();
            if (!assetId) {
                AssetsHelper.loadById(facebookWidget, content);
            }
        }

        if (openGraphWidget.length) {
            assetId = openGraphWidget.data("dropzoneElement").find("[data-asset]").val();
            if (!assetId) {
                AssetsHelper.loadById(openGraphWidget, content);
            }
        }

        if (twitterWidget.length) {
            assetId = twitterWidget.data("dropzoneElement").find("[data-asset]").val();
            if (!assetId) {
                AssetsHelper.loadById(twitterWidget, content);
            }
        }
    }


    //Options rollover
    $("body").on("click", '[data-action="show-rollover-options"]', function(e){
        e.preventDefault();
        $(this).next().css("display", "flex");
    });

    $("body").on("click", '[data-action="close-rollover-options"]', function(e){
        e.preventDefault();
        $(this).parent().hide();
    });

    // Dynamic fields. Og populate behaviour
    // Remove if subtitle and body has the property to populate Seo inputs
    var mirrorSelector = $('[data-mirror="defaultLang_metadata_metaDescription"]');
    if (mirrorSelector.length > 1) {
        mirrorSelector.each(function(){
            if ($(this).is("textarea")) {
                $(this).removeAttr("data-mirror");
            }
        });
    }

    var formComponents = new FormComponents(null);
    formComponents.bindAssetWidgetActions();

    /**
     * Change subsite control if more than one tab is open
     */
    if (Number(localStorage.tabs) > 0) {
        localStorage.tabs = Number(localStorage.tabs) + 1;
    } else {
        localStorage.tabs = 1;
    }

    $('[data-action="change-subiste"]').on("click", function(e){
        if (localStorage.tabs > 1) {
            e.preventDefault();
            showToastrNotification("warning", Translator.trans("common.subsite_control"));
        }
    });

    $(window).on('unload', function() {
        localStorage.tabs = Number(localStorage.tabs) - 1;
    });

    // Disable form submission with enter key (13)
    $(document).on('keypress', 'form', function (e) {
        var target = $(e.target);
        if (e.which === 13 && !target.is('textarea')) {
          e.preventDefault();
          return false;
        }
    });
});
