var textFadeable = !($.browser.msie && $.browser.version < 9);
var inspiratorFlashProperties = {
	swf: '/flash/',
	width: 745,
	height: 150,
	wmode: 'transparent',
	hasVersion: 9,
	hasVersionFail: function() { htmlInspirator.init(); }
};

$(document).ready(function() {
	$('.replace').replaceWithImage();


	var slideshow = $('.slideshow .image ul');
	slideshow.slidebox({
		width: 766,
		speed: 800,
		btnNext: '#slideshow-right',
		btnPrev: '#slideshow-left',
		bindText: '.text.bind',
		cycle: slideshow.hasClass("long") ? 15000 : 5000
	});

	// Inspirator Tab
	if ($('#inspirator').length) {
		toggleInspirator.init('#inspirator-wrap', '#inspirator', '#insp-stoerer', {closedTop: '-362px', wrapperClosedHeight: '32px', wrapperOpenHeight: '394px'});
		$('#insp-close').click(function() { toggleInspirator.toggle(); });
		$('#insp-stoerer').click(function() { toggleInspirator.toggle('open'); });
		toggleInspirator.showStoerer();
	}

	// Receptkategori Tab
	if ($('#rezeptkat').length) {
		toggleInspirator.init('#rezeptkat-wrap', '#rezeptkat', null, {closedTop: '-137px', wrapperClosedHeight: '29px', wrapperOpenHeight: '166px'});
		$('#insp-close').click(function() {
			toggleInspirator.toggle();
		});
	}
	// Inspirator Page
	else if ($('.p-inspirator #insp-app').length) {
		if (typeof($.flash) != 'undefined') {
			if ($.browser.msie && $.browser.version < 7) {
				setTimeout(function() {
					$('.p-inspirator #insp-app').flash(inspiratorFlashProperties);
				}, 500);
			} else {
				$('.p-inspirator #insp-app').flash(inspiratorFlashProperties);
			}
			setTimeout(function() { if ($('#insp-app object').length) trackEvent('Inspirator Flash', 'init'); }, 1000);
		}
		else htmlInspirator.init();
	}

	// Drawer (Inspirator...)
	if ($('#drawer').length) drawer.init();

	// Products Roundabout
	if ($('#roundabout-container').length) roundaboutMachine.init();

	// Rezeptselektor
	if ($('#rezeptselector').length) rezepte.initSelector();

	// Zutaten-ABC
	if ($('#letters').length) ingrAlphabet.init();

	// Adjust background wave
	if ($('#page.p-rezeptdetail').length) adjustWave($('#page.p-rezeptdetail .bluebox'), -124, 5);

	// Facebook Like
	$('div.fb-like').toIframe();

	// Phone numbers
	phone.makeLinks();

	// Klammeraffen
	$('.klammeraffe').text('@');

	// Kontaktformular
	if ($('#page.p-kontakt').length) kontaktForm.init();

	// Presse
	if ($('#page.p-presse').length) {
		$('a[data-email]').each(function() {
			var email = $(this).attr('data-email');
			this.href = 'mailto:' + email + '@lemaghreb.jp';
			$(this).find('span').text(email + '@lemaghreb.jp');
		});
	}

});


var roundaboutMachine = {
	container: null,
	productlist: null,
	roundabout: null,
	currentProducts: {kugel: 'classic', rolle: 'classic', minis: 'classic'},

	init: function() {
		this.container = $('#roundabout-container');
		this.productlist = $('#roundabout-container ul');
		this.roundabout = document.createElement('ul');
		this.initProducts();
		this.initRoundabout();
	},

	initProducts: function() {
		var elements = [
			{cat1: 'rolle', cat2: this.currentProducts.rolle},
			{cat1: 'kugel', cat2: this.currentProducts.kugel},
			{cat1: 'minis', cat2: this.currentProducts.minis}
		];
		var raM = this;
		for (i = 0; i < elements.length; i++) {
			var element = elements[i];
			var linkContent = this.productlist.find('ul.prod-cat-' + element.cat1 + ' li.prod-cat-' + element.cat2 + ' a').html();
			var div = document.createElement('div');
			$(div).html(linkContent);
			var li = document.createElement('li');
			$(li).addClass(element.cat1).append(div);
			this.roundabout.appendChild(li);
		}

		this.productlist.hide();
		$(this.container).append(this.roundabout);
		this.showProduct('rolle-classic', false);

		// Make Geschmacksrichtungen clickable
		$('#content .content .product').each(function() {
			var prodId = $(this).attr('id');
			var regex = new RegExp("([a-z]+)\-[a-z]+", "g");
			var result = regex.exec(prodId);
			if (result) {
				var prodCat1 = result[1];
				$(this).find('.sorten-menu li').each(function() {
					var prodCat2 = $(this).attr('class');
					$(this).find('a').click(function() {
						raM.changeProductCat(prodCat1, prodCat2);
						return false;
					});
				});
			}


		});
	},

	initRoundabout: function() {
		if ($.browser.msie) {
			if ($.browser.version == 7) {
				// IE7: Don't fix it, replace it with GIFs
				$("#roundabout-container img").fixPNG();
				$("#roundabout-container img").each(function () {
					//var image = this.src;
					//image = image.replace(/\.png$/, ".gif");
					//this.src = image;
				});
			} else {
				// IE 6/8:
				$("#roundabout-container img").fixPNG();
			}
		}
		$(this.roundabout).roundabout({
			minOpacity: 1.0,
			minScale: 0.7,
			shape: 'tearDrop',
			tilt: -6.5,
			duration: 400,
			reflect: true,
			clickToFocus: true,
			btnNext: '#slideshow-right',
			btnPrev: '#slideshow-left'
		});

		var raM = this;
		$('ul.roundabout-holder li').focus(function(e) {
			var prodCat1 = '';
			if ($(this).hasClass('kugel')) prodCat1 = 'kugel';
			if ($(this).hasClass('rolle')) prodCat1 = 'rolle';
			if ($(this).hasClass('minis')) prodCat1 = 'minis';
			var prodCat2 = raM.currentProducts[prodCat1];
			raM.showProduct(prodCat1 + '-' + prodCat2, true);
		}).blur(function(e) {
			var prodCat1 = '';
			if ($(this).hasClass('kugel')) prodCat1 = 'kugel';
			if ($(this).hasClass('rolle')) prodCat1 = 'rolle';
			if ($(this).hasClass('minis')) prodCat1 = 'minis';
			var prodCat2 = raM.currentProducts[prodCat1];
			if (textFadeable) $('#' + prodCat1 + '-' + prodCat2).fadeOut(400);
		});
	},

	showProduct: function(id, fade) {
		if (typeof(id) == 'object') {
			var regex = new RegExp("#([a-z\-]+)", "g");
			var result = regex.exec(id.href);
			if (result) id = result[1];
			else return true;
		}
		$('.product').hide();
		if (fade && textFadeable) $('#' + id).fadeIn(400);
		else $('#' + id).show();
		trackEvent('Products Roundabout', id);
		return false;
	},

	changeProductCat: function(cat1, cat2) {
		if (this.currentProducts[cat1] == cat2) return;
		var linkContent = this.productlist.find('ul.prod-cat-' + cat1 + ' li.prod-cat-' + cat2 + ' a').html();
		$('ul.roundabout-holder li.' + cat1 + ' div').html(linkContent);
		this.currentProducts[cat1] = cat2;
		this.showProduct(cat1 + '-' + cat2, false);
		//if ($.browser.msie && $.browser.version < 9) $('ul.roundabout-holder li.' + cat1 + ' img').fixPNG();
	},

	moveRoundaboutTo: function(index) {
		$(".roundabout-holder").roundabout_animateToChild(index);
	}
};

var htmlInspirator = {
	wrapper: null,
	time: 0,
	buttonPos: {30: '0px', 60: '-125px', 0: '-250px'},
	slotHeight: 0,
	lastReelPos: 0,
	buttonHot: false,
	recipeID: null,
	firstRun: true,

	init: function() {
		this.wrapper = $('#insp-html:visible');
		if (!this.wrapper.length) return;
		$('#insp-time-30').click(function() {htmlInspirator.setTime(30);});
		$('#insp-time-60').click(function() {htmlInspirator.setTime(60);});
		$('#insp-time-0').click(function() {htmlInspirator.setTime(0);});
		$('#insp-button').click(htmlInspirator.run);
		$.ajax({
			url: '/rezepte/slotreels/json',
			cache: true,
			dataType: 'json',
			success: htmlInspirator.receiveReelImages
		});
		this.slotHeight = $('#slot-1 .ingr:first').height();
		trackEvent('Inspirator HTML', 'init');
	},

	receiveReelImages: function(data) {
		var length = data.length;
		if (!data.length) return;
		for (slot = 1; slot < 5; slot++) {
			var suffled = shuffleArray(data.slice());
			var contrainer = $('#slot-' + slot + ' .ingr:first');
			for (var i = 0; i < length; i++) {
				contrainer.append('<div class="img"><img src="http://www.lemaghreb.jp/' + suffled[i] + '" alt></div>');
			}
		}
		htmlInspirator.updateLastReepPos(length);
		htmlInspirator.buttonHot = true;
	},

	resetReels: function() {
		for (slot = 1; slot < 5; slot++) {
			if (!htmlInspirator.firstRun) $('#slot-' + slot + ' .ingr .img:first').remove();
			var lastImg = $('#slot-' + slot + ' .ingr .img:last img').attr('src');
			$('#slot-' + slot + ' .ingr').css({top: '0px'}).prepend('<div class="img"><img src="' + lastImg + '" alt></div>');
			$('#slot-' + slot + ' .ingr .img:last').remove();
		}
		htmlInspirator.buttonHot = true;
		htmlInspirator.firstRun = false;
		htmlInspirator.updateLastReepPos();
	},

	updateLastReepPos: function(length) {
		if (!length) length = $('#slot-1 .ingr .img').length;
		htmlInspirator.lastReepPos = htmlInspirator.slotHeight * length * -1;
	},

	setTime: function(t) {
		$('#insp-time-' + this.time).removeClass('active');
		$('#insp-time-' + t).addClass('active');
		$('#insp-button').css({backgroundPosition: '0 ' + this.buttonPos[t]});
		this.time = t;
		this.run();
	},

	showRecipe: function() {
		showRecipe(htmlInspirator.recipeID);
	},

	run: function() {
		if (!htmlInspirator.buttonHot) return;
		htmlInspirator.buttonHot = false;
		for (slot = 1; slot < 5; slot++) {
			var delay = parseInt(Math.random() * 500);
			$('#slot-' + slot + ' .ingr:first').delay(delay).animate({top: (htmlInspirator.lastReepPos - 10) + 'px'}, 5000).animate({top: htmlInspirator.lastReepPos + 'px'}, 600);
			$('#slot-' + slot + ' .name').fadeOut(400).delay(4800 + delay).fadeIn(400);
		}
		setTimeout(htmlInspirator.showRecipe, 6000);
		setTimeout(function() {htmlInspirator.resetReels();}, 6300);
		setTimeout(function() {
			$.ajax({
				url: '/rezepte/slotmachine/' + htmlInspirator.time,
				cache: false,
				dataType: 'json',
				success: function(data) {
					htmlInspirator.recipeID = data.id;
					for (slot = 1; slot < 5; slot++) {
						$('#slot-' + slot + ' .ingr').append('<div class="img"><img src="http://www.lemaghreb.jp/' + data.ingredients[slot - 1].image + '" alt></div>');
						$('#slot-' + slot + ' .name').text(data.ingredients[slot - 1].name);
					}
				}
			});
		}, 400);
		trackEvent('Inspirator HTML', 'run');
	}
};

function shuffleArray(o) {
	for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

var toggleInspirator = {
	state: null,
	options: {},
	wrapperSel: null,
	wrapper: null,
	elementSel: null,
	element: null,
	stoererSel: null,
	stoerer: null,
	appInitialized: false,
	init: function(wrapperSel, elementSel, stoererSel, options) {
		this.wrapperSel = wrapperSel;
		this.elementSel = elementSel;
		this.wrapper = $(wrapperSel);
		this.element = $(elementSel);
		this.stoerer = $(stoererSel);
		if (this.stoerer.length) this.stoererSel = stoererSel;
		if ($(wrapperSel + '.closed').length) this.state = 'closed';
		else this.state = 'open';
		this.options = {
			speed: options.speed || 750,
			speedVari: options.speedVari || 75,
			easing: options.easing || 'swing',
			closedTop: options.closedTop || null,
			openTop: options.openTop || '0',
			wrapperClosedHeight: options.wrapperClosedHeight || null,
			wrapperOpenHeight: options.wrapperOpenHeight || null
		};
	},
	open: function() {
		this.toggle('open');
	},
	toggle: function(force) {
		if (force == 'open' && this.state == 'open') return;
		else if (force == 'close' && this.state == 'closed') return;
		if (this.state == 'open') {
			this.setState('closing');
			this.element.animate({top: this.options.closedTop}, this.options.speed, this.options.easing);
			this.wrapper.animate({height: this.options.wrapperClosedHeight}, this.options.speed + this.options.speedVari, this.options.easing, function() {toggleInspirator.setState('closed');});
			trackEvent('Drawer', 'close');
		}
		else if (this.state == 'closed') {
			if (!this.appInitialized) {
				if (typeof($.flash) != 'undefined') $('#insp-app').flash(inspiratorFlashProperties);
				else htmlInspirator.init();
				this.appInitialized = true;
			}
			this.wrapper.animate({height: this.options.wrapperOpenHeight}, this.options.speed - this.options.speedVari, this.options.easing, function() {toggleInspirator.setState('open');});
			this.element.animate({top: this.options.openTop}, this.options.speed, this.options.easing);
			this.setState('opening');
			this.hideStoerer();
			$(this.wrapperSel + ' div.fb-like-lazy').toIframe();
			trackEvent('Drawer', 'open');
		}
	},
	setState: function(state) {
		this.state = state;
		switch (state) {
			case 'closed':
				this.wrapper.addClass('closed');
				this.showStoerer();
				break;
			case 'opening':
				this.wrapper.removeClass('closed');
				break;
			default:break;
		}
	},
	showStoerer: function() {
		if (this.stoererSel) {
			$(this.stoererSel + ' img').fixPNG();
			var stoerer = this.stoerer;
			setTimeout(function() {
				stoerer.css({bottom: '22px', display: 'block', opacity: 0}).animate({bottom: '-10px', opacity: 1}, {duration: 1000});
			}, 500);
		}
	},
	hideStoerer: function() {
		if (this.stoererSel) {
			this.stoerer.animate({opacity: 0}, {duration: 1000});
		}
	},
	inspiratorShowRecipe: function(id) {
		recipe.loadShortID(id, toggleInspirator.replaceRecipe);
	},
	replaceRecipe: function(recipe) {
		$('#insp-recipe-title').attr('href', recipe.permalink).html(recipe.title);
		$('#insp-recipe-link').attr('href', recipe.permalink);
		$('#insp-recipe-ingredients').html('Zutaten: ' + recipe.ingr);
		$('#inspirator #insp-recipe .link').show();
	}
};


var drawer = {
	state: 'open',
	height: 0,
	element: null,
	wrapper: null,
	options: {
		speed: 750,
		speedVari: 75,
		easing: 'swing'
	},
	recipe: null,
	cssSet: false,

	init: function() {
		this.element = $('#drawer');
		this.wrapper = $('#drawer-wrapper');
		this.height = this.element.height();
	},

	setCSS: function() {
		if (!this.cssSet) {
			this.wrapper.css({height: this.height + 'px', position: 'relative'});
			this.element.css({position: 'absolute', left: '29px'});
			this.cssSet = true;
		}
	},

	open: function() {
		// Adjust
		this.height = this.element.height();
		this.element.css({top: '-' + this.height + 'px'});
		// Open
		this.wrapper.animate({height: this.height}, this.options.speed - this.options.speedVari, this.options.easing, function() {drawer.setState('open');});
		this.element.animate({top: 0}, this.options.speed, this.options.easing);
	},

	close: function() {
		this.setCSS();
		this.element.animate({top: '-' + this.height + 'px'}, this.options.speed, this.options.easing);
		this.wrapper.animate({height: 0}, this.options.speed + this.options.speedVari, this.options.easing, function() {drawer.setState('closed');});
	},

	setState: function(state) {
		this.state = state;
		if (state == 'closed' && this.recipe != null) {
			this.replaceRecipe(this.recipe);
			this.open();
		}
	},

	inspirator: function(time) {
		this.close();
		this.recipe = null;
		recipe.randomTime(time, drawer.receiveRecipe);
	},

	inspiratorShowRecipe: function(id) {
		this.close();
		this.recipe = null;
		recipe.loadID(id, drawer.receiveRecipe);
	},

	receiveRecipe: function(recipe) {
		if (!recipe.permalink) return;
		if (drawer.state == 'closed') {
			drawer.replaceRecipe(recipe);
			drawer.open();
		} else {
			drawer.recipe = recipe;
		}
	},

	replaceRecipe: function(recipe) {
		$('#recipe-title').attr('href', recipe.permalink).html(recipe.title);
		$('#recipe-desc').html(recipe.desc);
		$('#recipe-persons').text(recipe.pers);
		$('#recipe-ingredients').html(recipe.ingr);
		$('#recipe-img').attr('src', recipe.img).attr('alt', recipe.title);
		$('#recipe-time').removeClass().addClass('zeit ' + recipe.timeclass).find('p:first').text(recipe.time);
		$('#recipe-tags h3').text((recipe.tags.length > 1) ? 'Kategorien:' : 'Kategorie:');
		$('#recipe-tags p').html(recipe.tags.join(', '));
		$('#recipe-share .fb-like iframe').attr('src', recipe.fblike);
		drawer.recipe = null;
	}
};


var recipe = {
	randomTime: function(time, callback) {
		$.ajax({
			url: '/ajax/randomtime/' + time,
			type: 'post',
			cache: false,
			data: 'r',
			dataType: 'json',
			success: callback
		});
	},

	loadID: function(id, callback) {
		$.ajax({
			url: '/ajax/recipe/' + id,
			cache: true,
			dataType: 'json',
			success: callback
		});
	},

	loadShortID: function(id, callback) {
		$.ajax({
			url: '/ajax/recipeshort/' + id,
			cache: true,
			dataType: 'json',
			success: callback
		});
	}
};


function inspiratorFallbackSubmit() {
	drawer.inspirator($('#insp-time').val());
}

function inspiratorTestSubmit(id) {
	showRecipe($('#'+id).val());
}

function showRecipe(id) {
	if ($('#drawer article.recipe').length) drawer.inspiratorShowRecipe(id);
	else toggleInspirator.inspiratorShowRecipe(id);
}


/**
 * Slidebox: Slideshow box
 * @author André Zahn
 */
jQuery.fn.slidebox = function() {
	var options = (typeof arguments[0] != 'object') ? {} : arguments[0];
	options = {
		width: options.width || null,
		speed: options.speed || null,
		btnNext: options.btnNext || null,
		btnPrev: options.btnPrev || null,
		bindText: options.bindText || null,
		cycle: options.cycle || false
	};

	this.each(function(i) {
		var ref = jQuery(this);
		ref.data('slidebox', {
			pos: 0,
			width: options.width,
			speed: options.speed,
			boundTexts: {},
			textFadeable: !($.browser.msie && $.browser.version < 9)
		});

		var havingTextsBound = !!jQuery(options.bindText).length;
		if (options.bindText && havingTextsBound) {
			var boundTexts = jQuery(options.bindText).children();
			ref.data('slidebox').boundTexts = boundTexts;
			jQuery(boundTexts).hide();
			jQuery(boundTexts[ref.data('slidebox').pos]).show();
		}

		var fullWidth = ref.children("li").length * options.width;
		ref.css('position', 'absolute').css('width', fullWidth + 'px');

		if (options.btnNext) {
			jQuery(options.btnNext).bind('click.slidebox', function(e) {
				if (ref.parent().find(':animated').length) return false;
				var slides = ref.children();
				var newPos = ref.data('slidebox').pos + 1;
				if (newPos >= slides.length) {
					if (options.cycle && !havingTextsBound) {
						var pxPos = options.width * (newPos - 2) * -1;
						ref.css('left', pxPos+'px').find('li:first-child').appendTo(ref);
						newPos--;
					}
					else newPos = 0;
				}
				ref.data('slidebox').pos = newPos;
				ref.slidebox_animateToChild(newPos);
				return false;
			});
		}

		if (options.btnPrev) {
			jQuery(options.btnPrev).bind('click.slidebox', function(e) {
				if (ref.parent().find(':animated').length) return false;
				var slides = ref.children();
				var newPos = ref.data('slidebox').pos - 1;
				if (newPos < 0) {
					if (options.cycle && !havingTextsBound) {
						var pxPos = options.width * -1;
						ref.css('left', pxPos+'px').find('li:last-child').prependTo(ref);
						newPos++;
					}
					else newPos = slides.length - 1;
				}
				ref.data('slidebox').pos = newPos;
				ref.slidebox_animateToChild(newPos);
				return false;
			});
		}

		if (options.cycle) {
			window.setInterval(function() {
				$(options.btnNext).click();
			}, options.cycle);
		}
	});
	return this;
};

jQuery.fn.slidebox_animateToChild = function(childPos) {
	this.each(function(i) {
		var ref = jQuery(this);
		var data = ref.data('slidebox');
		var pxPos = data.width * childPos * -1;
		$(this).animate({left: pxPos+'px'}, data.speed);
		if (data.boundTexts.length) {
			if (data.textFadeable) {
				var textSpeed = data.speed / 2;
				jQuery(data.boundTexts).fadeOut(textSpeed);
				setTimeout(function() {
					jQuery(data.boundTexts[childPos]).fadeIn(textSpeed);
				}, textSpeed);
			} else {
				jQuery(data.boundTexts).hide();
				setTimeout(function() {
					jQuery(data.boundTexts[childPos]).show();
				}, data.speed);
			}
		}
		if (typeof(trackEvent) == 'function') trackEvent('Slidebox', 'page ' + (childPos + 1));
	});
};


/* Rezeptsuche */

var rezepte = {
	setTime: function(min) {
		trackEvent('Recipe Selector', 'set time ' + min);
		if (rezepte.checkTime(min) == false) return false;
		else {
			AZCookies.cookie('rezept_time', min);
			$('#rezeptselector .timebuttons div').removeClass('active');
			$('#rezeptselector #btntime' + min).addClass('active');
			//rezepte.setIngredients(rezepte.getIngredients(), true);
			rezepte.reorderPages();
			return true;
		}
	},

	pages: 1,
	itemsPerPage: 20,
	currentPage: 1,
	reorderPages: function() {
		// Reset
		$('.recipepagination ol').empty();
		var count = this.itemsPerPage;
		var total = 0;
		this.pages = 0;

		// Get current user settings
		var timeSetting = this.getTime();

		// Reorder
		$('#recipes article').each(function() {
			var thisTime;
			if ($(this).hasClass('time15')) thisTime = 15;
			else if ($(this).hasClass('time30')) thisTime = 30;
			else if ($(this).hasClass('time0')) thisTime = 0;

			log('this row has time: ' + thisTime);

			var useRecipe = false;
			if (timeSetting == 0) useRecipe = true;
			else if (timeSetting == 30 && (thisTime == 30 || thisTime == 15)) useRecipe = true;
			else if (timeSetting == 15 && thisTime == 15) useRecipe = true;

			if (useRecipe) {
				log('we use this recipe - ' + timeSetting);
				total++;
				count++;
				if (count > rezepte.itemsPerPage) {
					count = 1;
					rezepte.pages++;
					$('.recipepagination ol').append('<li onclick="rezepte.goToPage(this);" data-page="' + rezepte.pages + '">' + rezepte.pages + '</li> ');
				}

				var classname = 'page' + rezepte.pages;
				$(this).removeClass().addClass('time' + thisTime + ' ' + classname);
			}
		});

		this.goToPage($('.recipepagination ol li:first'));
		if (this.pages < 2) $('.recipepagination ol,.page-prev,.page-next').hide();
		else $('.recipepagination ol,.page-prev,.page-next').show();
		$('.recipecounter').text(total);
		// Add scrollTo event to bottom pagination
		$('#rezeptpagination2 li').bind('click', function() {
			$('#recipes').scrollTo(1000, -180);
		});

		// Set CSS for first and last pagination item
		this.paginationSetFirstLast();
	},

	paginationSetFirstLast: function() {
		$('#rezeptpagination1 li:first, #rezeptpagination2 li:first').addClass('first');
		$('#rezeptpagination1 li:last, #rezeptpagination2 li:last').addClass('last');
	},

	goToPage: function(e) {
		if (typeof(e) == 'number') var page = e;
		else var page = $(e).attr('data-page');
		this.currentPage = parseInt(page);
		//log('Gehe auf Seite ' + page + ' von ' + this.pages);
		$('.recipepagination ol li').removeClass('active');
		$('.recipepagination ol li[data-page="' + page + '"]').addClass('active');
		$('#recipes article').hide();
		$('#recipes article.page' + page).show();
		this.repaintIngedients();

		// Remove rest of recipes on last page
		if (page == this.pages) {
			//log('Wir sind auf der letzten Seite!');

			// Get current user settings
			var timeSetting = this.getTime();

			// Hide unwanted recipes on last page
			$('#recipes article.page' + page).each(function() {
				if ($(this).hasClass('time15')) thisTime = 15;
				else if ($(this).hasClass('time30')) thisTime = 30;
				else if ($(this).hasClass('time0')) thisTime = 0;

				if (timeSetting == 30 && thisTime == 0) $(this).hide();
				else if (timeSetting == 15 && thisTime != 15) $(this).hide();
			});
		}
		setTimeout(function() {
			$('article.page' + page + ' div.fb-like-lazy').toIframe();
		}, 1000);
		trackEvent('Recipe Selector', 'page ' + parseInt(page));
	},

	nextPage: function() {
		var p = rezepte.currentPage + 1;
		if (p <= rezepte.pages) rezepte.goToPage(p);
	},

	prevPage: function() {
		var p = this.currentPage - 1;
		if (p >= 1) this.goToPage(p);
	},

	getTime: function() {
		var min = AZCookies.cookie('rezept_time');
		if (rezepte.checkTime(min)) return min;
		else return '0';
	},

	checkTime: function(min) {
		if (typeof(min) == 'undefined') return false;
		if (String(min).match(/^(0|15|30)$/)) return true;
		else return false;
	},

	/*
	setIngredients: function(val, suddenly) {
		if (typeof(suddenly) == 'undefined') suddenly = false;
		log('setIngredients to ' + val);
		if (val == '1' || val == '0') AZCookies.cookie('rezept_ingr', val);
		$('#rezeptselector .ingrbuttons div').removeClass('active');
		$('#rezeptselector #btningr' + val).addClass('active');
		if (val == '0') {
			if (suddenly) {
				$('#recipes .ingredients').hide();
				$('#recipes .image').hide();
			} else {
				$('#recipes .ingredients').slideUp();
				$('#recipes .image').slideUp();
			}
		} else {
			if (suddenly) {
				$('#recipes .ingredients').show();
				$('#recipes .image').show();
			} else {
				$('#recipes .ingredients').slideDown();
				$('#recipes .image').slideDown();
			}
		}
	},
	*/

	repaintIngedients: function() {
		//this.setIngredients(this.getIngredients(), true);
	},

	repaintTime: function() {
		this.setTime(this.getTime());
	},

	getIngredients: function() {
		var ingr = AZCookies.cookie('rezept_ingr');
		if (ingr == '0') return '0';
		else return '1';
	},

	initSelector: function(withoutClickEvents) {
		this.setTime(this.getTime());
		//this.setIngredients(this.getIngredients());
		$('#btntime0').click(function() {rezepte.setTime('0');});
		$('#btntime15').click(function() {rezepte.setTime('15');});
		$('#btntime30').click(function() {rezepte.setTime('30');});
		//$('#btningr0').click(function() {rezepte.setIngredients('0');});
		//$('#btningr1').click(function() {rezepte.setIngredients('1');});
		if (!withoutClickEvents) {
			$('.page-prev span.button').click(function() {rezepte.prevPage();});
			$('.page-next span.button').click(function() {rezepte.nextPage();});
			$('footer.rezeptselector span.button').click(function() {$('#recipes').scrollTo(1000, -180);});
		}
	}

};



/**
 * 
 */
var ingrAlphabet = {
	current: null,
	maxChecked: 20,

	init: function() {
		$('#letters a').each(function() {
			var letter = $(this).text();
			if (ingrAlphabet.current == null) {
				ingrAlphabet.current = letter;
				$(this).addClass('active');
			}
			else $('#' + letter).hide();
			$(this).click(ingrAlphabet.goToLetter);
		});
		$('.ingredients input').change(ingrAlphabet.search);
		rezepte.setTime('0');
	},

	goToLetter: function() {
		var letter = $(this).text();
		$('#' + ingrAlphabet.current).hide();
		$('#' + letter).show();
		ingrAlphabet.current = letter;

		$('#letters a').removeClass('active');
		$(this).addClass('active');

		return false;
	},

	search: function() {
		var checked = $('.ingredients input:checked');
		var checkedlength = checked.length;
		if (!checkedlength) {
			$('#recipes').hide();
			return;
		}
		if (checkedlength > ingrAlphabet.maxChecked) {
			alert('Es kann nur nach maximal ' + ingrAlphabet.maxChecked + ' Zutaten gleichzeitig gesucht werden.');
			return;
		}
		var idList = new Array(checked.length);
		var nameList = new Array(checked.length);
		var i = 0;
		checked.each(function() {
			idList[i] = $(this).attr('id');
			nameList[i++] = $(this).val();
		});
		$.ajax({
			url: '/ajax/ingredientsearch',
			type: 'get',
			cache: true,
			data: {i: implode('-', idList)},
			dataType: 'json',
			success: function(data) {
				$('#search_terms').text(implode(', ', nameList));
				$('.recipecounter').text(data.recipes.length);
				$('#recipeslist').empty();
				for (i = 0; i < data.recipes.length; i++) {
					var recipe = data.recipes[i];
					var article = document.createElement('article');
					$(article).addClass(ingrAlphabet.timeClass(recipe.time)).append(ingrAlphabet.recipeHTML(recipe, nameList));
					document.getElementById('recipeslist').appendChild(article);
				}
				rezepte.initSelector(true);
			}
		});
		$('#recipes').show();
	},

	timeClass: function(time) {
		var tclass = 'time0';
		if (time <= 15) tclass = 'time15';
		else if (time <= 30) tclass = 'time30';
		return tclass;
	},

	recipeHTML: function(recipe, searchedNames) {
		// Highlight search matches
		for (var i = 0; i < recipe.ingr.length; i++) {
			var ingr = recipe.ingr[i];
			for (var j = 0; j < searchedNames.length; j++) {
				var searchTerm = searchedNames[j];
				if (ingr.indexOf(searchTerm) > -1) {
					recipe.ingr[i] = '<mark>' + ingr + '</mark>';
				}
			}
		}

		var html = '<h2><a href="' + recipe.url + '" rel="bookmark">' + recipe.title + '</a></h2>';
		html += '<p class="ingredients"><strong>Zutaten (' + recipe.matches + ' Treffer):</strong> ' + implode(', ', recipe.ingr) + '</p>';
		html += '<div class="image">';
		html += '<div class="mask"><img src="http://www.lemaghreb.jp/' + recipe.img + '" width="66" height="68" alt="' + recipe.title + '"></div>';
		html += '<div class="frame"><a href="' + recipe.url + '">' + recipe.title + '</a></div>';
		html += '</div>';
		html += '<p class="zeit ' + recipe.timeclass + '"><strong>' + recipe.time + ' Minuten</strong> Zubereitungszeit</p>';
		html += '<p class="author">' + recipe.author + '</p>';
		html += '<p class="link"><a href="' + recipe.url + '" class="button red-M"><span>Rezept anzeigen</span></a></p>';
		//html += '<div class="fb-like-lazy"><a href="http://www.facebook.com/plugins/like.php?href=' + escape(window.location.protocol + "//" + window.location.host + recipe.url) + '&amp;show_faces=false&amp;layout=button_count&amp;font=arial" rel="nofollow"></a></div>';
		return html;
	}

};



var AZCookies = {
	cookiesAvailable: null,
	cookieList: new Array(),

	testCookies: function() {
		this.cookiesAvailable = $.cookies.test();
		return this.cookiesAvailable;
	},

	setCookie: function(key, value) {
		if (this.testCookies()) {
			$.cookies.set(key, value);
		} else {
			this.cookieList[key] = value;
		}
		return true;
	},

	getCookie: function(key) {
		if (this.testCookies()) {
			return $.cookies.get(key);
		} else {
			return this.cookieList[key];
		}
	},

	cookie: function(key, value) {
		if (typeof(value) == 'undefined') return this.getCookie(key);
		else return this.setCookie(key, value);
	}
};



function log(msg) {
	//if (!!console) console.log(msg);
}


function adjustWave(e, offset, repeat) {
	var wavepos = e.offset().top + e.height() + offset;
	log('wavepos: ' + wavepos + ' --- repeat: ' + repeat);
	$('#page').css({backgroundPosition: '50% ' + wavepos + 'px'});
	if (repeat) {
		setTimeout(function() {
			adjustWave(e, offset, --repeat);
		}, 100);
	}
}


/**
 * Käsekochbuch Page Flip Overlay
 * @author André Zahn
 */
var kaesekochbuch = {
	wrapper: null,
	pages: null,
	current: null,
	flipSpeed: 200,
	pageWidth: 728,
	
	init: function() {
		this.wrapper = $('#book-preview');
		this.pages = this.wrapper.find('li');
		this.pages.each(function(index, e) {
			if (index > 0) $(e).hide();
			else kaesekochbuch.current = 0;
		});

		if (!$('#book-preview-close').length) {
			this.wrapper.append('<div id="book-preview-close"></div>');
			$('#book-preview-close').click(kaesekochbuch.close);
		}
		if (!$('#flip-prev').length) {
			this.wrapper.append('<a href="#" id="flip-prev"></a>');
			$('#flip-prev').click(kaesekochbuch.prev);
		}
		if (!$('#flip-next').length) {
			this.wrapper.append('<a href="#" id="flip-next"></a>');
			$('#flip-next').click(kaesekochbuch.next);
		}
		this.updateCorners();
		if ($.browser.msie) $('#book-preview-close').hide();

		this.preloadPage(this.current);
	},

	open: function() {
		if (kaesekochbuch.wrapper == null) kaesekochbuch.init();
		if (!$.browser.msie || $.browser.version < 7 || $.browser.version >= 9) kaesekochbuch.wrapper.fadeIn(400); // normal browsers and IE6
		else { // IE7-8
			kaesekochbuch.wrapper.show();
			$('#book-preview-close').show();
		}
		if ($.browser.msie && $.browser.version < 7) setTimeout(function() {$('#book-preview-close').show();}, 400); // IE6
		this.preloadPage(this.current + 1);
		trackEvent('Kochbuch-Vorschau', 'page ' + (this.current + 1));
	},

	close: function() {
		if (!$.browser.msie || $.browser.version < 7 || $.browser.version >= 9) kaesekochbuch.wrapper.fadeOut(400); // normal browsers and IE6
		else kaesekochbuch.wrapper.hide(); // IE7-8
		if ($.browser.msie && $.browser.version < 9) $('#book-preview-close').hide(); // IE6-8
	},

	updateCorners: function() {
		if (this.current == 0) $('#flip-prev').addClass('inactive');
		else $('#flip-prev').removeClass('inactive');
		if (this.current == this.pages.length - 1) $('#flip-next').addClass('inactive');
		else $('#flip-next').removeClass('inactive');
	},

	page: function(i) {
		trackEvent('Kochbuch-Vorschau', 'page ' + (i + 1));
		this.preloadPage(i + 1);
		//this.preloadPage(i - 1);
		var increase = (this.current < i) ? true : false;
		var hidePage = $(this.pages[this.current]);
		var showPage = $(this.pages[i]);
		setTimeout(function() {
			hidePage.hide();
		}, this.flipSpeed + 50);

		if (increase) {
			hidePage.css({zIndex: 1}).animate({width:'0px'}, this.flipSpeed);
			showPage.css({zIndex: 0, width: this.pageWidth + 'px'}).show();
		} else {
			hidePage.css({zIndex: 0});
			showPage.css({zIndex: 1, width: '0px'}).show().animate({width: this.pageWidth + 'px'}, this.flipSpeed);
		}

		this.current = i;
		this.updateCorners();
	},

	preloadPage: function(i) {
		if (i >= this.pages.length || i < 0) return;
		var pageImg = $(this.pages[i]).find('img');
		if (pageImg.length != 1) return;
		var src = pageImg.attr('src');
		if (src.match(/-p.jpg$/)) {
			src = src.replace('-p.jpg', '.jpg');
			var image = new Image();
			image.onload = function() {
				pageImg.attr('src', this.src);
			};
			image.src = src;
		}
	},

	prev: function() {
		if (kaesekochbuch.current > 0) {
			kaesekochbuch.page(kaesekochbuch.current - 1);
		}
		return false;
	},

	next: function() {
		if (kaesekochbuch.current < kaesekochbuch.pages.length - 1) {
			kaesekochbuch.page(kaesekochbuch.current + 1);
		}
		return false;
	}
}


/**
 * Kontaktformular
 */
var kontaktForm = {
	kForm: null,
	betreffSel: null,
	html5placeholder: false,

	init: function() {
		if ('placeholder' in document.createElement('input')) this.html5placeholder = true;
		this.kForm = $('form#kontakt');
		this.betreffSel = $('#f-betreff');
		this.updateBetreff();
		$('#f-betreff').change(this.updateBetreff);
		$("[placeholder]").textPlaceholder(); // HTML5 placeholder support
		this.kForm.submit(this.submit);
		$('#f-submit').click(this.submit);
	},

	updateBetreff: function() {
		if (kontaktForm.betreffSel.val() == '5') $('#f-reklamation').show();
		else $('#f-reklamation').hide();
	},

	submit: function() {
		var fields = {};
		var errors = false;
		kontaktForm.kForm.find('input[name]:visible,textarea[name]:visible,select[name]:visible').each(function() {
			var jThis = $(this);
			var required = (this.getAttribute('required') === '') ? true : false;

			if (jThis.attr('type') == 'radio') var val = kontaktForm.kForm.find('input[name=' + jThis.attr('name') + ']:checked:visible').val();
			else {
				if (!kontaktForm.html5placeholder && jThis.hasClass('text-placeholder')) var val = '';
				else var val = $.trim(jThis.val());
			}
			if (required && (typeof(val) == 'undefinded' || !val)) {
				jThis.parent().addClass('error');
				errors = true;
			} else {
				jThis.parent().removeClass('error');
				fields[jThis.attr('name')] = val;
			}
		});

		if (errors) {
			trackEvent('Kontaktformular', 'submit invalid in JS');
			alert('Bitte füllen Sie alle Pflichtfelder aus.');
		} else {
			$.ajax({
				url: '/ajax/kontakt',
				type: 'post',
				cache: false,
				data: fields,
				success: function(data) {
					if (data.errors.length) {
						for (var i = 0; i < data.errors.length; i++) {
							kontaktForm.kForm.find('[name=f-' + data.errors[i] + ']').parent().addClass('error');
						}
						trackEvent('Kontaktformular', 'submit invalid in Ajax');
					} else {
						trackEvent('Kontaktformular', 'submit valid');
					}
					if (data.message) alert(data.message);
				}
			});
		}
	}
};


/**
 * Detect phones with the ability to make calls
 * @author André Zahn
 */
var phone = {
	phone: null,
	detect: function() {
		if (this.phone != null) return true;
		this.phone = false;
		var uagent = navigator.userAgent.toLowerCase();
		var phones = 'iphone,android,blackberry'.split(',');
		for (var i in phones) {
			if (uagent.search(phones[i]) > -1) {
				this.phone = phones[i];
				break;
			}
		}
		return true;
	},
	type: function() {
		this.detect();
		return this.phone;
	},
	isPhone: function() {
		return !!this.type();
	},
	makeLinks: function() {
		if (this.isPhone()) {
			$('[data-tel]').each(function(i, e) {
				e = $(e);
				var tel = e.attr('data-tel');
				if (tel) {
					e.wrap('<a href="tel:' + tel + '" />');
					e.attr('data-tel', '');
				}
			});
		}
	}
};


function implode(glue, pieces) {
	var i = '', retVal='', tGlue='';
	if (arguments.length === 1) {
		pieces = glue;
		glue = '';
	}
	if (typeof(pieces) === 'object') {
		if (pieces instanceof Array) return pieces.join(glue);
		else {
			for (i in pieces) {
				retVal += tGlue + pieces[i];
				tGlue = glue;
			}
			return retVal;
		}
	} else {
		return pieces;
	}
}
