$(function () {
    $('.stopPropagation').click(function (event) {
        event.stopPropagation();
    });

    // Walidacja zmiany hasła w oknie modalnym dla admina
    $('#resetPasswordModal').submit(function () {
        var valPass = $('#passwordModal').val();
        var valPassConf = $('#repasswordModal').val();
        if (valPass == '') {
            $('#passwordModal').css('border-color', 'red');
            $('.changePasswordModalRequired').css('display', 'block');
            return false;
        } else if (valPass != valPassConf) {
            $('#repasswordModal').css('border-color', 'red');
            $('.changePasswordModalThesame').css('display', 'block');
            return false;
        } else {
            $('#repasswordModal').css('border-color', '#ccc');
            $('.changePasswordModalThesame').css('display', 'none');
            $('#passwordModal').css('border-color', '#ccc');
            $('.changePasswordModalRequired').css('display', 'none');
        }
    });

    // Link Generator.
    var $linkGenerator = $('.link-generator');
    if ($linkGenerator.length > 0) {
        $linkGenerator.linkGenerator({
            link: Routing.generate('wi_admin_menu_link_generator_link'),
            linkItems: Routing.generate('wi_admin_menu_link_generator_items'),
            linkModules: Routing.generate('wi_admin_menu_link_generator_modules'),
        });
    }
    // Link Generator.
    var $linkGeneratorTiny = $('.link-generator-tiny');
    if ($linkGeneratorTiny.length > 0) {
        $linkGeneratorTiny.linkGenerator({
            link: Routing.generate('wi_admin_menu_link_generator_link'),
            linkItems: Routing.generate('wi_admin_menu_link_generator_items'),
            linkModules: Routing.generate('wi_admin_menu_link_generator_modules'),
        });
    }

    // Podlgąd treści w tinyMCE
    if($('.tinymceShowContent').length > 0){
        tinymce.init({
            selector: 'textarea.tinymceShowContent',
            readonly : 1,
            height: 500,
            toolbar: false,
            plugins: '',
            menubar: false,
            valid_children: '+body[style]',
            content_css: [sciezkaCss, sciezkaCss2],
        });
    }

    // Klikanie nagłówków boxów
    $('.box-header').on('click', function (e) {
        if(e.target.className == 'box-header bg-transparent'){
            $('i[data-widget="collapse"]', this).click();
        }
    })
});
//responsive menu slicknav
$(function () {
    "use strict";
    $('.counter-up').counterUp({
        delay: 10
        , time: 3000
    });
    $('.counter-up-fast').counterUp({
        delay: 5
        , time: 1000
    });
    //circular progress animation
    $('.circlestat').circliful();
});
$(function () {
    "use strict";
    var logo = $('img.biglogo').attr('src');
    $('.slicknav').slicknav({
        label: "<img class='logoMobile' src = " + logo + ">"
    });
    /*
     * INITIALIZE BUTTON TOGGLE
     * ------------------------
     * always use this code for toggle and close button effect
     */
    $(".side-bar").accordionze({
        accordionze: true
        , speed: 300
        , closedSign: '<b class="fa fa-circle"></b>'
        , openedSign: '<b class="fa fa-circle"></b>'
    });
    $(".slim-scroll").slimscroll({
        height: "180px"
        , alwaysVisible: false
        , size: "3px"
    });
    $(".off-canvas-nest").slimscroll({
        height: "600px"
        , alwaysVisible: false
        , position: 'left'
        , alwaysVisible: true
        , allowPageScroll: true
        , size: "3px"
    });
    $(".sidebar-fixed").slimscroll({
        height: "360px"
        , width: "260px"
        , position: 'left'
        , alwaysVisible: true
        , allowPageScroll: true
        , distance: '-1px'
        , size: "4px"
    });
});
/*
 * Add collapse and remove events to boxes
 */
(function ($) {
    "use strict";
    $("[data-widget='collapse']").click(function () {
        //Find the box parent
        var box = $(this).parents(".box").first();
        //Find the body and the footer
        var bf = box.find(".box-body, .box-footer");
        if (!box.hasClass("collapsed-box")) {
            box.addClass("collapsed-box");
            bf.slideUp();
        }
        else {
            box.removeClass("collapsed-box");
            bf.slideDown();
        }
    });
})(jQuery);
//Find the box parent
(function ($) {
    "use strict";
    $("[data-widget='remove']").click(function () {
        var box = $(this).parents(".box").first();
        box.slideUp();
    });
})(jQuery);

$(function () {
    "use strict";
    var $modal = $('#ajaxSuggestions');
    $('.repportSuggestions').on('click', function () {
        $('.canvasRightSite').foundation('close');
        $.ajax({
            type: 'GET',
            url: Routing.generate('wi_admin_core_suggestions_index'),
            success: function (ret) {
                $modal.html(ret).foundation('open');
            },
            error: function () {
                var html='<p>' + $('#ajaxSuggestions').attr('data-ajaxError') + '</p>'
                $modal.html(html).foundation('open');
            }
        });
    });
    var pathInfo = $('#pathInfo').attr('data-pathInfo');
    //console.log(pathInfo);
    $('#ajaxSuggestions').on('click', '.suggestiosnButton', function () {
        var content = $('#contentSuggestion').val();
        var name = $('#nameSuggestion').val();

        if (content === '' || name === ''){
            $('.validationSuggestionForm').removeClass('hide');
        } else {
            $.ajax({
                type: 'GET',
                url: Routing.generate('wi_admin_core_suggestions_send'),
                data: {
                    content: content,
                    name: name,
                    url: pathInfo,
                },
                success: function (ret) {
                    $modal.html(ret);
                    setTimeout(function () {
                        $modal.foundation('close');
                    }, 4000);
                },
                error: function (ret) {
                    var html='<p>' + $('#ajaxSuggestions').attr('data-ajaxError') + '</p>'
                    $modal.html(html);
                },
            });
        }

    });
    $('#ajaxSuggestions').on('submit', 'form[name="suggestionForm"]', function () {
        var content = $('#contentSuggestion').val();
        var name = $('#nameSuggestion').val();

        if (content === '' || name === ''){
            $('.validationSuggestionForm').removeClass('hide');
        } else {
            $.ajax({
                type: 'GET',
                url: Routing.generate('wi_admin_core_suggestions_send'),
                data: {
                    content: content,
                    name: name,
                    url: pathInfo,
                },
                success: function (ret) {
                    $modal.html(ret);
                    setTimeout(function () {
                        $modal.foundation('close');
                    }, 4000);
                },
                error: function (ret) {
                    var html='<p>' + $('#ajaxSuggestions').attr('data-ajaxError') + '</p>'
                    $modal.html(html);
                },
            });
        }
        return false;
    });

    $('.sendMessages').on('click', function () {
        var content = $('#yourQuestion').val();
        var name = $('#yourEmail').val();

        if (content === '' || name === ''){
            $('.validationMessagesForm').removeClass('hide');
        } else {
            $('.validationMessagesForm').addClass('hide');
            if(! walidacjaEmail(name)){
                $('.validEmail').removeClass('hide');
                return false;
            } else {
                $('.validEmail').addClass('hide');
            }

            $.ajax({
                type: 'GET',
                url: Routing.generate('wi_admin_core_messages_send'),
                data: {
                    content: content,
                    name: name,
                    url: pathInfo,
                    formName: 'Right Menu Contact Form'
                },
                success: function (ret) {
                    if(ret){
                        $('.successSend').removeClass('hide');
                        $('#yourQuestion').val('');
                        $('#yourEmail').val('');
                    }
                },
                error: function (ret) {
                    $('.errorSend').removeClass('hide');
                }
            });
        }

    });

    $('form[name="sendMessages"]').on('submit', function () {
        var content = $('#yourQuestion').val();
        var name = $('#yourEmail').val();

        if (content === '' || name === ''){
            $('.validationMessagesForm').removeClass('hide');
        } else {
            $('.validationMessagesForm').addClass('hide');
            if(! walidacjaEmail(name)){
                $('.validEmail').removeClass('hide');
                return false;
            } else {
                $('.validEmail').addClass('hide');
            }

            $.ajax({
                type: 'GET',
                url: Routing.generate('wi_admin_core_messages_send'),
                data: {
                    content: content,
                    name: name,
                    url: pathInfo,
                    formName: 'Right Menu Contact Form'
                },
                success: function (ret) {
                    if(ret){
                        $('.successSend').removeClass('hide');
                        $('#yourQuestion').val('');
                        $('#yourEmail').val('');
                    }
                },
                error: function (ret) {
                    $('.errorSend').removeClass('hide');
                }
            });
        }
        return false;

    });

    function walidacjaEmail(email) {
        var pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        var is_email = pattern.test(email);

        if(is_email){
            return true;
        }
        return false;
    }

    $('#resetPasswordModal').on('submit', function () {
        var password = $('#passwordModal').val();
        var rePassword = $('#repasswordModal').val();

        if(password != '' && (password == rePassword)){
            $.ajax({
                type: 'POST',
                url: Routing.generate('wi_admin_admin_administrators_reset_password'),
                data: {
                    password: password,
                    rePassword: rePassword,
                },
                success: function (ret) {
                    if(ret){
                        $('.successPasswordReset').removeClass('hide');
                    } else {
                        $('.errorPasswordReset').removeClass('hide');
                    }
                },
                error: function (ret) {
                    $('.errorPasswordReset').removeClass('hide');
                }
            });
        }
        return false;
    });

    // Zmiana języka.
    $('.buttonSaveLanguage').on('click', function () {
        var language = $('.inputLanguage:checked').val();
        if(language != ''){
            $.ajax({
                type: 'GET',
                url: Routing.generate('wi_admin_admin_administrators_change_language'),
                data: {
                    language: language,
                },
                success: function (ret) {
                    if(ret){
                        location.reload();
                    }
                },
                error: function (ret) {

                }
            });
        }
    });
});

$(function () {
    "use strict";
    $("#skin-select #toggle").click(function () {
        if ($(this).hasClass('active')) {
            $('.profile-logo').addClass('smallLogo');
        } else {
            $('.profile-logo').removeClass('smallLogo');
        }
    });
});

$(function () {
   "use strict";
   $(window).load(function () {
       var answerContact = $('#inboxInfo').attr('data-inboxcontactmenu');
       var answerLead = $('#inboxInfo').attr('data-inboxleadmenu');

       $('.inboxContactMenu').append('<small class="side-menu-noft">' + answerContact + '</small>');
       $('.inboxLeadMenu').append('<small class="side-menu-noft">' + answerLead + '</small>');
   });
});


function addLink(imgLink, editor, tinyMCE){
    imgLink = null;
    if(tinyMCE) {
        tinyMCE.execCommand('mceFocus',false, $('.mceEditor:visible').prev().attr('id'));
    }
    var node = editor.selection.getNode();
    //console.log(node);
    var rng = editor.selection.getRng();
    if(node.nodeName == 'A') {
        $('#linkURL').val(node.href);
        $('#linkText').val(node.text);
        $('#linkTitle').val(node.title);
        $('#linkTitle').val(node.title);
        $('#classCss').val(node.className);
        var rel = node.rel;
        if (rel == 'lightbox') {
            $('#linkRel').val('lightbox');
        } else if (rel == 'canonical') {
            $('#linkRel').val('canonical');
        } else if (rel == 'nofollow noopener') {
            $('#linkRel').val('nofollow');
        } else {
            $('#linkRel').val('norel');
        }

        if (node.target) {
            $('#linkGoal').val('newWindow');
        }
        editor.selection.select(node)
    } else if(node.nodeName == 'IMG') {
        imgLink = node;
        if(rng.endContainer.nodeName == 'A'){
            var rngNodeParent = rng.endContainer;
            $('#linkURL').val(rngNodeParent.href);
            $('#linkText').val(rngNodeParent.text);
            $('#linkTitle').val(rngNodeParent.title);
            $('#classCss').val(rngNodeParent.className);
            var rel = rngNodeParent.rel;
            if (rel == 'lightbox') {
                $('#linkRel').val('lightbox');
            } else if (rel == 'canonical') {
                $('#linkRel').val('canonical');
            } else if (rel == 'nofollow noopener') {
                $('#linkRel').val('nofollow');
            } else {
                $('#linkRel').val('norel');
            }

            if (rngNodeParent.target) {
                $('#linkGoal').val('newWindow');
            }
            editor.selection.select(rngNodeParent)
        }
       // console.log(editor.selection.getRng());
    } else if (rng.startOffset != rng.endOffset) {
        $('#linkText').val(rng.startContainer.data.substr(rng.startOffset, rng.endOffset));
    }
    if(imgLink != null){
        $('.linkTextHideImg').addClass('hide');
    }
    $('#linkiModal').foundation('open');
    return imgLink;
}

$( function() {
    var $search = $('#search');

    if ($search.length > 0) {
        $.widget( "custom.catcomplete", $.ui.autocomplete, {
            _create: function() {
                this._super();
                this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
            },
            _renderMenu: function( ul, items ) {
                var that = this,
                    currentCategory = "";
                $.each( items, function( index, item ) {
                    var li;
                    if ( item.category != currentCategory ) {
                        ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                        currentCategory = item.category;
                    }
                    li = that._renderItemData( ul, item );
                    if ( item.category ) {
                        li.attr( "aria-label", item.category + " : " + item.label );
                    }
                });
            }
        });
        $search.on('keypress', function () {
            var value = $(this).val();
            if(value.length == 2) {
                $.ajax({
                    type: "POST",
                    url: Routing.generate('wi_admin_core_get_autocomplete_data'),
                    //dataType: "jsonp",
                    data: {
                        search: value
                    },
                    success: function (data) {
                        $("#search").catcomplete({
                            delay: 0,
                            source: data,
                            autoFocus: true,
                            select: function( event, ui ) {
                                if(ui.item.typ == 'page'){
                                    window.location.href=Routing.generate('wi_admin_pages_show', {'id': ui.item.id});
                                } else if(ui.item.typ == 'blog'){
                                    window.location.href=Routing.generate('wi_admin_blog_show', {'id': ui.item.id});
                                } else if(ui.item.typ == 'news'){
                                    window.location.href=Routing.generate('wi_admin_news_show', {'id': ui.item.id});
                                }
                            },
                        });
                    },
                    error: function (data) {
                    }
                });
            }
        });
    }
} );

$(function () {
   // Wyświetlanie licznika znaków w meta data
    $('.metaTags input:text, .metaTags textarea').each(function () {
        var textLenght = $(this).val().length;
        var id = this.id;
        $(this).after('<span class="textLenghtMeta textLenght' + id + '">[' + textLenght + ']</span>');
    });

   $('.metaTags input:text, .metaTags textarea').on('keyup click', function () {
       var textLenght = $(this).val().length;
       var id = this.id;
       $('.textLenght' + id).html('[' + textLenght + ']');
       //$(this).after('<span class="textLenght' + id + '">[' + textLenght + ']</span>');
   });
});

$(function () {
    var $changeDepartment = $('#change_department');

    if ($changeDepartment.length > 0) {
        $changeDepartment.change(function () {
            window.location.href = Routing.generate('wi_admin_department_set_department', { id: $(this).val() });
        });
    }
});