/// <reference path="jquery-1.3.2.js" />

var allimg = 1;
var imgHotspots = new Array("img1", "img2", "img3", "img4", "img5");
var imgcount = 0;
var images = 0;
var subnavi = "";
var subsubnavi = "";
var subsubsubnavi = "";
var timeout = 1;
var navito = 1;
var timeoutTime = 200;
var currentNav = "";
var skip = 0;
var teaser = 0;
var hotspot = 0;
var languageselect = 0;
var mode = "";
var suggestion = 0;
var question = 0;
var newsletter = 0;
var dealer = 0;
var active;
var near = 0;
var subnaviopen = 0;
var rightarrow = 1;
var leftarrow = 1;
var activated = 0;
var navitext = 0.67;
var naviback = 0.95;
var ismiddle = 1;
var galleryThumbWidth = 496;    // Breite in Pixeln des Elements in dem die Thumbnails in der Gallery angezeigt werden
var galleryPageImageCount = 4;  // Anzahl der Thumbnail-Bilder in der Gallery
var currentGalleryPath;         // Pfad zum Bild der Gallery, das bei Click auf ein Thumb angezeigt werden soll
var currentalias = "europe";
var isProduct = 0;
var isProductLink = 0;
var ie6 = 0;

// die Mouseover-Bilder für die Navi vorladen
$(document).ready(function() {
    if(navigator.appVersion.indexOf("MSIE 6")>-1)
	{
		$("#footer").remove();
        skipIntro(3);
		skip = 1;
		ie6 = 1;
		$("#content").html("<div><br/><br/><br/>This Website cannot be displayed correctly in Internet Explorer 6. Please use Internet Explorer 7 or higher or a different browser.<br/><br/><br/>Diese Website kann im Internet Explorer 6 nicht richtig dargestellt werden. Bitte benutzen Sie den Internet Explorer ab Version 7 oder einen anderen aktuellen Browser.</div>");
		$("#content").css({'color': '#C2C2C2', 'font-size': '12px', 'text-align' : 'center'});
		$("#content").show();
	}
	else
	{
		var urls = [ 'bg_navi1.png', 'bg_naviTop_near.png', 'bg_naviTop_over.png' ];
		$.preload( urls, {
			base: '/images/pds2/'		
		});
	}
	
	if(CURRENTPOOL == "germanypds2")
	    currentalias = "germany";
	else if (CURRENTPOOL == "europepds2")
	    currentalias = "europe";
	else if (CURRENTPOOL == "worldpds2")
	    currentalias = "international";
	
	// Imagemaps auf Kategorie-Seiten
	
	var currenturl = window.location.href;
	if (currenturl.indexOf('products') > 0) 
	{
		if(currenturl.substring(currenturl.length - 9, currenturl.length) == 'products/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p9000electronics/communication/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p8000eyewear/sunglasses/';
			var link3 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p3000accessories/smallleathergoods/';
			var link4 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p3000accessories/writingtools/';
			var link5 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p2000luggage/roadster/';
			$("#default_img").find('img').attr('usemap', '#overviewmap');
			$("#default_img").append('<map name="overviewmap"><area href="' + link5 + '" coords="339,136,372,136,372,67,424,67,426,128,491,134,494,303,392,303,392,325,352,332,352,255,339,255" shape="poly"/><area href="' + link4 + '" coords="325,380,493,394" shape="rect"/><area href="' + link3 + '" coords="395,306,544,376" shape="rect"/><area href="' + link2 + '" coords="225,317,233,365,329,379,356,374,393,343,395,325,347,335,304,334,304,313" shape="poly"/><area href="' + link1 + '" coords="305,257,350,257,350,337,305,333" shape="poly"/></map>');
		}	
	}
	if (currenturl.indexOf('p1000') > 0) 
	{
		if(currenturl.substring(currenturl.length - 13, currenturl.length) == 'p1000fashion/')
		{
			$("#categorybuttons").css("width", "610px"); // dass Categorybuttons nicht über die Imagemap gehen
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p1000fashion/leisure/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p1000fashion/shoes/';			
			$("#default_img").find('img').attr('usemap', '#fashionmap');
			$("#default_img").append('<map name="fashionmap"><area href="' + link2 + '" coords="378,291,449,289,528,319,529,334,499,345,379,345" shape="poly"/><area href="' + link1 + '" coords="173,205,206,86,254,57,289,58,333,96,366,81,377,58,411,58,422,79,462,96,481,217,478,294,334,298,334,314,270,327,204,313,210,267" shape="poly"/></map>');
		}	
	}
	else if (currenturl.indexOf('p2000') > 0) 
	{
		if(currenturl.substring(currenturl.length - 13, currenturl.length) == 'p2000luggage/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p2000luggage/cervo20/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p2000luggage/roadster/';
			var link3 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p2000luggage/roadster/';			
			$("#default_img").find('img').attr('usemap', '#luggagemap');
			$("#default_img").append('<map name="luggagemap"><area href="' + link3 + '" coords="355, 105, 510, 105, 510, 350, 450, 350, 450, 230, 355, 230" shape="poly"/><area href="' + link2 + '" coords="133, 187, 329, 187, 329, 230, 250, 230, 250, 370, 133, 370" shape="poly"/><area href="' + link1 + '" coords="250, 230, 450, 390" shape="rect"/></map>');
		}		
	}
	else if (currenturl.indexOf('p3000') > 0) 
	{
		if(currenturl.substring(currenturl.length - 17, currenturl.length) == 'p3000accessories/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p3000accessories/smallleathergoods/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p3000accessories/writingtools/';
			var link3 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p3000accessories/fragrances/';			
			$("#default_img").find('img').attr('usemap', '#accessoriesmap');
			$("#default_img").append('<map name="accessoriesmap"><area href="' + link3 + '" coords="200,120,325,120,325,222,239,224,239,330,200,330" shape="poly"/><area href="' + link2 + '" coords="227,343,502,374" shape="rect"/><area href="' + link1 + '" coords="239,224,385,222,518,224,517,357,489,352,467,342,241,341" shape="poly"/></map>');
		}		
	}
	else if (currenturl.indexOf('p5000') > 0) 
	{
		$("#categorybuttons").css("width", "610px"); // dass Categorybuttons nicht über die Imagemap gehen
		if(currenturl.substring(currenturl.length - 11, currenturl.length) == 'p5000sport/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p5000sport/runningfitness/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p5000sport/golf/';
			var link3 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p5000sport/watersnow/';			
			$("#default_img").find('img').attr('usemap', '#sportmap');
			$("#default_img").append('<map name="sportmap"><area href="' + link3 + '" coords="193,299,238,136,274,122,273,83,340,84,341,125,378,139,418,301" shape="poly"/><area href="' + link2 + '" coords="383,162,390,138,423,124,429,113,466,114,470,123,505,141,518,185,490,194,488,204,448,207,417,316,441,343,441,381,360,378,295,400,279,382,316,363,351,318,414,305" shape="poly"/><area href="' + link1 + '" coords="215,333,216,321,287,285,424,292,450,212,512,214,531,311,516,358,443,359,427,321,392,305,350,316,327,344,232,346" shape="poly"/></map>');
		}		
	}
	else if (currenturl.indexOf('p6000') > 0) 
	{
		if(currenturl.substring(currenturl.length - 16, currenturl.length) == 'p6000timepieces/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p6000timepieces/dashboard/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p6000timepieces/indicator/';
			var link3 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p6000timepieces/flat6/';			
			$("#default_img").find('img').attr('usemap', '#timemap');
			$("#default_img").append('<map name="timemap"><area href="' + link3 + '" coords="312,97,389,97,427,199,437,199,437,231,427,231,391,371,313,371,271,219" shape="poly"/><area href="' + link2 + '" coords="428,131,486,131,487,153,531,226,490,304,489,349,427,349,426,304,409,272,443,218,417,175" shape="poly"/><area href="' + link1 + '" coords="206,127,265,129,265,156,280,181,271,220,283,260,267,293,266,346,206,346,206,295,193,264,178,223,194,181,206,159" shape="poly"/></map>');
		}		
	}
	else if (currenturl.indexOf('p7000') > 0) 
	{
		$("#categorybuttons").css("width", "610px"); // dass Categorybuttons nicht über die Imagemap gehen
		if(currenturl.substring(currenturl.length - 10, currenturl.length) == 'p7000home/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p7000home/kitchenknives/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p7000home/lighting/';					
			$("#default_img").find('img').attr('usemap', '#lightingmap');
			$("#default_img").append('<map name="lightingmap"><area href="' + link2 + '" coords="218,150,310,146,465,86,488,86,534,291,522,342,565,342,565,355,465,355,465,341,509,341,517,307,475,109,428,113,276,171,217,171" shape="poly"/><area href="' + link1 + '" coords="153,256,289,245,288,200,310,193,330,194,344,180,374,180,391,198,428,200,423,323,302,302,301,337,209,358,409,341,419,355,262,379,152,359" shape="poly"/></map>');
		}		
	}
	else if (currenturl.indexOf('p8000') > 0) 
	{
		$("#categorybuttons").css("width", "610px"); // dass Categorybuttons nicht über die Imagemap gehen
		if(currenturl.substring(currenturl.length - 13, currenturl.length) == 'p8000eyewear/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p8000eyewear/readingtools/';
			var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p8000eyewear/sunglasses/';
			var link3 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p8000eyewear/readingtools/';			
			$("#default_img").find('img').attr('usemap', '#eyewearmap');
			$("#default_img").append('<map name="eyewearmap"><area href="' + link3 + '" coords="172,309,311,269,548,296,553,318,410,397,175,370" shape="poly"/><area href="' + link2 + '" coords="77,247,178,239,281,251,173,313,77,294" shape="poly"/><area href="' + link1 + '" coords="369,253,445,235,529,249,528,259,470,294,371,276" shape="poly"/></map>');
		}		
	}
	else if (currenturl.indexOf('p9000') > 0) 
	{
		$("#categorybuttons").css("width", "610px"); // dass Categorybuttons nicht über die Imagemap gehen
		if(currenturl.substring(currenturl.length - 17, currenturl.length) == 'p9000electronics/')
		{			
			var link1 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p9000electronics/communication/';
			//var link2 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p9000electronics/communication/';
			//var link3 = window.location.protocol + '//' + window.location.hostname + '/' + currentalias + '/' + CURRENTLANGUAGE + '/' + 'products/p9000electronics/communication/accessories/';
			$("#default_img").find('img').attr('usemap', '#electronicsmap');
			$("#default_img").append('<map name="electronicsmap"><area href="' + link1 + '" coords="200,100,550,350" shape="rect"/></map>');
		}		
	}
	
	/* DESIGN STORE SITES */
	/* Set icb_content height if icb_title exists */
	$(document).ready(function() {
		$('.inner_content_box').each(function(index) {
			if($(this).find('.icb_title').length > 0) {	
				$(this).find('.icb_content').css("top", $(this).find('.icb_title').outerHeight() + 2 );
			}
		});			
	});		
	
});

// mousemove-Event abfangen
$().mousemove(function(e)
{	 
	 actionOnMouseMove(e.pageX,e.pageY)
});

(function($) {
   $.fn.found = function(myFunction) {
      if(this.length) {
         myFunction.call(this);
      }
   };
})(jQuery);

// Paging-Funktionalität
(function($) {	    
	$.fn.quickPager = function(options) {
	
		var defaults = {
			pageSize: 1,
			currentPage: 1,
			callback: ''
		};
		
		var options = $.extend(defaults, options);		
		
		return this.each(function() {	
						
			var selector = $(this);	
			var pageCounter = 1;
			
			selector.wrap("<div class='simplePagerContainer'></div>");
			
			selector.children().each(function(i){					
				if(i < pageCounter*options.pageSize && i >= (pageCounter-1)*options.pageSize) {
				$(this).addClass("simplePagerPage"+pageCounter);
				}
				else {
					$(this).addClass("simplePagerPage"+(pageCounter+1));
					pageCounter ++;
				}					
			});			
			
			selector.children().hide();
			selector.children(".simplePagerPage"+options.currentPage).show();
			
			if(pageCounter <= 1) {
				return;
			}			
			
			var pageNav = "<div class='simplePagerNav'><span id='current'>";
			pageNav += options.currentPage + "</span> / " + pageCounter;			
			pageNav += "&nbsp;&nbsp;&nbsp;<img alt='-' src='/images/pds2/arrow_text_last_out.png' />&nbsp;&nbsp;&nbsp;<img alt='+' src='/images/pds2/arrow_text_next_out.png' />";			
			pageNav += "</div>";			
			
			selector.after(pageNav);			
						
			selector.parent().find(".simplePagerNav img").click(function() {			
				if($(this).attr("alt") == '+' && options.currentPage < pageCounter)
				{
					options.currentPage++;	
					selector.children().hide();			
					selector.find(".simplePagerPage"+options.currentPage).show();
					
					$("#current").html(options.currentPage);
					
					return false;
				}
				else if($(this).attr("alt") == '-' && options.currentPage > 1)
				{
					options.currentPage--;
					selector.children().hide();			
					selector.find(".simplePagerPage"+options.currentPage).show();
					
					$("#current").html(options.currentPage);
					
					return false;
				}				
			});
			
			if(options.callback != '')
			{
				callbackfunc = options.callback;
				callbackfunc();
			}
		});		
	}
})(jQuery);

//--------------------
// Class Hotspot
//--------------------
function Hotspot(x, y, id, img, number) 
{  
  this.x = x;
  this.y = y;
  this.id = id;
  this.number = number;
  this.img = img;
  this.activated = false;
}

//-----------------------
// Matrix Functions
//-----------------------

// Welche Seite angezeigt wird
var matrixPage = 1;

// Anzahl der Seiten der Matrix
var pageCount = 0;

// Wieviele Bilder pro Seite angezeigt werden
var imgPerPage = 12;

// Flag ob rechter Pfeil angezeigt wird
var rightMatrixArrow = 1;

// Flag ob linker Pfeil angezeigt wird
var leftMatrixArrow = 1;

// Bildbreite mit rechtem Rand in Pixel
var imgWidth = 236;

// Breite einer Seite
var pageWidth = 944;

// Offset des Produktlabels in der Matrix
var mProductOffsetX = 12;
var mProductOffsetY = 16;

// Timeout fuer das zuruecknehmen der Abblendung der Produkte
var fullviewTimeout = null;
var shortTime = 200;


// Pfeile zur Navigation durch die Matrix initialisieren

function setupMatrixArrows() {
    // Seitenanzahl ermitteln
    var images = $("#thumbs .page li").length;
    pageCount = $("#thumbs .page").length;

    // Setzt die Breite des Bilder-Containers
    var breite = pageCount * pageWidth;

    $("#thumbs").width( breite);

    // Prueft, ob Pfeile angezeigt werden sollen
    checkMatrixArrows(1);

    // Bindet die Funktionen der Pfeile
	$("#matrixleft").click( moveMatrixToLeft);
	$("#matrixright").click( moveMatrixToRight);

	$("#matrixleft").hover(function(){
		$("#thumbs").stop().animate(
			{ left: "-" + (((matrixPage - 1) * pageWidth) - 100)}, 500
		);
	}, function(){
		$("#thumbs").stop().animate(
			{ left: "-" + ((matrixPage - 1) * pageWidth)}, 500
		);
	});

	$("#matrixright").hover(function(){
		$("#thumbs").stop().animate(
			{ left: "-" + (((matrixPage - 1) * pageWidth) + 100)}, 500
		);
	}, function(){
		$("#thumbs").stop().animate(
			{ left: "-" + ((matrixPage - 1) * pageWidth)}, 500
		);
	});
}


// Pfeile ausblenden

function hideMatrixArrows( time) {
	$(".arrow").fadeOut( time);
	rightMatrixArrow = 0;
	leftMatrixArrow = 0;
}


// Prueft ob die Pfeile zum Scrollen angezeigt werden sollen

function checkMatrixArrows( time) {
    if( pageCount == 1) {
        $(".arrow").hide();
        rightMatrixArrow = 0;
        leftMatrixArrow = 0;
    } else if( matrixPage == pageCount && rightMatrixArrow == 1) {
		$("#matrixleft").fadeIn( time);
		$("#matrixright").hide();
		rightMatrixArrow = 0;
	} else if( matrixPage == pageCount && leftMatrixArrow == 0) {
		$("#matrixleft").fadeIn( time);
		leftMatrixArrow = 1;
	} else if( matrixPage == 1 && leftMatrixArrow == 1) {
		$("#matrixright").fadeIn( time);
		$("#matrixleft").hide();
		leftMatrixArrow = 0;
	} else if( matrixPage == 1 && rightMatrixArrow == 0) {
		$("#matrixright").fadeIn( time);
		rightMatrixArrow = 1;
	} else if( matrixPage > 1 && matrixPage < pageCount) {
		$(".arrow").fadeIn( time);
		rightMatrixArrow = 1;
		leftMatrixArrow = 1;
	}
	// Matrix einblenden
	$('#matrix').fadeIn();
}


// Schiebt die Matrix nach Rechts

function moveMatrixToRight() {
	$("#matrixleft").show();
	leftMatrixArrow = 1;
	var left = "-" + (matrixPage * pageWidth);
	matrixPage++;
	$("#thumbs").stop().animate(
		{ left: left
		  }, {
		duration: 500,
		easing: "easeOutBack"
		});
	checkMatrixArrows(200);
}


// Schiebt die Matrix nach links

function moveMatrixToLeft() {
	$("#matrixright").show();
	rightMatrixArrow = 1;
	matrixPage--;
	checkMatrixArrows(200);

	var left = "-" + ((matrixPage - 1) * pageWidth);
	$("#thumbs").stop().animate(
		{ left: left
		  }, {
		duration: 500,
		easing: "easeOutBack"
		});
}


// Zoom Effekt fuer die Matrix hinzufuegen
// Funktion uebernommen von http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery

function bindEffect() {
    $("ul.page li").hover(function() {
	$(this).css({'z-index' : '10'}); /*Add a higher z-index value so this image stays on top*/
	$(this).find('img').stop() /* Add class of "hover", then stop animation queue buildup*/
		.animate({
			top: '-20px',
			left: '-30px',
			width: '212px', /* Set new width */
			height: '141px', /* Set new height */
			padding: '0'
		}, 200, setupLightBox( this)); /* this value of "200" is the speed of how fast/slow this hover animates */

	} , function() {
	$(this).css({'z-index' : '0'}); /* Set z-index back to 0 */
	$(this).find('img').stop()  /* Remove the "hover" class , then stop animation queue buildup*/
		.animate({
			top: '0',
			left: '0',
			width: '152px', /* Set width back to default */
			height: '101px', /* Set height back to default */
			padding: '0'
		}, 400, closeLightBox( this));
    });
}


// Zeigt die Lightbox ueber der Matrix an und zeigt den Tooltip des Produkts

function setupLightBox( imageItem) {
    if (fullviewTimeout != -1) { clearTimeout( fullviewTimeout);};

    // Andere Bilder abdunkeln
    var all = $(imageItem).parent().children();
    $(all).addClass( "hover");
    $(imageItem).removeClass( "hover");

    // Produktlabel anzeigen
    var info = $(imageItem).children().eq(0).children().eq(0).attr( "alt");
    $("#mproductlabel").text( info);

    // Damit der alt-Text nicht vom Browser angezeigt werden kann, diesen l�schen
    $(imageItem).children().eq(0).children().eq(0).attr( "alt", "");

    var xScroll = $(window).scrollLeft();
    var yScroll = $(window).scrollTop();

    $(imageItem).children().eq(0).children().eq(0).bind( "mousemove", function( event) {
        $("#mproductlabel").css( "top", (event.clientY + yScroll + mProductOffsetY) + "px");
        $("#mproductlabel").css( "left", (event.clientX + xScroll + mProductOffsetX) + "px").show();
    });
}


// Setzt einen Timeout zum ausblenden der Lightbox und nimmt die Settings f�r den Tooltip zurueck

function closeLightBox( imageItem) {
    fullviewTimeout = setTimeout(function() { doCloseLightbox( imageItem);}, shortTime);

    $(imageItem).unbind( "mousemove");
    $("#mproductlabel").hide();

    // Den alt-Text wieder einsetzen
    var text = $("#mproductlabel").text();
    $(imageItem).children().eq(0).children().eq(0).attr( "alt", text);
}


// Blendet die Lightbox ueber der Matrix aus
function doCloseLightbox( imageItem) {
    var all = $(imageItem).parent().children();
    $(all).removeClass( "hover");
}

//------------------------------
// Matrix Functions END
//------------------------------


function renderFonts(elem, font, hover)
{
    if(CURRENTLANGUAGE != 'de' && CURRENTLANGUAGE != 'en' && elem != '.navibutton')
        return;
    
    if (hover == null){
        hover = false;
    }
    if(font == 'PD')
    {
        var elements = $(elem);
	    var i = elements.length;
	    while ( i-- ) 
	    {
		    var text = $(elements[i]).html();
		    var newtext = text.replace(/ß/, "ss");
		    newtext = newtext.replace(/P´/, "&szlig;");
		    $(elements[i]).html(newtext);
	    }        
        Cufon.replace(elem, { fontFamily: 'Porsche Design Font', hover: hover });
    }
    else if(font == 'Helv')
    {
        Cufon.replace(elem, { fontFamily: 'HelveticaNeue LT 65 Medium', hover: hover, hoverables: { div: true } });
    }
}

function refreshFonts(elem)
{
    if(CURRENTLANGUAGE != 'de' && CURRENTLANGUAGE != 'en' && elem != '.navibutton' && elem != '#products' && elem != '#studio' && elem != '#company') // && elem != '#porschedesignshop')
        return;
        
    Cufon.refresh(elem);
}

function homeIntro()
{	
	if(skip == 1)
		return;
		
	renderFonts('#intro1', 'PD');
	renderFonts('#intro2', 'PD');	
	renderFonts('.navibutton', 'PD', true);	
	renderFonts('#teaserheader', 'PD');	
	renderFonts('#teasertext', 'PD');	
	renderFonts('#fullteaserheader', 'PD');
	renderFonts('#fullteasersubheader', 'PD');
	renderFonts('#footer .tools', 'Helv', true);
	renderFonts('#hl_header', 'Helv');
	renderFonts('#hl_button a', 'Helv');	
	
	$('.naviback').fadeTo(1, naviback);	
	$('.navibutton').fadeTo(1, navitext);	
	
	var url = window.location.href;
	if (url.indexOf("skipintro=1") != -1)
	{		
		skipIntro(0);		
		return;
	}
	else
	{
		$("#skip").show();
	}
	if (url.indexOf("showteaser=1") != -1)
	{
		skipIntro(1);
		return;
	}
	if (url.indexOf("dealersearch=1") != -1)
	{
		skipIntro(2);
		return;
	}
	activateSubnavi();	
	$("#intro1").fadeIn(1000, function() {setTimeout(showNext, 3000);});			
}

function loadImage(sName, sUrl)
{ 
    var elem = document.getElementById(sName);
    if (elem) elem.src = sUrl;
}

function unloadImage(sName)
{ 
    var elem = document.getElementById(sName);
    if (elem) elem.src = "/images/pds2/dummy.gif";
}

function showNext()
{
	if (skip == 1)
		return;	
	$("#intro1").fadeOut(1000, function() {$("#intro2").fadeIn(1000, function() {setTimeout(showImgs, 3000);});});	
	$("#header").slideDown(3000);	
}

function showImgs()
{
	if (skip == 1)
		return;
	$("#skip").hide();
	$("#intro2").fadeOut(2000);	
	$("#mainnavi").fadeIn(2000);
	images = $(".img247").length;
	//buildHotspots();
	setTimeout(cacheImages, 2000);	
}

//--------------------------------------------
// builds all Hotspots of all Images
//--------------------------------------------
function buildHotspots()
{
	hs1_1 = new Hotspot(175, 130, "intro-afterwork-p8801readingtool", "1", "1");
	hs1_2 = new Hotspot(330, 310, "intro-afterwork-dashboardtitanchronograph", "1", "2");
	hs1_3 = new Hotspot(785, 165, "intro-afterwork-p9521mobilephone", "1", "3");
	hs1_4 = new Hotspot(110, 430, "intro-afterwork-groovescufflinks", "1", "4");
	hs2_1 = new Hotspot(270, 230, "intro-business-tecflexfountainpen", "2", "1");
	hs2_2 = new Hotspot(380, 90, "intro-business-pandesklamp", "2", "2");
	hs2_3 = new Hotspot(610, 350, "intro-business-indicator", "2", "3");	
	hs3_1 = new Hotspot(483, 64, "intro-watersnow-p8471sunglasses", "3", "1");
	/*hs3_2 = new Hotspot(597, 112, "intro-watersnow-sailingjacketii", "3", "2");*/
	hs3_3 = new Hotspot(621, 241, "intro-watersnow-deckshortsii", "3", "3");
	hs3_4 = new Hotspot(638, 408, "intro-watersnow-horizonii", "3", "4");		
	/*hs4_1 = new Hotspot(420, 34, "intro-porschetarga-blousondouble", "4", "1");*/
	hs4_2 = new Hotspot(163, 215, "intro-porschetarga-cl2briefbagm", "4", "2");
	/*hs4_3 = new Hotspot(270, 428, "intro-porschetarga-shoestokyol2", "4", "3");*/
	hs5_1 = new Hotspot(380, 310, "intro-travel-frenchclassictrolley550", "5", "1");
	hs5_2 = new Hotspot(455, 100, "intro-travel-worldtimer", "5", "2");
	/*hs6_1 = new Hotspot(712, 94, "intro-board-blousondouble", "6", "1");*/
	hs6_2 = new Hotspot(573, 200, "intro-board-rattrapantelimitededition", "6", "2");
	hs6_3 = new Hotspot(780, 348, "intro-board-theessenceeaudetoilette", "6", "3");
	hs6_4 = new Hotspot(672, 369, "intro-board-p9522mobilephone", "6", "4");	
	hs6_5 = new Hotspot(382, 363, "intro-board-tecflexballpointpen", "6", "5");
	hs6_6 = new Hotspot(473, 374, "intro-board-functionalitykeyring", "6", "6");
	hs7_1 = new Hotspot(380, 185, "intro-sunglasses02-p8480sunglasses", "7", "1");
	hs7_2 = new Hotspot(380, 340, "intro-sunglasses02-jacket", "7", "2");
	hs8_1 = new Hotspot(670, 280, "intro-travel02-intro-travel-frenchclassictrolley550g", "8", "1");
	hs8_2 = new Hotspot(370, 250, "intro-travel02-frenchclassicbriefcasem", "8", "2");
	hs8_3 = new Hotspot(225, 370, "intro-travel02-mobilephonep9522", "8", "3");
	
	/* ============== Hotspots sind deaktiviert =========================== */	
	/*imgHotspots["img1"] = new Array(hs1_1, hs1_2, hs1_3, hs1_4);
	imgHotspots["img2"] = new Array(hs2_1, hs2_2, hs2_3);
	imgHotspots["img3"] = new Array(hs3_1, hs3_3, hs3_4);	
	imgHotspots["img4"] = new Array(hs4_2);	
	imgHotspots["img5"] = new Array(hs5_1, hs5_2);
	imgHotspots["img6"] = new Array(hs6_2, hs6_3, hs6_4, hs6_5, hs6_6);	
	imgHotspots["img7"] = new Array(hs7_1, hs7_2);	
	imgHotspots["img8"] = new Array(hs8_1, hs8_2, hs8_3);*/		
}

//-------------------------------------------------
// activates Hotspots of specific Image
//-------------------------------------------------

function activateHotspots(img)
{
	deactivateHotspots();
	$("#img" + img).addClass("active247");	
	var hs_id = "";
	
	/* ============== Hotspots sind deaktiviert =========================== */
	/*for(i = 0; i < imgHotspots["img" + img].length; i++)	
	{	
		hs_id = imgHotspots["img" + img][i].id;
		$("#content").append("<div id='" + hs_id + "' name='hs" + imgHotspots["img" + img][i].img + "_" + imgHotspots["img" + img][i].number + "' class='hotspotdiv'><img src='/images/pds2/Hotspot.png'/><div class='hotspot'></div></div>");
		$("#" + hs_id).css("left", imgHotspots["img" + img][i].x);
		$("#" + hs_id).css("top", imgHotspots["img" + img][i].y);		
	}*/
	
	$(".hotspotdiv").find('img').css({position: 'relative'});
	
	$(".hotspotdiv").hover(function() {		
	$(this).find('img').stop()
		.animate({			
			top: '-1px',
			left: '-2px',			
			width: '30px',
			height: '18px'	
		}, 100);
	}, function() {	
	$(this).find('img').stop()
		.animate({			
			top: '0',
			left: '0',
			width: '26px',
			height: '16px'
		}, 100);
	$(this).stop()
		.animate({
			marginTop: '0', 
			marginLeft: '0',
			top: (window[$(this).attr("name")].y) + "px",
			left: (window[$(this).attr("name")].x) + "px"
		}, 100);	
	});
	$(".hotspotdiv").click(function() {
		var id = $(this).attr("id");		
		$("#content .hotspot").fadeOut(1);
		$(this).stop()
		.animate({			
			marginTop: '0', 
			marginLeft: '0',
			height: '450px',
			width: '960px',
			top: '0',
			left: '0'		
		}, 100);
		$(this).find('img').stop()
		.animate({			
			width: '455px',
			height: '217px',
			top: '116px',
			left: '218px'
		}, 100, function(){				
				hsLayerShow(id);
			}		
		);		
	});
	showTeaser();
}

//--------------------------------------
// deactivates current Hotspots
//--------------------------------------

function deactivateHotspots()
{
	$(".hotspotdiv").remove();
}

//---------------------------
// show Hotspot Layer
//---------------------------

function hsLayerShow(id)
{
    hotspot = 1;	
	$("#hotlayer").fadeIn(50);
	$(".hl_back").fadeTo(1, 0.93);
	$(".hotspotdiv").fadeOut(1);	
	hideArrows(50);	
	$("#hotlayer").click(function(){
	    hotspot = 0;		
		$("#" + id).css({height: '25px', width: '40px'});		
		$("#hotlayer").fadeOut(50);
		$("#hl_text").html("");
		$("#hl_img").attr("src", "/images/PDS2/dummy.gif");
		$("#content .hotspotdiv").fadeIn(50);
		$("#content .hotspot").fadeIn(50);
		$("#hl_links").hide();		
		checkArrows(50);
	});	
	refreshFonts('#hl_header');
	refreshFonts('#hl_button a');	
	$("#productloader").show();
	getKBaseData(id);	
}

/*============================================================================*/
/*==================== FAKE WATCH LAYER BEGIN ================================*/
/*============================================================================*/


/*function closeFWWWindow() {
    $("#fwwlayer").fadeOut(100);
    $("#fwwlayer_back").fadeOut(100);
    $("#fwwlayer").empty();
}*/

function serializeXmlContent(content, defaultXml) {
    var contenttext = "";
    try {
        contenttext = new XMLSerializer().serializeToString(content);
    }
    catch (e) {
        try {
            contenttext = content.xml;
        }
        catch (e) {
            contenttext = defaultXml;
            return;
        }
    }
    return contenttext;
}

function getFWWKBaseData(id) {
    // holt die Inhalte immer aus dem Pool 'germanypds2' in der jeweiligen Sprache
    url = "/Kbase.aspx?pool=germanypds2&type=kbase&id=" + id + "&lang=" + CURRENTLANGUAGE;

    $.get(url, function (data) {
        var xml = $(data).find('content');
        var h2 = $(xml).find('h2');
        var img = $(h2).find('img');
        var title = $(img).attr('alt');

        var div = $(xml).find("div[class='knowledgebaseWrapper']");
        var contentdiv = $(div).find("div[class='innerContent']");
        var firstcontent = contentdiv[0];

        titletext = title;
        contenttext = serializeXmlContent(firstcontent, '<div id="innerContent">no content found...</div>');
        contenttext = '<span class="header">' + titletext + '</span>' + contenttext;
        $("#fwwlayer").empty();
        $("#fwwlayer").html(contenttext);
        //$("#fwwlayer").prepend('<div class="closeWindowButton" onclick="closeFWWWindow();"><img src="/images/PDS2/hl_close.jpg" id="closeBtn"></div>')
        //renderFonts('#fwwlayer .header', 'Helv');
        //$("#fwwlayer_back").show();
        //$("#fwwlayer_back").fadeTo(1, 0.93);
        //$("#fwwlayer").fadeIn(100);
		Shadowbox.open({				    
					content:	$("#fwwlayer").html(),
					player: 	"html",
					height: 	220
				});		
    });
}

/*============================================================================*/
/*==================== FAKE WATCH LAYER END ==================================*/
/*============================================================================*/

function getKBaseData(id)
{	
    // holt die Inhalte immer aus dem Pool 'germanypds2' in der jeweiligen Sprache
	url = "/Kbase.aspx?pool=germanypds2&type=kbase&id=" + id + "&lang=" + CURRENTLANGUAGE;	
	
	$.get(url, function(data){		
		var xml = $(data).find('content');		
		var h2 = $(xml).find('h2');
		var img = $(h2).find('img');
		var title = $(img).attr('alt');
		
		var imgdiv = $(xml).find("div[class='introImage']");
		var image = $(imgdiv).find('img').attr("src");		
		
		var div = $(xml).find("div[class='knowledgebaseWrapper']");
		var contentdiv = $(div).find("div[class='innerContent']");
		var content = $(contentdiv).find("ul");		
		var firstcontent = content[0];		
		
		var contenttext = "";
		try
		{
		    contenttext = new XMLSerializer().serializeToString(firstcontent);
		}
		catch(e)
		{
		    try
		    {
		        contenttext = firstcontent.xml;
		    }
		    catch(e)
		    {
		        $("#productloader").hide();
		        $("#hl_text").html("<div id='hl_header'>no content found...</div>");
		        return;
		    }
		}
		var contentlink = $(contentdiv).find("p").find("a");
				    
		$(contentlink).attr("href", "/" + currentalias + "/" + CURRENTLANGUAGE + $(contentlink).attr("href"));		
		
		var urls = [ image ];
		$.preload( urls, {			
			onComplete: function(data) { fadeInLayerContent(image, title, contenttext, contentlink); }		
		});		
	});
}

function fadeInLayerContent(image, title, contenttext, contentlink)
{
	$("#hl_img").hide();
	$("#hl_img").attr("src", image);
	$("#hl_img").fadeIn();
	$("#hl_text").html("<div id='hl_header'>" + title + "</div>" + contenttext);
	$("#hl_button").html($(contentlink).outerHTML());	
	$("#hl_links").fadeIn();
	refreshFonts('#hl_header');	
	$("#productloader").hide();
}

function showFooter()
{
	if(ie6 == 1)
		return;
	else if(skip==0)	
		$("#footer").slideDown(500);	
	else
		$("#footer").show();
	calculateNavi();
	$("#tool1").click(function(){	    
		showDealerSearch();
	});
	$("#tool2").click(function(){	    
		showQuestion();
	});
	$("#tool3").click(function(){	    
		showNewsletter();
	});
	$("#tool4").click(function(){	    
		showSuggestion();
	});		
}

function showTeaser()
{
	if(teaser == 1) return;
	if($("#teaser[class='visible']").length > 0)
	{		
		sas_tmstp = Math.round(Math.random()*10000000000);
		$("body").append('<iframe src="http://www3.smartadserver.com/track/ift.asp?68558;7883;'+sas_tmstp+';[value];[reference]" width="1" height="1" frameborder="0">  </iframe>');
		
		var lang = CURRENTLANGUAGE;
		var buttons = [ 'btn_mehrerfahren_' + lang + '.jpg', 'btn_moreinfo_' + lang + '.jpg', 'btn_ansicht_schliessen_' + lang + '.jpg', 'bg_state_03.jpg' ];
		$.preload( buttons, {
			base: '/images/pds2/teaser/',		
			onComplete: function(data) 
			{ 
				$("#teaserbutton").css('background-image', 'url(../../images/pds2/teaser/btn_mehrerfahren_' + lang + '.jpg)');
				//$("#teasershopbutton").css('background-image', 'url(../../images/pds2/teaser/btn_moreinfo_' + lang + '.jpg)');				
				//$("#teasershopbutton").css('background-image', 'url(../../images/pds2/teaser/btn_checkin_' + lang + '.jpg)');
				$("#productsteaserbutton").css('background-image', 'url(../../images/pds2/teaser/btn_moreinfo_' + lang + '.jpg)');
				//$("#productsteaserbutton").css('background-image', 'url(../../images/pds2/teaser/btn_checkin_' + lang + '.jpg)');
				$("#closeteaserbutton").css('background-image', 'url(../../images/pds2/teaser/btn_ansicht_schliessen_' + lang + '.jpg)');
			}		
		});		
		
	    renderFonts('#teaserbutton', 'Helv');	
	    $("#teaser").slideDown(500);
		$("#teaserarrow").stop(true, true).fadeIn(500);		
    	
	    $("#teaser").hover(function(){
		    $("#teaser").stop().animate({
			    "height" : "436px"
		    }, 1000, fillTeaser());
		    $(".hotspotdiv").fadeOut(50);	
		    hideArrows(50);
	    }, function(){
		    $("#teaser").stop().animate({
			    "height" : "49px"
		    }, 1000, emptyTeaser());		
		    checkHotspots(200);	
		    checkArrows(200);	
	    });
    	
	    $("#teaserbutton").click(showFullTeaser);
		//$("#teasershopbutton").click(function(){
			/*if(currentalias == "germany")
				window.open('http://berlin.porsche-design.de/germanypds/');				
			else
				window.open('http://berlin.porsche-design.de/europepds/');*/
			//window.open('http://itunes.com/app/porschedesign');
		//});
	}
}

function showTeaserNow()
{
	$("#teaserheader").hide();
	$("#teasertext").hide();
	$("#teaser").css({
			"width" : "950px",
			"height" : "436px"
		});
	$("#teaser").show();
	fillFullTeaser();
	$("#teaser").unbind('mouseenter mouseleave'); 
}

function fillTeaser()
{
	loadImage("teaserimg", "/images/pds2/teaser.jpg");
	//$("#teaserimage").stop(true, true).fadeIn(500);
	$("#teaserbutton").stop(true, true).fadeIn(500);
	$("#teasershopbutton").stop(true, true).fadeIn(500);
	$("#teaserarrow").stop(true, true).fadeOut(500);	
}

function emptyTeaser()
{
	$("#teaserimage").stop(true, true).fadeOut(500);
	$("#teaserbutton").stop(true, true).fadeOut(500);
	$("#teasershopbutton").stop(true, true).fadeOut(500);
	$("#teaserarrow").stop(true, true).fadeIn(500);	
}

function showFullTeaser()
{	
	var lang = CURRENTLANGUAGE;
	$("#teaser").unbind('mouseenter mouseleave'); 
	$("#teaserimage").fadeOut(1000);
	$("#teaserbutton").fadeOut(1000);
	$("#teasershopbutton").fadeOut(1000);
	$("#teaserheader").fadeOut(1000);
	$("#teasertext").fadeOut(1000);
    // (SK) take background image from fullteaser image
	//$("#teaser").css('background-image', 'url(../../images/pds2/teaser/bg_state_03.jpg)');	
	$("#teaser").css('background-image', 'url(' + $('#hometeaser-vkr-full').attr('src') + ')');	
	$("#teaser").stop().animate({
			"width" : "950px"
		}, 1000, fillFullTeaser);
}

function fillFullTeaser()
{
	//loadImage("fullteaserimg", "/images/pds2/fullteaser.jpg");
	//$("#fullteaserimage").fadeIn(100);
	$("#fullteaserheader").fadeIn(100);
	$("#fullteasersubheader").fadeIn(100);
	$("#fullteasertext").fadeIn(100);
	//renderFonts('#closeteaserbutton', 'Helv');
	//renderFonts('#productsteaserbutton', 'Helv');	
	$("#closeteaserbutton").click(closeFullTeaser);	
	$("#closeteaserbutton").fadeIn(100);	
	$("#productsteaserbutton").fadeIn(100);
	$("#productsteaserbutton").click(function(){
	/*
		if(currentalias == "germany")
				window.open('http://berlin.porsche-design.de/germanypds/');				
			else
				window.open('http://berlin.porsche-design.de/europepds/');
	*/
		window.location.href = window.location.protocol + '//' + window.location.host + "/" + window.currentalias + "/" + window.CURRENTLANGUAGE + '/products/p9000electronics/communication/smartphone/4046901677626/';
				
		/*window.open('http://www.formandfunction-thebattle.com/');*/
	});
}

function closeFullTeaser()
{
	teaser = 0;
	$("#fullteaserimage").fadeOut(100);
	$("#fullteaserheader").fadeOut(100);
	$("#fullteasersubheader").fadeOut(100);
	$("#fullteasertext").fadeOut(100);
	$("#closeteaserbutton").fadeOut(100);
	$("#productsteaserbutton").fadeOut(100);	
	$("#teaser").fadeOut(function(){
		$("#teaser").css({"height" : "49px", "width" : "230px", "background-image" : "url(../../images/pds2/teaser/bg_state_02.jpg)"});
		$("#teaserheader").show();
		$("#teasertext").show();
		showTeaser();
	});
	checkHotspots(200);	
	checkArrows(200);	
}

function cacheImages()
{
    showFooter(); 
    showPreloader();
    
    //left Pixel from allimgs
    var lp = getRandomPixel();
    	   
    alttags = new Array();
    elements = new Array();    
    $("#allimgs .img247").each(function()
    {
        alttags.push($(this).attr("alt")); 
        elements.push($(this));       
    });
    var randomimg = new Array();
    randomimg.push(alttags[allimg - 1]);
    
    $.preload( randomimg, {
        onComplete: function(data) {
		    
		    elements[allimg - 1].attr("src", elements[allimg - 1].attr("alt"));
		    elements[allimg - 1].attr("alt", "");
		    go(data, lp); 
		}
    });		
}

function go(data, lp)
{	
	if (data.loaded == data.total) 
	    zoomImages(lp);	
}

function zoomImages(lp)
{    
    hidePreloader();      
	var duration = 1000;
	if(skip == 1)
		duration = 1;
	var speed = "easeInExpo";	
	$("#allimgs").animate(
		{ left: lp + "px",
		  top: "0px"
		  }, {
		queue: false,
		duration: duration,
		easing: speed		
		}).fadeIn(duration, function(){activateHotspots(allimg);});
	$("#allimgs > img").animate(
		 { width: "960px",
		   height: "475px"}, {			   
		duration: duration,
		easing: speed		
		});
	setTimeout("calculateMeta()", 1000);	
	preloadAll();		
}

function preloadAll()
{    
    $.preload( alttags, {
		onComplete: function(data) {
		    if(data.index != (allimg - 1))
		    {		    
		        elements[data.index].attr("src", elements[data.index].attr("alt"));
		        elements[data.index].attr("alt", "");		        
		    }
		    checkComplete(data);		    
		}		
	});
}

function checkComplete(data)
{
    if (data.loaded == data.total)
        showArrows();
}

// Arrows beim Start einblenden
function showArrows()
{
	if(skip == 0)
	{		
		checkArrows(2000);		
		$("#skip").hide();
	}
	else
	{		
		checkArrows(1);		
		checkHotspots(1);
	}
	
	$("#left").click(moveToLeft);
	$("#right").click(moveToRight);
	
	$("#left").hover(function(){
	    $(".hotspotdiv").fadeOut(50);	
		$("#allimgs").stop().animate(		
			{ left: "-" + (((allimg - 1) * 960) - 100)}, 500			
		);
	}, function(){
		$("#allimgs").stop().animate(
			{ left: "-" + ((allimg - 1) * 960)}, 500			
		);
		checkHotspots(500);
	});
	
	$("#right").hover(function(){
	    $(".hotspotdiv").fadeOut(50);	
		$("#allimgs").stop().animate(		
			{ left: "-" + (((allimg - 1) * 960) + 100)}, 500			
		);
	}, function(){
		$("#allimgs").stop().animate(
			{ left: "-" + ((allimg - 1) * 960)}, 500			
		);
		checkHotspots(500);
	});			
}

function hideArrows(time)
{
	$(".arrow").fadeOut(time);
	rightarrow = 0;
	leftarrow = 0;
}

// Arrows während der Navigation ein- bzw. ausblenden
function checkArrows(time)
{	
	if(allimg == images && rightarrow == 1)
	{
		$("#left").fadeIn(time);
		$("#right").hide();
		rightarrow = 0;
	}
	else if(allimg == images && leftarrow == 0)
	{
		$("#left").fadeIn(time);		
		leftarrow = 1;
	}
	else if(allimg == 1 && leftarrow == 1)
	{
		$("#right").fadeIn(time);
		$("#left").hide();
		leftarrow = 0;
	}
	else if(allimg == 1 && rightarrow == 0)
	{
		$("#right").fadeIn(time);		
		rightarrow = 1;
	}
	else if(allimg > 1 && allimg < images)
	{
		$(".arrow").fadeIn(time);
		rightarrow = 1;
		leftarrow = 1;
	}	
}

// Überprüfen ob Hotspot noch geöffnet ist - ansonsten die Spots einblenden
function checkHotspots(time)
{
    if(hotspot == 0)
        $(".hotspotdiv").fadeIn(time);
}

function moveToRight()
{
    $("#img" + allimg).removeClass("active247");	
	$("#left").show();	
	leftarrow = 1;
	var left = "-" + (allimg * 960);
	allimg++;
	$("#allimgs").stop().animate(
		{ left: left 
		  }, {		
		duration: 500/*,
		easing: "easeOutBack"*/		
		});	
	activateHotspots(allimg);
	checkArrows(200);	
}

function moveToLeft()
{
    $("#img" + allimg).removeClass("active247");
	$("#right").show();
	rightarrow = 1;
	allimg--;	
	checkArrows(200);	
	
	var left = "-" + ((allimg - 1) * 960);
	$("#allimgs").stop().animate(
		{ left: left 
		  }, {		
		duration: 500/*,
		easing: "easeOutBack"*/		
		});	
	activateHotspots(allimg);	
}

function getRandomPixel()
{
	// eigentlich für 8 Bilder gemacht, derzeit sind aber nur 4 Bilder auf der Startseite (sekundenzahl ändern wenn sich anzahl der bilder ändert)
	
	var random = 0;
	var now = new Date();
	var seconds = now.getSeconds();	
	if(seconds > 0 && seconds < 16)
	{
		random = -960;
		allimg = 2;
	}
	/*else if(seconds > 13 && seconds < 21)
	{
		random = -3840;
		allimg = 5;
	}*/
	else if(seconds > 15 && seconds < 31)
	{
		random = 0;
		allimg = 1;
	}
	else if(seconds > 30 && seconds < 46)
	{
		random = -1920;
		allimg = 3;
	}
	/*else if(seconds > 35 && seconds < 44)
	{
		random = -6720;
		allimg = 8;
	}
	else if(seconds > 43 && seconds < 51)
	{
		random = -4800;
		allimg = 6;
	}
	else if(seconds > 50 && seconds < 60)
	{
		random = -5760;
		allimg = 7;
	}*/
	else
	{
		random = -2880;
		allimg = 4;
	}
	return random;
}

//window.onresize = buildNew;

function buildNew()
{
   var top = parseInt(getViewPort("height")) / 2 - 50;
   top2 = parseInt(getViewPort("height")) / 2 - 155;
   left2 = parseInt(getViewPort("width")) / 2 - 200;
   
   $("#leftimg").css("top", top + "px");
   $("#left").css("display","block");
   $("#rightimg").css("top", top + "px");
   $("#right").css("display","block");   
   $("#article").css("top", top2 + "px");
   $("#article").css("left", left2 + "px");
   if(ismiddle)
   {
		$(".active").css("top", top2 + "px");
		$(".active").css("left", left2 + "px");
	}
	xborder = parseInt(getViewPort("width")) - 500;   
}

function getViewPort(viewport)
{
 var viewportwidth;
 var viewportheight;
 
 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
 }
 
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

 else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
 }
 
 // older versions of IE
 
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
 }
  
 if (viewport == "width")
	return viewportwidth
 if (viewport == "height")
	return viewportheight;
}

function showText()
{
	$("#text").fadeIn(1000, showSubtext);	
}

function showSubtext()
{
	$(".subtext").fadeIn(1000);
	showArticleFromLeft(1);
}

function showArticleFromLeft(num)
{	
	if(num > articles) num = 1;
	$("#article" + num).css({left: "-410px"});

	left2plus = "67px";
	left2minus = "54px";
	$("#article" + num).css("top", "36px");
	$("#article" + num).css("opacity", 0);
	
	$("#article" + num).animate({opacity: 1}, {queue: false, duration: 370, easing: 'easeInExpo'});
	$("#article" + num).animate({left:left2plus},400,"swing").animate({left:left2minus},200).animate({left:"57px"},100);	
	ismiddle = num;	
	$("#article" + num).removeClass("inactive");
	$("#article" + num).addClass("active");
	activearticle = $("#article" + num).attr('id');
	$("#product ." + activearticle).fadeIn();
	$(".productimg.active").show();	
	if(detailDataStruct["products"][detailDataStruct["currentIndex"]].zoom != "")
	{
		$("#zoom").fadeIn( 200);
		/*LazyLoad.css('/Script/PDS2/shadowbox/shadowbox.css');
		LazyLoad.js('/Script/PDS2/shadowbox/shadowbox.js', function(){
			Shadowbox.init({handleOversize: "drag"});
			$("#zoom").fadeIn( 200);
		});*/		
	}
	checkVariants();
	updatePreviews();	
}

function showArticleFromRight(num)
{	
	if(num == 0) num = articles;
	$("#article" + num).css({left: "718px"});

	left2plus = "47px";
	left2minus = "60px";
	$("#article" + num).css("top", "36px");
	$("#article" + num).css("opacity", 0);
	
	$("#article" + num).animate({opacity: 1}, {queue: false, duration: 370, easing: 'easeInExpo'});
	$("#article" + num).animate({left:left2plus},400,"swing").animate({left:left2minus},200).animate({left:"57px"},100);	
	ismiddle = num;	
	$("#article" + num).removeClass("inactive");
	$("#article" + num).addClass("active");
	activearticle = $("#article" + num).attr('id');
	$("#product ." + activearticle).fadeIn();
	$(".productimg.active").show();
	if(detailDataStruct["products"][detailDataStruct["currentIndex"]].zoom != "")
	{
		$("#zoom").fadeIn( 200);		
		/*LazyLoad.css('/Script/PDS2/shadowbox/shadowbox.css');
		LazyLoad.js('/Script/PDS2/shadowbox/shadowbox.js', function(){
			Shadowbox.init({handleOversize: "drag"});
			$("#zoom").fadeIn( 200);
		});*/
	}
	checkVariants();
	updatePreviews();	
}

// different Mouseposition-dependant actions
function actionOnMouseMove(x,y)
{
	var top = $('#wrapper').offset().top;
	var left = $('#wrapper').offset().left;
	
	var tborder = top;
	var lborder = left;
	var rborder = left + 960;
	var bborder = top + 547;
	
	var navi_tborder = tborder + 150;
	
	if(x > lborder && x < rborder)
	{
		if(y < navi_tborder && y > top && near == 0)
		{
			$('.navibutton').stop().fadeTo(400, 1);
			$('.naviback').stop().fadeTo(400, 1);
			$(".navibutton").addClass("near");
			$(".naviback").addClass("near");
			refreshFonts('.navibutton');			
			near = 1;
			$(".navi_trenner").hide();
		}
		else if(near == 1 && y > navi_tborder && subnaviopen == 0 || near == 1 && y < top && subnaviopen == 0)
		{
			$('.navibutton').stop().fadeTo(400, navitext);
			$('.naviback').stop().fadeTo(400, naviback);
			$(".navibutton").removeClass("near");
			$(".naviback").removeClass("near");
			refreshFonts('.navibutton');			
			near = 0;
			$(".navi_trenner").show();
		}		
	}
	else
	{
		if(near == 1)
		{
			$('.navibutton').stop().fadeTo(200, navitext);
			$('.naviback').stop().fadeTo(200, naviback);
			near = 0;
		}
		$(".navibutton").removeClass("near");
		$(".navibutton").removeClass("active");
		$(".naviback").removeClass("near");
		$(".naviback").removeClass("active");
		refreshFonts('.navibutton');		
		$(".navi_trenner").show();
	}	
}

function rightClick(num)
{	
	$("#zoom").fadeOut( 200);	
	$(".active").stop().animate(
		{ left: "-13px" }, {
		duration: 300,
		easing: 'easeInQuart'
		}).animate(
		{ opacity: 0 }, {
		queue: false,
		duration: 380,
		easing: 'easeInExpo'
		}).animate(
		{ left: "718px" }, {
		duration: 600,
		easing: 'easeOutQuart'
		});	
	$(".active").css({opacity: 1});
	setTimeout(function() {
		$("#article" + num).removeClass("active");
		$("#article" + num).addClass("inactive");
		$("#article" + num).hide();
		showArticleFromLeft(num + 1);
	}, 1000);
}

function leftClick(num)
{
	$("#zoom").fadeOut( 200);
	$(".active").stop().animate(
		{ left: "127px" }, {		
		duration: 300,
		easing: 'easeInQuart'
		}).animate(
		{ opacity: 0 }, {
		queue: false,
		duration: 380,
		easing: 'easeInExpo'
		}).animate(
		{ left: "-410px" }, {			
		duration: 600,
		easing: 'easeOutQuart'
		});	
	$(".active").css({opacity: 1});	
	setTimeout(function() {
		$("#article" + num).removeClass("active");
		$("#article" + num).addClass("inactive");
		$("#article" + num).hide();
		showArticleFromRight(num - 1);
	}, 1000);
}

function products()
{
    if (timeout != -1) 
	{
	    clearTimeout(timeout);
	}
	if (subnaviopen == 0)
	{
        navito = setTimeout(products_hover, 200);
    }
    else
    {
        products_hover();
    }
}

function products_hover()
{	
	$("#studio").removeClass("active");
	$("#studiodiv").removeClass("active");
	$("#company").removeClass("active");
	$("#companydiv").removeClass("active");
	$("#porschedesignshop").removeClass("active");
	$("#porschedesignshopdiv").removeClass("active");	
	$("#products").addClass("active");
	$("#productsdiv").addClass("active");
	$("#subnavi li a").css({color: '#dcdcdc'});	
	$(".hotspotdiv").fadeOut(50);	
	hideArrows(50);
	hideMatrixArrows(50);
	$("#subnavi").slideDown("fast");
	$(".subnavi_content").hide();
	$(".subsubnavi_content").hide();
	$(".subsubsubnavi_content").hide();
	$("#subnavi_products .subnavi_content").show();
	subnavi = "products";
	subnaviopen = 1;
	refreshFonts('.navibutton');	
}

function products_out()
{
    timeout = setTimeout(hideSubnavi, timeoutTime);
    if (navito != -1) 
    {
        clearTimeout(navito);        
    }    
}

function studio()
{
    if (timeout != -1) 
	{
	    clearTimeout(timeout);
	}
	if (subnaviopen == 0)
	{
        navito = setTimeout(studio_hover, 200);
    }
    else
    {
        studio_hover();
    }	
}

function studio_hover()
{	
	$("#products").removeClass("active");
	$("#productsdiv").removeClass("active");
	$("#company").removeClass("active");
	$("#companydiv").removeClass("active");
	$("#porschedesignshop").removeClass("active");
	$("#porschedesignshopdiv").removeClass("active");	
	$("#studio").addClass("active");
	$("#studiodiv").addClass("active");
	$("#subnavi li a").css({color: '#dcdcdc'});	
	$(".hotspotdiv").fadeOut(50);	
	hideArrows(50);
	hideMatrixArrows(50);
	$("#subnavi").slideDown("fast");
	$(".subnavi_content").hide();
	$(".subsubnavi_content").hide();
	$(".subsubsubnavi_content").hide();
	$("#subnavi_studio").show();
	subnavi = "studio";
	subnaviopen = 1;
	refreshFonts('.navibutton');	
}

function studio_out()
{		
	timeout = setTimeout(hideSubnavi, timeoutTime);
	if (navito != -1) 
    {
        clearTimeout(navito);        
    } 
}

function company()
{
    if (timeout != -1) 
	{
	    clearTimeout(timeout);
	}
	if (subnaviopen == 0)
	{
        navito = setTimeout(company_hover, 200);
    }
    else
    {
        company_hover();
    }	
}

function company_hover()
{	
	$("#studio").removeClass("active");
	$("#studiodiv").removeClass("active");
	$("#products").removeClass("active");
	$("#productsdiv").removeClass("active");
	$("#porschedesignshop").removeClass("active");
	$("#porschedesignshopdiv").removeClass("active");	
	$("#company").addClass("active");
	$("#companydiv").addClass("active");
	$("#subnavi li a").css({color: '#dcdcdc'});	
	$(".hotspotdiv").fadeOut(50);	
	hideArrows(50);
	hideMatrixArrows(50);
	$("#subnavi").slideDown("fast");
	$(".subnavi_content").hide();
	$(".subsubnavi_content").hide();
	$(".subsubsubnavi_content").hide();
	$("#subnavi_company").show();
	subnavi = "company";
	subnaviopen = 1;
	refreshFonts('.navibutton');	
}

function company_out()
{		
	timeout = setTimeout(hideSubnavi, timeoutTime);
	if (navito != -1) 
    {
        clearTimeout(navito);        
    }	
}

function porschedesignshop()
{
    if (timeout != -1) 
	{
	    clearTimeout(timeout);
	}
	if (subnaviopen == 0)
	{
        navito = setTimeout(porschedesignshop_hover, 200);
    }
    else
    {
        porschedesignshop_hover();
    }
}

function porschedesignshop_hover()
{	
	$("#studio").removeClass("active");
	$("#studiodiv").removeClass("active");
	$("#company").removeClass("active");
	$("#companydiv").removeClass("active");
	$("#products").removeClass("active");
	$("#productsdiv").removeClass("active");
	$("#porschedesignshop").addClass("active");
	$("#porschedesignshopdiv").addClass("active");
	$("#subnavi li a").css({color: '#dcdcdc'});	
	$(".hotspotdiv").fadeOut(50);	
	//hideArrows(50);
	//hideMatrixArrows(50);
	//$("#subnavi").slideDown("fast");
	$(".subnavi_content").hide();
	$(".subsubnavi_content").hide();
	$(".subsubsubnavi_content").hide();
	//$("#subnavi_porschedesignshop").show();
	//subnavi = "porschedesignshop";
	//subnaviopen = 1;
	//refreshFonts('.navibutton');	
	
    timeout = setTimeout(hideSubnavi, timeoutTime);
    if (navito != -1) 
    {
        clearTimeout(navito);        
    }  	
}

function porschedesignshop_out()
{
    timeout = setTimeout(hideSubnavi, timeoutTime);
    if (navito != -1) 
    {
        clearTimeout(navito);        
    }    
}

function subnaviover()
{
	if (timeout != -1) 
	{ 
	    clearTimeout(timeout); 
	}	
}

function subnaviout()
{	
	//if (timeout != -1) 
	//{ 
	//    clearTimeout(timeout); 
	//}
    timeout = setTimeout(hideSubnavi, timeoutTime);	
}

function hideSubnavi()
{
	subnaviopen = 0;
	$('.navibutton').fadeTo(200, navitext);
	$('.naviback').fadeTo(200, naviback);
	$(".navibutton").removeClass("near");
	$(".naviback").removeClass("near");
	$(".navibutton").removeClass("active");
	$(".naviback").removeClass("active");
	$(".navi_trenner").show();
	$("#subnavi").slideUp("fast", function(){
		$(".subsubnavi_content").hide();
		$(".subsubsubnavi_content").hide();
	});
	checkHotspots(200);	
	checkArrows(200);
	checkMatrixArrows(200)
	refreshFonts('.navibutton');	
}

function skipIntro(mode)
{	
	if(mode == 1)
	{
		showTeaserNow();
		teaser = 1;
	}
	if(mode == 2)
	{
		showDealerSearch();
	}
	else if (mode == 3)
	{
		$("#header").show();
		return;
	}
	skip = 1;
	$("#header").show();
	$('.naviback').fadeTo(1, naviback);
	$('.navibutton').fadeTo(1, navitext);		
	$("#mainnavi").show();
	images = $(".img247").length;
	buildHotspots();
	cacheImages();
	$("#intro1").hide();
	$("#intro2").hide();
	$("#skip").hide();
	activateSubnavi();		
}

function defaultState()
{
	$("#skip").hide();
	$("#header").show();
	
	if(ie6 == 1)
		return;
	
	$("#footer").show();
	renderFonts('.navibutton', 'PD', true);	
	renderFonts('#product .productname', 'PD');	
	renderFonts('.h1', 'PD');	
	renderFonts('#footer .tools', 'Helv', true);
	$('.naviback').fadeTo(1, naviback);	
	$('.navibutton').fadeTo(1, navitext);			
	$("#mainnavi").show();	
	//$("#meta").show();
	activateSubnavi();
	$('.tooltip').hover(
		function () {
        showToolTip($(this).html());
      }, 
      function () {
        hideToolTip();
      }
	);
	calculateNavi();
	calculateMeta();
	
	$("#tool1").click(function(){	    
		showDealerSearch();
	});
	$("#tool2").click(function(){	    
		showQuestion();
	});
	$("#tool3").click(function(){	    
		showNewsletter();
	});
	$("#tool4").click(function(){	    
		showSuggestion();
	});				
}

function calculateMeta()
{
    $("#meta").fadeIn("fast");
    var offset = $("#wrapper").offset();
	var metawidth = document.getElementById("meta").offsetWidth;
	var lmargin = offset.left + 935 - metawidth;
	$("#meta").css("left", lmargin);
	
	$(window).bind("resize", function(){
	    var offset = $("#wrapper").offset();
	    var metawidth = document.getElementById("meta").offsetWidth;
	    var lmargin = offset.left + 935 - metawidth;
	    $("#meta").css("left", lmargin);
	});	
}

function calculateNavi() 
{
	var productswidth = document.getElementById("products").offsetWidth;
	$("#productsdiv").css("width", productswidth);
	var studiowidth = document.getElementById("studio").offsetWidth;
	$("#studiodiv").css("width", studiowidth);
	var companywidth = document.getElementById("company").offsetWidth;
	$("#companydiv").css("width", companywidth);
	var porschedesignshopwidth = document.getElementById("porschedesignshop").offsetWidth;
	$("#porschedesignshopdiv").css("width", porschedesignshopwidth);
	var restwidth = 960 - productswidth - studiowidth - companywidth - porschedesignshopwidth;
	$("#mainnavi_rest").css("width", restwidth - 2);
	$("#mainnavi_restdiv").css("width", restwidth);	
	$("#trenner_1").css("left", productswidth - 1);
	$("#trenner_2").css("left", productswidth + studiowidth - 7);
	$("#trenner_3").css("left", productswidth + studiowidth + companywidth - 13);
	$("#trenner_4").css("left", productswidth + studiowidth + companywidth + porschedesignshopwidth - 19);
	$("#navi_trenner").show();	
}

function showToolTip(tip)
{
	getKBaseData(id, img);
}

function updatePreviews()
{
	var articlescount = $("#product .productimg").length;
	
	// update last preview
	var last = ismiddle - 1;
	if(last == 0) last = articlescount;
	var test = $("#article" + last).find('img');
	if(test.length > 0)
		$("#prevleft").find('img').attr('src', $("#article" + last).find('img').attr('src').replace(/filetype=normal/, 'filetype=productmatrix'));
	else
		$("#prevleft").find('img').attr('src', '/images/pds2/no_picture.png');	
	$("#prevleft_text").text($(".article" + last + ".productname").text().replace(/ß/g, 'P´'));
	
	// update next preview
	var next = ismiddle + 1;
	if(next > articlescount) next = 1;
	var test = $("#article" + next).find('img');
	if(test.length > 0)
		$("#prevright").find('img').attr('src', $("#article" + next).find('img').attr('src').replace(/filetype=normal/, 'filetype=productmatrix'));
	else
		$("#prevright").find('img').attr('src', '/images/pds2/no_picture.png');
	$("#prevright_text").text($(".article" + next + ".productname").text().replace(/ß/g, 'P´'));
}

function showLastPreview()
{
	$("#prevleft").show();
}

function showNextPreview()
{	
	$("#prevright").show();
}

function matrix()
{	
	setupMatrixArrows();
	bindEffect();
}

function detail()
{
	if(ie6 == 1)
		return;	
	
	LazyLoad.js('/Script/PDS2/ui.selectmenu.js');	
	
    isProduct = 1;    
    
	var infoheight = 0;
	var openbasket = 0;
	variantdropdowns = 0;
	
	//renderFonts('#product .productprice', 'PD');
	renderFonts('#infolist .liHeader', 'Helv');
	renderFonts('.actionbutton', 'Helv');
	renderFonts('#basketHeader', 'Helv');
	
	$("#infolist").accordion({ header: '.liHeader', collapsible: true, active: false, fillSpace: true });
	// wenn im xslt schon alle Daten fertig geladen wurden, dann ruf finishPageload auf. Ansonsten warte noch 2 Sekunden
	if(xsltvar != 0) 
	{
		finishPageload(xsltvar);		
	}
	else 
	{
		window.setTimeout( function(){finishPageload(xsltvar);}, 2000);		
	}		
		
	/*$("#add2basket").click(function(){	    
	    
		var pool = CURRENTPOOL;
		var language = CURRENTLANGUAGE;
		
		var currentProduct = detailDataStruct.products[detailDataStruct.currentIndex];
		var articleid = currentProduct.orderId;
		var variantid = "";
		if(currentProduct.variants.length > 0)
			variantid = currentProduct.variants[currentProduct.currentVariant].orderId;
		var url = "/Add2Basket.aspx?pool=" + pool + "&lang=" + language + "&articleid=" + articleid + "&variantid=" + variantid;		
		
		var response;
	
		$.get(url, function(data){
			response = data;
			
			// hier wird der Warenkorb neu erstellt
			LoadPersonalizedContent();				
		});	
	});*/
	
	$("#shopteaser").click(function(){
		if(checkAvailability() == "true")
		{
			var shopurl = getShopurl();							
						
			//$("#shopteaser").show();				
			//$("#tool5").find('a').attr('href', shopurl);
			window.open(shopurl);
		}	
	});
	
	$("#button2").click(function(){	    
		showDealerSearch2();        
	});
	
	var detailText = $("#detailContent").html();

	var fwwText = $("#fwwtext").html();
	if (detailText.indexOf('[FWW]') >= 0) {
	    detailText = detailText.replace("[FWW]", '<a href="javascript:openFWW()" class="fwwlink">' + fwwText + '</a>');
	    $("#product").prepend('<div id="fwwlayer_back"></div>');
	    $("#product").prepend('<div id="fwwlayer"></div>');
	}

	openFWW = function (e) {
	    getFWWKBaseData("fakewatchwarninglayer");
		renderFonts('#sb-player .header', 'Helv');
	}
	
	var detailSplit = detailText.split("[NC]");
	var newDetailText = "<ul class='paging'>";
	
	for(var i=0; i < detailSplit.length; i++)
	{
		newDetailText += "<li>" + detailSplit[i] + "</li>";		
	}
	newDetailText += "</ul>";
	$("#detailContent").html(newDetailText.replace(/\[BR\]/g, "<br/>"));
	
	$("ul.paging").quickPager();
		
	$("#infolist .liHeader").click(function(){
	    refreshFonts("#infolist .liHeader");		
		if (openbasket == 1)
		{
			$("#info").animate({height : infoheight}, 100);
			openbasket = 0;
			basketClose();
		}
	});
	$("#last img").hover(
	function () {	
		this.src = this.src.replace("_out","_over");
		showLastPreview();		
	},
	function () {
		this.src = this.src.replace("_over","_out");
		$("#prevleft").hide();
	});
	$("#next img").hover(
	function () {	
		this.src = this.src.replace("_out","_over");
		showNextPreview();		
	},
	function () {
		this.src = this.src.replace("_over","_out");
		$("#prevright").hide();
	});
		
	$(".highlight").hover(
	function () {	
		$(this).addClass('highlightOver');	
	},
	function () {
		$(this).removeClass('highlightOver');
	});
	
	articles = $("#product .productimg").length;
	
	lastclick = function(e)
	{
		unbindClicks();
		
		 $("#infolist").accordion( 'activate' , false );
		 refreshFonts("#infolist .liHeader");		 
		 if(variantdropdowns == 1)
		 {
			 $(".dropdown").fadeOut(500);
			 $(".dropdown_arrow").hide();
			 $("#views").fadeIn( 500);
			 variantdropdowns = 0;
		 }
		 leftClick(ismiddle);			 
		 $("#product ." + activearticle).fadeOut();
		 $("#prevleft").hide();

        // Seiteninhalte fuer neues Produkt aktualisieren
        detailDataStruct.prevProduct();  
		checkShopTeaser();        
	};
		
	nextclick = function(e)
	{
		unbindClicks();
	
		$("#infolist").accordion( 'activate' , false );
		refreshFonts("#infolist .liHeader");	
		if(variantdropdowns == 1)
		{
			$(".dropdown").fadeOut(500);
			$(".dropdown_arrow").hide();
			$("#views").fadeIn( 500);
			variantdropdowns = 0;
		}
		rightClick(ismiddle);			
		$("#product ." + activearticle).fadeOut();
		$("#prevright").hide();

        // Seiteninhalte fuer neues Produkt aktualisieren
        detailDataStruct.nextProduct(); 
		checkShopTeaser();        
	};
	
	bindClicks();
	
	activearticle = $("#product .active").attr('id');	
	$("." + activearticle).show();
	//$(".productprice").hide();
		
	$("#basketHeader").click(function()
	{
		if (openbasket == 0)
		{
			$("#infolist").accordion( 'activate' , false );				
			refreshFonts("#infolist .liHeader");	
			basketOpen();
			infoheight = $("#info").css("height");
			var basketheight = document.getElementById("basket").offsetHeight - document.getElementById("basketHeader").offsetHeight;
			var newheight = infoheight.replace(/px/, "") - basketheight;
			$("#info").animate({height : newheight + "px"}, 100);
			openbasket = 1;				
		}
		else
		{
			$("#info").animate({height : infoheight}, 100);
			openbasket = 0;
			basketClose();				
		}
	});	
	
	if(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect.length == 0)
	{
	    checkShopTeaser();
	}	
}

function getShopPool() {

    /* Alt (SK) Da alle Produktinhalte aus germanypds2 kommen und sich nur
       anhand der sprache unterscheiden, wird der shoppool jetzt auch anhand der Sprache ermittelt
    var pool = CURRENTPOOL;	
    var shoppool = "";
    if(pool == "germanypds2")
    shoppool = "germanypds";
    else
    shoppool = "europepds";
    return shoppool;
    */

    var lan = CURRENTLANGUAGE;
    var shoppool = "";
    if (lan == "de")
        shoppool = "germanypds";
    else
        shoppool = "europepds";
    return shoppool;
}

function getShopurl()
{	
	shoppool = getShopPool();		
	
	var currentProduct = detailDataStruct.products[detailDataStruct.currentIndex];
	var articleid = currentProduct.orderId;
	
	if(currentProduct.variants.length > 0)
	{
		articleid = currentProduct.variants[currentProduct.currentVariant].orderId;
	}
	
	var currenturl = window.location.href;
	var pos = currenturl.indexOf("/products/") + 10;
	var category = currenturl.substr(pos, 5);
	
	var shopurl = "http://berlin.porsche-design.de/" + shoppool + "/" + category + "/" + articleid + "/";
	return shopurl;
}

function finishPageload(data) {
	var article = detailDataStruct["currentIndex"] + 1;
	ismiddle = detailDataStruct["currentIndex"] + 1;
    $("#loaddummy").remove();    
    $("#article" + article).show();
    $("#product .productname").css( "color", "#fff");
    refreshFonts('#product .productname');    

    $("#infoblock").animate( { marginLeft: "718px", opacity: 1}, 1200, function() {
        if(detailDataStruct.products.length > 1)
        {
            $("#last").fadeIn( 200);
            $("#next").fadeIn( 200);
        }
        $(".article" + article).fadeIn( 200); 
		var currentProduct = detailDataStruct.products[detailDataStruct.currentIndex];
		var currentVariantIndex = currentProduct.currentVariant;
		var currentVariant = currentProduct.variants[ currentVariantIndex];	
		if(currentProduct.zoom != "")
		{
			$("#zoom").fadeIn( 200);
			/*LazyLoad.css('/Script/PDS2/shadowbox/shadowbox.css');
			LazyLoad.js('/Script/PDS2/shadowbox/shadowbox.js', function(){
				Shadowbox.init({handleOversize: "drag"});
				$("#zoom").fadeIn( 200);
			});*/						
		}
		//if(detailDataStruct["products"][detailDataStruct["currentIndex"]].variants.length > 0)
		//{
			checkVariants();
		//}
		//else
		//{
		//	$("#views").fadeIn( 200);
		// 	bindet die Klick-Events an die Blätter-Pfeile
		//	setTimeout('bindClicks()', 1000);
		//}
		//$('.ui-selectmenu-menu').jScrollPane();
    });
    
    var urls = [ 'Shopteaser_bg_over.jpg', 'button_hellgrau_over.png' ];
	$.preload( urls, {
		base: '/images/pds2/'		
	});

	updatePreviews();	
}

function checkVariants()
{
	//if(variantdropdowns == 0 && detailDataStruct["products"][detailDataStruct["currentIndex"]].variants.length > 0)
	//{
	
	$("#infolist").accordion('activate', 0);
	$(".detailtext").addClass( "ui-state-active");						
	$("#views").fadeIn( 200);		
	updatePops();						
	refreshFonts("#infolist .liHeader");	
	
	//variantdropdowns = 1;
	//}
	
	// bindet die Klick-Events an die Blätter-Pfeile
	setTimeout('bindClicks()', 1000);
}

function bindClicks()
{
	$("#next").bind('click', nextclick);
	$("#last").bind('click', lastclick);
}

function unbindClicks()
{
	$("#next").unbind('click', nextclick);
	$("#last").unbind('click', lastclick);
}

function checkShopTeaser()
{
	var shopurl = "http://berlin.porsche-design.de/" + getShopPool() + "/";	
    if(checkAvailability() == "true")
	{
        $("#shopteaser").show();
		shopurl = getShopurl();		
	}
    else	
        $("#shopteaser").hide();		
	$("#tool5").find('a').attr('href', shopurl);
}

function checkAvailability()
{
    var currentProduct = detailDataStruct.products[detailDataStruct.currentIndex];
    if(currentProduct.variants.length > 0)
    {    
        var currentVariantIndex = currentProduct.currentVariant;
        var currentVariant = currentProduct.variants[ currentVariantIndex];
        return currentVariant.available;		
    }
    else
        return currentProduct.available;		
}

function basketOpen()
{
	$("#basketHeader").addClass('activeBasket');
	//Cufon.refresh("#basketHeader");
	if(variantdropdowns == 1)
	{
		$(".dropdown").fadeOut(500);
    $(".dropdown_arrow").fadeOut(500);
    $("#views").fadeIn( 500);
	}
}

function basketClose()
{
	$("#basketHeader").removeClass('activeBasket');
	//Cufon.refresh("#basketHeader");
}

function updateCufonPrice()
{
    //renderFonts('#product .productprice', 'PD');	
}

function productsStart()
{
    renderFonts('#productinfo .productheadline', 'PD');		
	changeInfoTimeout = 0;	
	$("#productbuttons li a").hover(
	function () {
		clearTimeout(changeInfoTimeout);
		$(this).parent().css({"background-image" : "url(/images/pds2/products_over.jpg)"});
		changeInfos($(this).parent().attr('id'));
	},
	function () {
		$(this).parent().css({"background-image" : "url(/images/pds2/products_out.jpg)"});
		changeInfoTimeout = setTimeout(function(){changeInfos("default");}, 100);
	});
	
	var urls = [ 'products_over.jpg' ];
	$.preload( urls, {
		base: '/images/pds2/'		
	});
}

function categoryStart()
{
	if(ie6 == 1)
		return;
		
	//var text = $("#default_head").html();
	//var newtext = text.replace(/P´/, "&szlig;");
	//$("#default_head").html(newtext);
	
	renderFonts('#productinfo .productheadline', 'PD');
	renderFonts('#show_all a', 'Helv', true);	

	changeCategoryTimeout = 0;
	$("#productbuttons li a").hover(
	function () {		
		$(this).parent().css({"background-image" : "url(/images/pds2/products_over.jpg)"});		
	},
	function () {
		$(this).parent().css({"background-image" : "url(/images/pds2/products_out.jpg)"});		
	});
	
	$("#categorybuttons li a").hover(
	function () {
		clearTimeout(changeCategoryTimeout);
		$("#categorybuttons li").removeClass('activecat');	
		$(this).parent().addClass('activecat');
		$("#categorybuttons li.activecat").stop().fadeTo(1, 1);		
		$(this).find('img').stop().animate({			
			top: '20px'				
		}, 200);		
		changeCategory($(this).parent().attr('id'));
	},
	function () {		
		$(this).find('img').stop().animate({			
			top: '1px'				
		}, 200);		
		$(this).parent().removeClass('activecat');
		if($("#categorybuttons li.activeteaser").length > 0)
		{
		    $("#categorybuttons li.activeteaser").addClass('activecat');		   
		    changeCategoryTimeout = setTimeout(function(){changeCategory($("#categorybuttons li.activeteaser").attr('id'));}, 100);		    
		}		
		else
		    changeCategoryTimeout = setTimeout(function(){changeCategory("default");}, 100);		
	});
	
	if($("#categorybuttons li.activeteaser").length > 0)
	{	    
		$("#categorybuttons li.activeteaser").addClass('activecat');
		changeCategory($("#categorybuttons li.activeteaser").attr('id'));		
	}
}

function lineStart()
{
    renderFonts('#linehead', 'PD');
    renderFonts('#line_show_all a', 'Helv', true);	
}

function error()
{
	$("#mainnavi").hide();
	$("#tools").hide();
	$("#meta").hide();
	$("#search").hide();
	$("#header").find('a').attr('href', 'http://www.porsche-design.com/?skipintro=1');
	$("#linetext").append('<br/><br/><a href="http://www.porsche-design.com/?skipintro=1">www.porsche-design.com</a>');
}

function text1()
{
	if(ie6 == 1)
		return;		
	
	renderFonts('#infoname', 'PD');
    renderFonts('#infosub', 'Helv');
    renderFonts('#pagernext', 'Helv', true);
    renderFonts('#pagerprev', 'Helv', true);
    
    $("ul[class!=paging][id!=infonavi] li").css("list-style", "square");
	$("ul[class!=paging][id!=infonavi]").css("padding-left", "13px");
	$("#infonavi ul").css("padding-left", "0px");
	$("#subnavi ul").css("padding-left", "0px");	
	
	if($("#producttable").length > 0)
	{
		$("div.paging").quickPager();
		
		var tables = $("#producttable table");
		var i = tables.length;
		while ( i-- ) {	
			$(tables[i]).find("tr:odd").css("background-color", "#151515");
		}
	}
	
	if($("#infopict").length > 0)
	{		
		var zoomhref = $("#infopict").find("a").attr("href");
		if(zoomhref.substr((zoomhref.length - 1), 1) != "=")
		{
			/*LazyLoad.css('/Script/PDS2/shadowbox/shadowbox.css');
			LazyLoad.js('/Script/PDS2/shadowbox/shadowbox.js', function(){
				Shadowbox.init({handleOversize: "drag"});				
			});*/
			$("#infopict").find("a").attr("href", "javascript:void(0)");
			$("#infopict .pictzoom").show();
			$("#infopict .pictzoom").click(function(){
				Shadowbox.open({				    
					content:	$("#infopict").find('img').attr('src').replace(/filetype=normal/, 'filetype=zoom'),
					player: 	"img"
				});
			});
		}
		else
			$("#infopict").find("a").attr("href", "javascript:void(0)");
	}		
}

function infotextFadeIn()
{
	$("#infotext").fadeIn();
}

function text4()
{
	if(ie6 == 1)
		return;	
	
	renderFonts('#infoname', 'PD');
	renderFonts('#infosub', 'Helv');
	renderFonts('#pagernext', 'Helv', true);
    renderFonts('#pagerprev', 'Helv', true);
	
	$("ul[class!=paging][id!=infonavi] li").css("list-style", "square");
	$("ul[class!=paging][id!=infonavi]").css("padding-left", "13px");
	$("#infonavi ul").css("padding-left", "0px");
	$("#subnavi ul").css("padding-left", "0px");

	if($("#infopict").length > 0)
	{		
		var zoomhref = $("#infopict").find("a").attr("href");
		if(zoomhref.substr((zoomhref.length - 1), 1) != "=")
		{
			/*LazyLoad.css('/Script/PDS2/shadowbox/shadowbox.css');
			LazyLoad.js('/Script/PDS2/shadowbox/shadowbox.js', function(){
				Shadowbox.init({handleOversize: "drag"});				
			});*/
			$("#infopict").find("a").attr("href", "javascript:void(0)");
			$("#infopict .pictzoom").show();
			$("#infopict .pictzoom").click(function(){
				Shadowbox.open({				    
					content:	$("#infopict").find('img').attr('src').replace(/filetype=normal/, 'filetype=zoom'),
					player: 	"img"
				});
			});
		}
		else
			$("#infopict").find("a").attr("href", "javascript:void(0)");
	}
	
	if($("#infotext"))
	{		
		$("ul.paging").quickPager({callback: infotextFadeIn });				
	}
		
	if($("#gallery"))
	{
		$("#infopict").find("a").attr("href", "javascript:void(0)");
		$("#infopict .galleryzoom").show();
	}

  // Geaendert fuer IE6/7 kompatibilitaet von mv
	$("#infopict .galleryzoom").click(function(){
        var dialog  = $("#gallery");
        var width = 526;
        var top = 80;

        var fullWidth = $("#wrapper").width();
        var offset = $("#wrapper").offset();
        var left = (fullWidth - width) / 2;

        $("body").append( "<div id='lightbox_back'></div>");
				$("#lightbox_back").css('opacity','0');
				$("#lightbox_back").show();
				$("#lightbox_back").fadeTo("slow", 0.8);
        $("#thumbnails img").fadeTo("slow", 0.5);

        // Ist noetig fuer IE67, weil IE67 den z-index ignoriert
        $("#gallery").remove();
        $("body").append( dialog);

        // Die InfoBox ist in Body eingehaengt, muß also "von Hand" ueber wrapper positioniert werden, wenn sich die
        // Fenstergroesse aendert.
        $(window).resize( function() {
            offset = $("#wrapper").offset();
            $("#gallery").css({
                top: offset.top + top + "px",
                left: offset.left + left + "px"
            });
        });				

        // Die InfoBox stylen
        $("#gallery").css({
            position: "absolute",
            top: offset.top + top + "px",
            left: offset.left + left + "px"
        }).fadeIn("slow");

				var availablePages = Math.floor($("#thumbnails ul").children().length / (galleryPageImageCount + 1));
				if(availablePages == 0)
				{
					$(".galleryPagerNav").hide();
				}
				else
				{
					var pages = availablePages + 1;
					$("#gallerypages").html(pages);
				}

        $("#thumbnails img").mouseenter( function() {
            currentGalleryPath = $(this).attr( "alt");
            $(this).attr( "alt", "");
        });

        $("#thumbnails img").mouseleave( function() {
            $(this).attr( "alt", currentGalleryPath);
        });

        $("#thumbnails img").click( function() {
            $("#fullimage img").attr( "src", currentGalleryPath);
						$("#gallery_text").html( $(this).attr( "title"));
        });

        $("#thumbnails img").hover( function() {
            $(this).fadeTo( 100, "1");
        }, function() {
            $(this).fadeTo( 100, "0.5");
        });

        $("#lightbox_back").click(function(){
            $("#lightbox_back").remove();
            $("#gallery").hide();
        });
        $("#gallery_close").click(function(){
            $("#lightbox_back").remove();
            $("#gallery").hide();
        });

        $("#gallery_prev").click( function() {
            var offset = $("#thumbnails ul").position().left;
            var offsetInt = Math.abs( parseInt( offset));

            var page = offsetInt / galleryThumbWidth;

            if( page > 0) {
                offsetInt -= galleryThumbWidth;

                $("#thumbnails ul").animate({ left: "-" + offsetInt + "px"}, 500, function() {$("#gallerycurrent").text( page);});
    }
        });
        $("#gallery_next").click( function() {
            var offset = $("#thumbnails ul").position().left;
            var offsetInt = Math.abs( parseInt( offset));

            var page = offsetInt / galleryThumbWidth;            

            if( page < (availablePages)) {
                offsetInt += galleryThumbWidth;
                $("#thumbnails ul").animate({ left: "-" + offsetInt + "px"}, 500, function() {$("#gallerycurrent").text( page + 2);});
            }
        });
    });	
}

function sitemap()
{
	$("#overviewlist").accordion({ header: '.liHeader', fillSpace: true, collapsible: true, active: 'display none' });
}

function changeInfos(id)
{	
	$("#productinfo div").removeClass("activeproducts");
	$("#" + id + "_head").addClass("activeproducts");
	$("#" + id + "_text").addClass("activeproducts");
	$("#" + id + "_img").addClass("activeproducts");	
}

function changeCategory(id)
{
	if(id == 'default') 
		$("#categorybuttons li").stop().fadeTo(200, 1);
	else if($("#categorybuttons li.activeteaser").length > 0)
	{	    
	    $("#categorybuttons li.activecat").stop().fadeTo(1, 1);
	    $("#categorybuttons li:not(.activecat)").stop().fadeTo(200, 0.3);
	}
	else
		$("#categorybuttons li:not(.activecat)").stop().fadeTo(200, 0.3);	
	$("#productinfo div").removeClass("activeproducts");
	$("#" + id + "_head").addClass("activeproducts");
	$("#" + id + "_text").addClass("activeproducts");
	$("#" + id + "_img").addClass("activeproducts");	
}

function showNav2(obj, topic)
{	
	$(".subnavi_content li").removeClass("subactive");	
	$(obj).parent().addClass("subactive");
	$("#subnavi_" + subnavi + " .subactive").found(function(){
		$("#subnavi_" + subnavi + " li a").css({color: '#746556'});
	});
	$(obj).css({color: '#dcdcdc'});

	subsubnavi = topic;	
	$(".subsubnavi_content").hide();
	$(".subsubsubnavi_content").hide();
	$("#subsubnavi_" + subsubnavi + " li a").css({color: '#dcdcdc'});		
	$("#subsubnavi_" + subsubnavi).show();
}

function hideNav2(obj)
{
	var elem = $(obj);	
	subnavitimeout = setTimeout(function(){subnaviMOut(elem);}, 50);
}

function showNav3(obj, topic)
{
	clearTimeout(subnavitimeout);
	$(obj).parent().addClass("subsubactive");
	$("#subsubnavi_" + subsubnavi + " .subsubactive").found(function(){
		$("#subsubnavi_" + subsubnavi + " li a").css({color: '#746556'});				
	});
	$(obj).css({color: '#dcdcdc'});
	
	subsubsubnavi = topic;
	$(".subsubsubnavi_content").hide();
	$("#subsubsubnavi_" + topic + " li a").css({color: '#dcdcdc'});	
	$("#subsubsubnavi_" + topic).show();		
}

function hideNav3(obj)
{
	var subelem = $(obj);	
	subsubnavitimeout = setTimeout(function(){subsubnaviMOut(subelem);}, 50);
}

function activateSubnavi()
{
	if(activated == 1) return;
	else activated = 1;

	$(".subsubsubnavi_content li a").hover(
    function () {			
			clearTimeout(subsubnavitimeout);
			$(this).parent().addClass("subsubsubactive");
			$("#subsubsubnavi_" + subsubsubnavi + " .subsubsubactive").found(function(){
				$("#subsubsubnavi_" + subsubsubnavi + " li a").css({color: '#746556'});				
			});
			$(this).css({color: '#dcdcdc'});			
    },
    function () {
			var subsubelem = $(this).parent();
			setTimeout(function(){subsubsubnaviMOut(subsubelem);}, 50);      
    });
}

function subnaviMOut(elem)
{	
	elem.removeClass("subactive");	
}

function subsubnaviMOut(elem)
{
	elem.removeClass("subsubactive");	
}

function subsubsubnaviMOut(elem)
{
	elem.removeClass("subsubsubactive");		
}

function zoomImage()
{
	var currentIndex = detailDataStruct.currentIndex;
	var currentProduct = detailDataStruct.products[ currentIndex];
	var viewIndex = currentProduct.currentView;	
	
	var source = $("#product .active").find('img').attr('src');
	var last_char = source.substr((source.length - 1), 1);
	
	if(viewIndex == -1 || currentProduct.views[viewIndex].zoom == "")
	{
		last_char = '1';
	}
	
	if(last_char == '2')
	{
		Shadowbox.open({
					content:	$("#product .active").find('img').attr('src').replace(/filetype=normal2/, 'filetype=zoom2'),
					player: 	"img"
			});
	}
	else if(last_char == '3')
	{
		Shadowbox.open({
					content:	$("#product .active").find('img').attr('src').replace(/filetype=normal3/, 'filetype=zoom3'),
					player: 	"img"
			});
	}
	else if(last_char == '4')
	{
		Shadowbox.open({
					content:	$("#product .active").find('img').attr('src').replace(/filetype=normal4/, 'filetype=zoom4'),
					player: 	"img"
			});
	}
	else if(last_char == '5')
	{
		Shadowbox.open({
					content:	$("#product .active").find('img').attr('src').replace(/filetype=normal5/, 'filetype=zoom5'),
					player: 	"img"
			});
	}
	else if(last_char == '6')
	{
		Shadowbox.open({
					content:	$("#product .active").find('img').attr('src').replace(/filetype=normal6/, 'filetype=zoom6'),
					player: 	"img"
			});
	}
	else
	{	
		// (SK) wenn eine Variante aufgerufen wird, dann wollen wir auch deren zoomgrafik, so denn eine vorhanden ist. 
        var zoom = currentProduct.zoom;
        if (currentProduct.currentVariant != -1 && currentProduct.variants[currentProduct.currentVariant] != undefined) {
			if (currentProduct.variants[currentProduct.currentVariant].zoom != "") {
				zoom = currentProduct.variants[currentProduct.currentVariant].zoom;
			}
        }	
		// (SK - END)
		
		Shadowbox.open({
					//content:	$("#product .active").find('img').attr('src').replace(/filetype=normal/, 'filetype=zoom'),
					//content:	currentProduct.zoom,
					content: 	zoom, // (SK)
					player: 	"img"
			});
	}
}




/****************/
/* Shoproutinen */
/****************/


/*
*   Zeigt eine Infobox an mit einem Infoicon und einer Headerzeile mit 7 Textzeilen
*   infoId ist ein String mit dem Basisnamen für die Box
*   top ist die entsprechende Coordinate der Infobox relativ zu #wrapper
*   width ist die gewuenschte Breite der Infobox
* */

function showHtmlInfo( infoId, top, width) {
    var dialog  = $("#" +infoId);

    var fullWidth = $("#wrapper").width();
    var offset = $("#wrapper").offset();
    var left = (fullWidth - width) / 2;

    // Lightbox erstellen und anzeigen
    $("body").append( "<div id='lightbox_back'></div>");
    $("#lightbox_back").show().fadeTo(1, 0.8);
    $("#lightbox_back").click( function() {
        $("#" + infoId).hide();
        $("#lightbox_back").remove();
    });

    // Ist noetig fuer IE67, weil IE67 den z-index ignoriert
    $("#" +infoId).remove();
    $("body").append( dialog);

    // Die InfoBox ist in Body eingehaengt, muß also "von Hand" ueber wrapper positioniert werden, wenn sich die
    // Fenstergroesse aendert.
    $(window).resize( function() {
        offset = $("#wrapper").offset();
        $("#" +infoId).css({
            top: offset.top + top + "px",
            left: offset.left + left + "px"
        });
    });

    // Die InfoBox positionieren und anzeigen
    $("#" +infoId).css({
        top: offset.top + top + "px",
        left: offset.left + left + "px",
        width: width + "px"
    }).show();

    // Den Schliessen-Button aktivieren
    $("#" + infoId + " .infoboxclose").click( function() {
        $("#" + infoId).hide();
        $("#lightbox_back").remove();
    });
}




/*
*   Löscht einen Artikel aus dem Warenkorb.
 */
function deleteArticle( target) {
    var row = $(target).parent().parent().parent().parent();
    $(row).slideUp( 200, function() { setTimeout( $(row).remove(), 200);});
}



/*
*   Erhöht im Warenkorb die Menge eines Produktes um eines.
 */
function quantityPlus( target) {
    var currentQ = $(target).siblings( ".quannum").eq( 0);
    var currentInt = parseInt( currentQ.text());
    var nextInt = currentInt + 1;

    currentQ.text( nextInt );
    $(target).siblings( ".hiddennum").eq( 0).attr( "value", nextInt);
}


/*
*   Reduziert im Warenkorb die Menge eines Produktes um eines.
 */
function quantityMinus( target) {
    var currentQ = $(target).siblings( ".quannum").eq( 0);
    var currentInt = parseInt( currentQ.text());
    var nextInt = currentInt - 1;

    currentQ.text( nextInt );
    $(target).siblings( ".hiddennum").eq( 0).attr( "value", nextInt);
}

function findDefaultVariant()
{
	var currentProduct = detailDataStruct.products[detailDataStruct.currentIndex];
	var first = new Array();
	var firstindices = new Array();
	var second = new Array();
	var secondindices = new Array();
	var third = new Array();
	var thirdindices = new Array();	
	if(currentProduct.variantSelect.length > 0)
	{
		var firstVariant = currentProduct.variantSelect[0].defaultVal;
		if(currentProduct.variants.length > 0)
		{
			for(var i=0; i < currentProduct.variants.length; i++)
			{
				var definitionlength = currentProduct.variants[i].definition.length;
				for(var j=0; j < definitionlength; j++)
				{					
					if(currentProduct.variants[i].definition[j].value == firstVariant)
					{
						first.push(currentProduct.variants[i]);
						firstindices.push(i);
					}
				}
			}
		}		
	}
	if(currentProduct.variantSelect.length > 1)
	{
		var secondVariant = currentProduct.variantSelect[1].defaultVal;
		if(first.length > 0)
		{
			for(var i=0; i < first.length; i++)
			{
				var definitionlength = first[i].definition.length;
				for(var j=0; j < definitionlength; j++)
				{	
					if(first[i].definition[j].value == secondVariant)
					{
						second.push(first[i]);
						secondindices.push(firstindices[i]);
					}
				}
			}
		}
	}
	if(currentProduct.variantSelect.length > 2)
	{
		var thirdVariant = currentProduct.variantSelect[2].defaultVal;
		if(second.length > 0)
		{
			for(var i=0; i < second.length; i++)
			{
				var definitionlength = second[i].definition.length;
				for(var j=0; j < definitionlength; j++)
				{	
					if(second[i].definition[j].value == thirdVariant)
					{
						third.push(second[i]);
						thirdindices.push(secondindices[i]);						
					}
				}
			}
		}
	}
	if(currentProduct.variantSelect.length == 1)
		currentProduct.currentVariant = firstindices[0];
	else if(currentProduct.variantSelect.length == 2)
		currentProduct.currentVariant = secondindices[0];
	else if(currentProduct.variantSelect.length == 3)
		currentProduct.currentVariant = thirdindices[0];
		
    if(checkAvailability() == "true")
	{
        $("#shopteaser").show();
		var shopurl = getShopurl();			
		$("#tool5").find('a').attr('href', shopurl);
	}
}

function findFirstVariant(popId, value)
{
    var currentProduct = detailDataStruct.products[detailDataStruct.currentIndex];
	
	if(currentProduct.variantSelect.length == 2)
	{	    
        for(var i = 0; i < currentProduct.variants.length; i++)
        {
            for(var j = 0; j < 2; j++)
            {
                if(currentProduct.variants[i].definition[j].popId == popId)
                {
                    if(currentProduct.variants[i].definition[j].value == value)
                    {
                        currentProduct.currentVariant = i;						
						var currVar = currentProduct.variants[i];			
						if(currVar.zoom.length == "")			
							$("#zoom").hide();			
						else			
							$("#zoom").show();
                        for(var k=0; k<2;k++)
                        {
                            if(currentProduct.variantSelect[k].popId != popId)
                            {
                                for(var l = 0; l < 2; l++)
                                {
                                    if(currentProduct.variants[i].definition[l].value != value)
                                    {
                                        for(var m = 0; m < currentProduct.variantSelect[k].content.length; m++)
                                        {
                                            if(currentProduct.variantSelect[k].content[m].value == currentProduct.variants[i].definition[l].value)
                                            {
                                                currentProduct.variantSelect[k].selectedId = m;
                                                if(k == 0)
                                                {
                                                    if($('select#example').selectmenu('value') != m)
                                                        $('select#example').selectmenu('value', m);
                                                }
                                                else if (k==1)
                                                {
                                                    if($('select#example2').selectmenu('value') != m)
                                                        $('select#example2').selectmenu('value', m); 
                                                }
                                            }
                                        }
                                    }
                                } 
                            }
                        }
                        $("input[id='selectedproductid']").attr('value', currentProduct.variants[i].orderId);                        
                        return;
                    }
                }
            }
        }
	}
	else if(currentProduct.variantSelect.length == 3)
	{
	    for(var i = 0; i < currentProduct.variants.length; i++)
        {
            for(var j = 0; j < 3; j++)
            {
                if(currentProduct.variants[i].definition[j].popId == popId)
                {
                    if(currentProduct.variants[i].definition[j].value == value)
                    {
                        currentProduct.currentVariant = i;
						var currVar = currentProduct.variants[i];			
						if(currVar.zoom.length == "")			
							$("#zoom").hide();			
						else			
							$("#zoom").show();
                        for(var k=0; k<3;k++)
                        {
                            if(currentProduct.variantSelect[k].popId != popId)
                            {
                                for(var l = 0; l < 3; l++)
                                {
                                    if(currentProduct.variants[i].definition[l].value != value)
                                    {
                                        for(var m = 0; m < currentProduct.variantSelect[k].content.length; m++)
                                        {
                                            if(currentProduct.variantSelect[k].content[m].value == currentProduct.variants[i].definition[l].value)
                                            {
                                                currentProduct.variantSelect[k].selectedId = m;
                                                if(k == 0)
                                                {
                                                    if($('select#example').selectmenu('value') != m)
                                                        $('select#example').selectmenu('value', m);
                                                }
                                                else if (k==1)
                                                {
                                                    if($('select#example2').selectmenu('value') != m)
                                                        $('select#example2').selectmenu('value', m); 
                                                }
                                                else if (k==2)
                                                {
                                                    if($('select#example3').selectmenu('value') != m)
                                                        $('select#example3').selectmenu('value', m); 
                                                }
                                            }
                                        }
                                    }
                                } 
                            }
                        }                     
                        $("input[id='selectedproductid']").attr('value', currentProduct.variants[i].orderId);                                                  
                        return;
                    }
                }
            }            
        }
	}	
}

function showSuggestion()
{
    if(suggestion == 0)
    {
        //showPreloadLayer();        
        tb_remove();
        showToolsback(330);        
	    setTimeout("showFooterRecommendation()", 500);	
	    suggestion = 1;
	}
}

function showQuestion()
{
    if(question == 0)
    {
        //showPreloadLayer();        
        tb_remove();
        showToolsback(120);	    
	    setTimeout("showFooterQuestion()", 500);	
	    question = 1;
	}
}

function showNewsletter()
{
    if(newsletter == 0)
    {
        //showPreloadLayer();        
        tb_remove();
        showToolsback(215);	    
	    setTimeout("showFooterNewsletter()", 500);	
	    newsletter = 1;
	}
}

function showDealerSearch()
{
    if(dealer == 0)
    {
        //showPreloadLayer();
        tb_remove();        	    
	    setTimeout("showFooterDealerSearch()", 500);	
	    dealer = 1;
    }
}

function showDealerSearch2()
{
    if(dealer == 0)
    {
        //showPreloadLayer();
        tb_remove();	    
	    setTimeout("showArticleDealerSearch()", 500);	
	    dealer = 1;
    }
}

function showFooterQuestion()
{
    mode = "question";
    tb_show(null, window.location.protocol + '//' + window.location.hostname + '/all/pds2/footertools/question.aspx?title=' + escape(getActualTitle()) + '&url=' + escape(getActualUrl()) + '&lang=' + CURRENTLANGUAGE + 'TB_iframe=true&height=267&width=245', false)
    bindResize(mode);
}

function showFooterRecommendation()
{
    mode = "recommendation";
    tb_show(null, window.location.protocol + '//' + window.location.hostname + '/all/pds2/footertools/recommendation.aspx?url=' + escape(getActualUrl()) + '&lang=' + CURRENTLANGUAGE + '&TB_iframe=true&height=267&width=245', false)
    bindResize(mode);
}

function showFooterNewsletter()
{
    mode = "newsletter";
    tb_show(null, window.location.protocol + '//' + window.location.hostname + '/all/pds2/footertools/newsletter.aspx?lang=' + CURRENTLANGUAGE + '&TB_iframe=true&height=267&width=245', false)
    bindResize(mode);
}

function showFooterDealerSearch()
{
    isProductLink = 0;
    
    mode = "dealersearch";
    tb_show(null, window.location.protocol + '//' + window.location.hostname + '/all/pds2/dealersearch/world.aspx?lang=' + CURRENTLANGUAGE + '&TB_iframe=true&height=475&width=960', false);
    bindResize(mode);
}

function showArticleDealerSearch()
{
    isProductLink = 1;
    
    productname = "";
    productnumber = "";
    producthst = "";
    productimg = "";
    productcategory = "";
    
    var currentProduct = detailDataStruct.products[detailDataStruct.currentIndex];
    productimg = escape(currentProduct.thumb.replace(/filetype=thumbnail/, 'filetype=search'));
    producthst = currentProduct.manufacturerId;
    productnumber = currentProduct.orderId;
    productname = currentProduct.name;	
    productcategory = currentProduct.category;
    
    var currentVariantIndex = currentProduct.currentVariant;
    var currentVariant = -1;
    if(currentVariantIndex >= 0)
    {
        currentVariant = currentProduct.variants[currentVariantIndex];
        productimg = escape(currentVariant.thumb.replace(/filetype=thumbnail/, 'filetype=search'));
        producthst = currentVariant.manufacturerId;
        productnumber = currentVariant.orderId;         
    }    
    mode = "dealersearch";
    tb_show(null, window.location.protocol + '//' + window.location.hostname + '/all/pds2/dealersearch/storelocator.aspx?lang=' + CURRENTLANGUAGE + '&productname=' + escape(productname) + '&productnr=' + productnumber + '&hst=' + producthst + '&category=' + productcategory + '&productimg=' + productimg + '&TB_iframe=true&height=475&width=960', false);
    bindResize(mode);
}

function showToolsback(left)
{    
    $("#tools_back").css("left", left);    
    $("#tools_back").stop().fadeTo("fast", 0.93).animate({ height: "308px"}, 500);        
}

function bindResize(mode)
{
    var offtop = 0;
    var offleft = 0;
    if(mode == "dealersearch")
    {
        offtop = 43;
        offleft = 0;
    }
    if(mode == "recommendation")
    {
        offtop = 209;
        offleft = 330;
    }
    if(mode == "question")
    {
        offtop = 209;
        offleft = 120;
    }
    if(mode == "newsletter")
    {
        offtop = 209;
        offleft = 215;
    }
    $(window).bind("resize", function(){
        offset = $("#wrapper").offset();
        $("#TB_window").css({
            top: offset.top + offtop + "px",
            left: offset.left + offleft + "px"
        });
    });
    
}

function unbindResize()
{
    $(window).unbind("resize");
    
    // meta muss immer noch auf resize reagieren
    $(window).bind("resize", function(){
	    var offset = $("#wrapper").offset();
	    var metawidth = document.getElementById("meta").offsetWidth;
	    var lmargin = offset.left + 935 - metawidth;
	    $("#meta").css("left", lmargin);
	});
}

function getActualUrl()
{
    return self.location.href;
}

function getActualTitle() {
    return document.title;
}

function showPreloader()
{   
	$("#wrapper").append("<div id='preloader'></div>");	
}

function hidePreloader()
{
    $("#preloader").remove();
}

function showLanguageSelect()
{    
    $("body").append( 
    "<div id='languageSelect'>" + 
    "<div id='language_back'></div>" + 
    "<div id='language_choice'>" + 
    "<div class='lang_option'><a href='" + window.location.protocol + "//" + window.location.hostname + "/" + currentalias + "/de/?skipintro=1'>deutsch</a></div>" + 
    "<div class='lang_option'><a href='" + window.location.protocol + "//" + window.location.hostname + "/" + currentalias + "/en/?skipintro=1'>english</a></div>" + 
    //"<div class='lang_option'><a href='" + window.location.protocol + "//" + window.location.hostname + "/" + currentalias + "/zh/?skipintro=1'>中文</a></div>" + 
    "<div class='lang_option'><a href='" + window.location.protocol + "//" + window.location.hostname + "/" + currentalias + "/jp/?skipintro=1'>日本語</a></div>" + 
    "</div>" + 
    "</div>");
    $("#language_back").css('opacity','0');	
	$("#language_back").fadeTo("fast", 0.9);
	$("#languageSelect").show();
	languageselect = 1;	
	$("#languageSelect").click(function(){$("#languageSelect").remove(); languageselect = 0;});
	
	$(".lang_option").hover(function(){
	    $(this).addClass("active");	    
	},function(){
	    $(this).removeClass("active");
	});
	
	//document click closes LanguageSelect
	$(document)
		.mousedown(function(event){
		    if(languageselect == 1)
		    {
			    setTimeout(function() { $("#languageSelect").remove(); }, 500);
			    languageselect = 0;
			}
		});
}

// ProductDeatilScript Functions

function findVariant(popId, value) 
{
    first = new Array();
    firstindices = new Array();
    second = new Array();
    secondindices = new Array();
    third = new Array();
    thirdindices = new Array();

    var currentProduct = detailDataStruct.currentIndex;
    var pIndex = 0; // Index indem der Value von der aktuellen popId steht
    for (var h = 0; h < detailDataStruct.products[currentProduct].variantSelect.length; h++)
    {
        if(detailDataStruct.products[currentProduct].variantSelect[h].popId == popId)
        pIndex = h;
    }
    var variantlength = detailDataStruct.products[currentProduct].variants.length;
    for( var i = 0; i < variantlength; i++)
    {
        var definitionlength = detailDataStruct.products[currentProduct].variants[i].definition.length;
        for(var j=0; j < definitionlength; j++)
        {
            if(detailDataStruct.products[currentProduct].variants[i].definition[j].popId == popId)
            {
                if(detailDataStruct.products[currentProduct].variants[i].definition[j].value == value)
                {
                    first.push(detailDataStruct.products[currentProduct].variants[i]);
                    firstindices.push(i);
                }
            }
        }
    }
    if(detailDataStruct.products[currentProduct].variantSelect.length == 1)
    {
        detailDataStruct.products[currentProduct].currentVariant = firstindices[0];
        $("input[id='ProductID']").attr('value', detailDataStruct.products[currentProduct].variants[firstindices[0]].orderId);
		var currProduct = detailDataStruct["products"][detailDataStruct["currentIndex"]];
		var currVar = currProduct.variants[firstindices[0]];			
		if(currVar.zoom.length == "")			
			$("#zoom").hide();			
		else			
			$("#zoom").show();
    }

    if(detailDataStruct.products[currentProduct].variantSelect.length == 2)
    {
        for(var i = 0; i < 2; i++)
        {
            if(detailDataStruct.products[currentProduct].variantSelect[i].popId != popId)
            {
                var selectedId = detailDataStruct.products[currentProduct].variantSelect[i].selectedId;
                var selectedValue = detailDataStruct.products[currentProduct].variantSelect[i].content[selectedId].value;
                for(var j = 0; j < first.length; j++)
                {
					for(var k = 0; k < 2; k++)
					{
						if(first[j].definition[k].value == selectedValue)
						{
							second.push(first[j]);
							secondindices.push(firstindices[j]);
						}
					}
                }
            }
        }        
        if(secondindices.length > 0)
        {
            detailDataStruct.products[currentProduct].currentVariant = secondindices[0];
            $("input[id='ProductID']").attr('value', detailDataStruct.products[currentProduct].variants[secondindices[0]].orderId);
			var currProduct = detailDataStruct["products"][detailDataStruct["currentIndex"]];
			var currVar = currProduct.variants[secondindices[0]];			
			if(currVar.zoom.length == "")			
				$("#zoom").hide();			
			else			
				$("#zoom").show();			
        }
        else
        {
            //alert('mit der Auswahl gibt es keine Variante');
            findFirstVariant(popId, value);
        }
    }
    
    if(detailDataStruct.products[currentProduct].variantSelect.length == 3)
    {
        var popId2 = -1;
        for(var i = 0; i < 3; i++)
        {
            if(detailDataStruct.products[currentProduct].variantSelect[i].popId != popId)
            {
                var selectedId = detailDataStruct.products[currentProduct].variantSelect[i].selectedId;
                var selectedValue = detailDataStruct.products[currentProduct].variantSelect[i].content[selectedId].value;
                for(var j = 0; j < first.length; j++)
                {
					for(var k = 0; k < 3; k++)
					{
						if(first[j].definition[k].value == selectedValue)
						{
							if(jQuery.inArray(firstindices[j], secondindices) == -1)
							{
								second.push(first[j]);
								secondindices.push(firstindices[j]);
								popId2 = detailDataStruct.products[currentProduct].variantSelect[i].popId;
							}
						}
					}
                }
            }
        }

        for(var k = 0; k < 3; k++)
        {
            if(detailDataStruct.products[currentProduct].variantSelect[k].popId != popId && detailDataStruct.products[currentProduct].variantSelect[k].popId != popId2)
            {
                var selectedId = detailDataStruct.products[currentProduct].variantSelect[k].selectedId;
                var selectedValue = detailDataStruct.products[currentProduct].variantSelect[k].content[selectedId].value;
                for(var l = 0; l < second.length; l++)
                {
                    if(second[l].definition[k].value == selectedValue)
                    {
                        third.push(second[l]);
                        thirdindices.push(secondindices[l]);
                    }
                }
            }
        }        
        if(thirdindices.length > 0)
        {
            detailDataStruct.products[currentProduct].currentVariant = thirdindices[0];
            $("input[id='ProductID']").attr('value', detailDataStruct.products[currentProduct].variants[thirdindices[0]].orderId);
			var currProduct = detailDataStruct.products[currentProduct];
			var currVar = currProduct.variants[thirdindices[0]];
			if(currVar.zoom == "")
				$("#zoom").hide();
			else
				$("#zoom").show();
        }
        else 
        {
            //alert('mit der Auswahl gibt es keine Variante');
            findFirstVariant(popId, value);
        }
    }
	checkShopTeaser();    
}

// Liest die Daten für das aktuelle Produkt aus und aktualisiert die Inhalte der Varianten popup-Menues
function updatePops() 
{
    var currentIndex = detailDataStruct.currentIndex;
    var currentProduct = detailDataStruct.products[ currentIndex];
    var currentSelects = [];

    if( undefined != currentProduct) 
    {
        // Für das dargestellt Produkt gibt es eine Datenstruktur
        var currentVariantIndex = currentProduct.currentVariant;
        if( -1 == currentVariantIndex) 
        {
            // Das Produkt selbst wird gerade angezeigt
            currentSelects = currentProduct.variantSelect;
        } 
        else 
        {
            // Es wird eine Variante angezeigt
            var currentVariant = currentProduct.variants[ currentVariantIndex];
            if( undefined != currentVariant) 
            {
                //currentSelects = currentVariant.variantSelect;
                currentSelects = currentProduct.variantSelect;
            }
        }

        // Clean slate
        if(currentProduct.currentVariant == -1)
        {
            showFirst = false;
            showSecond = false;
            showThird = false;
        }

        // Die popups aktualisieren und anzeigen
        for( var index = 0; index < currentSelects.length; index++) 
        {
            var thisSelect = currentSelects[ index];
            var thisId = thisSelect.popId;
            var orientation = thisSelect.orientation;
            var thisContent = thisSelect.content;

            if($("#" + thisId).length > 0)
            {
                $("#" + thisId + " select").empty();
                $("#" + thisId + "_arrow img").attr('src', '/Images/PDS2/' + orientation + '.png');
                if (index == 0) 
                {
                    $("#" + thisId + " select").attr('id', 'example');                    
                }
                else if (index == 1) 
                {
                    $("#" + thisId + " select").attr('id', 'example2');
                }
                else if (index == 2) 
                {
                    $("#" + thisId + " select").attr('id', 'example3');
                }                
            }
            else
            {
                var name = '';
                var example = '';
				var labelid = '';
                if (index == 0) {name = 'filesA'; example = 'example'; labelid = 'label'}
                else if (index == 1) {name = 'filesB'; example = 'example2'; labelid = 'label2'}
                else if (index == 2) {name = 'filesC'; example = 'example3'; labelid = 'label3'}
                var newselectdiv = $('<div></div>').appendTo($("#product")).attr({'class': 'dropdown', 'id': thisId});
                var newselectlabel = $('<label></label>').appendTo($(newselectdiv)).attr('for', name);
                newselectlabel.html(thisSelect.caption);
				newselectlabel.attr('id', labelid);
                var newselectspan = $('<span></span>').appendTo($(newselectlabel)).attr('class', 'selectarrow');
                newselectspan.html('&#160;');
                var newselect = $('<select></select>').appendTo($(newselectdiv)).attr({name: name, id: example});

                var newarrowdiv = $('<div></div>').appendTo($("#product")).attr({'class': 'dropdown_arrow', 'id': thisId + '_arrow'});
                var arrowimg = $('<img/>').appendTo($(newarrowdiv)).attr({src: '/Images/PDS2/' + orientation + '.png', alt: ''});

                $('select#' + example).change( function() {                
                var index = $('select#' + example + ' option:selected')[0].index;
                var value = $('select#' + example + ' option:selected')[0].value;        
                findVariant(thisId, value);
                detailDataStruct.saveChange(thisId, index);
                detailDataStruct.updatePage();
                detailDataStruct.showBaseImage();
                });
            }
            for( var option = 0; option < thisContent.length; option++) 
            {
                var thisOption = thisContent[ option];

                var optionHtml = "<option class='" + thisOption.className + "' value='" + thisOption.value + "'";        
                if( option == thisSelect.selectedId) 
                {
			        optionHtml += " selected='selected'";
                }

                optionHtml += ">" + thisOption.text + "</option>";
                $("#" + thisId + " select").append( optionHtml);
            }

            if(currentProduct.currentVariant == -1)
            {
                variantcount = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect.length;

                if( detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[0].popId == thisId) 
                {
                    var currentVariantselect = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[0];
                    var defaultIndex = 0;
                    var default1 = currentVariantselect.defaultVal;
                    showFirst = true;
                    var icons0 = "[";
                    for(var i = 0; i < currentVariantselect.content.length; i++)
                    {
                        if(currentVariantselect.content[i].value == default1)
                        {
                            defaultIndex = i;
                            currentVariantselect.selectedId = i;
                        }
                        icons0 += "{find: '." + currentVariantselect.content[i].value + "'}";
                        if(i != currentVariantselect.content.length - 1)
                            icons0 += ",";
                        else
                            icons0 += "]";
                    }
                    $('#' + thisId + ' select#example').selectmenu({style: 'dropdown'});
                    var selectwidth = $('#' + thisId)[0].offsetWidth;
                    $('#' + thisId + ' select#example').selectmenu('destroy');
                    $('#' + thisId + ' select#example').selectmenu({
                    icons: eval(icons0),
                    style: 'dropdown',
                    width: selectwidth,
                    maxHeight: 200,
                    index: defaultIndex
                    });
                } 
                else if(variantcount > 1 && showSecond == false) 
                {
                    if( detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[1].popId == thisId) 
					{
						var currentVariantselect = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[1];
						var defaultIndex = 0;
						var default2 = currentVariantselect.defaultVal;
						showSecond = true;
						var icons1 = "[";
						for(var i = 0; i < currentVariantselect.content.length; i++)
						{
							if(currentVariantselect.content[i].value == default2)
							{
								defaultIndex = i;
								currentVariantselect.selectedId = i;
							}
							icons1 += "{find: '." + currentVariantselect.content[i].value + "'}";
							if(i != currentVariantselect.content.length - 1)
								icons1 += ",";
							else
								icons1 += "]";
						}
						$('#' + thisId + ' select#example2').selectmenu({style: 'dropdown'});
						var selectwidth2 = $('#' + thisId)[0].offsetWidth;
						$('#' + thisId + ' select#example2').selectmenu('destroy');
						$('#' + thisId + ' select#example2').selectmenu({
						icons: eval(icons1),
						style: 'dropdown',
						width: selectwidth2,
						maxHeight: 200,
						index: defaultIndex
						});					
					} 
				} 
				else if(variantcount > 2) 
				{
					if( detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[2].popId == thisId) 
					{
						var currentVariantselect = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[2];
						var defaultIndex = 0;
						var default3 = currentVariantselect.defaultVal;
						showThird = true;
						var icons2 = "[";
						for(var i = 0; i < currentVariantselect.content.length; i++)
						{
							if(currentVariantselect.content[i].value == default3)
							{
								defaultIndex = i;
								currentVariantselect.selectedId = i;
							}
							icons2 += "{find: '." + currentVariantselect.content[i].value + "'}";
							if(i != currentVariantselect.content.length - 1)
								icons2 += ",";
							else
								icons2 += "]";
						}
						$('#' + thisId + ' select#example3').selectmenu({style: 'dropdown'});
						var selectwidth3 = $('#' + thisId)[0].offsetWidth;
						$('#' + thisId + ' select#example3').selectmenu('destroy');
						$('#' + thisId + ' select#example3').selectmenu({
						icons: eval(icons2),
						style: 'dropdown',
						width: selectwidth3,
						maxHeight: 200,
						index: defaultIndex
						});
					}
				}
			}
			detailDataStruct.updateOrderId();
		}
    
		if(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect.length > 0 && detailDataStruct.products[detailDataStruct.currentIndex].currentVariant == -1)
		{
			findDefaultVariant();
		}        

		if( $(".hasvariants").hasClass( "ui-state-active")) 
		{
			//$("#zoom").fadeOut( 200);
			$("#views").fadeOut( 200);
			if( showFirst) 
			{
				var top = parseInt(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[0].top);
				var left = parseInt(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[0].left);
				var orientation = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[0].orientation;
				var variantid = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[0].popId;
				var x_offset;
				var y_offset;
				var x_offset1;
				var y_offset1;
				if (orientation == "top-right") { x_offset = -5; y_offset = -42; x_offset1 = 99; y_offset1 = -49; }
				else if (orientation == "bottom-right") { x_offset = -5; y_offset = -5; x_offset1 = 99; y_offset1 = 30; }
				else if (orientation == "top-left") 
				{ 
					x_offset = -99; y_offset = -42; y_offset1 = -49;
					x_offset1 = -99 - $("#" + variantid).innerWidth();
				}
				else if (orientation == "bottom-left") 
				{ 
					x_offset = -99; y_offset = -5; y_offset1 = 30;
					x_offset1 = -99 - $("#" + variantid).innerWidth();
				}
				$("#" + variantid).fadeIn( 500);
				$("#" + variantid).css({'top' : (top + y_offset1) + 'px', 'left' : (left + x_offset1) + 'px'});
				$("#" + variantid + "_arrow").fadeIn( 500);
				$("#" + variantid + "_arrow").css({'top' : (top + y_offset) +  'px', 'left' : (left + x_offset) + 'px'});
			}
			if( showSecond) 
			{
				var top = parseInt(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[1].top);
				var left = parseInt(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[1].left);
				var orientation = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[1].orientation;
				var variantid = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[1].popId;
				var x_offset;
				var y_offset;
				var x_offset1;
				var y_offset1;
				if (orientation == "top-right") { x_offset = -5; y_offset = -42; x_offset1 = 99; y_offset1 = -49; }
				else if (orientation == "bottom-right") { x_offset = -5; y_offset = -5; x_offset1 = 99; y_offset1 = 30; }
				else if (orientation == "top-left") 
				{ 
					x_offset = -99; y_offset = -42; y_offset1 = -49;
					x_offset1 = -99 - $("#" + variantid).innerWidth();
				}
				else if (orientation == "bottom-left") 
				{ 
					x_offset = -99; y_offset = -5; y_offset1 = 30;
					x_offset1 = -99 - $("#" + variantid).innerWidth();
				}
				$("#" + variantid).fadeIn( 500);
				$("#" + variantid).css({'top' : (top + y_offset1) + 'px', 'left' : (left + x_offset1) + 'px'});
				$("#" + variantid + "_arrow").fadeIn( 500);
				$("#" + variantid + "_arrow").css({'top' : (top + y_offset) + 'px', 'left' : (left + x_offset) + 'px'});
			}
			if( showThird) 
			{
				var top = parseInt(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[2].top);
				var left = parseInt(detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[2].left);
				var orientation = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[2].orientation;
				var variantid = detailDataStruct.products[detailDataStruct.currentIndex].variantSelect[2].popId;
				var x_offset;
				var y_offset;
				var x_offset1;
				var y_offset1;
				if (orientation == "top-right") { x_offset = -5; y_offset = -42; x_offset1 = 99; y_offset1 = -49; }
				else if (orientation == "bottom-right") { x_offset = -5; y_offset = -5; x_offset1 = 99; y_offset1 = 30; }
				else if (orientation == "top-left") 
				{ 
					x_offset = -99; y_offset = -42; y_offset1 = -49;
					x_offset1 = -99 - $("#" + variantid).innerWidth();
				}
				else if (orientation == "bottom-left") 
				{ 
					x_offset = -99; y_offset = -5; y_offset1 = 30;
					x_offset1 = -99 - $("#" + variantid).innerWidth();
				}
				$("#" + variantid).fadeIn( 500);
				$("#" + variantid).css({'top' : (top + y_offset1) + 'px', 'left' : (left + x_offset1) + 'px'});
				$("#" + variantid + "_arrow").fadeIn( 500);
				$("#" + variantid + "_arrow").css({'top' : (top + y_offset) + 'px', 'left' : (left + x_offset) + 'px'});
			}
		}		
	}
}

// Aktualisiert die Darstellung der Icons für die alternativen Produktansichten
function updateViews() 
{
	var currentIndex = detailDataStruct.currentIndex;
	var currentProduct = detailDataStruct.products[ currentIndex];
	var currentView;
	var currentVariant = currentProduct;

	if( undefined != currentProduct) 
	{
		// Für das dargestellt Produkt gibt es eine Datenstruktur
		var currentVariantIndex = currentProduct.currentVariant;
		if( -1 == currentVariantIndex) 
		{
			// Das Produkt selbst wird gerade angezeigt
			currentView = currentProduct.views;
		} 
		else 
		{
			// Es wird eine Variante angezeigt
			currentVariant = currentProduct.variants[ currentVariantIndex];
			if( undefined != currentVariant) 
			{
				currentView = currentVariant.views;
			}
		}
	}
	
	if( undefined != currentView && currentView.length > 0) 
	{	
		// alle Thumbs vom vorigen Artikel löschen
		for(var i = 0; i < 5; i++) 
		{			
			$("#views").children().eq(1).remove();			
		}		
		$("#views").children().eq( 0).attr( "src", currentVariant.thumb).fadeIn( 200);
		var index = 0;
		for(; index < currentView.length; index++) 
		{
			var thisView = currentView[ index];			
			var change = index;			
			$("#views").append("<img src='" + thisView.thumb + "' alt='' />");
			$("#views").children().eq( index + 1).fadeIn( 200);
			$("#views").children().eq( index + 1).click( function() {changeImage(change);});			
		}

		// Die nicht benötigten Thumbs ausblenden
		for(; index < 5; index++) 
		{
			$("#views").children().eq( index + 1).fadeOut( 200);
		}
	} 
	else 
	{
		$("#views").children().fadeOut( 200);
	}
}

// Zeigt nach klick in eine alternative Produktansichte das entsprechende Bild an
function changeImage( viewIndex) 
{
	var currentIndex = detailDataStruct.currentIndex;
	var currentProduct = detailDataStruct.products[ currentIndex];
	var currentView;
	var currentImage;

	if( undefined != currentProduct) 
	{
		// Für das dargestellt Produkt gibt es eine Datenstruktur
		var currentVariantIndex = currentProduct.currentVariant;
		if( -1 == currentVariantIndex || undefined == currentVariantIndex) 
		{
			// Das Produkt selbst wird gerade angezeigt
			currentView = currentProduct.views;
			currentImage = currentProduct.image;
		} 
		else 
		{
			// Es wird eine Variante angezeigt
			var currentVariant = currentProduct.variants[ currentVariantIndex];
			if( undefined != currentVariant) 
			{
				// Die Variante speichern damit der Index der alternativen Produktansicht gespeichert werden kann
				currentProduct = currentVariant;
				currentView = currentVariant.views;
				currentImage = currentVariant.image;
			}
		}
	}

	if( undefined != currentView) 
	{
		var path;

		if( -1 == viewIndex) 
		{
			path = currentImage;
		} 
		else 
		{
			path = currentView[ viewIndex].image;
		}

		$("#article" + (currentIndex + 1) + " img").attr( "src", path);
		currentProduct.currentView = viewIndex;
	}
}

function unsubscribe()
{
    var email = "";
    try
    {
        email = getURLParam("email");
    }
    catch(e)
    {
        email = "";
    }
    
    var url = "/NewsletterRegistration.aspx?action=optout&email=" + email;
    var response = "";	
	
	if(email != "")
	{	    
	    $.get(url, function(data){		
    		response = data;
	    });
	}
}

function getURLParam(strParamName)
{
    var strReturn = "";
    var strHref = window.location.href;

    if ( strHref.indexOf("?") > -1 )
    {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");

        for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
        {
            if (aQueryString[iParam].indexOf(strParamName + "=") > -1 )
            {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return strReturn;
}

function isIE()
{
    if(navigator.userAgent.match(/MSIE \d\.\d+/))
        return true;
    return false;
}

//********************************************************************************************************
//  PLUG-INS
//********************************************************************************************************

// outerHTML like innerHTML
(function($) {
 // Returns whether or not a result set has results in it
 $.fn.outerHTML = function() {
   var result = "";
   try
   {
    result = $('<div>').append( this.eq(0).clone() ).html();
   }
   catch(e)
   {
    result = this.get(0).xml;
   }
   return result;
 };
})(jQuery);


// Preload of images
(function($) {
	var $preload = $.preload = function( original, settings ){
		if( original.split ) // selector
			original = $(original);

		settings = $.extend( {}, $preload.defaults, settings );
		var sources = $.map( original, function( source ){
			if( !source ) 
				return; // skip
			if( source.split ) // URL Mode
				return settings.base + source + settings.ext;
			var url = source.src || source.href; // save the original source
			if( typeof settings.placeholder == 'string' && source.src ) // Placeholder Mode, if it's an image, set it.
				source.src = settings.placeholder;
			if( url && settings.find ) // Rollover mode
				url = url.replace( settings.find, settings.replace );
			return url || null; // skip if empty string
		});

		var data = {
			loaded:0, // how many were loaded successfully
			failed:0, // how many urls failed
			next:0, // which one's the next image to load (index)
			done:0, // how many urls were tried			
			total:sources.length // how many images are being preloaded overall
		};
		
		if( !data.total ) // nothing to preload
			return finish();
		
		var imgs = $(Array(settings.threshold+1).join('<img/>'))
			.load(handler).error(handler).bind('abort',handler).each(fetch);
		
		function handler( e ){
			data.element = this;
			data.found = e.type == 'load';
			data.image = this.src;
			data.index = this.index;
			var orig = data.original = original[this.index];
			data[data.found?'loaded':'failed']++;
			data.done++;

			// This will ensure that the images aren't "un-cached" after a while
			if( settings.enforceCache )
				$preload.cache.push( 
					$('<img/>').attr('src',data.image)[0]
				);

			if( settings.placeholder && orig.src ) // special case when on placeholder mode
				orig.src = data.found ? data.image : settings.notFound || orig.src;
			if( settings.onComplete )
				settings.onComplete( data );
			if( data.done < data.total ) // let's continue
				fetch( 0, this );
			else{ // we are finished
				if( imgs && imgs.unbind )
					imgs.unbind('load').unbind('error').unbind('abort'); // cleanup
				imgs = null;
				finish();
			}
		};
		function fetch( i, img, retry ){
			// IE problem, can't preload more than 15
			if( img.attachEvent /* msie */ && data.next && data.next % $preload.gap == 0 && !retry ){
				setTimeout(function(){ fetch( i, img, true ); }, 0);
				return false;
			}
			if( data.next == data.total ) return false; // no more to fetch
			img.index = data.next; // save it, we'll need it.
			img.src = sources[data.next++];
			if( settings.onRequest ){
				data.index = img.index;
				data.element = img;
				data.image = img.src;
				data.original = original[data.next-1];
				settings.onRequest( data );
			}
		};
		function finish(){
			if( settings.onFinish )
				settings.onFinish( data );
		};
	};

	 // each time we load this amount and it's IE, we must rest for a while, make it lower if you get stack overflow.
	$preload.gap = 14; 
	$preload.cache = [];
	
	$preload.defaults = {
		threshold:2, // how many images to load simultaneously
		base:'', // URL mode: a base url can be specified, it is prepended to all string urls
		ext:'', // URL mode:same as base, but it's appended after the original url.
		replace:'' // Rollover mode: replacement (can be left empty)		
	};

	$.fn.preload = function( settings ){
		$preload( this, settings );
		return this;
	};
})( jQuery );

// easing Effects
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {		
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/**
 * @class LazyLoad
 * @static
 */
LazyLoad = function () {  

  // Shorthand reference to the browser's document object.
  var d = document,

  // Reference to the <head> element.
  head,

  // Requests currently in progress, if any.
  pending = {},

  // Queued requests.
  queue = {css: [], js: []},

  // User agent information.
  ua;

  function createNode(name, attrs) {
    var node = d.createElement(name), attr;

    for (attr in attrs) {
      if (attrs.hasOwnProperty(attr)) {
        node.setAttribute(attr, attrs[attr]);
      }
    }

    return node;
  }
  
  function finish(type) {
    var p = pending[type];

    if (!p) { return; }

    var callback = p.callback,
        urls     = p.urls;

    urls.shift();

    // If this is the last of the pending URLs, execute the callback and
    // start the next request in the queue (if any).
    if (!urls.length) {
      if (callback) {
        callback.call(p.scope || window, p.obj);
      }

      pending[type] = null;

      if (queue[type].length) {
        load(type);
      }
    }
  }
  
  function getUserAgent() {
    // No need to run again if ua is already populated.
    if (ua) { return; }

    var nua = navigator.userAgent,
        pF  = parseFloat,
        m;

    ua = {
      gecko : 0,
      ie    : 0,
      opera : 0,
      webkit: 0
    };

    m = nua.match(/AppleWebKit\/(\S*)/);

    if (m && m[1]) {
      ua.webkit = pF(m[1]);
    } else {
      m = nua.match(/MSIE\s([^;]*)/);

      if (m && m[1]) {
        ua.ie = pF(m[1]);
      } else if ((/Gecko\/(\S*)/).test(nua)) {
        ua.gecko = 1;

        m = nua.match(/rv:([^\s\)]*)/);

        if (m && m[1]) {
          ua.gecko = pF(m[1]);
        }
      } else if (m = nua.match(/Opera\/(\S*)/)) {
        ua.opera = pF(m[1]);
      }
    }
  }
 
  function load(type, urls, callback, obj, scope) {
    var i, len, node, p, url;

    // Determine browser type and version.
    getUserAgent();

    if (urls) {
      // Cast urls to an Array.
      urls = urls.constructor === Array ? urls : [urls];
     
      if (type === 'css' || ua.gecko || ua.opera) {
        queue[type].push({
          urls    : [].concat(urls), // concat ensures copy by value
          callback: callback,
          obj     : obj,
          scope   : scope
        });
      } else {
        for (i = 0, len = urls.length; i < len; ++i) {
          queue[type].push({
            urls    : [urls[i]],
            callback: i === len - 1 ? callback : null, // callback is only added to the last URL
            obj     : obj,
            scope   : scope
          });
        }
      }
    }
    
    if (pending[type] || !(p = pending[type] = queue[type].shift())) {
      return;
    }

    head = head || d.getElementsByTagName('head')[0];
    urls = p.urls;

    for (i = 0, len = urls.length; i < len; ++i) {
      url = urls[i];

      if (type === 'css') {
        node = createNode('link', {
          href : url,
          rel  : 'stylesheet',
          type : 'text/css'
        });
      } else {
        node = createNode('script', {src: url});
      }

      if (ua.ie) {
        node.onreadystatechange = function () {
          var readyState = this.readyState;

          if (readyState === 'loaded' || readyState === 'complete') {
            this.onreadystatechange = null;
            finish(type);
          }
        };
      } else if (type === 'css' && (ua.gecko || ua.webkit)) {
        // Gecko and WebKit don't support the onload event on link nodes, so we
        // just have to finish after a brief delay and hope for the best.
        setTimeout(function () { finish(type); }, 50 * len);
      } else {
        node.onload = node.onerror = function () { finish(type); };
      }

      head.appendChild(node);
    }
  }

  return {
    
    css: function (urls, callback, obj, scope) {
      load('css', urls, callback, obj, scope);
    },
    
    js: function (urls, callback, obj, scope) {
      load('js', urls, callback, obj, scope);
    }

  };
}();
