/* ------------------------ */
/* --- helper functions --- */
/* ------------------------ */

function getLocalisationFromClassAttribute(selector) {
	var classAttribute = $(selector).attr('class');
	var classes = classAttribute.split(' ');
	var localisation;
	$.each(classes, function(key, value) {
		localPosition = value.indexOf('local_');
		if (localPosition > -1) {
			localisation = value.substr(6);
		}
	})
	return localisation;
}

/* ------------ */
/* --- shop --- */
/* ------------ */

function addToCart(formId) {
	$.post('ajax.php', 'action=addToCart&' + $('#' + formId).serialize(), function(data) {
		$('#cart-status a span').text(data);
		quantity = $('#' + formId + ' .shopquantityfield').val();
		$('#' + formId + ' .shopquantityfield').val('');
		if (quantity > 0) {
			// container fuellen
			$('#pop').text('+' + quantity);
			// positionen ermitteln
			posForm = $('#' + formId + ' .shopquantityfield').offset();
			posCart = $('#cart-status a span').offset();
			// animation
			$('#pop').css({
				'display': 'block',
				'left': posForm.left,
				'top': posForm.top
			}).animate({
				'left': posCart.left,
				'top': posCart.top,
				'font-size': 12
			}, 1500, function(){
				$('#pop').css({
					'display': 'none',
					'top': '-5000px',
					'left':' -5000px',
					'font-size': 30
				});
			});
		}
	});

	return false;
}

function updateCart(id, q) {
	$.post('ajax.php', 'action=updateCart&id=' + id + '&quantity=' + q, function(data) {
		$('#cart-status a span').text(data);
	});

	return false;
}

$(function() {
	$('#cart .shopquantityfield').bind('keyup', function() {
		updateCart($(this).attr('id'), $(this).val());
	});

	$('.removeItem').click(function() {
		var id = 'id_' + $(this).attr('id');
		$.post('ajax.php', 'action=removeItem&id=' + id, function(data) {
			$('#cart-status a span').text(data);
		});
		$(this).parent('tr').fadeOut();
	})
});

/* ------------- */
/* --- /shop --- */
/* ------------- */

$(function() {

	/* ###################### */
	/* ### document ready ### */
	/* ###################### */

	/* --------------- */
	/* --- uniform --- */
	/* --------------- */

	/*
    $("#dealersearch input").uniform();

    $("#dealersearch form").validationEngine({
        validationEventTriggers:"keyup blur change"
    });
     */

	/* ------------------- */
	/* --- produktwelt --- */
	/* ------------------- */

	// breite der dt ermitteln
	maxWidth = 0;
	$('div#main.produktwelt #content dt').each(function(index){
		var original = $(this);
		var kopie = $(this).clone();
		original.after(kopie);
		kopie.css({
			display: "inline-block"
		})
		var width = kopie.width();
		if (width>maxWidth) {
			maxWidth = width;
		}
		kopie.remove();
	});

	// subheader clonen und
	$('div#main.produktwelt #content dl').each(function(index){
		var dt = $(this).find('dt');
		var subheader = $(this).find('.subheader').clone();
		dt.after(subheader);
		$(this).addClass('min').find('.subheader:nth(0)').addClass('min');
	});

	// abstand setzen
	$('#main.produktwelt #content dl dd.subheader.min').css({
		left: maxWidth
	});

	// toggle
	$('div#main.produktwelt #content dl dd.toggle').each(function(){
		// define variables
		var animationDuration = 1000;
		var heightDl = 0;
		var heightElements = 0;
		var heightImages = $(this).siblings('.images').height();
		var heightDt = $(this).siblings('dt').outerHeight(true);
		var elements = '.subheader:not(.min), .labels, .description, .assortment, .link';

		// calculate element's height
		$(this).parent('dl').children(elements).each(function(){
			heightElements += $(this).outerHeight(true);
		});

		// calculate dl's height
		if(heightElements > heightImages) {
			heightDl = heightElements;
		} else {
			heightDl = heightImages;
		}
		heightDl += heightDt;

		// toggle functionality
		// TODO: redundanten code minimieren (beim umbau von eifachem toggle zu accordion "passiert"...)
		$(this).toggle(function() {
			// slideshows
			$('div#main.produktwelt #content dl dd.images ul').cycle('stop');
			$(this).parent('dl').find('dd.images ul').cycle({
				fx: 'fade',
				pause: 1,
				timeout: 5000
			});
			// alle nicht min-dls minimieren
			$('div#main.produktwelt #content dl:not(.min) dd.toggle').css({
				backgroundPosition: '0 0'
			});
			$('div#main.produktwelt #content dl:not(.min) .subheader:nth(0)').fadeIn(animationDuration);
			$('div#main.produktwelt #content dl:not(.min)').css({
				overflow: 'hidden'
			}).animate({
				paddingBottom: 0,
				height: heightDt
			}, animationDuration)
			.addClass('min');
			// einblenden der aktuellen dl
			$(this)
			.css({
				backgroundPosition: '0 -20px'
			})
			.siblings('.subheader:nth(0)').fadeOut(animationDuration)
			.parent('dl').css({
				overflow: 'hidden'
			})
			.animate({
				paddingBottom: 25,
				height: heightDl
			}, animationDuration)
			.removeClass('min');
		}, function() {
			// slideshows (= redundant! s. o.)
			$('div#main.produktwelt #content dl dd.images ul').cycle('stop');
			$(this).parent('dl').find('dd.images ul').cycle({
				fx: 'fade'
			});
			if($(this).parent('dl').hasClass('min')) {
				// alle nicht min-dls minimieren (= redundant! s.o.)
				$('div#main.produktwelt #content dl:not(.min) dd.toggle').css({
					backgroundPosition: '0 0'
				});
				$('div#main.produktwelt #content dl:not(.min) .subheader:nth(0)').fadeIn(animationDuration);
				$('div#main.produktwelt #content dl:not(.min)').css({
					overflow: 'hidden'
				}).animate({
					paddingBottom: 0,
					height: heightDt
				}, animationDuration)
				.addClass('min');
				// einblenden der aktuellen dl (= redundant! s.o.)
				$(this)
				.css({
					backgroundPosition: '0 -20px'
				})
				.siblings('.subheader:nth(0)').fadeOut(animationDuration)
				.parent('dl').css({
					overflow: 'hidden'
				})
				.animate({
					paddingBottom: 25,
					height: heightDl
				}, animationDuration)
				.removeClass('min');
			} else {
				$(this)
				.css({
					backgroundPosition: '0 0'
				})
				.siblings('.subheader:nth(0)').fadeIn(animationDuration)
				.parent('dl').css({
					overflow: 'hidden'
				})
				.animate({
					paddingBottom: 0,
					height: heightDt
				}, animationDuration)
				.addClass('min');
			}
		});
	});

	// mouseover-bild-einblendung
	$('td.dim').mouseover(function(){
		$('td.dim img').css({
			display: 'none'
		});
		$(this).find('img').css({
			display: 'block'
		});
	});
	$('td.dim').mouseout(function(){
		$('td.dim img').css({
			display: 'none'
		});
	});

	/* ------------- */
	/* --- login --- */
	/* ------------- */

	toggleText = $('#login-link a').text();
	$('#login-link').toggle(function(){
		$('#login').animate({
			top: 0
		}, 300);
		$('#logo a').css({
			backgroundPosition: '0 -72px'
		});
		$(this).find('a').text('X');
	}, function() {
		$('#login').animate({
			top: -100
		}, 300);
		$('#logo a').css({
			backgroundPosition: '0 0'
		});
		$(this).find('a').text(toggleText);
	})

	/* ---------------------- */
	/* --- produktkatalog --- */
	/* ---------------------- */

	$('form select.limitfield, form select.filterfield').change(function() {
		$(this).closest("form").submit();
	});

	$('form select.limitfield, form select.filterfield').uniform();

	/* ------------------------------ */
	/* --- partnerbereich :: news --- */
	/* ------------------------------ */

	$('div.partnerbereich div.news-item').each(function(){

		// animation (hoehe, fade, toggle-text)
		var animationDuration = 1000;
		var imageHeight = $(this).find('ul.images li.first img').height();
		var introHeight = $(this).find('div.teaser').height();
		var newsItemHeightOld = $(this).height();
		var newsItemHeightNew = Math.max(imageHeight, introHeight) + $(this).find('h3').height();

		$(this).find('div.text, ul.images li:not(.first)').css({
			display: 'none'
		});

		$(this).css({
			height: newsItemHeightNew
		});

		$(this).find('p.toggle').toggle(function(){
			$(this).parent('div.news-item')
			.animate({
				height: newsItemHeightOld
			}, animationDuration)
			.find('div.text, ul.images li:not(.first)').fadeIn(animationDuration);
			// TODO: folgende 4 zeilen sind redundant und koennten in eine funktion ausgelagert werden (s.u.)
			var textAlt = $(this).text();
			var textNeu = getLocalisationFromClassAttribute($(this))
			$(this).text(textNeu);
			$(this).removeClass('local_' + textNeu).addClass('local_' + textAlt);
		}, function(){
			$(this).parent('div.news-item').animate({
				height: newsItemHeightNew
			}, animationDuration)
			.find('div.text, ul.images li:not(.first)').fadeOut(animationDuration);
			// TODO: folgende 4 zeilen sind redundant und koennten in eine funktion ausgelagert werden (s.o.)
			var textAlt = $(this).text();
			var textNeu = getLocalisationFromClassAttribute($(this))
			$(this).text(textNeu);
			$(this).removeClass('local_' + textNeu).addClass('local_' + textAlt);
		});

		// image-swapping
		$(this).find('ul.images li:not(.first) img').click(function(){
			var srcImageNew = $(this).attr('src');
			var srcImageOld = $(this).parent().parent().find('li.first img').attr('src');
			$(this).attr('src', srcImageOld);
			$(this).parent().parent().find('li.first img').attr('src', srcImageNew);
		})
	});

	/* ----------------------------- */
	/* --- homepage :: slideshow --- */
	/* ----------------------------- */

	$('#main.homepage .wrapper').append('<div id="slideshownav"></div>');

	$('#main.homepage #slideshow').cycle({
		fx: 'fade',
		pause: 1,
		timeout: 5000,
		pager:  '#slideshownav'
	});

	/* --------------------------------------------- */
	/* --- formulare :: defaults ein-/ausblenden --- */
	/* --------------------------------------------- */

	inputDefaults = {}
	$("form:not(#contactform) input:text").focus(function() {
		var element = $(this);
		inputDefaults[element.attr("id")] = element.val();
		element.val('');
	});
	$("form:not(#contactform) input:text").blur(function() {
		var element = $(this);
		if (element.val() == '') {
			element.val(inputDefaults[element.attr("id")]);
		}
	});

	/* ----------------------- */
	/* --- jquery.validate --- */
	/* ----------------------- */

	$("#contactform").validationEngine();

	/* ----------------------- */
	/* --- jquery.fancybox --- */
	/* ----------------------- */

	$(".fancybox, .bildRechtsFancybox").fancybox();

/* ####################### */
/* ### /document ready ### */
/* ####################### */

});

