

/**
 * Google Preview
 *
 * @author Ryan Chase
 * @version 1.0
 * @url http://www.blastam.com/blog/index.php/2013/03/how-to-track-downloads-in-google-analytics-v2
 */
(function ($, document) {
    $(document).ready(function(){
        var filetypes = /\.(zip|exe|dmg|pdf|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;

        $('a').on('click', function (event) {
            var el = $(this),
                track = true,
                href = this.href,
                isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);

            if (!href.match(/^javascript:/i)) {
                var elEv = [];
                elEv.value = 0, elEv.non_i = false;
                if (href.match(/^mailto\:/i)) {
                    elEv.category = "email";
                    elEv.action = "click";
                    elEv.label = href.replace(/^mailto\:/i, '');
                    elEv.loc = href;
                }
                else if (href.match(filetypes)) {
                    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                    elEv.category = "download";
                    elEv.action = "click-" + extension[0];
                    elEv.label = href.replace(/ /g, "-");
                    elEv.loc = href;
                }
                else if (href.match(/^https?\:/i) && !isThisDomain) {
                    elEv.category = "external";
                    elEv.action = "click";
                    elEv.label = href.replace(/^https?\:\/\//i, '');
                    elEv.non_i = true;
                    elEv.loc = href;
                }
                else if (href.match(/^tel\:/i)) {
                    elEv.category = "telephone";
                    elEv.action = "click";
                    elEv.label = href.replace(/^tel\:/i, '');
                    elEv.loc = href;
                }
                else track = false;

                if (track) {
                    ga('send', 'event', elEv.category.toLowerCase(), elEv.action.toLowerCase(), elEv.label.toLowerCase(), elEv.value, {'nonInteraction': elEv.non_i});
                }
            }
        });
    });
})($, document);

$(function() {
    $("#tx_cookies_close").click(function(){
        $(this).closest("#tx_cookies").find("#tx_cookies_showPermanent").show();
        $(this).closest("#tx_cookies_inner").hide();
    });
    $("#tx_cookies_showPermanent").click(function(){
        $(this).hide();
        $(this).closest("#tx_cookies").find("#tx_cookies_inner").show();
    });
    if($("#tx_cookies_inner").attr("data-hide") == 1) {
        $("#tx_cookies_inner").hide();
    }
    if($("#tx_cookies_showPermanent").attr("data-hide") == 0) {
        $("#tx_cookies_showPermanent").hide();
    }

    $("#tx_cookies_hide").submit(function(e) {
        e.preventDefault();
        // Set cookie
        var d = new Date();
        d.setTime(d.getTime() + ($(this).attr("data-expire")*24*60*60*1000));
        var expires = 'expires=' + d.toUTCString();
        document.cookie = 'tx_cookies_hidden=1;' + expires + ';path=/';
        // Close cookie hint
        $(this).closest("#tx_cookies").find("#tx_cookies_close").click();
    });
});
$(document).ready(function() {
    $('.tx-randombanners').randomize();
    $('.tx-randombanners a').on('click', function(){
        $.ajax({
            type: 'POST',
            url: 'index.php',
            data:  {
                'eID': 'randombanners',
                'banner': $(this).attr('data-uid')
            },
            success: function() {
                return true;
            }
        });
    });
});

/**
 * Rearrange child elements in random order
 *
 * @see http://jsfiddle.net/C6LPY/2/
 */
(function($) {
    $.fn.randomize = function() {
        return this.each(function() {
            var parent = $(this);
            var children = parent.children();
            while(children.length) {
                parent.append(children.splice(Math.floor(Math.random() * children.length), 1)[0]);
            }
        });
    }
})(jQuery);
$(function(){

    // Business card accordion
    $.each($('.tx_rrrestaurants-cards'), function() {
        if($(this).children('.tx_rrrestaurants-show.card').length > 1) {
            $(this).find('.tx_rrrestaurants-show.card .businesscard-more').show();
            $(this).find('.tx_rrrestaurants-show.card .businesscard-more-info').hide();
        }
    });
    $('.tx_rrrestaurants-show.card .businesscard-more a').click(function() {
        $(this).hide().closest('.businesscard-more').next().slideDown();
    });

    // Status for restaurant favorite
    $('.checkRestaurantFavoriteText, .checkRestaurantFavoriteShow').each(function(index) {
        $.ajax({
            type: 'POST',
            data: {
                type: 304,
                'tx_rrrestaurants_restaurants[restaurant]': $(this).attr('data-uid')
            },
            dataType: 'json'
        }).done(function(data){
            if(data.text){
                $('.checkRestaurantFavoriteText').text(data.text);
                $('.checkRestaurantFavoriteShow').show();
            }
        });
    });

    // Status for restaurant opening hours (restaurant listing and details)
    if($('.checkRestaurantOpeningHour').length) {
        restaurantUids = $.makeArray(
            $('.checkRestaurantOpeningHour').map(function(){
                return $(this).attr('data-uid');
            })
        );
        checkRestaurantOpeningHour(restaurantUids);
    }

    // Autocomplete
    acOptionsCity = {
        name: 'cities',
        header: '<h3>Städte</h3>',
        remote: '/?id=356&type=302&no_cache=1&tx_rrrestaurants_app[action]=autocompleteSearchHeader&tx_rrrestaurants_app[type]=city&tx_rrrestaurants_app[search]=%QUERY',
        limit: 5,
        minLength: 3,
        maxParallelRequests: 1,
        template: [
            '<span class="name">{{name}}</span>',
            '<span class="description">{{description}}</span>'
        ].join(''),
        engine: Hogan
    };
    acOptionsLocation = $.extend({}, acOptionsCity);
    acOptionsLocation.name = 'locations';
    acOptionsLocation.remote = '/?id=356&type=302&no_cache=1&tx_rrrestaurants_app[action]=autocompleteSearchHeader&tx_rrrestaurants_app[type]=location&tx_rrrestaurants_app[search]=%QUERY';
    acOptionsRestaurant = $.extend({}, acOptionsCity);
    acOptionsRestaurant.name = 'restaurants';
    acOptionsRestaurant.header = '<h3>Restaurants</h3>';
    acOptionsRestaurant.remote = '/?id=356&type=302&no_cache=1&tx_rrrestaurants_app[action]=autocompleteSearchHeader&tx_rrrestaurants_app[type]=restaurant&tx_rrrestaurants_app[search]=%QUERY';
    acOptionsRestaurant.limit = 10;
    acOptionsPerson = $.extend({}, acOptionsCity);
    acOptionsPerson.name = 'persons';
    acOptionsPerson.header = '<h3>Personen</h3>';
    acOptionsPerson.remote = '/?id=356&type=302&no_cache=1&tx_rrrestaurants_app[action]=autocompleteSearchHeader&tx_rrrestaurants_app[type]=person&tx_rrrestaurants_app[search]=%QUERY';
    acOptionsPerson.limit = 10;
    $('.tx-rr-restaurants input.ac-city').typeahead([acOptionsCity]);
    $('.tx-rr-restaurants input.ac-location').typeahead([acOptionsLocation]);
    $('.tx-rr-restaurants input.ac-restaurant').typeahead([acOptionsRestaurant]);
    $('.tx-rr-restaurants input.ac-person').typeahead([acOptionsPerson]);
    $('.tx-rr-restaurants input.ac-city-restaurant-person').typeahead([acOptionsRestaurant, acOptionsCity, acOptionsPerson]);
    $('.tx-rr-restaurants input.ac').on('typeahead:selected', function($e, $datum, $a){
        $(this).closest('form').find('input[name|="tx_rrrestaurants_restaurants[type]"]').val($datum.type);
        $(this).closest('form').find('input[name|="tx_rrrestaurants_restaurants[id]"]').val($datum.uid);
        // submit form after selecting a suggestion
        $(this).closest('form.ac-autoSubmit').submit();
    });

    // Google Maps
    /*$('#googleMapsMax').on('click', function(){
        Shadowbox.init({
            overlayColor:    '#ffffff',
            onOpen:            onOpen,
            onFinish:        onOpen,
            onChange:        onOpen
        });
        Shadowbox.open({
            content:    '<div id="googleMapsMaxContent"></div>',
            player:        'html',
            title:        'Google Maps',
            onOpen:        onOpen,
            height:        600,
            width:        1200
        });
        return false;
    });
    function onOpen(){
        //$('#map-canvas').appendTo('#googleMapsMaxContent');
        alert('open');
    }*/

    // HTML5 globe
    $(document).on('change', '.tx_rrrestaurants-toppositions select', function(){
        country = $(this).val();
        selectCountry(country);
    });

    // User rating
    if($('form[name="rating"] #fbox-rating input:checked').val() == 11) {
        $('#fbox-bonus').hide();
    }
    $(document).on('change', 'form[name="rating"] #fbox-rating input:checked', function(){
        if($(this).val() == 11) {
            $('#fbox-bonus').hide();
        } else {
            $('#fbox-bonus').show();
        }
    });

    // Control "remove" for input fields
    $.each($('input.form-control-remove'), function() {
        $(this).wrap('<div class="form-control-remove-outer"></div>');
        $(this).after('<span class="glyphicon glyphicon-remove"></span>');
        if(!$(this).val()) {
            $(this).next('.glyphicon-remove').hide();
        }
    });
    $('.form-control-remove-outer .glyphicon').on('click', function() {
        $(this).fadeOut().siblings('input.form-control-remove').val('').focus();
    });
    $('input.form-control-remove').on('keyup', function() {
        if($(this).val()) {
            $(this).next('.glyphicon-remove').fadeIn();
        } else {
            $(this).next('.glyphicon-remove').fadeOut();
        }
    });


    /**************************************************
     * AJAX loading of more contents
     */
    $('.ajaxLoad').on('click', '.ajaxLoad-trigger-click a', function(e){
        e.preventDefault();
        $parent = $(this).closest('.ajaxLoad-trigger');
        $parent.children('.ajaxLoad-trigger-click').hide();
        $parent.children('.ajaxLoad-trigger-loading').show();
        $.ajax({
            url: $(this).attr('href'),
        }).done(function(data){
            data = $.trim(data);
            $parent.slideUp(500, function(){
                $(this).remove();
                if(data) {
                    $('.ajaxLoad').append(data);
                    restaurantUids = $.makeArray(
                        $(data).filter('.checkRestaurantOpeningHour').add($(data).find('.checkRestaurantOpeningHour')).map(function(){
                            return $(this).attr('data-uid');
                        })
                    );
                    checkRestaurantOpeningHour(restaurantUids);
                    updateScrollToFixedRrRestaurants();
                }
            });
        })
        .fail(function(jqXHR){
            $parent.html('Sorry, an error occured. Please reload this page.<br>Error URL: ' + $('.ajaxLoad-trigger').attr('data-url') + '<br>Error status: ' + jqXHR.status + ' (' + jqXHR.statusText + ')');
        });
    });

});

$(window).on("load", function(e) {
    updateScrollToFixedRrRestaurants();
});

function updateScrollToFixedRrRestaurants() {
    // Fixed filter on right side
    $.each($('.scroll-to-fixed-rrRestaurants'), function() {
        $(this).trigger('detach.ScrollToFixed');
        var marginTop = 20;
        var parent = $(this).closest('.row');
        var limit = parent.offset().top + parent.height() - $(this).height() - marginTop;
        $(this).scrollToFixed({
            marginTop: marginTop,
            minWidth: 755,
            zIndex: 100,
            removeOffsets: true,
            limit: limit,
            spacerClass: 'scroll-to-fixed-spacer'
        });
    });
}

function loadTOP10(country){
    loadRestaurants(country);
}

function countryLabelClicked(country){}

function loadRestaurants(country){
    $.ajax({
        type: 'POST',
        data: {
            type: 305,
            'tx_rrrestaurants_restaurants[country]': country
        },
        dataType: 'json'
    }).done(function(data){
        if(data.top10){
            $('.tx_rrrestaurants-toppositions').parent().html(data.top10);
        }
        if(data.capital){
            $('#tx_rrrestaurants-globe-input').val(data.capital);
        }
    });
}

function checkRestaurantOpeningHour(restaurantUids) {
    date = new Date();
    if(date.getHours() >= 1 && date.getHours() <= 23) { // Display opening hours only from 1 am to 23 pm
        $.ajax({
            type: 'GET',
            data: {
                type: 306,
                'tx_rrrestaurants_restaurants[restaurants]': restaurantUids
            },
            dataType: 'json'
        }).done(function(openedRestaurants){
            $.each(openedRestaurants, function(index, value){
                if(value == 'openedLunch' && date.getHours() >= 14) { // Do not display lunch after 14 pm
                    return;
                }
                $('.checkRestaurantOpeningHour[data-uid=' + index + ']').addClass(value);
            });
        });
    }
}
/* no fixed header: if($('header').length) {
    var headerHeight = document.getElementsByTagName('header')[0].offsetHeight;
    var adHeight = document.getElementById('ad-superbanner').offsetHeight;
    var headerHeightWithoutAd = headerHeight - adHeight;
    var navMobileHeight = document.getElementById('nav-mobile').offsetHeight;
    var heightNav = isMobile() ? headerHeight + navMobileHeight : headerHeight;
}*/

$(function(){
    // Responsive tables
    $(document).trigger('enhance.tablesaw');

    // Bootstrap Tooltip
    //$('[data-toggle="tooltip"]').tooltip();

    // Fixed top navigation
    // no fixed header: $('#page_outer').css('padding-top', headerHeight);
    /* no animations for menu because of problems in iPhone
    $('#header-main').outerHeight(headerHeight);
    $('#nav-mobile').css('top', headerHeight);*/
    $('#navbar-header-main-mobile').scrollToFixed();
    // no fixed header: $('.tablesaw-bar').scrollToFixed({marginTop: navMobileHeight});

    // Fixed elements
    $('.scroll-to-fixed').scrollToFixed({
        marginTop: 20
    });
    $('.tablesaw-bar').scrollToFixed();

    // Auto submit of select
    $('.autoSubmit select').on('change', function(){
        window.location.href = $(this).val();
    });
    // Auto submit of forms
    $('form.autoSubmitAtOnce').submit();

    // Auto submit of form filter
    $('.autoSubmitOnChange select').on('change', function(){
        $(this).closest('form').submit();
    });

    // Position of search input field (important for mobile)
    if(isMobile()) {
        $('.tx_rrrestaurants-searchheader form input').focus(function() {
            $('html, body').animate({
                // no fixed header: scrollTop: $(this).closest('.tx_rrrestaurants-searchheader').offset().top - navMobileHeight
                scrollTop: $(this).closest('.tx_rrrestaurants-searchheader').offset().top
            }, 500);
        });
    }

    // Print dialog
    $('.print-dialog').on('click', function(){
        window.print();
    });

    // EXT:cookies: Show cookie hint
    if(!getCookieValue('tx_cookies_hidden')) {
        $('#tx_cookies').slideDown();
    }

    // Smooth Scrolling
    $('a[href*="#"]:not([href="#"], .tabs > ul > li > a, .panel-default .panel-heading a)').click(function(e) {
        if(location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            smoothScroll($(this.hash));
            e.preventDefault();
        }
    });

    // Activate first tab, if no tab is defined as active
    $.each($('.tabs'), function(){
        if(!$(this).find('.nav-tabs').children('li.active').length) {
            $(this).find('.nav-tabs li:first-child').addClass('active');
        }
        if(!$(this).find('.tab-content').children('.tab-pane.active').length) {
            $(this).find('.tab-content .tab-pane:first-child').addClass('active in');
        }
    });

    // Fixed top navigation: Current page called with anchor link
    if(window.location.hash) {
        smoothScroll($(window.location.hash));
    }
    if($('#scrollHere').length) {
        smoothScroll($('#scrollHere'));
    }

    // Left bar: show contact
    $('#lb-contact > a').on('click', function(){
        $('#lb-contact').width(300);
        $('#lb-contact > a').toggle();
        $('#lb-contact-extended').toggle();
        return false;
    });
    $('#lb-contact .lb-contact-close').on('click', function(){
        $('#lb-contact').width('auto');
        $('#lb-contact > a').toggle();
        $('#lb-contact-extended').toggle();
    });

    // Hide fluid pagebrowser if it contains only one page TODO
    $.each($('.f3-widget-paginator'), function(){
        if($(this).children('li').length < 2) {
            $(this).hide();
        }
    });

    // Date picker
    if($('[data-toggle="datepickerReservation"]').length) {
        $('[data-toggle="datepickerReservation"]').datepicker({
            autoHide: true,
            language: 'de-DE',
            startDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
            trigger: $('.input-group').find('input')
        });
    }
    // Show datepicker when clicking on icon
    $('.input-group-addon .glyphicon-calendar').on('click', function(e) {
        e.stopPropagation();
        $(this).closest('.input-group').find('input').datepicker('show');
    });

    // Ext. eventnews
    $('.news-month-view .table .hasevents a').on('click', function(){
        if(!$(this).hasClass('active')){
            $('.news-month-view .articles > .frame').hide();
            $('.news-month-view .table .hasevents a').removeClass('active');
            $('#' + $(this).attr('data-tooltip')).toggle();
            $(this).toggleClass('active');
        }
    });

    // Contact form: hide field "restaurant" if it contains no value
    if(!$('form#contact input#contact-restaurant').val()) {
        $('form#contact input#contact-restaurant').closest('.form-group').remove();
    }

    // Popup on startpage: Close popup
    $('#overlay-close').on('click', function(){
        $('#overlay').fadeOut();

        // Set cookie
        var d = new Date();
        d.setTime(d.getTime() + (24*60*60*1000));
        var expires = 'expires=' + d.toUTCString();
        document.cookie = 'overlay_hidden=1;' + expires + ';path=/';
    });

});

function isMobile() {
    return navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/);
}

function smoothScroll(target) {
    target = target.length ? target : $('[name=' + hash.slice(1) +']');
    if(target.length) {
        $('html, body').animate({
            // no fixed header: scrollTop: parseInt(target.offset().top) - heightNav
            scrollTop: parseInt(target.offset().top)
        }, 1000);
    }
}

function loadIfScreenWidth(screenWidth, element, html) {
    if($(window).width() >= screenWidth) {
        $(element).html(html);
    }
}

/**
 * @see http://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript
 *
 * @param k: name of cookie
 * @returns value of cookie
 */
function getCookieValue(k) {
    var b = document.cookie.match('(^|;)\\s*' + k + '\\s*=\\s*([^;]+)');
    return b ? b.pop() : '';
}