// Bestimmt die grade angezeigte Zahlungsart auf der Zahlungsartseite
var activePaymentType = 0;
var initialFooterPosition;
var overlay_positionZero = null;
var overlay_positionOne = null;
var overlay_positionTwo = null;
var overlay_positionThree = null;
var overlay_positionFour = null;
var VariantInfos = new Object();
var cartMessageTimer;


if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}
function onBlur() {
	stopMultiteaser();
};
function onFocus(){
	restartMultiteaser();
};

var index = 1;
var aktivesElement = 1;
$(document).ready( function() {
	$('#search_field').bind('keyup', function(e){
		suggestion(e);
	});
	
	$('#suggestions').bind('keyup', function(e){
		suggestion(e);
	});
		
		
	function suggestion (e) {
		var curKey = e.keyCode;
		var parent;
		var id;
		var anzahl;
		if ($('.makiert').size() > 0) {
			id = $('.makiert :first-child').attr('id');
			id = id.split('_');
			index = id[1];
		}
		switch (curKey) {
		
			case 38:
				e.preventDefault();
				$('#suggestions').css('display', 'block');
				$('#suggestions').off('hover');
				anzahl = $('#kategorien > div').size();
				anzahl += $('#marken > div').size();
				anzahl += $('#produkte > div').size();
				if (index <= 0) {
					$('.makiert').removeClass('makiert');
					$('#Searchlink_'+aktivesElement).removeClass('active');
					$('#Searchlink_'+anzahl).addClass('active');
					parent = $('#Searchlink_'+anzahl).parent();
					$(parent).addClass('makiert');
					aktivesElement = anzahl;
					index = anzahl;
				} else {
					$('.makiert').removeClass('makiert');
					$('#Searchlink_'+aktivesElement).removeClass('active');
					index--;
					$('#Searchlink_'+index).addClass('active');
					parent = $('#Searchlink_'+index).parent();
					$(parent).addClass('makiert');
					aktivesElement = index;
					
				}
				break;
			case 40:
				e.preventDefault();
				$('#suggestions').off('hover');
				$('#suggestions').css('display', 'block');
				anzahl = $('#kategorien > div').size();
				anzahl += $('#marken > div').size();
				anzahl += $('#produkte > div').size();

				if (index == anzahl) {
					$('.makiert').removeClass('makiert');
					$('#Searchlink_'+aktivesElement).removeClass('active');
					aktivesElement = 0;
					index = 0;
				} else {
					$('.makiert').removeClass('makiert');
					$('#Searchlink_'+aktivesElement).removeClass('active');
					index++;
					$('#Searchlink_'+index).addClass('active');
					parent = $('#Searchlink_'+index).parent();
					$(parent).addClass('makiert');
					aktivesElement = index;
					
				}
				break;
			case 13: // return
				if ($('#suggestions .active').length > 0) {
					window.location = $('#suggestions .active').attr('href');
				} else {
					$('#searchform').submit();
				}
					
				break;
			default:
				$('#suggestions .active').removeClass('active');
				index = 0;
				getSuggestions($('#search_field').val());			
		}
	}
	$('#multiteaser_smallpictures  #multiteaser_arrow_left_nojscript').remove();
	$('#multiteaser_smallpictures  #multiteaser_arrow_right_nojscript').remove();
	$('#multiteaser_smallpictures  .small-image').remove();
	
	$('#searchform').submit(function(e){
		if($('#search_field').val() == 'SUCHE' || $('#search_field').val() == 'SEARCH'){
			e.preventDefault();
			if(localeString == 'de_DE')
				alert('Bitte gib einen Suchbegriff ein');
			else
				alert('Please enter a search');	
		}
	});

	$('#FIELD_cashpoints').click(function(){
		if	($(this).attr('checked'))
			$('#voucherform').append('<input type="hidden" name="cashpoints" value="1" id="checked_cp" />');
		else
			$('#checked_cp').remove();

	});

	// delay main menu layer
	jQuery('#head').removeClass('use-hover');
	var config = {
		over: function(){ jQuery('.menu ul li ul.ShopMenu li').removeClass('hover'); jQuery(this).addClass('hover'); },
		timeout: 500, // number = milliseconds delay before onMouseOut
		out: function(){ jQuery(this).removeClass('hover'); }
	};
	jQuery(".menu ul li ul.ShopMenu li").hoverIntent( config );

	documentready(); // fuer Ajax-Aufruf

	$(window).resize(function() {
		moveProductOverlays();
	});
	
	// Lieblingsmarken speicher Button ausblenden wenn js an 
	$('.lieblingsmarkenspeichern').css('display', 'none');
	
	/******************************************/
	/*** Logik zum Aufsliden von Containern ***/
	/******************************************/

	var activePaymentType;
	$(".closeslide").click( function(){	
		$('#PaymentType_' + activePaymentType).slideToggle('slow');
		$('#InfoPaymentType_' + activePaymentType).slideToggle('slow');
		$('#teaser_' + activePaymentType).css('display', 'block');
		activePaymentType = 0;
	});
	
	$(".slidedown").click( function() {
		id = $(this).attr("rel");
		if ($('.empty_login_container'))
			$('.empty_login_container').slideToggle('slow');

		if ($('#Info' + id))
			$('#Info' + id).slideToggle('slow');

		$('#' + id).slideToggle('slow');

		SplittedID = id.split("_");

		if (SplittedID[0] == "PaymentType"){
			if (activePaymentType != 0) {
				$('#PaymentType_' + activePaymentType).slideToggle('slow');
				$('#InfoPaymentType_' + activePaymentType).slideToggle('slow');
				$('#teaser_' + activePaymentType).css('display', 'block');
			}
			$('#teaser_' + SplittedID[1]).css('display', 'none');
			activePaymentType = SplittedID[1];
		}
	});

	$("#ProductDetectorDelete").click( function() {
		$("#InputHiddenTask").attr('value', "delete");
		$(this).closest('form').submit();
	});

	/**********************/
	/*** Top 5 Produkte ***/
	/**********************/

	$("#top_five_products .headlines div div a").click( function() {
		splittedID = $(this).attr('id').split('_');

		$("#top_five_products .headlines div").removeClass("active");
		$("#top_five_products .headlines ." + splittedID[1]).addClass("active");
		$("#top_five_products .headlines .arrow img").attr("src", DSTORE_BASE_URL+"/customGates/resources/binaries/universal/icons/shop_top5_arrow_right.gif");
		$("#top_five_products .headlines .active .arrow img").attr("src", DSTORE_BASE_URL+"/customGates/resources/binaries/universal/icons/shop_top5_arrow_down.gif");
		$("#top_five_products .category .productlist").addClass("hide");
		$("#productlist_" + splittedID[1]).removeClass("hide");
		
		// Links Alle Produkte
		$("#top_five_products .all_products a").addClass("hide");
		$("#top_five_products .all_products #top_five_link_" + splittedID[1]).removeClass("hide");
		
	});
	

	/**
	 * Dynamisch aufklappender Footer
	 */
	initialFooterPosition = $("#footer").offset().top;

	// iOS unterstuetzt kein position:fixed, soll ab iOS 5 funktionieren
	if(navigator.platform != 'iPad' && navigator.platform != 'iPhone' && navigator.platform != 'iPod')
	{
		// Nur sichtbar, wenn JavaScript aktiv
		$("#stickyfooter").removeClass("hidden");
		$('.ajax_small_trolley .container #login.spacer .login .container_input label').css('width', '130px');
		$('.trolley .voucher_code .padding .input_container .submit input[type="text"]').css('width', '105px');
		$('.trolley .container .quantity select').addClass('width');
	}
	
	if($("#stickyfooter").offset().top + $("#stickyfooter").height() >= $("#footer").offset().top)
	{
		$("#stickyfooter").addClass("sticky");
		$("#stickyfooter img").attr("src", DSTORE_BASE_URL + '/customGates/resources/binaries/'+localeString+'/icons/service.png');
	}

	$("#stickyfooter img").click(function()
	{
		if(!$("#stickyfooter").hasClass('sticky'))
		{
			if($("#stickyfooter").hasClass('closed'))
			{
				var height = $('.sitecontainer_spacer').height();

				$("#footer").removeClass("normal");
				$("#footer").addClass("preopen");
				$("#footer").switchClass("preopen", "open", 1000);
				$("#stickyfooter").switchClass("closed", "open", 1000);
				$("#stickyfooter img").attr("src", DSTORE_BASE_URL + '/customGates/resources/binaries/'+localeString+'/icons/service_down.png');

				$('.sitecontainer_spacer').css('height', height);
			}
			else
			{
				$("#footer").switchClass("open", "preclosed", 1000);
				$("#footer").addClass("normal");
				$("#footer").removeClass("preclosed");
				$("#stickyfooter").switchClass("open", "closed", 1000);
				$("#stickyfooter img").attr("src", DSTORE_BASE_URL + '/customGates/resources/binaries/'+localeString+'/icons/service_up.png');

			}
		}

	});

//	var mySwfStore = new SwfStore({
//		namespace: 'titus',
//		swf_url: DSTORE_BASE_URL+ "/customGates/lib/functions/storage.swf",
//		debug: false,
//		onready: function(){
//			
//			var sid = mySwfStore.get('SID');
//			var uniqueid = mySwfStore.get('UniqueID')
//			
//			if(typeof DSTORE_COOKIE_PATH != 'undefined' && DSTORE_COOKIE_PATH != '')
//				cookiePath = DSTORE_COOKIE_PATH;
//			else
//				cookiePath = '/';
//
//			if(sid)
//				$.cookie("SID", sid, { path: cookiePath});
//			else
//				mySwfStore.set('SID', $.cookie("SID"));
//
//			if(uniqueid)
//				$.cookie("UniqueID", uniqueid, { path: cookiePath});
//			else
//				mySwfStore.set('UniqueID', $.cookie("UniqueID"));
//		},
//		onerror: function(){}
//	});

   $('#search_field').focus(function(){
	   	if($(this).attr("value") == "SUCHE") 
		   $(this).attr("value", "");
	
   		if($(this).attr("value") == "SEARCH") 
   			$(this).attr("value", "");
   
   });

   $('#search_field').blur(function(){
	   if($(this).attr("value") == "") 
		   $(this).attr("value", "SUCHE");
	   $('#suggestions').fadeOut();
	   index = 0;
	   $('#suggestions .active').removeClass('active');
   });
   
   // Falls das Produktmelder Overlay existiert, dann soll es angezeigt werden.
   if ($('#ProductDetector_NewProductsLayer').length > 0) {
	   ModalDialog = $('#ProductDetector_NewProductsLayer').modal({
			overlayCss: {
		    backgroundColor: '#000',
		    cursor: 'wait'
		  },
		  containerCss: {
		    height: 600,
		    width: 820,
		    border: '1px solid #3a3a3a',
		    backgroundColor: '#FFF'
		  }
		});
   }
   
   $('.latest_news #newsticker ul').jcarousel({
		vertical: true,
		scroll: 3
	});

	$('.category .productlist.list .selectsize').on("change", function(e) {
//	$('.category .productlist.list .selectsize').change( function(e) {
	  // Als erstes den hinterlegten Wert aus der CustomSelectbox ermitteln
	  activeValue = $(this).parent("div").children("a").children("span.selectBox-label").html();
	  // Anschließend alle Options
	  options =  $(this).find("option");
	  // Anschließend das Active Option ermitteln
	  for(var i = 0; i < options.length; i++) {
		  if ($(options[i]).html() == activeValue) {
			  treeNodeID = $(options[i]).val();
			  break;
		  } // if ($(options[i]).html() == activeValue)
	  } // for(val in options)

	  $(this).parents(".add_to_trolley").find(".submit_cart").unbind("click");

	  if (VariantInfos[parseInt(treeNodeID)]['Info'] == 'coming soon') {
		  // Warenkorb Bild austauschen
		  $(this).parents(".add_to_trolley").children('form').children('.submit').children('.input').html('<input type="image"' 
			+ ' src="' + DSTORE_BASE_URL+'/customGates/resources/binaries/'+localeString+'/buttons/shop_produktanzeige_benachrichtigen.gif"'
			+ ' alt="Coming soon" title="Coming soon" />'
		  );
		  // Warenkorb Action austauschen
		  $(this).parents(".add_to_trolley").find('input[name="screen"]').val('dstore.account.productdetector');
		  $(this).parents(".add_to_trolley").find('input[name="ClassName"]').val('ProductDetector');
		  $(this).parents(".add_to_trolley").find('input[name="task"]').val('add_product');

		  $(this).parents(".add_to_trolley").find('div.input').removeClass("submit_cart").addClass("commingsoon");
		  
		  // Infotext austauschen
		  text_first = $(this).parents(".wrapper").children(".text_kundeninfo").children(".first").html();
		  text_last = $(this).parents(".wrapper").children(".text_kundeninfo").children(".last").html();

		  image = '<img src="' + DSTORE_BASE_URL + '/customGates/resources/binaries/'+localeString+'/icons/produktanzeige_comingsoon.gif"'
				+ ' alt="Coming Soon" title="Coming Soon" /><br>';

		  $(this).parents(".add_to_trolley").children('form').children('.kundeninfo').html(image + text_first + ' ' + VariantInfos[parseInt(treeNodeID)]['Date'] + ' '+ text_last);
		  $(this).parents(".add_to_trolley").children('form').children('.kundeninfo').addClass("active");
		  $(this).parents(".add_to_trolley").children('form').children('.submit').children('.input').remove("soldout");
	  } else if (VariantInfos[parseInt(treeNodeID)]['Info'] == 'lieferbar' || VariantInfos[parseInt(treeNodeID)]['Info'] == 'Lieferbar') {
		  $(this).parents(".add_to_trolley").children('form').children('.kundeninfo').removeClass("active");
		  
		  $(this).parents(".add_to_trolley").find('input[name="screen"]').val('dstore.order.trolley');
		  $(this).parents(".add_to_trolley").find('input[name="ClassName"]').val('Trolley');
		  $(this).parents(".add_to_trolley").find('input[name="task"]').val('update');

		  $(this).parents(".add_to_trolley").find('div.input').removeClass("commingsoon").addClass("submit_cart");
		  
		  // Warenkorb Bild austauschen
		  $(this).parents(".add_to_trolley").children('form').children('.submit').children('.input').html('<input type="image"' 
				+ ' src="' + DSTORE_BASE_URL+'/customGates/resources/binaries/'+localeString+'/buttons/shop_productlist_to_trolley.gif"'
				+ ' alt="" title="" />'
			  );

		  $(this).parents(".add_to_trolley").children('form').children('.submit').children('.input').remove("soldout");

		  
//		  $(this).parents(".add_to_trolley").find(".submit_cart").on("click", function(e) {
		  $(this).parents(".add_to_trolley").find(".submit_cart").click( function(e) {
				e.preventDefault();
				submitCartFromList($(this).parents("form"));
		  });
		  
	  } else if (VariantInfos[parseInt(treeNodeID)]['Info'] == 'soldout') {
		  $(this).parents(".add_to_trolley").children('form').children('.kundeninfo').removeClass("active");
		  
		  $(this).parents(".add_to_trolley").find('input[name="screen"]').val('dstore.order.trolley');
		  $(this).parents(".add_to_trolley").find('input[name="ClassName"]').val('Trolley');
		  $(this).parents(".add_to_trolley").find('input[name="task"]').val('update');
		  
		  // Warenkorb Bild austauschen
		  $(this).parents(".add_to_trolley").children('form').children('.submit').children('.input').html('<img alt="" title=""'  
				+ ' src="' + DSTORE_BASE_URL+'/customGates/resources/binaries/'+localeString+'/icons/produktanzeige_soldout.gif" />'
		  );
		  $(this).parents(".add_to_trolley").children('form').children('.submit').children('.input').addClass("soldout");
	  }
   });
   
   
   $("a.product_detector").hover(function(e)
   {			
		this.t = this.title;
		this.title = "";									  
		$("body").append(
			"<p id='product_detector_tooltip'>"
			+ '<span class="icon">&nbsp;'
			+ '</span>'
			+ '<span class="text">'
			+ this.t 
			+ '</span>'
			+"</p>"
		);
		$("#product_detector_tooltip")
			.css("top",($("a.product_detector").offset().top ) + "px")
			.css("left",($(".right_colum").offset().left + 50) + "px")
			.fadeIn(50);		
    },
	function()
	{
		this.title = this.t;		
		$("#product_detector_tooltip").remove();
    });	
	
//	$("a.tooltip").mousemove(function(e){
//		$("#tooltip")
//			.css("top",(e.pageY - xOffset) + "px")
//			.css("left",(e.pageX + yOffset) + "px");
//	});			

}); // $(document).ready( function()

function documentready()
{ 
	$(".add_to_trolley form .submit_cart").click( function(e) {
		e.preventDefault();
		submitCartFromList($(this).parents("form"));
	});
	
	$(".trolley .add_to_trolley").click( function(e) {
		e.preventDefault();
		submitCart($(this).parents("form"));
	});
	
	$("a.share_product").click(function() {
		rel = $(this).attr("rel");
		rels = rel.split(' ');
		treeNodeID = rels[0];

		openShareProductDialog(treeNodeID);
	});

	// Grössentabellen link auf der extended Produktansicht.
	$(".size .link .sizetable").attr("target", "");
	$(".size .link .sizetable").attr("href", "javascript:void(0);");
	
	$(".size .link .sizetable").click( function () {
		parameters = $(this).attr("rel").split(" _");
		$.ajax({
			   type: "GET",
			   url: DSTORE_BASE_URL + "/index.php",
			   data: 'screen=dstore.shop.ajax.groessentabellen&Hersteller='
				   		+parameters[0]+'&Bereich='+parameters[1]+'&Oberkategorie='
				   		+parameters[2]+'&Kategorie='+parameters[3]+'&Name='+parameters[4]+"&Kids="
				   		+parameters[5],
			   dataType: 'json',
			   success: function(msg)
			   {
					if (msg.MAIN != '') {
						$('#AjaxContainer').html(unescape(msg.MAIN));
						ModalDialog = $('#AjaxContainer').modal({
							overlayCss: {
						    backgroundColor: '#000',
						    cursor: 'wait'
						  },
						  containerCss: {
						    overflow: 'auto',
						    border: '1px solid #3a3a3a',
						    backgroundColor: '#FFF'
						  },
						  onShow : function(dialog){ }
						});
			   		}
			   },
			   error: function(xhr)
			   {
				   //alert(xhr.responseText);
			   }
		});
	});
	

	// QuickView in Produktlisten
	var quickViewOut = {};
	$(".productlist.summary .picture .inner").hoverIntent({
		over:function(){
			var pictureElem = $(this).parent(".picture");
			var id = pictureElem.attr("id").split("t");

			quickViewOut[id] = false;
			if ($('#ProductOverlay_'+id[1]+' .overlay').find('.product_picture').length == 0) {
				$.ajax({
				   type: "GET",
				   url: DSTORE_BASE_URL + "/" +localeString +"/index.php",
				   data: 'screen=dstore.shop.ajax.product_overlay&TreeNodeID='+id[1],
				   dataType: 'json',
				   success: function(msg)
				   {
					   if(quickViewOut[id] == true)
							return;
					   
					   $('#ProductOverlay_'+id[1]+' .overlay').html(unescape(msg.MAIN));
					   
					   // In QuickView das gleiche Bild anzeigen wie in der Liste
					   nextButton = pictureElem.find('.inner .next');
					   if(nextButton.length > 0){
						   var attr = nextButton.attr('rel');
						   var bcids = attr.substring(0, attr.length - 1).split('|');
						   var img = pictureElem.find('.inner img');
						   var currentBCID = img.attr('id');
						   
						   if(jQuery.inArray(currentBCID, bcids) != -1){
							   var overlaypic = pictureElem.find('.container_overlay .pic_product img');
							   var params = overlaypic.attr('src').split('?');
							   params = params[1].split('&');
							   var transform = "";
							   for (var i = 1; i < params.length; i++) {
								   transform += '&'+params[i];
							   }
							   overlaypic.attr("src", DSTORE_BASE_URL + '/gateTools/scripts/binary.php?BinaryCodeID='+ currentBCID + transform);
						   }
					   }
					   
					   $('#ProductOverlay_'+id[1]).css('opacity', '');
					   $('#ProductOverlay_'+id[1]).stop().fadeIn(50);
					   
				   },
				   error: function(xhr)
				   {
	//					alert(xhr.responseText);
				   }
				});
			} else {
			   $('#ProductOverlay_'+id[1]).css('opacity', '');
			   $('#ProductOverlay_'+id[1]).stop().fadeIn(50);
			}
				
		},
		timeout: 20,
		out:function(){
			id = $(this).parent(".picture").attr("id").split("t");
			quickViewOut[id] = true;
			$('#ProductOverlay_'+id[1]).stop().fadeOut(50);
		}
	});
	
	
	/*** Produktoverlays am Browerfenster ausrichten ***/
	moveProductOverlays();
	
	$("select").each(function (i) {
		if(!$(this).hasClass('fixedwidth'))
		{
			 $(this).css('width', $(this).outerWidth()+4);
		}

      });

	$("select")
		.selectBox()
		.focus( function(){})
		.blur( function(){})
		.change( function(){
		});
		
		if(window.location.hash) 
		{
			var hash_value = window.location.hash.replace('#', '');

			if(hash_value == "BVRRWidgetID")
			{
				showProductViewTab('rating');
				$(this).scrollTop($("#BVRRContainer").offset().top);
			}
		}

	$("#product_details .headlines a").click( function() {
		splittedID = $(this).attr('id').split('_');
		
		showProductViewTab(splittedID[1]);
	});


/*** Produktbilder durchswitchen */
	
	$('.prev').each(
		function(){
			$( this ).bind (
				"click",
				function(){

					var attr = $(this).attr('rel');
					var bcids = attr.substring(0, attr.length - 1).split('|');
					var length = bcids.length;

					var img = $(this).parent().children().find('.product_image');

					var id = img.attr('rel');
					var size = img.attr('src').split('?');
					size = size[1].split('&');
					var transform = "";
					for (var i = 1; i < size.length; i++) {
						transform += '&'+size[i];
					}

					var pos = jQuery.inArray(id, bcids);

					var overlaypic = $(this).parent().parent().find('.container_overlay').find('.pic_product').find('img');

					if(pos > 0 )
					{
						newbcid = bcids[pos-1];
					}
					else
					{
						newbcid = bcids[length-1];
					}
					img.attr("src", "");
					img.attr("src", DSTORE_BASE_URL + '/gateTools/scripts/binary.php?BinaryCodeID='+ newbcid + transform);
					overlaypic.attr("src", DSTORE_BASE_URL + '/gateTools/scripts/binary.php?BinaryCodeID='+ newbcid +'&convert[-resize]=246x356');
					img.attr("rel", newbcid);

				}
		);
		}
	);

	$('.next').each(
		function(){
			$( this ).bind (
				"click",
				function(){
					attr = $(this).attr('rel');
					var bcids = attr.substring(0, attr.length - 1).split('|');
					var binaries = new Array();
					for (var i=1; i < bcids.length; i++) {
						binaries[i-1] = bcids[i];
					}
					binaries[i-1] = bcids[0];
					bcids = binaries;
					var length = bcids.length;
					
					var img = $(this).parent().children().find('.product_image');

					var id = img.attr('rel');

					var srcstr = img.attr('src');
					
					if (srcstr.indexOf("/list_extended/") >= 0)
					{
						var transform = '&convert[-resize]=192x282';
					}
					else if(srcstr.indexOf("/ details_list/") >= 0)
					{
						var transform = '&convert[-quality]=85&convert[-resize]=120x176';
					}
					else if (srcstr.indexOf("/list/") >= 0)
					{
						var transform = '&convert[-quality]=85&convert[-resize]=134x200';
					}
					else
					{
						var size = img.attr('src').split('?');

						size = size[1].split('&');
						var transform = "";
						for (var j = 1; j < size.length; j++) {
							transform += '&'+size[j];
						}
					}

					

					var pos = jQuery.inArray(id, bcids);

					var overlaypic = $(this).parent().parent().find('.container_overlay').find('.pic_product').find('img');

					if(pos < length -1 )
					{
						newbcid = bcids[pos+1];
					}
					else
					{
						newbcid = bcids[0];
					}

					img.attr("src", DSTORE_BASE_URL + '/gateTools/scripts/binary.php?BinaryCodeID='+ newbcid + transform);
					overlaypic.attr("src", DSTORE_BASE_URL + '/gateTools/scripts/binary.php?BinaryCodeID='+ newbcid +'&convert[-resize]=246x356');
					img.attr("rel", newbcid);

				}
		);
		}
	);

	/**
	 * Dynamisch aufklappender Footer
	 */

	initialFooterPosition = $("#footer").offset().top;

	// Nur sichtbar, wenn JavaScript aktiv
	$(".small_trolley .container .popdown").removeClass("hidden");
	$(".small_trolley .container .popdown").unbind('click');
	$(".small_trolley .container .popdown").click(function() {
		openTrolleyOverlay();
	});

} // function documentready()

$(window).load( function() {
	if($('#multiteaser').length > 0)
		initMultiteaser();
});

/**************************/
/*** Scrollbarer Footer ***/
/**************************/
$(window).scroll(function() {
	var footer = $('#footer');
	var servicelabel = $('#stickyfooter');

	if(servicelabel.hasClass("closed"))
	{
		if(servicelabel.offset().top + servicelabel.height() >= footer.offset().top)
		{
			servicelabel.addClass("sticky");
			$("#stickyfooter img").attr("src", DSTORE_BASE_URL + '/customGates/resources/binaries/'+localeString+'/icons/service.png');
		}

		if($(window).scrollTop() + $(window).height() < servicelabel.offset().top + servicelabel.height())
		{
			servicelabel.removeClass("sticky");
			$("#stickyfooter img").attr("src", DSTORE_BASE_URL + '/customGates/resources/binaries/'+localeString+'/icons/service_up.png');
		}
	}
	else
	{
		if(servicelabel.hasClass("open"))
		{
			if(servicelabel.offset().top >= initialFooterPosition -56)
			{
				footer.removeClass("open");
				footer.addClass("normal");
				servicelabel.removeClass("open");
				servicelabel.addClass("closed");
				servicelabel.addClass("sticky");
				
			}
		}
	}
});

/***********************************/
/*** Produktoverlays verschieben ***/
/***********************************/
function moveProductOverlays() {

	if ($("div.container_overlay").parents(".productlist").hasClass("topfive") == false) {
		if ($(document).width() < 1171) {
			width = (1171 - parseInt($(document).width())) / 2;	
			$("div.container_overlay .overlay").each(function() {
				if ($(this).hasClass("position_0")) {

					if (overlay_positionZero == null)
						overlay_positionZero = $(this).css("left");
					left = (parseInt(overlay_positionZero) + parseInt(width)) + -1;
					
					$(this).css("left", left);
				} else if ($(this).hasClass("position_1")) {
					if (overlay_positionOne == null)
						overlay_positionOne = $(this).css("left");
					
					left = (parseInt(overlay_positionOne) + parseInt(width)) + -1;
					$(this).css("left", left);
				} else if ($(this).hasClass("position_2")) {
					if (overlay_positionTwo == null)
						overlay_positionTwo = $(this).css("left");
					
					left = (parseInt(overlay_positionTwo) + parseInt(width)) + -1;
					$(this).css("left", left);
				} else if ($(this).hasClass("position_3")) {
					if (overlay_positionThree == null)
						overlay_positionThree = $(this).css("left");
					
					left = (parseInt(overlay_positionThree) + parseInt(width)) + -1;
					$(this).css("left", left);
				} else if ($(this).hasClass("position_4")) {
					if (overlay_positionFour == null)
						overlay_positionFour = $(this).css("left");
					
					left = (parseInt(overlay_positionFour) + parseInt(width)) + -1;
					$(this).css("left", left);
				} 
				$(this).css("left", "-"+width);	
			});
		}
	}
}


function markInputFields(ids, className)
{
	var idArray = ids.split("¶");

	for(var j = 0; j < idArray.length; j++)
	{
		document.getElementById(idArray[j]).className += ' '+ className;
		
		if (idArray[j] == "FIELD_geburtsdatum_day" || idArray[j] == "FIELD_geburtsdatum_month" || idArray[j] == "FIELD_geburtsdatum_year")
			idArray[j] = "FIELD_geburtsdatum";

		if (document.getElementById('LABEL_'+idArray[j]))
			document.getElementById('LABEL_'+idArray[j]).className += ' '+ className;

	} // for(var i = 0; i < idArray.length; i ++)
	
} // function markFields()

var i=1;
var multiteaser=null;
var elements=0;


/******************************/
/*** Multiteaser Startseite ***/
/******************************/
function initMultiteaser() {
	
	$('#multiteaser_smallpictures ul li').removeClass('hide');
	elements=1;
 	while(document.getElementById('Multiteaser_'+elements)){
 		elements++;
 	}

 	elements--;
 	startMultiteaser();
 	
 	$('#multiteaser_smallpictures ul').jcarousel({
 		wrap:'circular'
 	});
}

function startMultiteaser()
{
	if($('#Multiteaser_'+i).length > 0)
	{
		SecondsToLife = $('#Multiteaser_'+i).attr("rel");
		Seconds = SecondsToLife.split("_");
		window.clearInterval(multiteaser);
		multiteaser = setInterval('nextMultiteaserElement()', Seconds[1] * 1000);
	}
}

function restartMultiteaser(){
	startMultiteaser();
}

function stopMultiteaser(){
	window.clearInterval(multiteaser);
}

function nextMultiteaserElement() {
	$('#Multiteaser_'+i).fadeOut("normal");
	$('.MultiteaserIcon'+i).removeClass("active");
	if ((i + 1) > elements)
		i = 1;
	else
		i++;

	$('#Multiteaser_'+i).fadeIn("normal", function() {
		$('#multiteaser_smallpictures ul').jcarousel('scroll' ,jQuery.jcarousel.intval(i));
	});
	$('.MultiteaserIcon'+i).addClass("active");
	SecondsToLife = $('#Multiteaser_'+i).attr("rel");
	Seconds = SecondsToLife.split("_");
	window.clearInterval(multiteaser);
	multiteaser = setInterval('nextMultiteaserElement()', Seconds[1] * 1000);
}

function showMultiteaserElement(j) {
	stopMultiteaser();
	if (i != j) {
		$('#Multiteaser_'+i).fadeOut("normal");
		$('.MultiteaserIcon'+i).removeClass("active");
		$('#Multiteaser_'+j).fadeIn("normal");
		$('.MultiteaserIcon'+j).addClass("active");
		i=j;
	}
	multiteaser = setInterval('startMultiteaser()', 15000);
}

/** Countdown fürs Liveshopping */
function countdown(year, month, day, hour, minute) {

	$('#stunden :first-child').html("");
	$('#minuten :first-child').html("");
	$('#sekunden :first-child').html("");
	
	
	Today = new Date();
	Todays_Year = Today.getFullYear() - 2000;
	Todays_Month = Today.getMonth();                  
	Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(), 
	                      Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();                                 
	Target_Date = (new Date(year, month - 1, day, hour, minute, 00)).getTime();                  
	
	Time_Left = Math.round((Target_Date - Todays_Date) / 1000);
	
	if(Time_Left < 0)
	 Time_Left = 0;
	var days = Math.floor(Time_Left / (60 * 60 * 24));
	Time_Left %= (60 * 60 * 24);
	var hours = Math.floor(Time_Left / (60 * 60));
	Time_Left %= (60 * 60);
	var minutes = Math.floor(Time_Left / 60);
	Time_Left %= 60;
	var seconds = Time_Left;
	if(hours < 10) { h0 ='0'; } else { h0=''; }
	if(minutes < 10) { m0 ='0'; } else { m0=''; }
	if(seconds < 10) { s0 ='0'; } else { s0=''; }
	
	var newTime = h0+hours+'h '+m0+minutes+'min '+s0+seconds+'sec';
	
	var h = h0+hours;
	var m = m0+minutes;
	var s = s0+seconds;

	// document.getElementById("countdown").firstChild.replaceData(0, laenge, newTime);
	$('#stunden :first-child').html(h);
	$('#minuten :first-child').html(m);
	$('#sekunden :first-child').html(s);

	setTimeout('countdown(\'' + year + '\',\'' + month + '\',\'' + day + '\',\'' + hour + '\',\'' + minute + '\');', 1000);
}

function submitCartFromList(form)
{
	$(form).children("input[name='screen']").attr('value', 'dstore.order.ajax.trolley');

	$.ajax({
		   type: "GET",
		   url: DSTORE_BASE_URL + '/index.php',
		   data: $(form).serialize(), 
		   dataType: 'json',
		   success: function(msg)
		   {
			   $('.msgContainer').remove();
			   
			   productElem = $(form).closest('.product');
			   if(msg.ErrorMessage != undefined){
				   $(productElem).find('.wrapper').prepend(
					   '<div class="msgContainer">'
						+'<img title="" alt="" src="'+DSTORE_BASE_URL
						+'/customGates/resources/binaries/universal/icons/message_error.gif" />'
						+'<div class="text">'+unescape(msg.ErrorMessage)
						+'<div class="clearer"></div></div></div>'
					);
			   }
			   else{
				   submitCartAction(msg, productElem);
				   $(productElem).find('.success_message').css('display', 'block');
				   $(productElem).find('.success_message').delay(6000).fadeOut();
			   }
		   },
		 	error: function(response)
		 	{
			   closeOverlayLoader();
			   
			   $(form).children(".AddToCart").children("input").attr('disabled', '');
		 	}
	});
}

function submitCart(form)
{
	$(form).children("input[name='screen']").attr('value', 'dstore.order.ajax.trolley');
	$(form).children("input[name='ClassName']").attr('value', 'Trolley');

	$.ajax({
		   type: "GET",
		   url: DSTORE_BASE_URL + '/index.php',
		   data: $(form).serialize(), 
		   dataType: 'json',
		   success: function(msg)
		   {
			   if(msg.ErrorMessage != undefined){
				   clearTimeout(cartMessageTimer);
				   $('#msg_error .text').html(unescape(msg.ErrorMessage));
				   $('#product .right_colum .trolley .error_message').fadeIn();
				   cartMessageTimer = setTimeout(function(){
					   $('#product .right_colum .trolley .error_message').fadeOut();
				   }, 10000);
			   }
			   else{
				   clearTimeout(cartMessageTimer);
				   
				   submitCartAction(msg, $('#product'));
				   $('#product .right_colum .trolley .success_message').css('display', 'block');
				   cartMessageTimer = setTimeout(function(){
					   $('#product .right_colum .trolley .success_message').fadeOut();
				   }, 10000);
			   }
		   },
		 	error: function(response)
		 	{
			   closeOverlayLoader();
			   
			   $(form).children(".AddToCart").children("input").attr('disabled', '');
		 	}
	});
	
}

function submitCartAction(msg, elem){
	target = $('#small_trolley_icon');
	productImage = $(elem).find('.product_image');
    endPosition = target.offset(),
    startPosition = productImage.offset();
    windowHeight = $(window).height();
    
    endPositionTop = endPosition.top;
    if(startPosition.top > windowHeight){
    	endPositionTop = startPosition.top - windowHeight;
    }
    
     animation = {
             top: endPositionTop,
             left: endPosition.left,
             height: target.innerHeight(),
             width: target.innerWidth()
     };
    
    transfer = $('<div class="ui-effects-transfer"></div>')
    .appendTo(document.body)
    .css({
    		backgroundImage:'url('+productImage.attr('src')+')',
            top: startPosition.top,
            left: startPosition.left,
            height: productImage.innerHeight(),
            width: productImage.innerWidth(),
            position: 'absolute'
    })
    .animate(
			animation, 700, 'swing', function(){
				transfer.remove();
				$('.small_trolley_summary').html(unescape(msg.MAIN));
			});

}

function changeSize(elem){
	variantTNID = $(elem).find('option:selected').val();

	$.ajax({
		   type: "GET",
		   url: DSTORE_BASE_URL + '/'+ localeString + "/index.php",
		   data: 'screen=dstore.shop.ajax.change_size&TreeNodeID='+variantTNID,
		   dataType: 'json',
		   success: function(msg)
		   {			   
				if (msg.MAIN != '') 
				{
					$('#product .trolley').replaceWith(unescape(msg.MAIN));
				
					$(".trolley .add_to_trolley").click( function(e) {
						e.preventDefault();
						submitCart($(this).parents("form"));
					});
		   		}
				if (msg.LEFT != '') 
				{
					$('#Quantity').selectBox('destroy');
					$('#Quantity').replaceWith(unescape(msg.LEFT));
					
					$("#Quantity").each(function (i) 
					{
						if(!$(this).hasClass('fixedwidth'))
						{
							$(this).css('width', $(this).outerWidth()+4);
						}

					});

					$("#Quantity")
						.selectBox()
						.focus( function(){})
						.blur( function(){})
						.change( function(){
						});

		   		}
				if (msg.BOTTOM != '') 
				{
					$('#verknappung').replaceWith(unescape(msg.BOTTOM));
				}
				else
				{
					$('#verknappung').empty();
				}
				if (msg.SIZE != '') 
				{
					$('#masse').replaceWith(unescape(msg.SIZE));
				}
				else
				{
					$('#masse').empty();
				}
		   },
		   error: function(xhr)
		   {
//			   console.log(xhr);
		   }
	});
}

// Wenn in dem Gutscheinfeld im Warenkorb etwas steht aber noch nicht eingelöst wurde, dann wir eine meldung.
function checkVoucher() {
	
	if ($('#FIELD_voucher_code').val() != undefined && $('#FIELD_voucher_code').val() != "") {
		if (localeString == 'en_GB')
			alert("You've entered a vouchercode. Please click on \"redeem\" to encash your benefit.");
		else 
			alert("Du hast einen Gutscheincode eingegeben. Bitte klicke zunächst auf den \"Einlösen\"-Button um deinen Gutscheincode einzulösen.");
		$('#FIELD_voucher_code').css('border', '1px solid red');
	} else {
		$('#rollout').submit();
	}
}
