function TimeTableHandling() {
    'use strict';
    var self = this;
    var map;
    var polylines = [];
    var markers = [];
    var polylineUrls = [];
    var activeElements = 0;
    var addActiveElements = 4;
    var filter;

    this.init = function () {
        //self.initMap();
        //self.initTimetable();
        //self.didok();
        //self.station();
        self.getStopEvents();
        self.troubleMessages();
        self.setShipStops();
    }


    /**
     * map initialize
     */
    this.initMap = function () {

        var initializeFile = $('[data-polylines]').first();
        if (typeof initializeFile.data('polylines') !== 'undefined') {
            $.getJSON(initializeFile.data('polylines'), function (data) {
                var coordinates = data['latLng'];
                self.loadMap(coordinates);
            });
        } else {
            self.loadMap([47.173302, 8.516867]);
        }

        $(document).on('click', '.direction', function (e) {

            self.initFilter($(this).data('filter'));
            self.addStopEvents();

            polylineUrls.push($(this).data('polylines'));
            self.createPolylines();

        });

        $(document).on('click', '.route', function (e) {

            self.initFilter($(this).data('filter'));
            self.addStopEvents();

            var directions = $(this).next(".directions").find('.direction');
            directions.each(function(key, value){
                polylineUrls.push($(this).data('polylines'));
            });
            self.createPolylines();
        });
    }

    /**
     * init timetable
     */
    this.initTimetable = function () {
        $('.stop-event').slice(activeElements, addActiveElements).addClass('active');

        $(document).on('click', '.addActiveElements', function (e) {
            e.preventDefault();
            self.addStopEvents();
        });
    }

    /**
     * create polylines and add markers
     */
    this.createPolylines = function () {
        self.clearMap();
        polylineUrls.forEach(function(polylineUrl) {
            if(typeof polylineUrl !== 'undefined') {
                $.getJSON(polylineUrl, function (data) {
                    var coordinates = data['coordinates'];
                    if(coordinates){
                        var color = data['color'];
                        var polyline = L.polyline(coordinates, {color: color}).addTo(map);
                        polylines.push(polyline);
                    }
                    if(typeof data['latLng'] !== 'undefined'){
                        var marker = L.marker(data['latLng']).addTo(map).bindPopup("<b>"+data['title']+"</b>");
                        markers.push(marker);
                    }
                });
            }
        });
        polylineUrls = [];
    }

    /**
     * clear map (polylines and markers)
     */
    this.clearMap = function () {
        if(typeof polylines !== 'undefined') {
            polylines.forEach(function (polyline) {
                polyline.remove();
            });
            polylines = [];
        }
        if(typeof markers !== 'undefined') {
            markers.forEach(function (marker) {
                marker.remove();
            });
            markers = [];
        }
    }

    /**
     * laod map
     * @param coordinates
     */
    this.loadMap = function (coordinates) {

        if($("#mapid").length != 0) {
            map = L.map('mapid').setView([coordinates[0], coordinates[1]], 18);
            L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiaHVnaXNhbiIsImEiOiJjanhhNmdmZWwxM2VhM3ZuODFuM2l5eXN6In0.XkPvbvi54_CIVh9umpkM0A', {
                maxZoom: 18,
                attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
                '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
                id: 'mapbox.streets'
            }).addTo(map);

            if (typeof coordinates !== 'undefined') {
                var marker = L.marker(coordinates).addTo(map);
                markers.push(marker);
            }
        }
    }

    /**
     * didok
     */
    this.didok = function () {

        if($("#attributes").length !== 0) {
            $('.didok').devbridgeAutocomplete({
                minChars: 2,
                autoSelectFirst: true,
                lookup: function (query, done) {
                    var url = $('#attributes').attr('data-service-url') + '?tx_twwctimetable_pi5%5Bquery%5D=' + query;
                    $.ajax({
                        url: url,
                        dataType: 'json',
                        success: function (data) {
                            done(data);
                        },
                        error: function (data) {

                        }
                    });
                },
                onSelect: function (suggestion) {
                    var input = ($(this).attr('data-input'));
                    $("#" + input).val(suggestion.data);
                },
                onHint: function (suggestion) {

                }
            });


            $(document).on('click', '#add-via', function (e) {
                e.preventDefault();
                $( ".via.d-none" ).first().removeClass('d-none');

                if($('.via.d-none').length == 0){
                    $('#via-button-section').hide();
                }
            });

        };
    }

    /**
     * station
     */
    this.station = function () {

        if($("#station-search").length !== 0) {

            var stations;
            var resources = $('#station-search').data('resources');

            $.getJSON(resources, function (data) {
                stations = data;
                $('.find-station').devbridgeAutocomplete({
                    minChars: 2,
                    autoSelectFirst: true,
                    lookup: stations,
                    onSelect: function (suggestion) {
                        var stationId = '#station-'+suggestion['data'];
                        if($(stationId).length !== 0) {
                            var redirect = $(stationId).attr('href');
                            $(location).attr('href',redirect);
                        }
                    },
                    onHint: function (suggestion) {
                    }
                });
            });
        }
    }
    
    this.getStopEvents = function () {
        if($(".stop-events").length !== 0) {
            getStopEventContent();
            setInterval(getStopEventContent, 60000);
        }

        if($("#zbb-stop-events").length !== 0) {
            var url = $("#zbb-stop-events").data('url');
            $('#zbb-loader').show();
            $.ajax({
                url: url,
                success: function (data) {
                    $('#zbb-loader').hide();
                    $('#zbb-stop-events').html(data);
                },
                error: function(data){

                }
            });
        }


    }

    this.troubleMessages = function () {
        if(window.location.hash) {
            // open accordion
            var hash = window.location.hash.substring(1);
            if ($('.c'+hash).length) {
                $('.c'+hash).collapse();
            }
        }
        $('#error-messages a').bind('click', function(event) {
            if (this.pathname == window.location.pathname &&
                this.protocol == window.location.protocol &&
                this.host == window.location.host) {
                var hash = $(this).prop("hash").substring(1);
                if ($('.c'+hash).length) {
                    $('.c'+hash).collapse('show');
                }
            }
        });

        if($("#trouble-messages").length !== 0) {
            var url = $("#trouble-messages").data('src');
            $.ajax({
                url: url,
                success: function (data) {
                    $('.trouble-message-container').html(data);
                    $('#trouble-messages').show();

                    if($("#error-messages").length !== 0 && $("#message-count").length !== 0) {
                        var messages = $('#error-messages').data('count');
                        var notPlanned = $('#error-messages').data('notplanned');
                        $('#message-count,#message-count-mobile').html(messages);

                        if(notPlanned > 0 || messages >= 5){
                            $('#pills-contact-tab, #pills-contact, .mobile-toolbox').addClass('error');
                        } else if (messages > 0) {
                            $('#pills-contact-tab, #pills-contact, .mobile-toolbox').addClass('warning');
                        } else {
                            $('#pills-contact-tab, #pills-contact, .mobile-toolbox').addClass('success');
                        }
                    }

                },
                error: function(data){

                }
            });
        }

        if($("#technical-breakdown").length !== 0) {
            $("#pills-home-tab").addClass('disabled');
            $("#pills-home").removeClass('active');
        }

        if($("#technical-breakdown-message").length !== 0) {

            var url = $("#technical-breakdown-message").data('src');
            $.ajax({
                url: url,
                success: function (data) {
                    $('#technical-breakdown-message').html(data);

                    if ($("#technical-breakdown-alert").length != 0) {
                        var warning = getCookie("warning");
                        if (warning !== 'true') {
                            $('#technical-breakdown-message').css("display", "block");
                        } else {
                            $('#technical-breakdown-message').css("display", "block");
                            $('#technical-breakdown-message').addClass('small');
                            $('#technical-breakdown-alert').hide();
                        }
                        if (isMobile) {
                            $('#pills-tab li:last-child > a').click();
                        } else {
                            $('#pills-tab li:last-child > a').click();
                        }
                        $('body').addClass('error-on-page');
                    }
                },
                error: function(data){

                }
            });

            $(document).on('click', '#technical-breakdown-close', function (e) {
                e.preventDefault();
                $('#technical-breakdown-message').addClass('small');
                $('#technical-breakdown-alert').hide();

                setCookie('warning', true, 1);
            });

            $(document).on('click', '#open-breakdown', function (e) {
                e.preventDefault();
                $('#technical-breakdown-message').removeClass('small');
                $('#technical-breakdown-alert').show();

                setCookie('warning', false, 1);
            });
        }
    }


    this.setShipStops = function () {
        $(document).on('click', '.ship-stops', function (e) {
            e.preventDefault();
            $('#lake-map .station').removeClass('active');
            $('#lake-map .station').removeClass('start');
            $('#lake-map .station').removeClass('end');

            if(!$(this).hasClass('collapsed')){
                var data = $(this).data('didoks');
                if (typeof data !== 'undefined'){
                    var didoks = data.split(",");
                    for(var i = 0; i < didoks.length; i++) {
                        if(i == 0){
                            $('#didok-'+didoks[i]).addClass('start');
                        } else if(i == didoks.length-1){
                            $('#didok-'+didoks[i]).addClass('end');
                        } else {
                            $('#didok-'+didoks[i]).addClass('active');
                        }
                    }
                }
            }
        });
    }

}

function getStopEventContent(){

    var url = $(".stop-events").data('url');
    $.ajax({
        url: url,
        success: function (data) {
            var content = jQuery('<div>' + data + '</div>');
            content.find('.stop-event-entry').each(function() {
                var stopEventId = $(this).attr('id');
                $('#'+stopEventId).html($(this).html());

            });

            $('.stop-events').find('.departure-pdf').removeClass('departure-pdf');
        },
        error: function(data){

        }
    });

}

(function ($) {
    'use strict';
    $(document).ready(function () {
        var timeTableHandling = new TimeTableHandling();
        timeTableHandling.init();
    });
}(jQuery));

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}