$(function(){
   /* Startseite Slideshow */
/*    $(".slide-out").slideout({bindOnInit: false});
    // debug
    // try to catch slideshow events in slides
    $(".slide").bind('destroy.slideshow', function (e) {
        // unbind slideout behaviour, reset slideout position
        $(this).find('.slide-out').slideout('unbind').slideout('reset');
    }).bind('init.slideshow', function (e) {
        // bind slideout behaviour
        $(this).find('.slide-out').slideout('bind');
    });
    $("#slideshow").slideshow({timeOut:6000, duration: 1500});
 */

    /* Startseite Slideshow */
    $(".slide-out").slideout({bindOnInit: false});
    // debug
    // try to catch slideshow events in slides
    $(".slide").bind('destroy.slideshow', function (e) {
        // unbind slideout behaviour, reset slideout position
        $(this).find('.slide-out').slideout('unbind').slideout('reset');
    }).bind('init.slideshow', function (e) {
        var $this = $(this), $slideOut = $this.find('.slide-out'),
            $link = $slideOut.find('a:first');

        // make whole text clickable
        if ($link.length) {
            $this.find('.slide-text').css('cursor', 'pointer').click(function () {
                // unfortunately that doesn't navigate to the href
                //$link.click();
                window.location = $link.attr('href');
            });
        }
        // bind slideout behaviour
        $slideOut.slideout('bind');
    });
    $("#slideshow").slideshow({timeout:8000, duration: 400}) /* war: 1500, hat geruckelt */
      // add fixed width to slideshow controls div
      .find(".slideshow-controls").each(function () {
          var totalWidth = 0, $this = $(this);

          totalWidth = $this.find('.direct-selection').children().length * 13 // direct selection controls
            + 2 * 23; // prev-next controls
          $this.css('width', totalWidth + 'px');
      });


    $("#navi>ul>li,div.submenu>ul>li").each(function () {
        $(this).hoverIntent({
            over: function () {
                $(this).addClass("hover");
                // fire artificial event to enable other reactions
                $(this).trigger('hiEnter');
            },
            timeout: 300,
            out: function () {
                $(this).removeClass("hover");
                // fire artificial event to enable other reactions
                $(this).trigger('hiLeave');
            }
        });
    });
    

    /* Verhinderung des zitterns beim versehentlichen hover des highlights */
    $('#highlight').mouseenter(function (e) {
        e.stopPropagation();
    });

    
    var $navMarker = $('#highlight');
    if ($navMarker.length) { /* prüfen, ob das Element existiert */
      if ($('.submenu>ul>li.navi2Level2Selected').length) {
        var navMarkerStartY =  $('.submenu>ul>li.navi2Level2Selected').position().top;
        $navMarker.css('top', navMarkerStartY + 'px');
      }else{
        var navMarkerStartY = $navMarker.position().top; 
      }

        $('.submenu>ul>li').mouseenter(function (e) {
            var posTop = $(this).position().top;
            $navMarker.stop().animate({top: posTop + 'px'}); /* die ul benötigt position:relative!!! */
        });
        $('.submenu').mouseleave(function () {
            $navMarker.stop().animate({top: navMarkerStartY + 'px'});
        });
    }

// bs, 20110824 new tabs
    // setup ul.tabs to work as tabs for each div directly under div.panes
    //$("ul.tabs").tabs("div.panes > div");
    $("ul.tabs").each(function () {
        var $links = $("a", this),
            $container = $(this).parent().parent().find(".panes"); // @todo In a plugin, this would be a setting
        
        $links.click(function (evt) {
            var $previous,
                $current = $(this);
            evt.preventDefault();
            // Mark the current link or skip everything if tab is already active
            $previous = $links.filter('.current');
            if ($previous === $current) {
                return;
            }
            $previous.removeClass('current');
            $current.addClass('current');
            // .load seems not to work with script tags
// debug finding another way while retaining basic functionality above
//if (location.hash === '#wqtest') {
            $container.children().remove();
            $.get(this.href, function (htmlStr) {
                var htmlBody,
                    $placeHolder,
                    placeHolderId = 'placehoder-' + (new Date()).getTime();
                htmlBody = htmlStr.match(/<body.+?>([^§]+)<\/body>/m)[1];
                // place loaded html into a blind div to execute contained scripts in local context
                // then move the loaded pane into sight and remove the unnecessary rest
                $('<div style="width:1px;height:1px;overflow:hidden" id="' + placeHolderId + '" />').appendTo('body')
                    .html(htmlBody) // at this very moment, the script tags get executed and removed
                    .find(".panes > div").appendTo($container);
                $('#' + placeHolderId).remove();
            });
/*
} else {
            $container.load(this.href + " .panes > div");
}
*/
        });
    });


//    $("#imageBlockContainer").gallery();

    // FAQ
    //Hide (Collapse) the toggle containers on load
        $(".toggle_container").hide(); 
    
        //Switch the "Open" and "Close" state per click
        $(".trigger").toggle(function(){
            $(this).addClass("active");
            }, function () {
            $(this).removeClass("active");
        });
    
        //Slide up and down on click
        $(".trigger").click(function(){
            $(this).next(".toggle_container").slideToggle("fast");
        });
        
        //show/hide all answers
        $("a.showall").toggle(function(e){
          e.preventDefault();
          $("a.showall").html("Alle Fragen schließen");
          $(".toggle_container").show();    
        }, function(e) {
          e.preventDefault();
          $("a.showall").html("Alle Fragen öffnen");
          $(".toggle_container").hide();
        });

    /* Produkt-Navi */
    var $produktMenu = $('.position3');
    var $produktSubnavi = $('#produktSubnavigation').css({zIndex: 999, position: 'absolute', left: -1 * $produktMenu.position().left});
    $produktMenu.children('ul').replaceWith($produktSubnavi).end()
        // Bind to artificial events triggered by modified hoverIntent handlers
        .bind('hiEnter', function () {
            $produktSubnavi.show();
        }).bind('hiLeave', function () {
            $produktSubnavi.hide();
        });



    /* neu ab 22.11.2011: Produkt-Feature-Icons */
    $('body').removeClass('noJS').addClass('js');
    // Scripts for feature listing on product pages
    $("#features").each(function () {
        var $this = $(this),
            slideState = 'open',
            preventSlideOpen;

        function slideOpen() {
            // @todo Read out css instead of hard-coding values
            $this.parent().css('width', '375px');
            $this.animate({right: 0});
            // Reflect open slideout visually by changing the trigger's class
            $this.find('h2').addClass('active');
            slideState = 'open';
        }

        /* slideout */
        $this.wrap('<div class="slideout-container" />').find('h2').click(function () {
            if (slideState === 'open') {
                $this.animate({right: '-273px'}, {complete: function () {
                    // restore container width to enable click-through
                    // @todo Read out css instead of hard-coding values
                    $this.parent().css('width', '102px');
                }});
                // Reflect closed slideout visually by changing the trigger's class
                $(this).removeClass('active');
                slideState = 'closed';
            } else {
                slideOpen();
            }
        }).trigger('click');

        // Site-specific: Reposition container
        // Would work, if ancestor had overflow not set to hidden
        //$this.parent().offset({left: $("body").width() - $this.parent().width(), top: $("#productDetail").offset().top});
        // Thus we have to move it around in the DOM, which is not very screenreader-friendly
        // This variant fails in IE lt 9, because offset() expects top AND left coordinates, but we want it right-aligned.
        //$this.parent().appendTo("#wrap").offset({top: $("#productDetail").offset().top});
        // Luckily the positioning parent's top offset is 0 so we can use css manipulation instead.
        $this.parent().appendTo("#wrap").css({top: $("#productDetail").offset().top});

        /* tabs */
        $this.find('.feature-listing').each(function () {
            var $this = $(this),
                contents = $this.find('.feature'),
                navigation = $('<ul class="tabs-navigation" />').prependTo($this),
                pane = $('<div class="tabs-content"><div class="tabs-content-textcontainer" /></div>').appendTo($this).children().first(),
                tabs;

            // Generate tabs markup
            contents.each(function () {
                var $this = $(this),
                    title = $this.find('h3').html();

                // Navigation controls
                $('<li>' + title + '</li>').appendTo(navigation).data('tabs', {target: $this});
            });

            tabs = navigation.find('li');

            // Hide all contents
            contents.hide();

            // Wire tab changing functionality
            tabs.click(function () {
                var $this = $(this),
                    data = $this.data('tabs');

                // Reflect tab change in tab class names
                $this.siblings().removeClass('active').end().addClass('active');

                if ($.contains(pane.get(0), data.target.get(0))) {
                    // Tab is already active
                    // Make sure slideout is visible
                    slideOpen();
                    return;
                }

                // Put old content back
                pane.contents().hide().appendTo(pane.parent());
                // Move new content into pane
                data.target.appendTo(pane).show();

                // Mechanism to prevent unwanted slideOpen on init
                // Make sure slideout is visible any other time a user clicks a tab
                if (preventSlideOpen) {
                    preventSlideOpen = false;
                } else {
                    slideOpen();
                }
            });

            // Display first tab
            preventSlideOpen = true;
            tabs.eq(0).trigger('click');
        });

        /* tooltip */
        $this.find('.tabs-navigation li').each(function () {
            var $this = $(this),
                tabsData = $this.data('tabs'),
                content,
                tooltip;

            if (! tabsData) {
                // Tabsdata holds a reference to the tooltip contents
                // If tabsdata is not set, something went terribly wrong and we cannot continue
                $.error('Product feature tooltip requires tabs to be initialized');
                return;
            }

            // Save content for later use and hide it while maintaining accessibility
            content = tabsData.target.find('.excerpt').css({position: 'absolute', left: '-999em'});

            $this.hover(function (e) {
                var offsetX;

                // Generate tooltip markup and fill with content
                tooltip = $('<div class="tooltip-content" />').html(content.html())
                    .css('visibility', 'hidden').appendTo('body');
                offsetX = - (tooltip.width() + 10);
                // Position on mouse coordinates
                tooltip.css({position: 'absolute', left: e.pageX + offsetX,
                             top: e.pageY + 10, visibility: 'visible'});
            }, function () {
                tooltip.remove();
            });
        });
    });

});
