/* Author: katrink

 */
window.viewport = {
  height : function() {
    return $(window).height();
  },
  width : function() {
    return $(window).width();
  },
  scrollTop : function() {
    return $(window).scrollTop();
  },
  scrollLeft : function() {
    return $(window).scrollLeft();
  }
};
/**
 * @author katrink
 */
var merci;

if(!merci) {
  merci = {};
}

if( typeof jQuery != 'undefined') {
  jQuery.extend(merci, {

    // Global Variables
    resizeTimer : null,
    startedResize : false,

    init : function() {
      
      if((navigator.appVersion.indexOf("Mac") != -1)) {
        if($.browser.webkit){
          $("html").addClass("webkitMac");
        }
        if($.browser.mozilla){
          $("html").addClass("mozillaMac");
        }
      }
      
      merci.checkSoundCookie();
      merci.positionMainMenu();

      var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());

      /* Resizing Events */
      $(window).bind('resize', function(event) {
        if(merci.startedResize == false) {
          // Trigger Resize started
          merci.startedResize = true;
          $(window).trigger('resizeStart');
        }
        if(merci.resizeTimer) {
          clearTimeout(merci.resizeTimer);
        };
        merci.resizeTimer = setTimeout("merci.doSomething(" + event.timeStamp + ")", 500);
      });

      $(window).bind('resizeStart', function(event) {
        // Is something to do?
      });

      $(window).bind('resizeEnd', function(event) {
        merci.positionMainMenu();
        var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
        if($.fancybox) {
          $('#fancybox-overlay').css('left', $('.main').position().left);
        }
        $("#song .tabContent").tinyscrollbar();
      });
      
      // Some modules show the main menu etc. with delay -> Register Delay Event
      if($('body').hasClass('show') || $('body').hasClass('preview')) {
        $('.delayedShow').live('delayedshow', function() {
          $(this).fadeIn('slow');
          $('footer div#bottom p span').fadeIn('slow');
          $('header nav').slideDown('slow');
        });
      }
      
      /* Init module/page specific JS */
      if($('body').is('#Start')) {// && typeof modules != 'undefined'
        // Perlenkette laden
        log('perlenkette');
        merci.initIntro();
        merci.initPearlChain(newSize);
      } else if($('body').is('#SendStar') && $('#stars').length > 0) {// Are stars layers available?
        // Sternenhimmel laden
        log('Sternenhimmel');
        merci.initStars(newSize);
      } else if($('body').is('#Poems')) {
        log('Gedicht');
        merci.initPoems();
        if($('body').hasClass('show')){
          merci.playSound();
        }
      } else if($('body').is('#GiftCards')) {
        log('Kärtchen');
        merci.initGiftCards();
      } else if($('body').is('#FavoriteMovies')) {
        log('Lieblingsfilm');
        merci.initFavoriteMovies();
      } else if($('body').is('#Media') && $('body').hasClass('show')) {
        log("TV-Spot");
        merci.initTvspot();
      }else if($('body').is('#Media') && $('body').hasClass('ringtone')) {
        log("Ringtone");
        merci.initRingtone();
      }else if ($('body').is('#Products') && $('.main').is('#xmas')){
        merci.initXmas();
      } else if($('body').is('#Contacts')) {
        
        merci.initContact();
      } else if($('body').is('#Shop')) {
        
        // Description texts on payment selection page
        $('#payment input[type=radio]').change(function() {
          $('#payment div.checkbox').next('p').addClass('visuallyhidden')
          $(this).parents('div.checkbox').next('p').removeClass('visuallyhidden');
        });
        
        // Show "Edit receiver adress"-form in layer
        $("a.iframe").fancybox({
          autoScale : false,
          padding : 0,
          width : 280,
          height : 360,
          scrolling : "no",
          onStart : function() {
            $('#fancybox-wrap').removeClass('image');
            $('#fancybox-overlay').css('left', $('.main').position().left);
          }
        });
        
        // "Double check"-layer on delete button
        $('a.delete').click(function(event) {
          log(event);
          var that = this;
          $(that).next('.doubleCheckLayer').show();
          $('body').click(function() {
            $('.doubleCheckLayer').hide();
            $('body').unbind('click');
          });
          $(that).find('.cancel').click(function() {
            $('body').trigger('click');
            return false;
          });
          return false;
        });
      }else if($('body').is('#Valentine2012')){
        // Init max length for textarea
        $("textarea#valentine2012_message").maxTextarea({
          maxlength : 200, // Maximale Zeichenanzahl f�r "textarea"
          counter : 'span#count_chars', // Selektor f�r Element, das die Anzahl der verbleibenden Zeichen anzeigt
          callback : function(obj) { // Callback-Funktion wird aufgerufen, wenn "maxlength" erreicht wurde. obj = $("textarea")
          }
        });
        
        $('#valentineBox a.squareButton').click(function(){
          $('.lightGradientBox').toggle();
          $('h4.pager span').toggleClass('selected');
          return false;
        });
        
        $('#valentineBox li.captcha span').click(function(){
          $('#valentineBox .captcha input:checked').removeAttr('checked');
          $(this).children('input').attr("checked", "checked");
          $('form').submit();
        });
        
        if($.browser.msie && $('.col').find('div.column').length == 0) {
        $('.col').columnize({
          columns : 3,
          lastNeverTallest : true
        });
      }
      
      }

      // Full teaser clickable
      $('.teasers li>div').live('click',function() {
        if($(this).find('a').length > 0){
          window.location = $(this).find('a').attr('href');
        }
        return false;
      });
      
      // Shop "Geschenkkorb",...
      $('.scrollContent').tinyscrollbar();
      
      /* Browser Gniech */
      if($.browser.msie && $('body').is('#Meta') && $('.col').find('div.column').length == 0) {
        $('.col').columnize({
          columns : 3,
          lastNeverTallest : true
        });
      }
      
      $(window).bind('resizeEnd', function(event) {
        // Show Scrollbar
        if($('.scrollContent').has("div.scrollbar").length) {
          $('.scrollContent').tinyscrollbar_update();
        }
      });
      
      // Tab navigation in "Media/Song" & "Product/GDA"
      if($('ul.tabs').length > 0) {
        //Hide all content
        $(".tabContent").hide();

        // Show first tab content (only in Mediathek - Song)
        $("#song ul.tabs li:first").addClass("active").show();
        //Activate first tab
        $("#song .tabContent:first").show(1, function() {

          $("#song .tabContent:first").tinyscrollbar();

        });
        //On Click Event
        $("ul.tabs li").click(function() {

          $("ul.tabs li").removeClass("active");
          //Remove any "active" class
          $(this).addClass("active");
          //Add "active" class to selected tab
          $(".tabContent").hide();
          //Hide all tab content

          //Fade in the active ID content
          var activeTab = $(this).find("a").attr("href");
          //Find the href attribute value to identify the active tab + content
          $(activeTab).fadeIn(400, function() {

            // Show Scrollbar
            if($(activeTab).has("div.scrollbar").length) {
              $(activeTab).tinyscrollbar();
            }

          });
          return false;
        });
        if(location.hash) {
          $("ul.tabs li").find("a[href$=" + location.hash + "]").trigger('click');
        }
      }
      
      /* Download dropdown (Media/Backgrounds, Media/Ringtone)*/
      $('.download p').click(function(e) {
        $(this).next('ul').addClass('openSelect');
        e.preventDefault();
      });
      $('.download ul.openSelect').live('mouseleave', function(e) {
        $(this).removeClass('openSelect');
        e.preventDefault();
      });
      
      // Check placeholder support in input + fallback
      if(!$.support.placeholder) {
        $('input[placeholder]').each(function() {
          $(this).val($(this).attr('placeholder')).data('placeholder', $(this).attr('placeholder')).removeAttr('placeholder').bind({
            'focus' : function() {
              if($(this).val() == $(this).data('placeholder')) {
                $(this).val('');
              }
            },
            'blur' : function() {
              if($(this).val() == "") {
                $(this).val($(this).data('placeholder'));
              }
            }
          });
        });
      }

      // Product Preview in Shop Process
      $("a.overlay").fancybox({
        autoScale : false,
        padding : 0,
        type : "image",
        onStart : function() {
          $('#fancybox-wrap').addClass('image');
          $('#fancybox-overlay').css('left', $('.main').position().left);
        }
      });

      // Help Layer
      $("a.layer, #btnSendProduct").fancybox({
        autoDimensions : false,
        padding : 0,
        width : 716,
        height : 392,
        scrolling: 'no',
        onStart : function() {
          $('#fancybox-wrap').addClass('layer');
          $('#fancybox-overlay').css('left', $('.main').position().left);
        },
        onComplete : function() {
          
          if($.browser.msie && $('body').is('#Shop') && $('.col').find('div.column').length == 0) {
            $('.col').columnize({
              columns : 3,
              lastNeverTallest : true
            });
          };
          
          $('.scrollContent').tinyscrollbar();
          if($('body').is('#CreatePackage') && $('body').hasClass('new')) {
            $('#helpSend .cancel').click(function() {
              $.fancybox.close();
            });
            
            $('a#btnSubmit2Shop').prependTo('#helpSend .buttonHolder').show();

          }
        },
        onCleanup: function(){
          if($('body').is('#CreatePackage') && $('body').hasClass('new')) {
            $('a#btnSubmit2Shop').prependTo('#editor .buttonHolder').hide();
          }
        }
      });

      // Terms Layer in Forms
      $("a.terms").fancybox({
        autoScale : false,
        autoDimensions : false,
        padding : 0,
        width : 716,
        height : 392,
        scrolling : "no",
        type : 'ajax',
        onStart : function() {
          $('#fancybox-wrap').addClass('layer');
          $('#fancybox-overlay').css('left', $('.main').position().left);
        },
        onComplete : function() {
          $('#termsOfUse > div').wrap('<div class="viewport"><div class="overview"></div></div>');
          $('#termsOfUse').prepend('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
          ;
          $('#termsOfUse').addClass('scrollContent').tinyscrollbar();
          
          if($.browser.msie && $('.col').find('div.column').length == 0) {
            $('.col').columnize({
              columns : 3,
              lastNeverTallest : true
            });
          };
          
        }
      });

      merci.initDropdown();

      merci.addTrackByDataAttrsListener();
    },
    
    // Helper for settimeout method
    doSomething : function(timestamp) {
      // Trigger Resize finished
      merci.startedResize = false;
      $(window).trigger('resizeEnd');
      log('resizeEnd');
    },
    
    /* Set body#id according to viewport size */
    setBodyIdByViewportSize : function(width, height) {

      // Remove all classes
      $('body').removeClass('size1024 size1280 size1280x800 size1680');
      // Mac window is wider
      if(navigator.appVersion.indexOf("Mac") != -1){
        minWidth = 1009;
      }else{
        minWidth = 989;
      }
      // Wenn width <= 1024 dann 1024-Bilder nehmen
      if(width <= minWidth) {
        $('body').addClass('size1024');
        return '1024';
      } else if(width > minWidth && width <= 1280) {

        if(height >= 800) {
          // Wenn width > 1024 und width <= 1280 dann 1280-Bilder nehmen
          $('body').addClass('size1280');
        } else {
          $('body').addClass('size1280x800');
          return '1280x800';
        }
        return '1280';
      } else {
        // Wenn width > 1280 dann 1680-Bilder nehmen
        $('body').addClass('size1680');
        return '1680';
      }

    },
    
    positionMainMenu: function(){
      $('header nav > ul').css('margin-left', $('header li.say_merci div').innerWidth() + 'px')
      
    },
    
    checkSoundCookie : function() {
      log("Sound " + $.cookie('merci.sound'));
      if($.cookie('merci.sound') == 'off') {
        $.cookie('merci.sound', 'off', {
          expires : 7,
          path : '/'
        });
        $('#sound').addClass('off').removeClass('on');
      } else {
        $.cookie('merci.sound', 'on', {
          expires : 7,
          path : '/'
        });
        $('#sound').addClass('on').removeClass('off');
      }

      $('#sound').click(function() {
        if($.cookie('merci.sound') != 'on') {
          $.cookie('merci.sound', 'on', {
            expires : 7,
            path : '/'
          });
          $('#sound').addClass('on').removeClass('off');
          if(jwplayer() != undefined) {
            jwplayer().setMute(false);
          }

        } else {
          $.cookie('merci.sound', 'off', {
            expires : 7,
            path : '/'
          });
          $('#sound').addClass('off').removeClass('on');
          if(jwplayer() != undefined) {
            jwplayer().setMute(true);
          }
        }
        log("Sound " + $.cookie('merci.sound'));
        return false;
      });
    },
    setSoundState: function(state){
      if(state == false){ // Sound on
        $.cookie('merci.sound', 'on', {
            expires : 7,
            path : '/'
          });
      }else{ // Sound off
        $.cookie('merci.sound', 'off', {
            expires : 7,
            path : '/'
          });
      }
    },
    // Play background Sound
    playSound : function(){
      muteState = $.cookie('merci.sound') == 'off' ? true : false;
      jwplayer(options.movieName)
      .setup({
        id : "ringtone",
        flashplayer : options.flashplayer,
        width : '1',
        height : '1',
        file : options.file,
        screencolor : "ffffff",
        stretching : 'fill',
        skin: options.skin,
        controlbar: 'none',
        image: options.image,
        autoplay: true
      })
      .setMute(muteState);
    },
    initIntro : function() {
      log("Intro " + $.cookie('merci.intro'));
      if(!$.cookie('merci.intro') || showIntro=='true') {
        $.cookie('merci.intro', 'off', {
          path : '/'
        });
        $('#intro').show();
        var flashvars = {
          videoPath : ""
        };
        var params = {
          base : "swf/",
          wmode : "transparent"
        };
        swfobject.embedSWF(introPath, 'introSwf', '100%', '100%', '10', null, flashvars, params, {}, function() {
        });
      }
    },
    /**
     * Module "STARS"
     *
     **/
    /* Init */
    initStars : function(newSize) {

      // SEND NEW STAR
      if($('.main').is('#new') && $('body#SendStar').hasClass('new')) {
        starPositions = $('form input#star_stars[type=hidden]').val();

        if(starPositions == "") {

          if($.browser.msie) {
            merci.initParalax(newSize);
          } else {
            $('#layerStore img').load(function() {
              merci.initParalax(newSize);
            });
          }

          // Initially the form is hidden
          $('#starForm').hide();

          merci.bindStarEvents();

        } else {// User returns from preview

          // Show send form
          $('#starForm').show();

          // Move layers to their positions
          merci.resizeStars(newSize, starPositions);

          // Hide star handle because it's already dropped
          $('#handleStart').hide();
        }

        // Init max length for textarea
        $("textarea#star_message").maxTextarea({
          maxlength : 160, // Maximale Zeichenanzahl für "textarea"
          counter : 'span#count_chars', // Selektor für Element, das die Anzahl der verbleibenden Zeichen anzeigt
          callback : function(obj) { // Callback-Funktion wird aufgerufen, wenn "maxlength" erreicht wurde. obj = $("textarea")
          }
        });

        // Reset stars layers if window resized
        $(window).bind('resizeEnd', function(event) {

          var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
          //merci.initParalax(newSize);
        });
      }

      // ERROR IN FORM -> show form again, star is already set
      if($('body').hasClass('create') && $('.main').is('#new')) {
        // Re-position stars layers
        starPositions = $('form input#star_stars[type=hidden]').val();
        merci.resizeStars(newSize, starPositions);

        // Hide star handle because it's already dropped
        $('#handleStart').hide();

        $("#starHandle").trigger({
          type : 'freeze',
          decay : 0
        });

        // Show send form
        $('#starForm').show();

        // Init max length for textarea
        $("textarea#star_message").maxTextarea({
          maxlength : 160, // Maximale Zeichenanzahl f�r "textarea"
          counter : 'span#count_chars', // Selektor f�r Element, das die Anzahl der verbleibenden Zeichen anzeigt
          callback : function(obj) { // Callback-Funktion wird aufgerufen, wenn "maxlength" erreicht wurde. obj = $("textarea")
          }
        });
        
        // Reset stars layers if window resized
        $(window).bind('resizeEnd', {stars : starPositions}, function(event) {

          var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
          merci.resizeStars(newSize, event.data.stars);
        });
      }

      // PREVIEW
      if($('.main').is('#preview') && $('body#SendStar').hasClass('show')) {

        // Re-position stars layers
        starPositions = stars;
        merci.resizeStars(newSize, starPositions);

        // Reset stars layers if window resized
        $(window).bind('resizeEnd', {stars : starPositions}, function(event) {
          log('RESIZE');
          var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
          merci.resizeStars(newSize, event.data.stars);
        });

        merci.animateClaim();
        
        merci.playSound();
        
      }

      // SHOW
      if($('.main').is('#show') && $('body#SendStar').hasClass('show')) {

        // Re-position stars layers
        starPositions = stars;
        merci.resizeStars(newSize, starPositions);

        // Reset stars layers if window resized
        $(window).bind('resizeEnd', {stars : starPositions}, function(event) {

          var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
          merci.resizeStars(newSize, event.data.stars);
        });

        merci.animateClaim();
        
        merci.playSound();
        
      }

    },
    /* Claim Animation */

    animateClaim : function() {
      var flashvars = {
        videoPath : ""
      };
      var params = {
        base : "swf/",
        wmode : "transparent"
      };
      swfobject.embedSWF(starPath, 'animatedClaim', '989', '400', '10', null, flashvars, params, {}, function() {
      });

      $('#animatedClaim img').fadeIn(3750, 'easeInOutCirc', function() {

      });

      $("#deathStar").delay(3000).animate({
        height : 152,
        width : 152
      }, 1000, 'easeOutElastic');

      setTimeout(function() {

        $('.delayedShow').trigger('delayedshow');
      }, 5000);
    },
    /* Do parallax */
    initParalax : function() {

      $('#starHandle').parallax({
        mouseport : $("#stars"),
        takeoverThresh : 1
      }, {
        xparallax : 1,
        yparallax : 1,
        xorigin : 0,
        yorigin : 0,
        width : 131,
        height : 131
      }).trigger({
        type : 'freeze',
        decay : 0
      });

      // Declare parallax on layers
      $('.parallax-layer').parallax({
        mouseport : $("#stars")
      },{
        xparallax : 0.0,
        yparallax : 0.0,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.1,
        yparallax : 0.1,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.2,
        yparallax : 0.2,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.3,
        yparallax : 0.3,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.4,
        yparallax : 0.4,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.5,
        yparallax : 0.5,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.6,
        yparallax : 0.6,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.7,
        yparallax : 0.7,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.8,
        yparallax : 0.8,
        xorigin : 'center',
        yorigin : 'center'
      }, {
        xparallax : 0.9,
        yparallax : 0.9,
        xorigin : 'center',
        yorigin : 'center'
      }).trigger({
        type : 'freeze',
        decay : 0,
        x : 0.5,
        y : 0.5
      });

    },
    bindStarEvents : function() {
      // Mouse down on big star starts parallax animation
      $('#starHandle').one('mousedown', function(event) {
        // Unfreeze freezed layers
        $('.parallax-layer, #starHandle').trigger({
          type : 'unfreeze'
        });

        setTimeout(function() {
          merci.hideHandleStart();
        }, 1000);
        // Tell IE nothing happens on "mousemove"
        $(document).bind('mousemove', function() {
          return false;
        });
        // Freeze layers again on mouse up
        $(document).one('mouseup', function(event) {

          $('.parallax-layer').trigger({
            type : 'freeze'
          });
          $('#starHandle').trigger({
            type : 'freeze'
          });
          merci.calculateStarPositions();

          $('#starForm').show();

          // Re-Position layers if window has been resized after "mouseup"
          $(window).bind('resizeEnd', function(event) {
            var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
            merci.resizeStars(newSize);
          });
          return false;
        });
        return false;
      });
    },
    /* Hide handle after drag starts */
    hideHandleStart : function() {
      $('#handleStart').animate({
        height : 0,
        width : 0
      }, 'slow').hide();
    },
    /* Calculate layer positions for minimum resolution and save in hidden field */
    calculateStarPositions : function() {
      resTop = 355;
      resLeft = 858;
      maxTop = $('#stars').height() - $('#starHandle').height();
      maxLeft = $('#stars').width() - $('#starHandle').width();

      var starsPositions = [];

      $('#layerStore div').each(function(index, layer) {
        layerData = {};
        layerData['id']           = $(layer).attr('id');
        layerData['top']          = ($(layer).position().top / $('#layerStore').height()) * 100;
        layerData['left']         = ($(layer).position().left / $('#layerStore').width()) * 100;
        layerData['marginLeft']   = (parseInt($(layer).css('margin-left')) / $('#layerStore').width()) * 100;
        layerData['marginTop']    = (parseInt($(layer).css('margin-top')) / $('#layerStore').height()) * 100;
        starsPositions.push(layerData);
      });

      $('form input#star_stars[type=hidden]').val(JSON.stringify(starsPositions));

    },
    /* Re-arrange layers after window resize */
    resizeStars : function(newSize, starPositions) {

      if(starPositions != "") {
        log(starPositions);
        var json = JSON.parse(starPositions);

        $.each(json, function(index, layer) {

          $('#' + layer.id).css({
            'top' : layer.top  + '%',
            'left' : layer.left + '%',
            'marginTop' : ((layer.marginTop * $('#layerStore').height() ) / 100 ) + 'px', //(layer.marginTop/100) * $('#'+layer.id).height() *-1+'px',
            'marginLeft' : ((layer.marginLeft * $('#layerStore').width() ) / 100 ) + 'px' //(layer.marginLeft/100) * $('#'+layer.id).width() *-1+'px'
          });

        });
      }
    },
    /**
     * Module "POEMS"
     *
     **/
    /* Init poem animation */
    initPoems : function() {
      log('initPoems');
      // poem selection page
      if($('body#Poems').hasClass('new')) {

        merci.positionPoemCards();

        $('#poemsSelection ul li:last').addClass('open');

        merci.bindSortPoemsAni();
        
        $("p.salutation input").keyup(function() {
          contents = $(this).val();
          charlength = contents.length;
          if(charlength * 15 > 210) {
            newwidth = Math.min((charlength * 15), 500);
          } else if(charlength * 15 <= 210) {
            newwidth = 210;
          }

          $(this).css({
            width : newwidth
          });
        });
        return;
      }

      if($('body#Poems').hasClass('form')) {

        merci.setOpenPoemToFront();

        merci.bindSortPoemsAni();

        return;
      }

      if($('body#Poems').hasClass('show') && $('.main').is('#show')) {
        // Show delayed items
        setTimeout(function() {

          $('.delayedShow').trigger('delayedshow');
        }, 6000);
        return;
      }
    },
    positionPoemCards : function() {
      $('#poemsSelection li').each(function(index) {
        $(this).css({
          'top' : 25 * index + 'px'
        });

      });
    },
    bindSortPoemsAni : function() {

      $('#poemsSelection li h4').live('click', function() {

        // Karten tauschen
        $('#poemsSelection li .buttonHolder').hide();
        moveBackwards = $(this).parents('li').nextAll('li').reverse();
        moveForwards = $(this).parents('li').prevAll().andSelf();

        moveBackwards.css('z-index', '100').animate({
          marginTop : "-=400px",
          marginLeft : "+=30px"
        }, 600, function() {
          moveBackwards.each(function(index) {
            $(this).animate({
              marginTop : "0",
              marginLeft : "0",
              top : 25 * (moveBackwards.length - index - 1) + 'px'
            }, 600).removeClass('open').css('z-index', '0').prependTo($('#poemsSelection ul'));
          });
          $('#poemsSelection ul li:last').addClass('open').find('.buttonHolder').delay(500).fadeIn();
        });
        moveForwards.each(function(index) {
          $(this).animate({
            'top' : 25 * (index + moveBackwards.length)
          }, 600);
        });
        return false;
      });
    },
    setOpenPoemToFront : function() {

      $('li.open').prevAll().andSelf().appendTo($('#poemsSelection ul'));

      merci.positionPoemCards();
    },
    /**
     * Module "PEARL CHAIN" (Front page)
     *
     **/
    initPearlChain : function(stageWidth) {
      $(window).bind('resizeEnd', function(event) {
        var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
        merci.generatePearlHtml(newSize);
      });
      merci.generatePearlHtml(stageWidth);
    },
    generatePearlHtml : function(size) {
      $('div#stage').html();

      var html = '';
      var modules = $.parseJSON($('#modules').html());
      $.each(modules, function(index, item) {
        html += '<div class="module" data-index="' + index + '" data-hash="' + item.hash + '" data-fullscreen="false">' 
                + '<a href="#' + item.hash + '">' 
                  + '<img class="small" rel="" src="' + item.images[size][2] + '" alt="" />' 
                + '</a>' 
                + '<div class="zoom_item">' 
                  + '<a class="open_module" href="#zoom/' + item.hash + '">' 
                    + '<img class="zoom" src="' + item.images[size][1] + '" alt="" />' 
                    + '<img class="shadow" rel="" src="/images/module-shadow-593.png" alt="" />' 
                  + '</a>' 
                + '<div class="overlay ' + item.cssclass + ' ' + item.name + ' " id="overlay' + index + '">' 
                  + '<img class="full" rel="" src="' + item.images[size][0] + '" alt="" />' 
                  + item.overlay 
                + '</div>' 
              + '</div>' 
            + '</div>';
      });

      $('div#stage').html('<div class="scrollable" id="browsable"><div class="items">' + html + '</div></div>');

      // Help Layer in Send Product
      $("a.layer").fancybox({
        autoDimensions : false,
        padding : 0,
        width : 716,
        height : 392,
        onStart : function() {
          $('#fancybox-wrap').addClass('layer');
          $('#fancybox-overlay').css('left', $('.main').position().left);
        },
        onComplete : function() {
          $('.scrollContent').tinyscrollbar();
        }
      });

      merci.initZoomGallery(size);
    },
    initZoomGallery : function(size) {
      if(location.hash) {
        if(location.hash.replace('#', '').search(/^zoom/) == -1) {
          //log('zoomout');
          currentPearl = $('.module[data-hash="' + location.hash.replace('#', '') + '"]').not('.cloned').attr('data-index');
        } else {
          //log('zoomin');
          currentPearl = $('.module[data-hash="' + location.hash.replace('#', '').replace(/^zoom\//, '') + '"]').not('.cloned').attr('data-index');
        }

      } else {
        currentPearl = 0;
      }

      if(size == '1680') {
        moduleWidth = 734;
        moduleHeight = 348;
        fullWidth = 1564;
        fullHeight = 742;
      } else if(size == '1280') {
        moduleWidth = 506;
        moduleHeight = 244;
        fullWidth = 1263;
        fullHeight = 608;
      } else if(size == '1280x800') {
        moduleWidth = 542;
        moduleHeight = 233;
        fullWidth = 1263;
        fullHeight = 543;
      } else {
        moduleWidth = 482;
        moduleHeight = 229;
        fullWidth = 989;
        fullHeight = 486;
      }

      $("div#browsable").zoomGallery({
        item : '.module',
        initialIndex : currentPearl,
        hash : 'zoom',
        zoomWidth : moduleWidth,
        zoomHeight : moduleHeight,
        fullWidth : fullWidth,
        fullHeight : fullHeight
      });

      var api = $("#browsable").data('zoomGallery');

      api.onFullscreen(function(i, module) {
        // Tracking
        module.find('span[data-tracking-uri][data-tracking-code]').trigger('click');
      });
    },
    /**
     * Module "GIFT CARDS" (only print output)
     *
     **/
    initGiftCards : function() {

      $('textarea').focus();

      $('#heartsEdit textarea').resizeFont({
        maxChars : [10, 20, 30],
        fontSize : [51, 39, 33],
        lineHeight : [53, 49, 46],
        callback : function(elem) {
          merci.giftCardPrintStyles(elem)
        }
      });
      $('#lace_ribbonEdit textarea').resizeFont({
        maxChars : [10, 23, 30],
        fontSize : [39, 39, 32],
        lineHeight : [44, 44, 36],
        callback : function(elem) {
          merci.giftCardPrintStyles(elem)
        }
      });

      $('#daisiesEdit textarea').resizeFont({
        maxChars : [19, 20, 30],
        fontSize : [39, 39, 32],
        lineHeight : [44, 44, 36],
        callback : function(elem) {
          merci.giftCardPrintStyles(elem)
        }
      });
      
      $('#streaks_ribbonEdit textarea').resizeFont({
        maxChars : [10, 23, 30],
        fontSize : [39, 39, 32],
        lineHeight : [44, 44, 36],
        callback : function(elem) {
          merci.giftCardPrintStyles(elem)
        }
      });

      $('#red_bellsEdit textarea').resizeFont({
        maxChars : [10, 20, 30],
        fontSize : [51, 41, 33],
        lineHeight : [53, 49, 46],
        callback : function(elem) {
          merci.giftCardPrintStyles(elem)
        }
      });

      $('#glitter_bellsEdit textarea').resizeFont({
        maxChars : [10, 20, 30],
        fontSize : [51, 41, 33],
        lineHeight : [53, 49, 46],
        callback : function(elem) {
          merci.giftCardPrintStyles(elem)
        }
      });
    },
    /* Insert font styles in hidden field for PDF print */
    giftCardPrintStyles : function(textfield) {
      $(textfield).css('font-size');
      var cssObj = {
        'font-size' : parseInt($(textfield).css('font-size')),
        'line-height' : parseInt($(textfield).css('line-height')),
        'color' : $(textfield).css('color'),
        'top' : parseInt($(textfield).css('top')),
        'width' : parseInt($(textfield).css('width'))
      };
      $('#textStyles').val(JSON.stringify(cssObj));
    },
    /**
     * Module "FAVORITE MOVIES" (only print output)
     *
     **/
    initFavoriteMovies : function() {

      if($('div.main').is('#new')) {
        // New View
        merci.toggleEditScenes();
        merci.collectGreeting();
      } else if($('#previewMovie').length == 1) {
        // Form View
        merci.showPreview();
      } else if($('div.main').is('#show') || $('div.main').is('#preview')) {
        // Show View
        merci.showMovie();
        $(window).bind('resizeEnd', function(event) {
          var newSize = merci.setBodyIdByViewportSize(window.viewport.width(), window.viewport.height());
          merci.showMovie();
        });
      }
    },
    // Toggle steps "Insert Text for scene"
    toggleEditScenes : function() {
      // Next scene (Check input value)
      $('a.squareButton:not(.back)').click(function(event) { 
        var that = this;
        nextScene = $(that).attr('href');       

        if(merci.isSceneInputEmpty(nextScene)){
          merci.setErrorInput(
          $(that)
          .parents('div.scenes')
          .find('input[type="text"]'));
          
        }else{
          $('div.scenes').hide();
          $('div' + nextScene).show();
        }
        
        event.preventDefault();
      });
      
      // prev scene
      $('a.squareButton.back').click(function(event) { 
        prevScene = $(this).attr('href');       
        $('div.scenes').hide();
        $('div' + prevScene).show();
        event.preventDefault();
      });
      
      $('form').submit(function(){
        if(merci.isSceneInputEmpty('#scene4')){
          merci.setErrorInput($('#scene3 input[type="text"]'));
          return false;
        }
      });
      
    },
    // Check value in scene input
    isSceneInputEmpty: function(scene){
      
      if($('#scene' + (parseInt(/#scene(\d+)/.exec(scene)[1], 10) - 1)).find('input[type="text"]').val().length > 0){
        return false;
      }else{
        return true;
      }
    },
    // Highlight empty input
    setErrorInput: function($input){
      $input
        .addClass('error')
        .removeAttr('placeholder')
        .bind('keyup', function(){
          if($(this).val().length > 0){
            $(this).removeClass('error')
          }
        });
    },
    // Collect all texts from scenes
    collectGreeting : function() {
      $('form').submit(function(event) {
        greeting = "";
        $('input[type=text]').each(function() {
          greeting += $(this).val() + '\n';
        });

        $('#movieScenes textarea').val(greeting);

        return true;
      });
    },
    /* Small preview next to form */
    showPreview : function() {
      var flashInstalled = swfobject.ua.pv[0] != 0 ? true : false;
      log("Flash installed? " + flashInstalled);
      
      jwplayer("previewMovie").setup({
        id : options.movieName,
        flashplayer : options.flashplayer,
        width : 395,
        height : 244,
        controlbar : "none",
        autostart : true,
        bufferlength: '1',
        levels : options.levels,
        stretching : 'fill',
        skin: options.skin,
        image: options.image,
        plugins: options.plugin,
        'MomentsFlash.steps': options.steps, 
        'MomentsFlash.texts':options.texts
      })
      .onTime(function(v) {
        
        if(!flashInstalled){
          // Animate text at each step
          time = Math.round(v.position * 10) / 10;
          
          $.each(options.steps, function(index, value) {
            if(time >= value) {
              
              if(time < options.steps[index + 1] || options.steps[index + 1] == undefined) {
                duration = (options.steps[index + 1]) ? options.steps[index + 1]-options.steps[index] : v.duration - options.steps[index]
                duration = Math.floor(duration * 1000)
                merci.animateText('#step', index, duration);
              }
            }
          });
        }
      })
      .onComplete(function() {
        //merci.resetText();

      })
      .onPlay(function() {
        if(!flashInstalled){
          merci.resetText();
        }
      })
      .onPause(function(state){
        // Hide Text on Pause
        if(state["oldstate"] == "PLAYING" && !flashInstalled) {
          merci.resetText();
        }
      });
    },
    /* Show movie (final & preview) */
    showMovie : function() {
      var flashInstalled = swfobject.ua.pv[0] != 0 ? true : false;
      log("Flash installed? " + flashInstalled);
      // Get mute state from cookie
      muteState = $.cookie('merci.sound') == 'off' ? true : false;
      jwplayer("movie").setup({
        id : options.movieName,
        flashplayer : options.flashplayer,
        width : $('.main').width(),
        height : $('.main').height(),
        controlbar : "none",
        autostart : true,
        bufferlength: '3',
        levels : options.levels,
        screencolor : "af8359",
        backcolor: "af8359",
        stretching : 'fill',
        skin: options.skin,
        image: options.image,
        plugins: options.plugin,
        'MomentsFlash.steps': options.steps, 
        'MomentsFlash.texts':options.texts
      })
      .onTime(function(v) {

        if(!flashInstalled){
          // Animate text at each step
          time = Math.round(v.position * 10) / 10;
          
          $.each(options.steps, function(index, value) {
            if(time >= value) {
              
              if(time < options.steps[index + 1] || options.steps[index + 1] == undefined) {
                duration = (options.steps[index + 1]) ? options.steps[index + 1]-options.steps[index] : v.duration - options.steps[index]
                duration = Math.floor(duration * 1000)
                merci.animateText('#step', index, duration);
              }
            }
          });
        }
        
        
      })
      .onComplete(function() {
        
        // Reset texts at "The End"
        //merci.resetText();
        $('.delayedShow').trigger('delayedshow');
        
      })
      .setMute(muteState)
      .onPlay(function(state) {
        
        if(!flashInstalled){
          merci.resetText();
        }
        // Play
        $('.delayedShow').hide();

      })
      .onPause(function(state){
        // Hide Text on Pause
        if(state["oldstate"] == "PLAYING" && !flashInstalled) {
          merci.resetText();
        }
      });
    },
    // Text push animation
    animateText : function(txtId, i, duration) {
      
      if(jQuery.data($(txtId + i)[0], 'play') == undefined) {
        
        jQuery.data($(txtId + i)[0], 'play', 'on');

        duration = duration + 500;
        $(txtId + i).show();
        $aniItem = $(txtId + i);
        if($aniItem == $('#texts div:last-child')){
          duration = duration - 500;
        }
        $aniItem.find('.original')
        .show()
        .animate({
          opacity : 0.9
        }, { 
          queue: false, 
          duration: 500 
        })
        .animate({
          marginLeft : "+=" + (i + 3) + '%'
        }, {
          duration : duration 
        });


      }
    },
    resetText : function() {
      log("Reset");
      $('#texts div, #texts div p').stop().removeAttr('style').hide();
      $('#texts div').each(function(index, elem) {
        jQuery.removeData(elem, 'play');
      });
    },
    /**
     * MEDIA TV spot
     *
     **/
    initTvspot : function() {
      muteState = $.cookie('merci.sound') == 'off' ? true : false;
      jwplayer("movie").setup({
        id : "tvspot",
        flashplayer : options.flashplayer,
        width : $('.main').width(),
        height : $('.main').height(),
        image : options.image,
        autostart : true,
        bufferlength: '3',
        levels : options.levels,
        screencolor : "ffffff",
        stretching : 'fill',
        skin: options.skin
      }).onComplete(function() {
        $('.delayedShow').trigger('delayedshow');
      }).setMute(muteState).onPause(function(state) {
        if(state["newstate"] == "PAUSED") {
          //$('.delayedShow').show();
          $('.delayedShow').trigger('delayedshow');
        }
      }).onPlay(function(state) {
        if(state["oldstate"] == "PAUSED") {
          $('.delayedShow').hide();
          $('#Media.show header nav').hide();
        }
      }).onMute(function(state){
        log(state.mute);
        merci.setSoundState(state.mute);
      });
    },
    /**
     * MEDIA RINGTONE
     * 
     **/
    initRingtone : function(){
      jwplayer(options.movieName).setup({
        id : "ringtone",
        flashplayer : options.flashplayer,
        width : '30',
        height : '30',
        file : options.file,
        screencolor : "ffffff",
        stretching : 'fill',
        skin: options.skin,
        controlbar: 'none',
        image: options.image
      })
    },
    /**
     * Module "SEND PRODUCT" (editor)
     *
     **/
    /* Init Dropdown */
    initDropdown : function() {
      $('.dropdown dd').hide();

      $('.dropdown dt').bind({
        'mouseover' : function() {
          $('.dropdown dd').stop(true, true).slideDown();
        }
      });
      
      $('.dropdown dl a').bind('click', function() {
          $('.dropdown dd').stop(true, true).slideUp();
        });

      $('.dropdown dl').bind({
        'mouseleave' : function() {
          $('.dropdown dd').stop(true, true).slideUp();
        }
      });
    },
    initXmas: function(){
      $('#slider').slides({
          preload: true,
          generateNextPrev: false
        });
      },
    /* Change required-labels depending on selected subject */
    initContact:function(){
      merci.toogleRequiredFields();
      $('select#contact_subject').change(function(){
        merci.toogleRequiredFields();
      });
    },
    toogleRequiredFields: function(){
      var fields = ['street', 'phone', 'zip', 'city', 'country'];
      if($("select option:selected").val()== 'productcomplaint'){
        for (x in fields){
          $('label[for="contact_'+fields[x]+'"]').append('<span>*</span>').parents('div').addClass('field_with_errors');
        }
      }else{
        for (x in fields){
          $('label[for="contact_'+fields[x]+'"] span').parents('div').removeClass('field_with_errors');
          $('label[for="contact_'+fields[x]+'"] span').remove();
        }
      }
    },
    track : function(uri, code) {
      if(merci.env == "production") {
        dcsMultiTrack('DCS.dcsuri', uri, 'WT.ti', code);
      } else {
        merci.talkAboutTracking(uri, code);
      }
    },
    addTrackByDataAttrsListener : function() {
      $('*[data-tracking-code][data-tracking-uri]').click(function() {
        var that = $(this);
        merci.track(that.attr('data-tracking-uri'), that.attr('data-tracking-code'));
      });
    },
    talkAboutTracking : function(uri, code) {
      log("In production, I would track " + uri + " with code " + code + ".");
    }
  });
  /********************************* *********************************
   **************************** PAGE LOAD *****************************
   ********************************* *********************************/
  jQuery().ready(function() {
    merci.init();

  });
}
function closeIntro() {
  log("Intro close");
  $('#intro').fadeOut(function() {
    $(this).remove();
  });
}

function setWebtrendsOptoutCookie(cookieDomain){
	//WTLOPTOUT
	 $.cookie('WTLOPTOUT', 'yes', {
          expires : 3650,
          domain: cookieDomain,
          path : '/'
        });
	alert("Der Opt-Out-Cookie wurde für "+cookieDomain+" gesetzt!");
}
