var updateProductPrice = function(scope)
{
	var singlePrice = parseFloat($('.single_price', scope).val());
	
	var currentAmount = parseInt($('.quantity_current', scope).val());
	var amount = parseInt($('.quantity_wanted', scope).val());
	var quantityAvailable = parseInt($('.quantity_available', scope).val());
	var freeShippingLimit = parseInt($('.free_shipping_limit', scope).val());
	if(amount > quantityAvailable)
	{
		amount = quantityAvailable;
		$('.quantity_wanted', scope).val(amount);
	}
	var priceQuantity = roundToNDigits(amount * singlePrice, 2);
	$('.price_quantity', scope).html(
		'= ' + priceQuantity.toString().split('.').join(',') + ' &euro;'
	);
	if(priceQuantity > freeShippingLimit)
	{
		$('#free_shipping_info').show('slow');
	}
	else
	{
		$('#free_shipping_info').hide('fast');
	}
}


var updateCart = function(scope)
{
	var availableAmount = parseInt($('.quantity_available', scope).val());
	var currentAmount = parseInt($('.quantity_current', scope).val());
	var amount = parseInt($('.quantity_wanted', scope).val());
	if(amount > availableAmount) amount = availableAmount;
	if(amount < 1)
	{
		window.location.href = $('.del_link', scope).val();
		return;
	}
	var diff = amount - currentAmount;
	if(diff != 0)
	{
		$('.quantity_wanted_incr', scope).unbind('click');
		$('.quantity_wanted_decr', scope).unbind('click');
		$('.quantity_wanted', scope).unbind('blur');
		window.location.href = $(diff > 0 ? '.add_link_up' : '.add_link_down', scope).val().replace('|||', diff);
	}
}


var roundToNDigits = function(x, n)
{
  if (n < 1 || n > 14) return false;
  var e = Math.pow(10, n);
  var k = (Math.round(x * e) / e).toString();
  if (k.indexOf('.') == -1) k += '.';
  k += e.toString().substring(1);
  return k.substring(0, k.indexOf('.') + n+1);
}


var interval;
var slidePos = 0;
var slideTime = 10000;
var animateSlideshow = function(delta)
{
	if(delta == undefined) delta = -1;
	var slidelist = $('#slidelist');
	var nSlides = $('li', slidelist).length;
	var marginLeft = parseInt(slidelist.css('margin-left').split('px').join(''));
	slidePos = slidePos + (delta < 0 ? 1 : -1);
		if(slidePos > nSlides - 1) slidePos = 0;
		if(slidePos < 0) slidePos = nSlides - 1;
	slidelist.stop().animate({marginLeft: (-170 * slidePos) + 'px'}, 1000);
}


jQuery(document).ready(function()
{
	$('.p_thumb_wrap', '#center_column')
		.hover(
			function (e)
			{
				var scope = $(this);
				if(scope.hasClass('p_thumb_soldout')) return;
				if(!$.browser.msie)
				{
					$('.p_pricetag', scope).stop(false).animate({ top: '115px' }, 'fast');
					if($('.p_hover', scope).length > 0)
					{
						$('.p_cover', scope).stop(false).animate({ opacity: 0 });
						$('.p_hover', scope).stop(false).animate({ opacity: 1 });
					}
					$('.p_link_view', scope).stop(false).animate({ opacity: 1 });
					$('.p_link_cart', scope).stop(false).animate({ opacity: 1 });
					$('.p_award', scope).stop(false).animate({ opacity: 0 });
					$('.p_name', scope).stop(false).animate({ top: '180px' });
				}
				else
				{
					$('.p_pricetag', scope).css('top', '115px');
					if($('.p_hover', scope).length > 0)
					{
						$('.p_cover', scope).hide();
						$('.p_hover', scope).show();
					}
					$('.p_link_view', scope).show();
					$('.p_link_cart', scope).show();
					$('.p_award', scope).hide();
					$('.p_name', scope).css('top', '180px');
				}
			},
			function (e)
			{
				var scope = $(this);
				if(scope.hasClass('p_thumb_soldout')) return;
				if(!$.browser.msie)
				{
					$('.p_pricetag', scope).stop(false).animate({ top: '148px' });
					$('.p_cover', scope).stop(false).animate({ opacity: 1 });
					$('.p_hover', scope).stop(false).animate({ opacity: 0 });
					$('.p_link_view', scope).stop(false).animate({ opacity: 0 });
					$('.p_link_cart', scope).stop(false).animate({ opacity: 0 });
					$('.p_award', scope).stop(false).animate({ opacity: 1 });
					$('.p_name', scope).stop(false).animate({ top: '211px' }, 'fast');
				}
				else
				{
					$('.p_pricetag', scope).css('top', '148px');
					$('.p_cover', scope).show();
					$('.p_hover', scope).hide();
					$('.p_link_view', scope).hide();
					$('.p_link_cart', scope).hide();
					$('.p_award', scope).show();
					$('.p_name', scope).css('top', '211px');
				}
			}
		)
		.each(
			function ()
			{
				var scope = $(this);
				if(scope.hasClass('p_thumb_soldout')) return;
				if(!$.browser.msie)
				{
					$('.p_hover', scope).stop(false).css('opacity', '0').css('visibility', 'visible');
					$('.p_link_view', scope).stop(false).css('opacity', '0').css('visibility', 'visible');
					$('.p_link_cart', scope).stop(false).css('opacity', '0').css('visibility', 'visible');
				}
				else
				{
					$('.p_hover', scope).css('visibility', 'visible').hide();
					$('.p_link_view', scope).css('visibility', 'visible').hide();
					$('.p_link_cart', scope).css('visibility', 'visible').hide();
				}
			}
		)
	;
	
	$('div.error', '#center_column').fadeIn('slow');
	$('div.success', '#center_column').fadeIn('slow');
	
	$('.slideleft', '.slideshow')
		.click(function ()
		{
			clearInterval(interval);
			animateSlideshow(1);
			interval = setInterval('animateSlideshow()', slideTime);
		})
	;
	
	$('.slideright', '.slideshow')
		.click(function ()
		{
			clearInterval(interval);
			animateSlideshow(-1);
			interval = setInterval('animateSlideshow()', slideTime);
		})
	;
	
	interval = setInterval('animateSlideshow()', slideTime);
	
	if($.browser.msie)
	{
		$('.input', '#center_column')
			.focus(function ()
			{
				 $(this).addClass('input_focused');
			})
			.blur(function ()
			{
				 $(this).removeClass('input_focused');
			})
		;
	}
	
	if($('.quantity_wanted_p').length > 0)
	{
		$('.quantity_wanted')
			.keyup(function(event){
				if(parseInt($(this).val()) > 0)
				{
					if(event.keyCode == 13) $(this).blur();
				}
			})
			.blur(function ()
			{
				if(parseInt($(this).val()) > 0)
				{
					var scope = $(this).parent();
					updateProductPrice(scope);
					if($('body#order').length > 0) updateCart(scope);
				}
			})
		;
		
		$('.quantity_wanted_incr')
			.click(function ()
			{
				var scope = $(this).parent().parent();
				var input = $('.quantity_wanted', scope);
				 var value = parseInt(input.val());
				 var newValue = value + 1;
				 var quantityAvailable = parseInt($('.quantity_available', scope).val());
				 if(newValue <= quantityAvailable) input.val(newValue);
				 updateProductPrice(scope);
				 if($('body#order').length > 0) updateCart(scope);
			})
		;
		
		$('.quantity_wanted_decr')
			.click(function ()
			{
				var scope = $(this).parent().parent();
				 var input = $('.quantity_wanted', scope);
				 var value = parseInt(input.val());
				 var newValue = value - 1;
				 if(newValue > 0) input.val(newValue);
				 updateProductPrice(scope);
				 if($('body#order').length > 0) updateCart(scope);
			})
		;
		
		updateProductPrice($(this));
	}
	
	$('#search_query', '#meta')
		.focus(function ()
		{
			if($('#search_query', '#meta').val() == 'Suche') $('#search_query', '#meta').val('');
			$('#search_block_top', '#meta').addClass('search_block_top_active');
		})
		.blur(function ()
		{
			$('#search_block_top', '#meta').removeClass('search_block_top_active');
			if($('#search_query', '#meta').val() == '') $('#search_query', '#meta').val('Suche');
		})
		.blur()
	;
	
	$('#formNewsletter').submit(
		function()
		{
			var email = $('#ijtklt-ijtklt').val();
			if(!email.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i))
			{
				$('fieldset p', '#formNewsletter').remove();
				$('fieldset', '#formNewsletter').append('<p class="blockinfo blockwhite" style="margin-bottom: 5px;">Bitte geben Sie eine E-Mail-Adresse an.</p>');
			}
			else
			{
				addToNewsletter(email, '');
			}
			
			return false;
		}
	);
	
	if($('#phone', '#center_column').length > 0)
	{
		$('#phone', '#center_column').blur(
			function()
			{
				cleanNumbers($(this));
			}
		).blur();
	}
	
	
	$('#formDebit').submit(
		function()
		{
			debitError = false;
			debitErrorText = '';
			var debitName = $('#debit_name').val();
			cleanNumbers($('#debit_account'));
			var debitAccount = $('#debit_account').val();
			cleanNumbers($('#debit_bankcode'));
			var debitBankcode = $('#debit_bankcode').val();
			var debitBankname = $('#debit_bankname').val();
			
			if(debitName == undefined || debitName == '')
			{
				debitError = true;
				debitErrorText += 'Bitte geben Sie den Kontoinhaber an.<br />';
			}

			if(debitAccount == undefined || debitAccount == '')
			{
				debitError = true;
				debitErrorText += 'Bitte geben Sie die Kontonummer an.<br />';
			}

			if(debitBankcode == undefined || debitBankcode == '')
			{
				debitError = true;
				debitErrorText += 'Bitte geben Sie die Bankleitzahl an.<br />';
			}

			if(debitBankname == undefined || debitBankname == '')
			{
				debitError = true;
				debitErrorText += 'Bitte geben Sie den Namen der Bank an.<br />';
			}
			
			if(debitError)
			{
				$('div.error', '#center_column').remove();
				$('#formDebit').before('<div class="error" id="errorDiv"><p>' + debitErrorText + '</p></div>');
				$('div.error', '#center_column').fadeIn('slow');
				return false;
			}
		}
	);
	
});

var cleanNumbers = function(input)
{
	var nr = input.val();
		nr = nr.split(' ').join('');
		nr = nr.split('-').join('');
		input.val(nr);
}

var addToNewsletter = function(email, name)
{
	$.get(
		"../campaignmonitor/Subscriber.Add.php?m=" + email + "&n=" + escape(name),
		function(txt)
		{
			if((txt == 'Success' || txt.indexOf('Email Address exists in unconfirmed list') > -1) && name == '')
			{
				$('fieldset', '#formNewsletter').html('<p class="blockinfo blockwhite" style="margin-bottom: 5px;">Vielen Dank! Eine E-Mail zur Bestätigung Ihres Newsletter-Abos wurde an die angegebene Adresse versandt.</p>');
			}
		}
	);
}

var removeFromNewsletter = function(email)
{
	$.get(
		"../campaignmonitor/Subscriber.Unsubscribe.php?m=" + email,
		function(txt)
		{}
	);
}

var trackEvent = function(category, action, label)
{
	if(pageTracker != undefined && pageTracker != null)
	{
		pageTracker._trackEvent(category, action, label);
	}
}

