// JavaScript Document
var getSiteWrapCount = function () {
    return $('.siteWrap').length;
};

var siteWrapCount;
var widthOfElem;
var getWinSizeOnly;

var setPageWidth = function (getWinSizeOnly) {
    if (siteWrapCount > 1) {
        windowW = $(window).width();
        if (windowW - widthOfElem * (siteWrapCount - 1) > 1080)
            pageW = $(window).width() - widthOfElem * (siteWrapCount - 1);
        else
            pageW = 1080;
        if (!getWinSizeOnly) {
            $('.siteWrap').not('.closed').width(pageW);
            $('#site, #magazinHolzbau #first, #mainNav').width(pageW);
        }
    } else {
        $('.siteWrap').width($(window).width());
    }

};

var positionLogo = function () {
    if ($('#mainNav ul:first').length) {
        var offsetL = $('#mainNav ul:first').offset().left;
        $('#logo').width(offsetL + $('#logo img').width() + 32);
    }
};

var stickyFooter = function () {
    var offsetT = $('#container').offset().top;
    var containerH = $('#container').height();
    var footerH = $('.footer:first').height();
    var offsetB;

    if ($(window).height() > offsetT + containerH) {
        offsetB = $(window).height() - (offsetT + containerH + footerH) - 10;
    } else {
        offsetB = 0;
    }
    $('#container').css('paddingBottom', offsetB);
};


var initializePlatform = function () {
    // mainNav toggle
    $('#mainNav').after('<div id="menuOverlay"></div>');

    positionLogo();

    $(window).resize(function () {
        positionLogo();
    });

    $(window).on('load', function () {
        stickyFooter();

        $(window).resize(function () {
            stickyFooter();
        });
    });
};

var initializeOnReady = function () {
    $(".fancybox").fancybox({
                                openEffect: 'fade',
                                closeEffect: 'fade',
                                //prevEffect: 'fade',
                                //nextEffect: 'fade',

                                helpers: {
                                    title: {
                                        type: 'inside'
                                    },
                                    overlay: {
                                        locked: false
                                    }
                                }
                            });
    // add shadow on header after scrolling
    $(window).scroll(function (e) {
        if ($(window).scrollTop() > 0) {
            $('#header').addClass('scrollShadow');
        } else {
            $('#header').removeClass('scrollShadow');
        }
    });

    //init inline Labels
    $('.inlineLabel label').inFieldLabels();
    $('.powermail_label').inFieldLabels();
    $('.femanager_fieldset label').inFieldLabels();

    //uniform
    $('select, input[type="checkbox"], input[type="radio"]').uniform();

    //increase/decrease search on focus/blur


    $('#searchfield').focus(function () {
        $(this).animate({
                            'width': 180
                        }, 400);
    });
    $('#searchfield').blur(function () {
        $(this).animate({
                            'width': 50
                        }, 400);
    });


    //topcontent set anker und sidebarBoxes set anker
    //$('#sidebarNews a').each();


    $(document).on('click', '#mainNav li a:not(#mainNav ul ul li a)', function (e) {
        console.log($(this).attr('xlink:href'));

        var attr = $(this).attr('xlink:href');

        // For some browsers, `attr` is undefined; for others,
        // `attr` is false.  Check for both.
        if (typeof attr !== typeof undefined && attr !== false) {
            window.location.href = attr;
        }

        e.preventDefault();
        $('#mainNav li a').not($(this)).removeClass('toggleActive');
        var menuSubHeight;
        $('#mainNav .mainNavSubWrapper').hide();
        $(this).parent().find('.mainNavSubWrapper').show();

        if ($(this).hasClass('toggleActive')) {
            menuSubHeight = 0;
            $(this).removeClass('toggleActive');
            $('#mainNav').removeClass('menuOpen');
            $('#menuOverlay').fadeOut(300);
        } else {
            menuSubHeight = $(this).parent().find('.mainNavSubWrapper').height();
            $(this).addClass('toggleActive');
            $('#mainNav').addClass('menuOpen');
            $('#menuOverlay').fadeIn(300);
        }

        if ($('#site').hasClass('subpage') || $('#site').hasClass('metapage')) {
            $('#mainNav').animate({
                                      'paddingTop': menuSubHeight
                                  }, 500);
        } else {
            $('#mainNav').animate({
                                      'height': menuSubHeight + 80
                                  }, 500);
        }
        return false;
    });
    $(document).on('click', '#menuOverlay', function () {
        $('#mainNav .toggleActive').trigger('click');
    });

    //mainNav hover if mainNav is closed
    $(document).on({
                       mouseenter: function () {
                           $('#mainNav').addClass('closedHover');
                       },
                       mouseleave: function () {
                           $('#mainNav').removeClass('closedHover');
                       }
                   }, '#mainNav:not(.menuOpen) a');

    var renderSectionNav = function () {
        $.get('/typo3conf/ext/holzbauschweiz_template/Resources/Public/Images/Sections/sections.svg', function (data) {
            var svgContent = data;
            // render sections menu with svg
            var sectionsMenu;
            sectionsMenu = $('li.last .mainNavSubWrapper ul').detach();
            var sectionContainer = '<div class="section-map-container"><div class="map">' + svgContent + '</div><div class="section-menu"><ul>' + sectionsMenu.html() + '</ul></div></div> ';
            $('li.last .mainNavSubWrapper').prepend(sectionContainer);
        }, 'text');
    };

    if($('#platform.home').length == 0) {
        renderSectionNav();
    };

    // subNav toggle
    /*$('#subNav span').click(function() {
     $(this).parent().parent().find('ul').slideUp(function() {
     $(this).parent().find('span').removeClass('active');
     });
     $(this).parent().children('ul').filter(':hidden').slideDown();
     $(this).toggleClass('active');
     });*/

    // toggle boxes
    $(document).on('click', '.toggleList', function () {
        $this = $(this);
        if ($this.parent().hasClass('single')) {
            // toggle one
            $target = $(this).parent().find('.toggleContent').slideToggle(400);
            $(this).toggleClass('open');
        } else {
            // toggle all
            $(this).parents('#content').find('.toggleContent').slideUp();
            $(this).not('.open').parent().children('.toggleContent').slideDown(400, function () {
                $(window).trigger('resize');
                $(window).trigger('resize');
            });
            $('.toggleList').not($(this)).removeClass('open');
            $(this).toggleClass('open');
        }


    });

    // position of gmaps
    if ($('.tx-go-maps-ext').length) {
        var map = $('.tx-go-maps-ext').html();
        $('.tx-go-maps-ext').remove();

        $('#container').after('<div class="tx-go-maps-ext">' + map + '</div>');
    }

    $('#magazinHolzbau #first .siteTab').css({
                                                 'left': 80,
                                                 'backgroundPosition': '-117px 205px'
                                             });

    $('.siteTab').hide();
    $('.closed .siteTab').show();

    getWinSizeOnly = false;
    siteWrapCount = getSiteWrapCount();
    widthOfElem = 80;

    //Set classes for correct positioning
    if (siteWrapCount == 2) {
        //Holzbau and Other one
        $('.siteWrap:eq(1)').addClass('onlyOne');
    }


    setPageWidth();

    $(document).on('click', '.siteTab', function () {
        //$('#wrapper').attr('class','');
        //$('#wrapper').addClass($(this).parents('.siteWrap').attr('id'));
        $(window).scrollTop(0);
        $('.siteWrap').addClass('closed');
        $(this).parents('.siteWrap').removeClass('closed');
        setPageWidth(true);
        $(this).fadeOut(200);
    });

    $(document).on('click', '#site .siteTab', function () {
        $('.siteWrap.closed').animate({
                                          'width': 80
                                      }, 800, function () {
            $('.closed .siteTab').fadeIn(200);
        });
        $('#first .siteTab').animate({
                                         'left': pageW
                                     }, 800, function () {
            $(this).attr('style', '');
        });
    });

    $(document).on('click', '#first .siteTab', function () {
        $('#first').animate({
                                'width': pageW
                            }, 800, function () {
            $('.closed .siteTab').fadeIn(200);
        });

        $('#holzbau').animate({
                                  'width': 80
                              }, 800, function () {
            $('.closed .siteTab').fadeIn(200);
        });
    });

    $(document).on('click', '#holzbau .siteTab', function () {
        $('#holzbau, #first').animate({
                                          'width': pageW
                                      }, 800, function () {
            $('.closed .siteTab').fadeIn(200);
        });
        $('#first .siteTab').css('backgroundPosition', '-117px 205px');
        $('#first .siteTab').animate({
                                         'left': 80
                                     }, 800);
    });
};


var initializeDefault = function () {
    $(document).ready(function () {
        initializeOnReady();

    });


    $(window).resize(function () {
        setPageWidth();
    });

};


initializeDefault();

$(document).ready(function () {
    if ($('#platform').length > 0) {
        initializePlatform();

        if ($('#platform.home').length > 0) {
            initializeHome();
        }
    }

});

var getUrlParam = function (name, href) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(href);
    if (results == null) {
        return null;
    }
    else {
        return decodeURI(results[1]) || 0;
    }
}

// start of: check for secure dowload links and add a class to style them
$(window).on('load', function (e) {
    $('a').each(function () {
        var eID = getUrlParam('eID', this.href);
        if (typeof eID !== 'undefined' && eID === 'dumpFile') {
            $(this).addClass('secure-download');
            $(this).on('click', function (e) {
                Cookies.set('dumpFile', $(this).attr('href'), {expires: 1});
            });
        }
    });
    if (Cookies.get('dumpFile') != undefined) {
        $('.tx-felogin-pi1 form').on('submit', function (e) {
            $('.tx-felogin-pi1').toggle();
        });
    }


    var getUrlVars = function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    // check if we have to redirect to a secure download file
    var params = getUrlVars();
    if (params['dumpFileFrom'] != undefined) {
        location.href = '/index.php?' + decodeURIComponent(params['dumpFileFrom']);
    }

});