$(window).load(function(){
	$('div.syncHeight, fieldset.syncHeight').syncHeight({ 'updateOnResize': false });
});	

$(document).ready(function() {
	/* SubNavi
	************************************************/
	
	$('#subNav > ul > li').bind({
		mouseenter: function(e){
			var $listElement = $(this);
			
			$('#subNav .subNavActive').each(function(){
				$(this).removeClass('subNavActive');
			});
			
			if($listElement.find('ul').length != 0) {
				$listElement.addClass('subNavActive');
			}
		},
		mouseleave: function(e){
			$('#subNav .subNavActive').removeClass('subNavActive');
		}
	});
	
	$('div.navWidget ul li').bind({
		mouseover: function(e){
			var $listElement = $(this),
				ulIndex      = $listElement.closest('ul').prevAll().length,
				liIndex      = $(this).prevAll().length,
				boxHeight    = 190,
				yPos         = (((ulIndex * 10) + liIndex) * boxHeight);
				
			$listElement.closest('div.navWidget').find('div.navWidgetInfoInner').animate({ marginTop: '-' + yPos + 'px' }, 50);
		}
	});
	
	$('div.navWidgetI')
		
	/* activate accessibility tabs
	************************************************/
	
	var aTabConfig = {
		wrapperClass: 'aTabContent', 
		currentClass: 'active', 
		tabhead: 'h4', 
		tabbody: '.aTabDescr', 
		fx:'fadeIn', // Anzeigeeffekte:  'fadeIn', 'slideDown' oder 'show'
		fxspeed: 300,
		currentInfoText: 'current tab: ', 
		currentInfoPosition: 'prepend', 
		currentInfoClass: 'currentMeta',
		tabsListClass:'aTabList',
		syncheights: false,
		syncHeightMethodName:'syncHeight',
		saveState: true,
		autoAnchor: true,
		pagination: false 
	};
	
	// init Tabs
	$('.aTab').accessibleTabs(aTabConfig).find('> ul.aTabList').wrap('<div class="aTabList"></div>');
	
	// autolink forms to active tab
	$('ul.aTabList > li > a').live('click', function(e){
		var $form       = $(this).closest('form'),
			action      = $form.attr('action'),
			anchorIndex = action.indexOf('#'),
			activeId    = $form.find('ul.aTabList > li.active > a').attr('id');
		
		// remove old anchor
		if(anchorIndex != -1) {
			action = action.substring(0, anchorIndex);
		}
		
		// set new action
		$form.attr('action', action + '#' + activeId);
	});
	
	/* image zoom (fancybox)
	************************************************/
	
	$('a.iframe, a.imageZoom').fancybox({
		'padding': 0,
		'imageScale': true,
		'zoomOpacity': true,
		'zoomSpeedChange': 1000,
		'overlayShow': true,
		'overlayOpacity': 0,
		'enableEscapeButton': true,
		'hideOnOverlayClick': true,
		'hideOnContentClick': true,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'titleShow': true,
		'titlePosition': 'inside',
		'width': 950,
		'height': 500
	});
	
	$('a.youtube').click(function(e){
		e.preventDefault();
		
		$.fancybox({
			'padding': 0,
			'autoScale': false,
			'zoomOpacity': true,
			'zoomSpeedChange': 1000,
			'overlayShow': true,
			'overlayOpacity': 0,
			'enableEscapeButton': true,
			'hideOnOverlayClick': true,
			'hideOnContentClick': false,
			'transitionIn': 'elastic',
			'transitionOut': 'elastic',
			'titleShow': true,
			'titlePosition': 'inside',
			'width': 680,
			'height': 495,
			'href': this.href.replace(new RegExp('watch\\?v=', 'i'), 'v/'),
			'type': 'swf',
			'swf': { 'allowfullscreen': true }
		});
	});

	/* Funktion zeigt beim absenden eines Formulares das DIV loader an, vergrößert dessen Größe mit attr */
	$('input[type^="submit"]').click(function(){
		var scroll_position = get_scrolling_offset();
		var height_wrap	 = $('#globalWrap').height();
		var height_html	 = $('html').height();
		var height_total	= (height_wrap > height_html) ? height_wrap: height_html;
		$('#loader').attr({ style: "height: " + height_total + "px;"});
		$('#loaderimg').attr({ style: "position: absolute; width: 100%; top: " + (scroll_position - 0) + "px;"});
		$('#loader').toggle();
	});

	/********************************************
	********************************************/
	
	$('select.jump').change(function(){
		var target = $(this).find('option:selected').attr('value');
		
		location.href = target;
		console.log('eeee', target);
	});
	
	// External Links
	$('a.popup').click(function(e){
		e.preventDefault();
		window.open(this.href, '_blank');
	});
	/*
	$('a.external[@href^=http]').click(function(){
		var href = $(this).attr('href');
		window.open(href);
		return false;
	});
	$('a[@href^="#"]').click(function() {
		var parts		= this.href.split('#');
		var scrolltarget = '#' + parts[1];
		$(scrolltarget).ScrollTo(800);
		return false;
	});
	*/
	
	/* Submenu
	************************************************/
	
	//$('#subnavi').hide().slideDown(200);

	/********************************************
	********************************************/

	$('a.clone').click(function(){
		var div2clone = 'div.' + $(this).attr('rel') + ':last';
		$(div2clone).clone().insertAfter(div2clone);
		$(div2clone + ' input').each(function(){
			$(this).val('');
		})
		return false;
	});

	/********************************************
	********************************************/

	/* Hat ein Link eine Klasse namens confirm, bekommt er via Javascript eine Frage, die in rel steht */
	$('.confirm').click(function() {
		return confirm($(this).attr('rel') + '?');
	});

	/********************************************
	********************************************/

	$('select.pagingSetPage').change(function() {
		this.form.submit();
	});

	/********************************************
	********************************************/

	/* E-Mails umwandeln: <a href="mailto:box [at-no-spam] server.tld">title</a> */
	$('a.email').each(function(){
		var to_replace = '=at-no-spam=';
		var link	   = $(this).attr('href').replace(to_replace, '@');
		var address	= $(this).html().replace(to_replace, '@');

		$(this).html(address);
		$(this).attr('href', link);
	});

	/********************************************
	********************************************/

	$('div.message').animate({ opacity: 0 }, 5000).slideToggle('slow');
	$('div.extraMessage').hide().animate({ opacity: 100 }, 1000).slideToggle(1000);

	/********************************************
	********************************************/

	$('input.focusMe').focus();

	/********************************************
	********************************************/

	/* Toggle-Funktionen */
	$('.toggleBox > legend').each(function(){
		$(this).append(' <a href="#" class="toggleButton"><img src="/images/icons/16-em-open.png" width="16" height="16" alt="klappen" /></a>');
	});

	$('.toggleBox legend a.toggleButton').click(function(e){
		var toggleBox		= $(this).parent().parent('.toggleBox');
		var toggleBoxContent = toggleBox.find('.toggleBoxContent');
		var displayMode  	= toggleBoxContent.css('display');

		if(displayMode == 'block') {
			$(this).find('img').attr('src', '/images/icons/16-em-down.png');
		} else {
			$(this).find('img').attr('src', '/images/icons/16-em-open.png');
		}

		toggleBoxContent.slideToggle(500);

		return false;
	});

	/********************************************
	********************************************/

	/* Ausblenden der Hinweistafel nach 5 Sekunden */
	$('#globInfo').each(function(){
		var globInfoStatus = $('#globInfo').css('display');
		if(globInfoStatus == 'block') {
			$.timer(5000, function(timer) {
				if($('#globInfo').css('display') == 'block') {
					$('#globInfoMsg').fadeOut('slow');
					$('#globInfo').fadeOut('slow');
					$('#globInfoMsg').empty();
					$('#globInfo').empty();
				}
				timer.stop();
			});
		}
	});

	$('a.closeGlobInfo').click(function(){
		$('#globInfoMsg').fadeOut('slow');
		$('#globInfo').fadeOut('slow');
		$('#globInfoMsg').empty();
		$('#globInfo').empty();
		return false;
	});

	/* Höhe anpassen */
	var height_old = $('#globInfoMsg').height();
	var height_new = (height_old + 20);
	$('#globInfo').height(height_new);

	/********************************************
	********************************************/

	/* erhöht den Wert des Feldes, welches in rel="" angegeben wurde um 1 */
	$('.increase').live('click', function() {
		var field	= '#' + $(this).attr('rel');
		var newValue = Number($(field).val()) + Number(1);
		$(field).val(newValue);
		$('#cartNext').hide();
		return false;
	});

	/* reduziert den Wert des Feldes, welches in rel="" angegeben wurde um 1 */
	$('.decrease').live('click', function() {
		var field    = '#' + $(this).attr('rel'),
			newValue = Number($(field).val()) - Number(1);
			
		if(($(this).hasClass('min0') && newValue >= 0) || (newValue >= 1)) {
			$(field).val(newValue);
		}
		
		$('#cartNext').hide();
		return false;
	});

	/********************************************
	********************************************/

	/* Javascript-Druckfunktion (click = Druckdialog auf Klick, each = Element mit Klasse "printnowFocus" reicht) */
	$('.printnow').click(function(){
		window.print();
		return false;
	});

	$('.printnowFocus').each(function(){
		window.print();
		return false;
	});

	/********************************************
	********************************************/

	relatedProductSearch = {
		start: function() {
			timeout = 0;
			$('#relatedProductSearch').keyup(function() {
				if (this.timeout) {
					clearTimeout(this.timeout);
				}
				$('#spinnerBill').css('visibility', 'visible');
				this.timeout = setTimeout('relatedProductSearch.getdata()', 1000);
			});
		},
		getdata: function() {
			var inputvalue = $('#relatedProductSearch').val();
			if (inputvalue.length > 3) {
				$('#relatedProductResultList').load('/json/', {
					getData: 'relatedProducts',
					lieferantQuery: inputvalue
				});
				/*$('div.floatBox').css('display', 'block');*/
			}
			$('#spinnerBill').css('visibility', 'hidden');
		}
	}
	relatedProductSearch.start();

	/********************************************
	********************************************/

	$('a.relatedProductAdd').live('click', function(){
		var elementId   = $(this).attr('rel');
		var elementName = $(this).attr('title');

		var newElement  = '<li id="relatedProductElement' + elementId +'" class="checkbox">' + "\n"
						+ '	<span class="checkbox"><a href="#" class="relatedProductListDelete" rel="' + elementId +'"><img src="/images/icons/delete.png" alt="remove" /></a></span>' + "\n"
						+ '	' + elementName + "<br />\n"
						+ '	<span class="small gray">(ID ' + elementId + ')</span>' + "\n"
						+ '	<input type="hidden" name="relatedProducts[]" value="' + elementId +'" />'
						+ '</li>' + "\n";

		$('#relatedProductList').append(newElement);
		$('#relatedProductResult' + elementId).remove();

		return false;
	});

	$('a.relatedProductListDelete').live('click', function(){
		var elementId = $(this).attr('rel');
		$('#relatedProductElement' + elementId).remove();

		return false;
	});

	/********************************************
	********************************************/

	/* Produktschnellsuche über die Navigation */
	$('a.productQuickSearch').click(function(){
		$('#productQuickSearchField').attr('value', '');
		$('#productQuickSearchList').empty();
		$('#productQuickSearch').toggle('fast');

		return false;
	});

	productQuickSearch = {
		start: function() {
			timeout = 0;
			$('#productQuickSearch').keyup(function() {
				if (this.timeout) {
					clearTimeout(this.timeout);
				}
				$('#spinnerBill').css('visibility', 'visible');
				this.timeout = setTimeout('productQuickSearch.getdata()', 1000);
			});
		},
		getdata: function() {
			var inputvalue = $('#productQuickSearchField').val();
			if (inputvalue.length >= 1) {
				$('#productQuickSearchList').load('/json/', {
					getData: 'productQuickSearch',
					searchString: inputvalue
				});
				/*$('div.floatBox').css('display', 'block');*/
			}
			$('#spinnerBill').css('visibility', 'hidden');
		}
	}
	productQuickSearch.start();

	/********************************************
	********************************************/

	/* Tierarten */
	$('#tiervermittlung #tierart').live('change', function(){
		var tierartGiven = $(this).attr('value');

		$('#geschlecht').load('/json/', {
			getData: 'getSex',
			tierart: tierartGiven
		});
	});

	/********************************************
	********************************************/

	/* Shop > Produkte > Attributpreis setzen */
	$('select.setProductAttributePrice').change(function(e){
		var valueAttributeId = $(this).val(),
			ajaxUrl          = '/json/';
			
		$.ajax({
			url: ajaxUrl + '?getData=getProductAttributePrice&attributeId=' + valueAttributeId,
			cache: false,
			async: true,
			type: 'GET',
			dataType: 'json',
			success: function(jsonData){
				$('#productAttributePrice').html(jsonData.priceHtml);
				$('#productAttributeStock').html(jsonData.html);
				console.log('data', jsonData);
			}
		});
	});

	/********************************************
	********************************************/

	/* Höhe der Produktbox setzen */
	$('div#pDetailInfo').each(function(){
		var boxHeightL = $('#pDetailInfo div.L').height();
		var boxHeightR = $('#pDetailInfo div.R').height();
		var boxHeight  = (boxHeightL <= boxHeightR) ? boxHeightR: boxHeightL;

		if(boxHeightL >= boxHeightR) {
			$('#pDetailInfo div.R').height(boxHeightL);
		} else {
			$('#pDetailInfo div.L').height(boxHeightR);
		}
	});

	/********************************************
	********************************************/

	$('p#sendAdministrativeMail input[type=radio]').change(function(){
		var e   		= $(this);
		var value   	= e.attr('value');
		var fullNameStr = $('input[name=fullName]').attr('value');
		var orderIdStr  = $('input[name=orderId]').attr('value');

		if(value == 'keine') {
			$('#sendAdministrativeMailMessageBox').hide();
			$('textarea#sendAdministrativeMailMessage').html('');
		} else {
			$('#sendAdministrativeMailMessageBox').show();

			if(value == 'in_bearbeitung') {
				var templateFile = '/templates/docs/service/bestellungen/vorlagen/in_bearbeitung.tpl';
			} else if(value == 'sendung_versandt') {
				var templateFile = '/templates/docs/service/bestellungen/vorlagen/sendung_versandt.tpl';
			}

			// E-Mail-Template laden, Platzhalter ersetzen und Template-Inhalt in die Textarea setzen
			$.get(templateFile, function(templateContent){
				var modifiedContent = templateContent.replace(/{fullName}/g, fullNameStr);
				var modifiedContent = modifiedContent.replace(/{orderId}/g, orderIdStr);

				$('textarea#sendAdministrativeMailMessage').html(modifiedContent);
			});
		}
	});
	
	/* Service -> Profil -> Packstation
	********************************************/
	$('input.servicePackstation').bind('change', function(e){
		var value = $(this).attr('value');
		
		if(value == 'packstation') {
			$('label[for=adr2Company]').text('PACKSTATION PostNummer:');
			$('label[for=adr2Street]').text('PACKSTATION-Nummer (Beispiel: „PACKSTATION 113”):');
		} else {
			$('label[for=adr2Company]').text('Firmenname (optional):');
			$('label[for=adr2Street]').text('Straße und Hausnummer:');
		}
	});

	/* featured article home page
	************************************************/
	$('#featureItems').animelsFeatured();
});


(function(){
	$.fn.animelsFeatured = function() {
		return this.each(function(){
			var $wrapper    = $(this),
				$slider     = $wrapper.find('> ul').width(9999),
				$items      = $slider.find('> li'),
				$single     = $items.filter(':first')
				
				singleWidth = $single.outerWidth(),
				currentPage = 1
				pages       = $items.length;
				
			// clone items
			$items.filter(':first').before($items.slice(-1).clone().addClass('cloned')); 
			$items.filter(':last').after($items.slice(0, 1).clone().addClass('cloned'));
			$items = $slider.find('> li'); // reselect
			
			// reset scroll
			$wrapper.scrollLeft(singleWidth);
			
			// autoplay
			autoplay();
			
			function autoplay(){
				autoplayTimer = setInterval(function(){
					
					gotoPage(currentPage + 1)
					
					/*
					var $currentPageObj    = $slider.find('li:nth-child(' + (currentPage ) + ')'),
						$featureItemTeaser = $currentPageObj.find('div.featureItemTeaser');
						$featureItemPrice  = $currentPageObj.find('div.featureItemPrice');
				
					$featureItemTeaser.css('border', '1px solid white');
					$featureItemPrice.css('border', '1px solid yellow');
						
					$featureItemTeaser.css('margin-top', '-100px').delay(700).animate({ top: '120px'}, 100);
						
					console.log('currentPage', currentPage);
					*/
				}, 5000);
			}
			
			// start autoscroll
			$(this).bind({
				mouseenter: function(){
					clearInterval(autoplayTimer);
				},
				mouseleave: function(){
					autoplay();
				}
			});
			
			function gotoPage(page) {
				var dir  = page < currentPage ? -1: 1,
					n    = Math.abs(currentPage - page),
					left = (singleWidth * dir * n);
					
				$wrapper.filter(':not(:animated)').animate({
					scrollLeft: '+=' + left
				}, 500, function(){
					if(page == 0) {
						$wrapper.scrollLeft(singleWidth * pages);
						page = pages;
					} else if(page > pages) {
						$wrapper.scrollLeft(singleWidth);
						page = 1;
					}
					currentPage = page;
			 	});
			 	
			 	return false;
			}
			
			// 6. bind the back and forward links
			$('a.back', this).click(function () {
				gotoPage(currentPage - 1);
				return false;
			});
			
			$('a.forward', this).click(function () {
				gotoPage(currentPage + 1);
				return false;
			});
			
			// this currently refers to the element the plugin was bound to
			$(this).bind('goto', function(event, page) {
				gotoPage(page);
			});
			
			$(this).bind('next', function(){
				gotoPage(currentPage + 1);
			});
		});
	};
})(jQuery);


/**
* Funktion ermittelt die Position des Scrollbalkens auf der Seite
* Mehr Infos hier: http://www.quirksmode.org/viewport/compatibility.html
*
*/
function get_scrolling_offset() {
	var x,y;
	if (self.pageYOffset) {
		x = self.pageXOffset;
		y = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	} else if (document.body) {
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	return y;
}

