var tier_update = [];
var tier_interval;
var rotator_interval;

jQuery('document').ready(function($){
	$('.pager .pages ol li a.previous, .pager .pages ol li a.next').closest('li').remove();
	
	$('.pager .pages ol li:last-child').addClass('last');

	$('body:not(".cms-index-index") .slider').productslider({'items' : 4});
	$('body.cms-index-index .slider').productslider();
	
	if (!$('.breadcrumbs').length) {
		$('body').addClass('no-breadcrumbs');
	}
	
	if (!$('.sidenav li.active').length) {
		$('body:not(".is-blog") .sidenav li.level0.nav-1').addClass('active');
	}
	
	$('body.cms-page-view').each(function(i,e){ // auto current class in cms nav
		classes = $(this).attr('class').split(" ");
		$(classes).each(function(ix,ex){
			if (ex != "")
			{
				ex = ex.replace('cms-', '');
				if (ex != 'page-view')
				{
					$('.cms-nav li.' + ex).addClass('current');				
				}
			}
		});
	});
	
	$('body').each(function(i,e){ // auto current topcat
		classes = $.trim($(this).attr('class')).split(' ');
		$(classes).each(function(ind, elem){
			if (strpos(elem, 'categorypath') === false) { return };
			catpath = elem.split('-')
			catpath.shift();
			catpath = catpath.shift();
			$('body').addClass('rootcat-' + catpath);
		});
	});
	
	// remaining chars
	
	$('input.validate-length, textarea.validate-length').each(function(i,e){
		classes = $.trim($(this).attr('class')).split(' ');
		$(classes).each(function(ind, elem){
			if (strpos(elem, 'maximum-length-') === false) { return };
			elem = parseInt(elem.replace('maximum-length-', ''), 10);
			$(e).data('maxlen', elem);
		});
	});

	$('input.validate-length, textarea.validate-length').bind('keyup', function(e){
		curlen = $(this).val().length;
		maxlen = $(this).data('maxlen');
		remain = maxlen - curlen;
		
		if (remain < 0)
		{
			st = 'color:red';
		}
		else
		{
			st = '';
		}
		
		$('+p.note', this).html('Maximale Anzahl von Zeichen: <strong style="' + st + '">' + remain + '</strong>');
	});
	
	// newsletter focus/blur
	
	$('#newsletter').bind('focus', function(e){
		if ($(this).val() == 'Ihre E-Mail Adresse')
		{
			$(this).val('');
		}
	});

	$('#newsletter').bind('blur', function(e){
		if ($(this).val() == '')
		{
			$(this).val('Ihre E-Mail Adresse');
		}
	});
	
	
	// main start banner
	
	banner_num = $('.start-banner-main ul li').length;
	
	access_btns_string = '<div class="access-buttons">';
	$.each($('.start-banner-main ul li a'), function(i,e){
		access_btns_string += '<div class="access-button';
		if (i == 0) access_btns_string += ' active';
		access_btns_string += '" rel="' + (banner_num - i) + '">' + (banner_num - i) + '</div>';
	});
	access_btns_string += '</div>';
	$access_btns = $(access_btns_string);
	$('.start-banner-main').append($access_btns);

	
	$('.start-banner-main ul li').each(function(i,e){
		$(e).attr({'rel' : i + 1});
	});

	rotate_stuff = function(){
		el = jQuery('.start-banner-main ul li:last-child');
		
		$current_access_btn = jQuery('.access-button.active');
		$next_access_btn = $current_access_btn.next('.access-button');
		if (!$next_access_btn.length)
		{
			$next_access_btn = jQuery('.access-button').filter(':first');
		}
	
		$current_access_btn.removeClass('active');
		$next_access_btn.addClass('active');
		
//		jQuery('.start-banner-main ul li a').length()
		
		jQuery(el).fadeOut(2000, function(){
			xx = jQuery(this).detach();
			jQuery('.start-banner-main ul').prepend(xx);
			jQuery(xx).show();
		});
	}

	if ($('.cms-index-index').length > 0)
	{
		rotator_interval = setInterval('rotate_stuff()', 7000);
		
		$('.start-banner-main').hover(function(){
			clearInterval(rotator_interval);
		}, function(){
			clearInterval(rotator_interval);
			rotator_interval = setInterval('rotate_stuff()', 7000);		
		});
		
		$('.access-button').live('click', function(){
			clearInterval(rotator_interval);
			clicked_el = this;
			this_rel = jQuery(this).attr('rel');
//			alert('this rel is ' + this_rel);
			
			el = jQuery('.start-banner-main ul li:last-child');
			banner_rel = el.attr('rel');
//			alert('cur banner rel is ' + banner_rel);

			if (banner_rel != this_rel)
			{
				jQuery(el).fadeOut(0, function(){
					xx = jQuery(this).detach();
					jQuery('.start-banner-main ul').prepend(xx);
					jQuery(xx).show();
					jQuery(clicked_el).trigger('click');
				});			
			}
			else
			{
				$('.access-button.active').removeClass('active');
				$(this).addClass('active');			
//				rotator_interval = setInterval('rotate_stuff()', 7000);
			}
		});
	}

	// PRICEDIFF UPDATE

	left_until_free_shipping = (45 - freeshippingdiff).toFixed(2);

	if ((left_until_free_shipping > 0) && (left_until_free_shipping < 45)) {
		$('.freeshipping > p').html("Noch " + (' ' + left_until_free_shipping).replace('.', ',') + ' € bis zum kos&shy;ten&shy;freien Versand innerhalb DE!<a href="/zahlung-und-versand">Das Angebot gilt nicht für Nachnahme und Express Lieferungen</a>').css('background-color', 'yellow');
	}
	else if (left_until_free_shipping < 0)
	{
		$('.freeshipping > p').html("Ihre Lieferung erfolgt innerhalb DE versandkostenfrei!").css({'color' : '#62b500', 'font-weight' : 'bold'});	
	}

	// Noch 22,20 € bis zur versand&shy;kosten&shy;freien Lieferung

	$('body.checkout-cart-index').each(function(i,e){
//		alert("Noch X €, dann sparen Sie sich die Versandkosten!");
	});


	/* Niedrigster "ab"-Preis bei Staffelpreisen */
	
	if($('.catalog-product-view .tier-prices li').length > 0)
	{
		$('.prpr .price').html($('.catalog-product-view .tier-prices li').last().find('.price').html()); // update price shown at top - "ab XX €"

		tier_update[0] = parseFloat($('.product-options-bottom .price-cart .value .price').html().replace(' €', '').replace(',', '.'));

		$('.catalog-product-view .tier-prices li').each(function(){
			anzahl = $(this).html().match(/ab (\d{1,}) zu je/);
			preis = parseFloat($('.price', this).html().replace(' €', '').replace(',', '.'));
			tier_update[anzahl[1]] = preis;
		});
		
		$('.product-options input, .product-options select, .product-options textarea').bind('keyup change', function(){ 
			tier_interval = setInterval('recalcTierPrices()', 10) // don't ask, don't tell. without interval, there's conflicts with magento's own updating.
		});
	}
	
	$('.block-cat-shortdesc .block-content').each(function(){
		prevhtml = $(this).html();
		prevhtml = prevhtml.split('<!-- more -->');
		if (prevhtml.length > 1) {
			prevhtml[1] = '<span class="showme"><a class="showmore" href="#">mehr ...</a><span class="notshown">' + prevhtml[1] + '</span></span>';
			prevhtml = prevhtml.join(" ");
			$(this).html(prevhtml);
		}
	});
	
	$('.block-cat-shortdesc .block-content .showme .showmore').live('click', function(e){
		e.preventDefault();
		$(this).next('.notshown').show();
		$(this).remove();
	});


	// trusted shops erweiterung für newsletter
	
	$('#preconfirm').click(function(){
		$(this).closest('.pre-confirm').detach();
		$('.input-box').css({ 'display' : 'block' });
	});

});

recalcTierPrices = function(){
	clearInterval(tier_interval);
	current_qty = parseInt(jQuery('#qty').val().match(/\d{1,}/), 10);
	if ((current_qty == '') || !current_qty) return;
	sel_qty = current_qty;
	while (!tier_update[sel_qty])
	{
		sel_qty--;
	}
	
	price_add = 0;
	
	if (optionsPrice.getOptionPrices() instanceof Array)
	{
		price_add = optionsPrice.getOptionPrices()[0];
	}
	
	html = (tier_update[sel_qty] + price_add).toFixed(2) + " €";
	
	jQuery('.product-options-bottom .price-cart .value .price').html(html.replace('.', ','));
};

function limitYear($, year) {
	fromyear = parseInt(year, 10);
	$('.product-custom-option.datetime-picker').each(function(i,e){
		isyr = $.trim($(e).attr('id')).split('_').pop();
		if (isyr != "year") { return; }
		$('option', e).each(function(ix,ex){
			if (parseInt($(ex).attr('value'), 10) < fromyear)
			{
				$(ex).remove();
			}
		});
	});
}

(function($){
	$.fn.productslider = function(options){
		var settings = {
			'items' : 5
		};
		
		return this.each(function(){
			if (options) {
				$.extend(settings, options);
			}
			
			itemheight	= $('ul li', this).outerHeight(true);
			itemwidth	= $('ul li', this).outerWidth(true);
			maxstep		= $('ul li', this).length - settings.items;
			curstep		= 0;
			
			$(this).data('maxstep', maxstep);
			$(this).data('curstep', curstep);

			
			$(this).css({
				'height' : itemheight + 'px',
				'overflow' : 'hidden',
				'position' : 'relative'
			});

			width_diff	= $(this).innerWidth() - (itemwidth * settings.items);

			$('ul', this).css({
				'height' : itemheight + 'px',
				'width' : '100000px',
				'left' : (width_diff / 2) + 'px',
				'position' : 'absolute'
			});
			
			if (settings.items < $('ul li', this).length)
			{
				$(this).append('<a href="#" class="slidebtn goleft">nach links</a>');
				$(this).append('<a href="#" class="slidebtn goright">nach rechts</a>');	
			
				$('.slidebtn.goleft', this).css({
					'left' : '0',
					'width' : (width_diff / 2) + 'px',
					'height' : itemheight + 'px'
				}).animate({'opacity' : 0.2}, 0);
				$('.slidebtn.goright', this).css({
					'right' : '0',
					'width' : (width_diff / 2) + 'px',
					'height' : itemheight + 'px'
				});
				
				$('.slidebtn', this).click(function(e){
					e.preventDefault();
					slider = $(this).closest('div');
	
					maxstep = $(slider).data('maxstep');
					curstep = $(slider).data('curstep');
					
					nextstep = ($(this).hasClass('goleft')) ? curstep - 1 : curstep + 1;
					if ((nextstep < 0) || (nextstep > maxstep)) return;
					$('> ul', slider).animate({
						left : (($(this).hasClass('goleft')) ? '+' : '-') + '=' + itemwidth
					}, 600, 'easeOutCubic', function(){
						if (curstep == 0)
						{
							$('.slidebtn.goleft', slider).animate({'opacity' : 0.2}, 500);
						}
						else
						{
							$('.slidebtn.goleft', slider).animate({'opacity' : 1}, 500);				
						}
						
						if (curstep == maxstep)
						{
							$('.slidebtn.goright', slider).animate({'opacity' : 0.2}, 500);
						}
						else
						{
							$('.slidebtn.goright', slider).animate({'opacity' : 1}, 500);	
						}
					});
					curstep = nextstep;
					$(slider).data('curstep', curstep);
				});
			}
		});
	}
})(jQuery);

function strpos (haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
