var Werthers = {
  init : function() {
    this.replaceMenu();
    // Page history (Raute-Navigation)
    this.initNutritions();
    this.initFaq();
    $.historyInit(this.historyLoad, "jquery_history.html");
    $("a[rel='history']").click(function (event) {
      if ($.browser.msie && $.browser.version < 8) {
        var hash = this.href;
        hash = hash.replace(/^.*#/, '');
        $.historyLoad(hash);
      }
      this.blur();
    });

    // Menu animation
    this.initProductMenu();
    
    // Init Tracking
    this.initTracking();
    
    // A10000 stuff
    // Slideshow
    this.a10000_slide = 1;
    this.a10000_slide_enabled = true;
    window.setTimeout(Werthers.a10000Slideshow, 6000);
    this.b10000LabelRemover();
    $('<img src="/images/a/bg2.jpg" /><img src="/images/a/bg3.jpg" />');
    // TV-Spot
    $('#a10000 #link_spot, #b11000 #link_spot').click(function(event) {
      swfobject.embedSWF("/flash/videoplayer.swf", "spot", "991", "540", "9");
      $('#spot').addClass('active');
    });

    this.d20000Hover();
    this.d20000_products = Array("karamell_creme", "eclair", "sahnetoffees", "sahnebonbons", "feine_helle", "karamell", "caramelts", "karamell_mousse", "feine_herbe", "feine_herbe_karamell");

    if ($.browser.msie && $.browser.version == "7.0") {
      this.d21000MoveForm()
    }
  },
  
  replaceMenu : function() {
    $("#menu a").each(function() {
      var itm = $(this);
      var img_base = itm.text().toLowerCase().replace(/ä/g, "ae").replace(/ö/g, "oe").replace(/ü/g, "ue").replace(/ß/g, "ss").replace(/[^a-z0-9]+/g, "-")
      if (itm.hasClass("active")) {
        itm.html('<img src="/images/menu/'+ img_base + '-on.png" alt="'+ itm.text() + '" title="" />');
      }
      else {
        itm.html('<img src="/images/menu/' + img_base + '-off.png" alt="'+ itm.text() + '" title="" />');
        itm.hover(
          function() {
            $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, "-on.png");
          },
          function() {
            $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, "-off.png");
          }
        );
      }
    });
    $('#menu li').each(function(){
      var itm = $(this);
      if (itm.text().search(/^\s*\|\s*$/) != -1) {
        itm.html('<img src="/images/menu/divider.png" alt="|" />');
      }
    });
    $("#product-menu a").each(function() {
      var itm = $(this);
      var img_base = itm.text().toLowerCase().replace(/ä/g, "ae").replace(/ö/g, "oe").replace(/ü/g, "ue").replace(/ß/g, "ss").replace(/[^a-z0-9]+/g, "-")
      itm.html('<img src="/images/menu/' + img_base + '-off.png" alt="'+ itm.text() + '" title="" />&nbsp;');
      itm.hover(
        function() {
          $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, "-on.png");
        },
        function() {
          $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, "-off.png");
        }
      );
    });
    
  },
  
  // Rauto-Navigation, zeigt die passende Action, wenn sich der Teil nach der Route ändert.
  historyLoad : function(hash) {
    // Nutrition facts
    if (hash == "nutritions" || hash == "gda" || hash == "ingredients") {
      $('#nutrition-facts > div:not(#tab-'+ hash +')').slideUp(300);
      $('#nutrition-facts div#tab-' + hash).slideDown(600);
      $('#nutrition-facts ul a').removeClass('active');
      $('#nutrition-facts ul a[href=#'+ hash +']').addClass('active');
      Werthers.track(location.pathname + "/nutrition_facts", $('meta[name=WT.ti]').attr('content') + " Nährwertinformationen");
    }
    // FAQ
    else if (hash.match(/^faq[0-9]+$/)) {
      $('#f10000 #whitebox div:not(#tab-' + hash + ')').slideUp(600);
      $('#f10000 #tab-' + hash).slideDown(600);
      var a = $('#f10000 h2 a.active');
      a.removeClass('active').attr({'href' : a.attr('data-href')}).removeAttr('data-href');
      a.parent().removeClass('active');
      a = $('#f10000 h2 a[href=#'+ hash +']');
      a.addClass('active').attr({'data-href' : a.attr('href'), 'href' : '#faq0'});
      a.parent().addClass('active');
      if (hash != "faq0") {
        Werthers.track(location.pathname + "/" + hash, a.attr("data-track"));
      }
    }
  },
  
  initFaq : function() {
    $("#f10000 #whitebox div").hide();
  },
  
  initNutritions : function() {
    $("#nutrition-facts > div").hide();
  },
  
  // Initialisiert die Produkt-Menü-Ausklapp-Funktion. Beim mouseover wird das menü geöffnet, bei mouseout ein timeout gesetzt.
  // Dieser wird gelöscht, wenn man über Produktmenü geht und erneut gesetzt, wenn man dieses verlässt.
  // Beim Timout wird das Menü geschlossen.
  initProductMenu : function() {
    $('a[data-submenu=product]').hover(
      // Menüpunkt over: Menü öffnen, Timeout löschen
      function () {
        // Produktmenü und Schatten an richtige Position verschieben
        $('#product-menu, #product-menu-shadow').css({left : $('a[data-submenu=product]').position().left + $('#menu').position().left - 14});
        // Produktmenü ausfahren und Schatten einblenden
        $('#product-menu').animate({top : '83px'}, 500);
        $('#product-menu-shadow').animate({top: '77px'}, 100);
        // Hide-Timeout löschen, falls gesetzt
        window.clearTimeout(Werthers.hide_product_menu_timeout);
      },
      // Menüpunkt out: Timeout setzen
      function () {
        Werthers.hide_product_menu_timeout = window.setTimeout(Werthers.hideProductMenu , 1000);
      }
    );
    $('#product-menu').hover(
      // Submenü over: Timeout löschen
      function() { window.clearTimeout(Werthers.hide_product_menu_timeout); },
      // Submenu out: Timeout setzen
      function() { Werthers.hide_product_menu_timeout = window.setTimeout(Werthers.hideProductMenu , 1000);}
    );
  },
  // Wird beim Ablauf des Timeouts aufgerufen und schließt das Menü.
  hideProductMenu : function() {
    $('#product-menu').animate({top: '-35px'}, 500);
    window.setTimeout(function (){
      $('#product-menu-shadow').animate({top: '66px'}, 100);
    }, 400);
  },
  
  // Loggt Events auf die Konsole, wenn das Environment nicht production ist (Wird vom Backend im Layout gesetzt) und die Konsole vorhanden ist.
  log : function(msg) {
    if (this.environment != "production") {
      if (typeof console == "object") {
        console.log(msg);
      }
      else {
        if ($('#js_console').length == 0) {
          $('body').append('<div id="js_console">Console:</div>');
          $('#js_console').css({position: 'absolute', top: 0, left: 0, width: '250px', maxHeight: '250px', overflow: 'auto', background: 'white', color: 'black'});
        }
        $('#js_console').append('<div>' + msg + '</div>');
      }
    }
  },
  
  // Endlosanimation für die A10000, animiert die Bilder
  a10000Slideshow : function() {
    if (Werthers.a10000_slide_enabled) { // Disabled while displaying the video
      Werthers.a10000_slide = Werthers.a10000_slide + 1;
      if (Werthers.a10000_slide > 3) {
        Werthers.a10000_slide = 1;
      }
      //$('#background').fadeOut(); # Fade über weiß.
      $('#a10000 #background-fade').hide().css({backgroundImage : 'url(/images/a/bg' + Werthers.a10000_slide +'.jpg)'}).fadeIn(1000, function() {
        $('#a10000 #background').css({backgroundImage : 'url(/images/a/bg' + Werthers.a10000_slide +'.jpg)'}).show();
        $('#a10000 #background-fade').css({backgroundImage : 'none'});
      });
    }
    window.setTimeout(Werthers.a10000Slideshow, 6000);
  },
  
  // Entferne die Labels vom Submenü, da sie auch auf der Hintergrundgrafik drauf sind
  b10000LabelRemover : function() {
    $('#subnavi span.img').text('');
  },

  d20000Hover : function() {
	  /*$("#d20000 img[src*=-pack.png], #d20000 img[src*=-flag.png]").each(function(){
		  $(this).attr("data-left", $(this).position().left);
	  });*/
	  $("#d20000 area[data-product]").hover(
			function(event) {
				var product = $(event.target).attr("data-product");
				var current_flag = $("#"+ product + "_flag");
				var current_pack = $("#"+ product + "_pack");
				current_pack.animate({width : "+=10", heigth : "+=10", left : "-=5", top : "-=5"}, 100);
				current_flag.addClass("active");
				if (!$.browser.msie) {
					$("img[id*=_flag]").clearQueue();
					$("img[id*=_flag]").not(current_flag).fadeTo(300, 0.5);
					current_flag.fadeTo(300, 1.0);
			  }
			},
			function(event) {
			  $("#"+ $(event.target).attr("data-product") + "_pack").animate({width : "-=10", heigth : "-=10", left : "+=5", top : "+=5"}, 100);
				$("#"+ $(event.target).attr("data-product") + "_flag").removeClass("active");
		  	if (!$.browser.msie) {
				  $("img[id*=_flag]").fadeTo(300, 1.0);
				}
			}
		).click(function(event) {
		  if ($.browser.mozilla) {
		  $("#"+ $(event.target).attr("data-product") + "_pack").animate({width : "-=10", heigth : "-=10", left : "+=5", top : "+=5"}, 1);
			$("#"+ $(event.target).attr("data-product") + "_flag").removeClass("active");
	  	//if (!$.browser.msie) {
			  $("img[id*=_flag]").fadeTo(1, 1.0);
			}
		});
  },

  // Verschiebt das Form im DOM, weil es sonst unterhalb des Bogen liegt und teils nicht klickbar ist.
  // Nur im IE7 nötig
  d21000MoveForm : function() {
    var elem = $('#d21000 form, #d21001 form');
    elem.css({position: 'absolute', left: elem.offset().left, top: elem.offset().top, width: elem.width()})
    $("body")[0].appendChild(elem[0]);
  },
  
  // Fügt die Listeners an die entsprechenden Links an, um diese zu tracken
  initTracking : function() {
    // Storck-Logo:
    $('a[href=http://www.storck.com/de/]').click(function(){
      Werthers.track('/extern/www.storck.com/de/', 'Link Storck.com/de');
    });
    $('img#link_spot').click(function() {
      Werthers.track(location.pathname + "/tv_spot", 'Störer TV Spot');
    });
    $('#a10000 #teaser_schoko').click(function() {
      Werthers.track(location.pathname + '/teaser_choco', 'Teaser Startseite - Schokospezialitäten (B11000)');
    });
    $('#a10000 #teaser_bonbon').click(function() {
      Werthers.track(location.pathname + '/teaser_bonbon', 'Teaser Startseite - Bonbon');
    });
    $('#a10000 #teaser_geschichte').click(function() {
      Werthers.track(location.pathname + '/teaser_geschichte', 'Teaser Startseite - Markengeschichte (C10000)');
    });
    $('#b10000 #teaser_choco').click(function() {
      Werthers.track(location.pathname + '/teaser_choco', 'Teaser - Schokospezialitäten (B11000)');
    });
    $('#b10000 #teaser_bonbon').click(function() {
      Werthers.track(location.pathname + '/teaser_bonbon', 'Teaser  - Bonbons (B12000)');
    });
    $('#b10000 #teaser_sugar').click(function() {
      Werthers.track(location.pathname + '/teaser_sugar', 'Teaser - Zuckerfrei (B13000)');
    });
    $('#done #content a[href=/Produkte/Schokoladen-Spezialitaeten]').click(function(){
      Werthers.track(location.pathname + '/link', 'Schoko Spezialitäten Link');
    })
  },
  
  // Sendet einen Trackingcode
  track : function(uri, title) {
    dcsMultiTrack('DCS.dcsuri', uri, 'WT.ti', title);
  }
}
$(document).ready(function() { Werthers.init() });
function closeVideoPlayer() {
  $('#spot').replaceWith('<div id="spot"></div>');
}