$(function () {
    'use strict';
    var assetsBaseDir = $('#assetsBaseDir').attr('data-assetsbasedir');

    // wysłanie formularza
    $('.selectForm').on('change', function () {
        $('#selectFormForm').submit();
    });

    // Edycja odpowiedzi formularza
    $('.editAnswerField').on('click', function () {
        var field = $(this).attr('data-input');
        var button = $(this).attr('data-button');
        $('#' + field).removeAttr('readonly').focus();
        $('#' + button).removeClass('hide');
    });

    // włączenie dataTables dla messages
    if($('#messagesList').length>0){
        $('#messagesList').dataTable({
            ordering: false,
            searching: false,
            paging: false,
            info: false,
            "order": [
                [0, "desc"]
            ],
            "dom": '<f<t><"bottom"ilp>><"clear">',
            language: {
                url: language,
            }
        });
    }

    // włączenie dataTables dla leads
    if($('#leadsList').length>0){
        $('#leadsList').dataTable({
            ordering: false,
            searching: false,
            paging: false,
            info: false,
            "order": [
                [0, "desc"]
            ],
            "dom": '<f<t><"bottom"ilp>><"clear">',
            language: {
                url: language,
            }
        });
    }



    // Generator mapy Google
    var googleLat = ($('.googlemaps').length > 0 ? parseFloat($('.googlemaps').attr('data-lat')) : null);
    var googleLng = ($('.googlemaps').length > 0 ? parseFloat($('.googlemaps').attr('data-lng')) : null);
    var googleZoom = ($('.googlemaps').length > 0 ? parseInt($('.googlemaps').attr('data-zoom')) : 11);
    var googlePinInfo = ($('.pinWindowShow').length > 0 ? $('.pinWindowShow').html() : '');

    // włączenie podstawowego TinyMCE
    var imgLink = null;
    if ($('.textareaPinWindow').length > 0) {
        var imgLink;
        tinymce.init({
            selector: '.tinyBasicEditor',
            height: 150,
            theme: "modern",
            resize: "both",
            remove_script_host : false,
            convert_urls : false,
            object_resizing : true,
            menubar: false,
            plugins: [
                'advlist autolink lists image charmap print preview anchor textcolor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table contextmenu paste code help'
            ],
            toolbar: 'formatselect | bold italic underline forecolor  | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | webimpulsLink',
            content_css: [
                '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
                '//www.tinymce.com/css/codepen.min.css'],
            init_instance_callback: function (editor) {
                editor.on('Change', function (e) {
                    googlePinInfo = e.level.content;
                });
            },
            setup: function (editor) {
                editor.addMenuItem('webimpulsLink', {
                    text: insertLink,
                    icon: 'mce-ico mce-i-link',
                    context: 'insert',
                    onclick: function () {
                        imgLink = addLink(imgLink, editor, tinyMCE);
                    },
                });
                editor.addButton('webimpulsLink', {
                    text: '',
                    icon: 'link',
                    tooltip: insertLink,
                    onclick: function () {
                        imgLink = addLink(imgLink, editor, tinyMCE);
                    },
                    onpostrender: function () {
                        var btn = this;
                        editor.on('init', function() {
                            editor.formatter.formatChanged('link', function(state) {
                                btn.active(state);
                            });
                        });
                    }
                });
            }
        });
    }

    //initMap(googleLat, googleLng, googleZoom, googlePinInfo);
    $('.switchMapsGenerator').change(function () {
        if (this.checked) {
            $('.urlGoogleMaps').prop('readonly', true);
            $('.mapsGenerator').removeClass('hide');
            $('.mapsEmbed').addClass('hide');
            initMap(googleLat, googleLng, googleZoom, googlePinInfo, false);
        } else {
            $('.urlGoogleMaps').prop('readonly', false);
            $('.mapsGenerator').addClass('hide');
            $('.mapsEmbed').removeClass('hide');
        }
    });
    if ($('.urlGoogleMaps').length > 0) {
        $('.urlGoogleMaps').on('change', function () {
            var url = $(this).val();
            $('.googlemapsembed').html(url);
        });
    }
    $(window).load(function () {
        if($('.mapGoogleView').length > 0){
            initMap(googleLat, googleLng, googleZoom, googlePinInfo, true);
        } else {
            if ($('.mapsGenerator').length > 0 && ! $('.mapsGenerator').hasClass('hide')) {
                initMap(googleLat, googleLng, googleZoom, googlePinInfo, false);
            }
        }
    });


    // Włączenie choosen
    if($('.chosenSelect').length>0){
        $('.chosenSelect').chosen({
            allow_single_deselect: true,
        });
    }

    // Włączenie select2
    if($('.select2').length>0){
        $('.select2').select2({
            allowClear: true,
            width: 'resolve'
        });
    }

    // Zmiana statusu odpowiedzi / leada
    $('.formStatusChange').on('change', function () {
        var $this = $(this);
        var id = $this.data('id');
        var status = $this.val();
        $.ajax({
            url: Routing.generate('wi_admin_contact_update_status'),
            type: 'get',
            data: {
                id: id,
                status: status
            },
            success : function (response) {
                console.log(response);
                $('.formStatusChange[data-formid="formStatus-table'+id+'"]').attr('data-labelactiv', response).val(status);
                $('.formStatusChange[data-formid="formStatus-modal'+id+'"]').attr('data-labelactiv', response).val(status);
            },
            error : function (res) {

            }
        });

        return false;

    });

    // Dodanie notatki do odpowiedzi / leada
    $('.newNoteForm').on('click', function () {
        var id = $(this).data('idanswer');
        var message = $('textarea[data-idanswer="'+id+'"]').val();
        console.log(id);
        console.log(message);
        if(message.length > 0) {
            $.ajax({
                url: Routing.generate('wi_admin_contact_save_note'),
                type: 'get',
                data: {
                    id: id,
                    note: message
                },
                success: function (res) {
                    $('textarea[data-idanswer="'+id+'"]').val('');
                    var html = '<div class="row" ><div class="columns small-12 medium-2"><span>'+ res[0].date +'</span></div>' +
                    '<div class="columns small-12 medium-10"><p>' + res[0].note + '</p></div></div><hr>';

                    $('.answerNote[data-idanswer="'+id+'"]').prepend(html);
                },
                error: function (res) {
                    console.log(res);
                }
            });
        }

    });

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

    var valuePge = 0;
    if($('.select2page').length>0){
        valuePge = $('.select2page option:selected').val();
        $('.select2page').select2({
            allowClear: true,
            width: 'resolve'
        });
    }
    $('.select2page').on('change.select2', function (e) {
        var data = e.target.value;
        if(data === valuePge){
            $('.pageInline').removeClass('hide');
        } else {
            $('.pageInline').addClass('hide');
        }
    });

    // Walidacja dodawania nowego formularza
    $('form[name="wi_admin_contactbundle_form"').submit(function () {
        if($('.chosenSelect').val() === ''){
            $('.choseTypeValidInfo').removeClass('hide');
            return false;
        }
    });

    // Edycja artykułu
    $('.editPage').on('click', function () {
        $('.select2page').prop('disabled', false);
        $('.select2page option').prop('disabled', false);
        $(this).addClass('hide');
        $('.saveButtonPage').removeClass('hide');
    });

    $('.submitForm').mousedown(function () {
        $('.select2page').prop('disabled', false);
        $('.select2page option').prop('disabled', false);
    });


    // Recaptcha - pokaż formularz
    $('.recaptchaInput').on('change', function () {
        if(this.checked){
            $('.recaptchaKey').removeClass('hide');
        } else {
            $('.recaptchaKey').addClass('hide');
        }
    });

    // Autoreplay - pokaż formularz
    $('.replayInput').on('change', function () {
        if(this.checked){
            $('.contentReplay').removeClass('hide');
            $('.replySubjectBox').removeClass('hide');
        } else {
            $('.contentReplay').addClass('hide');
            $('.replySubjectBox').addClass('hide');
        }
    });

    // włączenie podstawowego TinyMCE dla maili
    if ($('.tinyMCEMail').length > 0) {
        var imgLink;
        tinymce.init({
            selector: ".tinyMCEMail",  // change this value according to your HTML
            plugins: [
                "advlist autolink lists charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                "save table contextmenu directionality template image paste textcolor",
                "template"
            ],
            height: '300',
            relative_urls: false,
            remove_script_host: false,
            document_base_url: assetsBaseDir,
            toolbar1: "insertfile undo redo | styleselect | fontselect | bold italic | alignleft aligncenter alignright alignjustify | numlist outdent indent | webimpulsLink image | preview | forecolor backcolor | webimpulsMedia | template",
            init_instance_callback: function (editor) {
                editor.on('Change', function (e) {
                    $('.previewReplay').html(e.level.content);
                    //console.log(e.level.content);
                });
            },
            image_list: Routing.generate('wi_admin_media_image_list'),
            templates: [
                {
                    title: "Simple replay",
                    url: assetsBaseDir + "js/templateMailKontakt/simple.html",
                    description: "Simple replay."
                },
                {
                    title: "Elegant replay",
                    url: assetsBaseDir + "js/templateMailKontakt/elegant.html",
                    description: "Elegant replay."
                }
            ],
            setup: function (editor) {
                editor.addMenuItem('webimpulsLink', {
                    text: insertLink,
                    icon: 'mce-ico mce-i-link',
                    context: 'insert',
                    onclick: function () {
                        imgLink = addLink(imgLink, editor, tinyMCE);
                    },
                });
                editor.addButton('webimpulsLink', {
                    icon: 'link',
                    tooltip: insertLink,
                    onclick: function () {
                        imgLink = addLink(imgLink, editor, tinyMCE);
                    },
                    onpostrender: function () {
                        var btn = this;
                        editor.on('init', function() {
                            editor.formatter.formatChanged('link', function(state) {
                                btn.active(state);
                            });
                        });
                    }
                });
            }
        });
    }


    // Edycja pol formularzy
    if($('.formFields').length > 0){
        $('.formFields').collection({
            position_field_selector: '.orderNrVal',
            prefix: 'collection',
            elements_selector: '> tr',
            name_prefix: 'child',
            hide_useless_buttons: true,
            add: false,
            remove: false,
        });
    }

    $('.formFields input').on('change', function () {
        $('.saveChangeInfo').removeClass('hide');
    });

    $('.collection-action').on('click', function () {
        $('.saveChangeInfo').removeClass('hide');
    });

    // Generowanie podglądu formularza
    $('.previewFormClick').on('click', function () {
        $('.previewForm').html('');

        $('.formFields tr').each(function ( index ) {
            var type = '';
            var field = '';
            $('.fieldType option:selected', this).each(function () {
                type = $(this).attr('data-type');
            });
            var label = $('.fieldLabel', this).val();
            var value = $('.fieldValue', this).val();
            var place = $('.fieldPlace', this).val();
            var requ = ($('.fieldRequ:checked', this).length > 0 ? '*' : '');

            if (type === 'textarea'){
                field = '<div class="columns"><label>' + label + requ + '</label></div>' +
                    '<div class="columns"><textarea rows="4" cols="50" placeholder="' + place + '">' + value + '</textarea></div>';
            } else {
                field = '<div class="columns small-5 medium-2"><label>' + label + requ + '</label></div>' +
                    '<div class="columns small-7 medium-10"><input type="' + type + '" placeholder="' + place + '"></div>';
            }

            var html = '<div class="row">' + field + '</div>';
            $('.previewForm').append(html);
        });



        $('#previewForm').foundation('open');
    });



});

// mapy Google
function initMap(googleLat, googleLng, googleZoom, googlePinInfo, readonly) {
    var center = {lat: googleLat, lng: googleLng, };
    var map = new google.maps.Map(document.getElementById('googleMaps'), {
        zoom: googleZoom,
        center: center,
    });
    var marker = new google.maps.Marker({
        map: map,
        draggable: false,
        position: center
    });
    var infowindow = new google.maps.InfoWindow({
        content: googlePinInfo
    });
    marker.addListener('click', function() {
        infowindow.open(map, marker);
    });
    if(! readonly){
        map.addListener( 'click', function(event) {
            marker.setPosition(event.latLng);
            $('.latMaps').val(event.latLng.lat());
            $('.lngMaps').val(event.latLng.lng());
        });
        map.addListener('zoom_changed', function (event) {
            var zoom = map.zoom;
            $('.zoomMaps').val(zoom);
        });
    }
}

