/**
 * @author alexander.farkas
 */

jQuery.noConflict();
(function($){

  function callOnDomReady() {

  // Initialize NetInsight Plugin for Event Link Tracking
  $('body').netinsight();

    $('html').addClass('js-on'); // html class
    $('body').removeClass('js-off');
    //Zebra-Tables
    $('div.text tbody tr:nth-child(odd)').addClass('odd');

  // Add helper text in search box
  prepareSearchBox();

    addPrintLink();

  // Open external links in new window
  $("a[rel='external']").attr("target","_blank");


    //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: true,
        autoBuffering: true
      }
      }
    );
    */

    $("div.audio a").each(function() {
      $(this).flowplayer({src: contextPath + "/docroot/swf/flowplayer.commercial-3.2.6.swf", wmode: "opaque"}, {
                plugins: {
                    controls: {
                        autoHide:"never",
                        fullscreen: false,
                        height: 24,
                        tooltips: null
                    },
          audio: {
            url: contextPath + '/docroot/swf/flowplayer.audio-3.2.2.swf'
          },
                    captions: {
                        button:"false"
                    }
                },
                clip: {
                    autoPlay: false
                }
      });
    });

     $('div.video a').each(function() {
    // Commercial version: /.resources/ce-templating-kit/swf/flowplayer.commercial-3.2.6.swf"
    // Original free version was /.resources/templating-kit/swf/flowplayer.swf
    $(this).flowplayer({src: contextPath + "/docroot/swf/flowplayer.commercial-3.2.6.swf", wmode: "opaque"}, {
      key: '#@ffdd7f07110d98bf771',
      version: [10, 0],
      expressInstall: "/dms/ce/flash/expressInstall.swf",
      cachebusting: true,
      onBeforeClick: function() {
        // if you need to something before click, put code here.
      },
      onLoad: function()  {
        // if you need to do something on load, put code here
      },
      onUnload: function() {
        // if you need to do something on unload, put code here
      },
      clip: {
        //captionUrl: $(this).attr('href').replace('/videos','/xml').replace('.mp4','.xml'),
        scaling: 'fit',
        //provider: 'pseudostreaming',

        //forceStop: false, // Eliminate the last second being cut off
        //duration: 30, // Force a length to avoid cutting off last second

        onLastSecond: function() {

        },

        // on movie pause
        onPause: function() {

        },

        // on movie resume
        onResume: function() {

        },

        // if screen is hidden, show it upon startup
        onStart: function(clip) {
           this.getScreen().css({opacity: 1});
          // Unica video tracking here
           var videoTitle = $(this.getParent()).attr("title").toLowerCase().replace(/[^a-zA-Z0-9\s]/g, ''); // Get the title and remove all non-alphanumeric characters
             ntptEventTag('ev=video&videoAction=start'

               + '&videoTitle=' + videoTitle

               + '&video=' + $(this)[0].getClip().url);
        },

        // when movie is done, unload movie
        onFinish: function() {
          this.getScreen().animate({opacity: 0.5}, 3000);
          this.unload();
          if(this.isFullscreen() && jQuery.browser.msie){
            document.body.focus();
          }
          // Unica video tracking here
          var videoTitle = $(this.getParent()).attr("title").toLowerCase().replace(/[^a-zA-Z0-9\s]/g, ''); // Get the title and remove all non-alphanumeric characters
          ntptEventTag('ev=video&videoAction=finish'

                 + '&videoTitle=' + videoTitle

                 + '&video=' + $(this)[0].getClip().url);
        },

        // when movie is stopped, unload movie
        onStop: function() {
          if(this.isFullscreen() && jQuery.browser.safari){
            this.toggleFullscreen();
            document.body.focus();
            unload = this.unload;
            setTimeout(function(){eval("unload()")},50);
          }else{
            this.unload();
            document.body.focus();
          }
        }
      }
    }).hover(
      function() {
        // find span.info element inside the player container and show it
        // $("span.info", this).fadeTo("slow", 0.7);
        if ($.support.opacity) {
          $("span.play-video", this).fadeTo("slow", 1);
        }
      },
      function() {
        // when mouse is removed - hide the info
        // $("span.info", this).fadeTo("slow", 0);
        if ($.support.opacity) {
          $("span.play-video", this).fadeTo("slow", 0.8);
        }
      }
    );

    // initially all info elements are hidden
    // $("span.info", this).css("opacity", 0);
    if ($.support.opacity) {
      $("span.play-video", this).css("opacity", 0.8);
    }
  });

    //different tabs
    createTabs();
    faqToc();


//Teaser-Switchers

  // Create the pager
    $('div.teaser-wrapper:not(.tw-paging,.tw-slider)')
      .each(function(){
        $('div.pager', this)
          .append('<div class="prev"><a id="prev" href="#">Previous</a></div><div class="next"><a id="next" href="#">Next</a></div>');
      });

  if(!$('body').hasClass('editMode')){ // Check to be sure we're not in edit mode
    // Call JQuery cycle plugin and set options
    $(".rack-design").cycle({
      fx:	'fade',
      speed:	1000,
      timeout:	8000,
      next:	'#next',
      prev:	'#prev'
    });
  }else{
    // In edit mode. Make sure homepage content is pushed down enough to clear the stage
    //var stageOffset = $('body#home #stage').height();
    //$('$body#home #branding').css('padding-top',stageOffset);
  }
  $(window).resize(setStageWidth); // Resize rotator when window changes size

    pagingTeaserSwitcher();
    slidingTeaserSwitcher();

    createShowBox();

    slidingTabs();

    addLandmarks();

    $.socialbookmark.init('li.social-b a');

  }

  // Change nav color on load
/*  function changeNavColor(){
    var urlPath = location.pathname;
    if(urlPath.search(/\/work(\.|\/)/) != -1){
      $('body').addClass('work');
    }else if(urlPath.search(/\/agency(\.|\/)/) != -1){
      $('body').addClass('agency');
    }else if(urlPath.search(/\/blog(\.|\/)/) != -1){
      $('body').addClass('blog');
    }
  }
*/
  // Add helper text in search box
  function prepareSearchBox(){
    var searchbox = $('#search-box input');
    searchbox.attr('value','Search c-e.com');
    searchbox.focus(function(){
      if(searchbox.attr('value') == 'Search c-e.com'){
        searchbox.attr('value', '');
      }
    })
    searchbox.blur(function(){
      if(searchbox.attr('value') == ''){
        searchbox.attr('value', 'Search c-e.com');
      }
    })

  }


  function createShowBox(){
  var showbox = $('.showbox');
    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;
              }
            }
          });
      });


  }

  // Set paging stage elements to full window width
  function setStageWidth(){
    var windowWidth = $(window).width() + 'px';
    $('.rack .stage-bg-container').css({'width':windowWidth});
    $(".rack-design").cycle({width:windowWidth}); //Reset cycle animation to use new width
  }


  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.prototype.options, {
        //Elements Classes
        atoms: 'div.rack-teaser',
        prevLink: 'div.prev span',
    nextLink: 'div.next span',
    //Options
    //direction: 'vertical',
      enableMwheel: false
  });


  $(callOnDomReady);
})(jQuery);

