/**
 * @author alexander.farkas
 */

jQuery.noConflict();
(function($){

        function callOnDomReady() {
                
                
                $('html').addClass('js-on'); // html class
                $('body').removeClass('js-off');
                //Zebra-Tables
                $('div.text tbody tr:nth-child(odd)').addClass('odd');

                addPrintLink();

                //wait for the swfobject DOM-Ready, so we can return a proper reference to flash object
                swfobject.addDomLoadEvent(function(){
                        $('div.flash').embedSWF();
                });
                
                $('#nav-global.megamenu').simpleMenu({
                        generateSkip: true,
                        skipStructure: '<a class="menu-skip" href="#" title="UntermenÃŒ {from} ÃŒberspringen">direkt zu MenÃŒ {to} springen</a>',
                        skipEndStructure: '<a class="menu-skip" href="#" title="ans Ende vom Menu springen">UntermenÃŒ {from} ÃŒberspringen</a>',
                        init: function(e, ui){
                                
                        },
                        //showHiddenOnFocus: true,
                        show: function(e, ui){
                                var menuBox = $('> div.menu-box', ui.menu)
                                        .css({
                                                top: ui.menu.outerHeight({margin: true}) * -1
                                        });
                                
                                ui.menu.addClass('menu-open');
                                menuBox.stop(true, true)
                                        .animate({
                                                top: 0
                                        });
                        },
                        hide: function(e, ui){
                                var menuBox = $('> div.menu-box', ui.menu);
                                menuBox.animate(
                                        {
                                                top: ui.menu.outerHeight({margin: true}) * -1
                                        },
                                        {complete: function(){
                                                ui.menu.removeClass('menu-open');
                                                menuBox.css({top: 0});
                                        }}
                                );
                                
                        }
                });
                
                //initialize flowplayer
                window.contextPath = window.contextPath ||
                        '';
                
                $("div.video a").flowplayer(
                        contextPath + "/.resources/templating-kit/swf/flowplayer.swf", {
                                // splash image
                                clip:{
                                        autoPlay: false,
                                        autoBuffering: true
                                }
                        }
                );

                //different tabs
                createTabs();
                faqToc();

                //Teaser-Switchers
                
                $('div.teaser-wrapper:not(.tw-paging,.tw-slider)')
                        .each(function(){
                                $('div.pager', this)
                                        .append('<div class="prev"><span /></div><div class="next"><span /></div>');
                                $(this).scroller();
                        });

                pagingTeaserSwitcher();
                slidingTeaserSwitcher();

                createShowBox();
                
                slidingTabs();
                
                addLandmarks();

                $.socialbookmark.init('li.social-b a');

                createYoutubeList();
                
                showEmployees();
                
                $('div.flickr-box').flickrFeed({
                        flickrWrapper: 'div.flickr-photos',
                        maxItemCount: 6,
                        wrapperTmpl: '<ul><%=items%></ul>',
                        template: '<li><a href="<%=imglink%>"><img src="<%=imgsrc%>" alt="<%=imgtitle%>" title="<%=imgtitle%>" /></a></li>'
                });
                
        }
        
        function createYoutubeList(){
                var ytDataCFG = {
                                        complete: function(data, status){
                                                if(status == 'success'){
                                                        startYTPlayer(data.DOMFeed.parent());
                                                }
                                        },
                                        youTubeParams: {
                                                'max-results': 3 //youtube feed generator: http://gdata.youtube.com/demo/index.html
                                        },
                                        itemTmpl: 
                                                '<li>' +
                                                        '<a class="youtube-video" href="<%=link%>">' +
                                                                '<img src="<%=thumbnail.url%>" alt="" />' +
                                                        '</a>' +
                                                        '<h3><a class="youtube-video" href="<%=link%>"><%=title%></a></h3>' +
                                                        '<p><%=description%></p>' +
                                                '</li>'
                                },
                        carouselExtension = {
                                feedWrapperTmpl: '<div class="teaser-wrapper tw-switcher"><div class="pager"></div><div class="rack"><div class="rack-design"><%=items%></div></div></div>',
                                youTubeParams: {
                                                'max-results': 20 //youtube feed generator: http://gdata.youtube.com/demo/index.html
                                        },
                                itemTmpl: 
                                        '<div class="rack-teaser">' +
                                                '<a class="youtube-video" href="<%=link%>">' +
                                                        '<img src="<%=thumbnail.url%>" alt="" />' +
                                                '</a>' +
                                                '<h2><a class="youtube-video" href="<%=link%>"><%=title%></a></h2>' +
                                                '<p><%=description%></p>' +
                                        '</div>'
                        };
                function startYTPlayer(jElm){
                        swfobject.addDomLoadEvent(function(){
                                $('div.youtube-player-wrapper', jElm).html('<div class="youtube-player"></div>');
                                jElm
                                        .youtubeList({
                                                player: 'div.youtube-player'
                                        });
                                if(jElm.is('.carousel')){
                                        $('div.pager', jElm).html('<div class="prev"><span/></div><div class="next"><span class="show"/></div>');
                                        $('div.teaser-wrapper', jElm).scroller();
                                }
                        });
                }
                
                $('div.youtube-widget:not(.youtube-feed, .carousel)').each(function(){
                        startYTPlayer($(this));
                });
                
                $('a.youtube-feed')
                        .each(function(){
                                var jElm = $(this);
                                jElm.youtubeData( (jElm.parent().is('.carousel')) ? $.extend({}, ytDataCFG, carouselExtension) : ytDataCFG);
                        });
                        
                                
        }
        
        function createShowBox(){
                var showboxCFG = {
                                setInitialContent: {
                                        'showbox-title': $('h1').html(), 
                                        prev: 'previous',
                                        next: 'next',
                                        'close-button': 'close',
                                        'play-pause': 'play'
                                },
                                
                                getTextContent: function(opener, content, ui){
                                        // Um Text aus einer dl-Structure zu holen (Magnolia-Style)
                                        
                                        var dl                          = opener.closest('dl'), //hole das nÃ€chst hÃ¶here dl
                                                dds                             = $('dd', dl), // hole die dd
                                                img                     = $('img', dl), // hole das img 
                                                extraContent    = ''
                                        ;
                                        
                                        //content objekt dient zur befÃŒllung der lightbox mit weiterem content
                                        //die eigenschaftsnamen stimmen mit den Klassen-Namen ÃŒberein
                                        
                                        //content['multimedia-box'] ist bereits mit dem grossen Bild vorbelegt
                                        //und wird nun mit dem alt Attribut des kleinen Bildes versehen
                                        content['multimedia-box'].attr('alt', img.attr('alt'));
                                        
                                        content['text-content'] = ''; // String in dem wir unser gesamt content zusammefÃŒgen
                                        
                                        dds.each(function(){
                                                var dd          = $(this),
                                                        html    = dd.html()
                                                ;
                                                if(dd.is('.caption')){
                                                        content['text-content'] += '<h2 class="caption">'+ html +'</h2>';
                                                } else if(dd.is('.longdesc')){
                                                        content['text-content'] += '<p class="longdesc">'+ html +'</p>';
                                                } else if(!dd.is('.zoom')) {
                                                        extraContent += '<li class="'+ this.className +'">'+ html +'</li>';
                                                }
                                        });
                                        
                                        if(extraContent){
                                                content['text-content'] += '<ul class="sb-extra">'+ extraContent +'</ul>';
                                        }
                                        
                                },
                                showContentAnim: function(ui, img, e, extras){
                                        var contentBox = $('div.content-box', ui.element);
                                        contentBox
                                                .queue(function(){
                                                        var duration    = 300,
                                                                width           = img[0].width, 
                                                                height
                                                        ;
                                                        
                                                        ui.element.css({height: ui.element.height()});
                                                        ui.fillContent();
                                                        width = ui.calcWidth(img, width);
                                                        
                                                        contentBox
                                                                .css(
                                                                        {width: width}
                                                                )
                                                                .animate(
                                                                        {opacity: 1}, 
                                                                        {duration: duration}
                                                                );
                                                                
                                                        ui.element
                                                                .animate({
                                                                        height: contentBox.outerHeight({margin: true}) + $('div.showbox-head', ui.element).outerHeight({margin: true})
                                                                }, {
                                                                                duration: duration,
                                                                                complete: function(){
                                                                                        ui.element.css({height: ''});
                                                                                }
                                                                        });
                                                        
                                                        contentBox.dequeue();
                                                });
                                }
                        };
                        
                $('div.tw-images').each(function(){
                        
                        $('a[rel=showbox]', this)
                                .addClass('showboxed')
                                .showbox($.extend({}, showboxCFG, {
                                        setInitialContent: {
                                                'showbox-title': $(':header', this).html(), 
                                                prev: 'previous',
                                                next: 'next',
                                                'close-button': 'close',
                                                'play-pause': 'play'
                                        }
                                }));
                });
                $('a[rel=showbox]:not(.showboxed)').showbox(showboxCFG);
        }
        function addLandmarks(){
                var landmarks = {
                        navigation: '#nav-global, #nav, #breadcrumb',
                        search: '#search-box',
                        article: 'div.text, div.teaser, div.opener, #comments li',
                        complementary: '#extras',
                        banner: '#branding',
                        main: '#main',
                        contentinfo: 'div.text-data, #site-info'
                };
                
                $.each(landmarks, function(landmark, sel){
                        $(sel).attr({role: landmark});
                });
        }

        function slidingTabs(){
                $.fn.mySlide = function(fn){
                        fn = fn || function(){};
                        return this.animate({
                                height: 'toggle',
                                opacity: 'toggle'
                        }, {
                                duration: 500,
                                complete: fn,
                                deque: true
                        });
                };
                
                $('ol.superpromos-toc')
                        .each(function(){
                                $(this)
                                        .bind('tabtreecollapse', function(e, ui){
                                                ui.panel
                                                        .stop(true, true)
                                                        .animate({
                                                                height: 'hide',
                                                                opacity: 0
                                                        }, {duration: 500});
                                        })
                                        .bind('tabtreeexpand', function(e, ui){
                                                ui.panel
                                                        .stop(true, true)
                                                        .animate({
                                                                height: 'show',
                                                                opacity: 1
                                                        }, {duration: 500});
                                        })
                                        .tabtree(
                                                {activeButtonClass: 'on', 
                                                selectEvents: 'mouseenter focus',
                                                handleDisplay: 'initial'
                                        })
                                        .find('a')
                                        .bind('click', function(e){
                                                
                                                if(e.pageX !== 0 && e.pageY !== 0){
                                                        var url = $($(this).attr('href'))
                                                                .find('a:first')
                                                                .attr('href');
                                                        if(url){
                                                                location = url;
                                                        }
                                                }
                                        });
                        });


        }

        function pagingTeaserSwitcher(){
                function myPag(status){
                                if(status == 'inactive'){
                                        $('a',this).animate({opacity: 0.5},{duration: 500});
                                } else {
                                        $('a',this).animate({opacity: 1},{duration: 500});
                                }
                        }
                        function myLink(status){
                                if(status == 'show'){
                                        this.animate({opacity: 1},{duration: 500});
                                } else {
                                        this.animate({opacity: 0},{duration: 500});
                                }
                        }
                        $('div.teaser-wrapper.tw-paging').scroller({
                                pagination: 'div.pagination',
                                paginationFn: myPag,
                                linkFn: myLink,
                                paginationTitleFrom: 'h2',
                                paginationAtoms: '<li class="pa-$number" title="$title"><a href="#">$number</a></li>'
                        });
        }

        function slidingTeaserSwitcher(){
                
                $('div.teaser-wrapper.tw-slider')
                        .each(function(){
                                var jElm = $(this),
                                        slider = $('div.slider', this)
                                                .css({display: 'block'})
                                                .wrap('<div class="slider-bar" />');
                                
                                $('div.slider-bar', this)
                                        .append('<span class="prev" /> <span class="next" />');
                                
                                function slideSliderCall(e, o, ui){
                                        ui = ui ||
                                                o;
                                        var val = (ui && isFinite(ui.value))? ui.value : (o) ? o.value : false;
                                        jElm
                                                .scroller('moveTo', val + '%', false);
                                }
                                
                                slider
                                        .slider({maxValue: 100})
                                        .bind('slide', slideSliderCall);
                                jElm
                                        .scroller({
                                        prevLink: 'div.slider-bar span.prev',
                                                nextLink: 'div.slider-bar span.next'
                                        })
                                        .bind('uiscrollerslide', function(e, d){
                                                slider
                                                        .slider('value', d.percentPos);
                                        });
                                
                        });
        }


        function addPrintLink(){

                function print(){
                        window.print();
                        return false;
                }

                $('<li class="print"><a href="#">Print</a></li>')
                        .prependTo('ul#text-features')
                        .find('a')
                        .click(print);
        }

        function faqToc() {
                var hash                = location.hash,
                        tabWidgets      = $('div.super-list'),
                        tabs            = $('h3 a', tabWidgets)
                ;

                if(hash){
                        tabs
                                .filter('[href='+hash+']')
                                .addClass('on');
                }

                tabWidgets
                        .bind('tabtreecollapse', function(e, ui){
                                ui.panel.stop(true, true).slideParentUp();
                        })
                        .bind('tabtreeexpand', function(e, ui){
                                ui.panel.stop(true, true).slideParentDown();
                        })
                        .tabtree({
                                        buttonSel: 'h3 a',
                                        activeButtonClass: 'on',
                                        toggleButton: true,
                                        multiSelectable: true, 
                                        handleDisplay: 'initial'
                                });
                        
        }

        $.fn.tabChangeAddon = function(){
                this
                        .bind('tabtreecollapse', function(e, ui){
                                ui.button.parent().removeClass('on');
                        })
                        .bind('tabtreeexpand', function(e, ui){
                                ui.button.parent().addClass('on');
                        });
                
                $('a.on', this)
                        .parent()
                        .addClass('on');
                return this;
        };

        function createTabs(){

                $('ol.text-box-toc, ol.toc-box-toc')
                        .each(function(){
                                $(this)
                                        .tabtree(
                                                {activeButtonClass: 'on'}
                                        )
                                        .tabChangeAddon();
                        });
        }


        $('html').addClass('js-on'); // html class
        
        $.extend($.ui.scroller.defaults, {
        //Elements Classes
        atoms: 'div.rack-teaser',
        prevLink: 'div.prev span',
                nextLink: 'div.next span'
        });

        function showEmployees() {
          $('a').click(function(){
              var help = '#detail' + this.id;
              var img = new Image();
              var src = $(this).attr('title');
             $('#detail'+ this.id).toggle(function() {
                if($('img', $(help)).length == 0)
                {
                         $(img).load(function(){
                                $(help).children('.text-right').children('.image').append(this);
                         })
                          .attr('src',src)
                }
             });
         });
        }
  function getTop() {
    // get the top of the content
    var top = $('#scroll-content').css('top');
    return trimPx(top);
  }
  
  function getBottom() {
          // get the bottom of the content
          return hidden + getTop();
  }

  function getHeight(id) {
          // get the height, including padding
          var height = $(id).height();
          var paddingTop = trimPx($(id).css("padding-top"));
          var paddingBottom = trimPx($(id).css("padding-bottom"));

          return height + paddingTop + paddingBottom;
  }

  function trimPx(value) {
          // remove "px" from values
          var pos = value.indexOf("px");
          if (pos != 0)
                  return parseInt(value.substring(0, pos));
          else
                  return 0;
  }

  var container;
  var content;
  var hidden;     // # of pixels hidden by the container

  function setScrollerDimensions() {
          container = getHeight("#stage-box");
          content = getHeight("#scroll-content");
          hidden = content - container;
  }

  function resetScroller() {
          setScrollerDimensions();
          $('#scroll-content').css('top', 0);
  }

  $(document).ready(function() {
 
       if ($('#stage-box').length !=0 && $('#scroll-content').length !=0 ) {
        
          setScrollerDimensions();
          
          if (getTop() != 0) {
                  $('a.up-arrow').fadeIn("slow");
          }
          if (getBottom() > 0) {
                  $('a.down-arrow').fadeIn("slow");
          }

          $('#scroll-controls a.down-arrow').mousedown(
                  function() {
                          if (hidden > 0) {
                                  var current = getTop();
                                  $('#scroll-content').animate({ top: -hidden });
                          }
                  }
          ).mouseup(function() {
                  $('#scroll-content').stop();
                  if (getTop() != 0) {
                          $('a.up-arrow').fadeIn("slow");
                  }
                  if (getBottom() == 0) {
                          $('a.down-arrow').fadeOut("slow");
                  }
          });
          
          $('#scroll-controls a.up-arrow').mousedown(
                  function() {
                          if (hidden > 0) {
                                  var current = getTop();
                                  $('#scroll-content').animate({ top: "0" });
                          }
                  }
          ).mouseup(function() {
                  $('#scroll-content').stop();
                  if (getTop() == 0) {
                          $('a.up-arrow').fadeOut("slow");
                  }
                  if (getBottom() > 0) {
                          $('a.down-arrow').fadeIn("slow");
                  }
          });
      }
  });
  
        $(callOnDomReady);
})(jQuery);
