// default values in inputs from title-Tags
function inputDefaultText() {
    jQuery('input[type=text]').each(function(){
		// setting the defaultValue
		var defaultValue = jQuery(this).attr('title');
		if(defaultValue) {
			// check if defaultValue or not
			if(jQuery(this).val() == '') {
				jQuery(this).val(defaultValue);
			} else if (jQuery(this).val() != defaultValue) {
				jQuery(this).addClass('notDefault');
			}
			// change the value and class on focus
			jQuery(this).focus(function(){
				if (jQuery(this).val() == defaultValue) {
					jQuery(this).val('').removeClass('notDefault').addClass('focused');
				}
				if (jQuery(this).val() != defaultValue) {
					jQuery(this).addClass('focused notDefault');
				}
			});
			// change the value and class on blur
			jQuery(this).blur(function(){
				if (jQuery(this).val() == '') {
					jQuery(this).val(defaultValue).removeClass('focused notDefault');
				} else {
					jQuery(this).removeClass('focused').addClass('notDefault');
				}
			});
		}
    });

    jQuery('form').submit(function() {
		jQuery('input[type=text]').each(function(){
			var defaultValue = jQuery(this).attr('title');
			if(defaultValue && jQuery(this).val() == defaultValue) {
				jQuery(this).val('');
			}
		});
    });
}

// tabs for recipeBox
function accessibleTabBox(targetClass) {
	jQuery('.' + targetClass).accessibleTabs({
		tabbody: '.singleTab',
		tabhead: 'h2',
		fx:'show',
		fxspeed:null,
		syncheights:false,
		autoAnchor:true
    });
}

// cycle teaserList
function cycleIntroTeaser() {
    // first is the active slide
    var teaserSlide = jQuery('.teaserSlide');
    teaserSlide.prepend('<ul class="teaserNavList">').cycle({
	    fx:'fade',
	    pager:'.teaserNavList',
	    activePagerClass:'active',
	    pagerAnchorBuilder: function(idx, slide) {
		    var slideNum = idx+1;
		    return '<li><a href="#">' +slideNum+ '</a></li>';
	    },
		pause: true,
		pauseOnPagerHover: true,
	    slideExpr: 'a',
	    timeout: 5000,
		allowPagerClickBubble: true
    });

	//jQuery('.teaserNavList').bind('click', function(e){
	//	window.setTimeout("pauseCycleIntroTeaser()", 10);
	//	e.stopPropagation();
	//	return false;
	//});
}

function pauseCycleIntroTeaser() {
	jQuery('.teaserSlide').cycle('pause');
}

// function initAfterAjaxReload
function initNordzucker() {
	accessibleTabBox('recipeTabBox');
}

function initProductSlider() {
	var productSet = jQuery('.productSet');
	var productTeaser = jQuery('.productTeaser');
	var productItems = productTeaser.find('a');

	var target = productSet.first();
	var productToHighlight = productItems.first();

	setActiveProductSlider(productToHighlight, target)

	jQuery('.productTeaser a').click(function(){
			// check hash and fix it if we got an absolute url
		var activeProductSet = jQuery(this).attr('href').split('#').pop();
		jQuery.history.load(activeProductSet);
		return false;
	});

		// initialize slider - if itemCount is less then the setting, we get an exception -> adjust if needed and hide the scroll buttons
	var itemCount = productItems.length;
	if (itemCount > 4) {
		productTeaser.find('ul').jcarousel({
			scroll:	1,
			visible: 4
		});
	} else {
		productTeaser.find('ul').addClass('noSlider');
	}
}

function setActiveProductSlider(productToHighlight, productItem) {
	jQuery('.productTeaser a').removeClass('active');
	productToHighlight.addClass('active');

	jQuery('.productSet').hide();
	productItem.show();
}


function initRecipeSlider(ajaxRequest) {
	var recipeSet = jQuery('.singleRecipeResult');
	var recipeTeaser = jQuery('#yourRecipeResultsList');
	var recipeItems = null;
	if (ajaxRequest === false) {
		recipeItems = recipeTeaser.find('li');
		storeRecipeSliderElements(recipeItems);
	} else {
		recipeItems = getRecipeSliderElements();
	}

//	var target = recipeSet.first();
//	var recipeToHighlight = recipeItems.first().find('a:first');

//	setActiveRecipeSlider(recipeToHighlight);

	// initialize slider - if itemCount is less then the setting, we get an exception -> adjust if needed and hide the scroll buttons
	var itemCount = recipeItems.length;

	if (itemCount > 4) {
		// remove all elements before initializing the slider
		recipeTeaser.empty();

		var recipeCarousel = recipeTeaser.jcarousel({
			scroll:	4,
			animation: 800,
			visible: 4,
			itemVisibleInCallback: {
				onBeforeAnimation: function(carousel, item, idx, state) {
//						var theImage = jQuery(item).find('img:first');
//						if (jQuery(theImage).attr('original')) {
//							jQuery(theImage).attr('src', jQuery(theImage).attr('original'));
//							theImage.removeAttr('original');
//						}
					},
				onAfterAnimation: function(carousel, item, idx, state) {
//						var theImage = jQuery(item).find('img:first');
//						if (jQuery(theImage).attr('original')) {
//							jQuery(theImage).attr('src', jQuery(theImage).attr('original'));
//							theImage.removeAttr('original');
//						}
				}
			},
			itemLoadCallback: mycarousel_itemLoadCallback
		});
	} else {
		// just load the real images for the recipe
		jQuery(recipeTeaser).append(recipeItems);
		jQuery(recipeTeaser).find('img').each(function(idx, theImage){
			theImage = jQuery(theImage);
			if (theImage.attr('original')) {
				theImage.attr('src', jQuery(theImage).attr('original'));
				theImage.removeAttr('original');
			}
		})
	}
}

function mycarousel_itemLoadCallback(carousel, state) {
    // Check if the requested items already exist
//    if (carousel.has(carousel.first, carousel.last)) {
//        return;
//    }
	var items = getRecipeSliderElements();
	carousel.size(items.length);
	var itemsToShow = items.slice(carousel.first - 1, carousel.last + 4);
	mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, itemsToShow);

};
function mycarousel_itemAddCallback(carousel, first, last, items) {
	jQuery(items).each(function(i, item){
		var theImage = jQuery(item).find('img:first');
		if (jQuery(theImage).attr('original')) {
			jQuery(theImage).attr('src', jQuery(theImage).attr('original'));
			theImage.removeAttr('original');
		}
		carousel.add(first + i, jQuery(item).html());
	});

//    jQuery('image', xml).each(function(i) {
//        carousel.add(first + i, mycarousel_getItemHTML(jQuery(this).text()));
//    });
}

function initVideoSlider() {
	var videoTeaser = jQuery('.videoTeaserSlider');
	var videoItems = videoTeaser.find('a');

	// initialize slider - if itemCount is less then the setting, we get an exception -> adjust if needed and hide the scroll buttons
	var itemCount = videoItems.length;

	if (itemCount > 3) {
		var videoCarousel = videoTeaser.jcarousel({
			scroll:	1,
			animation: 800,
			visible: 3
		});
	} else {
		jQuery(this).addClass('noSlider');
	}
}

function setActiveRecipeSlider(recipeToHighlight) {
	jQuery('#yourRecipeResultsList li').removeClass('active');
	jQuery(recipeToHighlight).parent().addClass('active');
}

function storeRecipeSliderElements(content) {
	// important: the dom elements will be removed to speed the carousel up -> store a clone of them
	jQuery('#yourRecipeResultsList').data('content', jQuery(content).clone());
}
function getRecipeSliderElements() {
	return jQuery('#yourRecipeResultsList').data('content');
}

function controlAgeInputAdults(selectObj){
	var selectedValue = jQuery('#select_adults').find('option:selected').val();
	jQuery('.age_3').hide();
	if(selectedValue == 2){
		jQuery('.age_3').show();
	} 
}
function controlAgeInputKids(selectObj){
	var selectedValue = jQuery('#select_kids').find('option:selected').val();
	jQuery('.age_4, .age_5, .age_6').hide();
	if(selectedValue == 2){
		jQuery('.age_4').show();
	} else if(selectedValue == 3) {
		jQuery('.age_4').show();
		jQuery('.age_5').show();
	} else if(selectedValue == 4) {
		jQuery('.age_4').show();
		jQuery('.age_5').show();
		jQuery('.age_6').show();
	}
}

jQuery(document).ready(function(){
	
	// gewinnspiel selects
	if(jQuery('.gewinnspielForm').length > 0){
		jQuery('.age_3, .age_4, .age_5, .age_6').hide();
		controlAgeInputAdults();
		controlAgeInputKids();
		jQuery('.gewinnspielForm select').bind('change', function(){
			controlAgeInputAdults();
			controlAgeInputKids();
		});
	}
	
    // looking for a hashValue in the URL
    if(jQuery('.productSet').length > 0) {
		initProductSlider();

		// related recipes
		jQuery('.sliderList').each(function(){
			var length = jQuery(this).find('li').length;
			if(length > 2) {
				jQuery(this).jcarousel({
					scroll:	2,
					visible: 2,
					itemFallbackDimension: 195
				});
			} else {
				jQuery(this).addClass('noSlider');
			}
		});
		jQuery('.textSliderList').each(function(){
			var length = jQuery(this).find('li').length;

			if(length > 1) {
				jQuery(this).jcarousel({
					scroll:	1,
					visible: 1,
					itemFallbackDimension: 390
				});
			} else {
				jQuery(this).addClass('noSlider');
			}
		});

		jQuery.history.init(function(hash){
			var productToHighlight, productItem;
			if(hash) {
				productToHighlight = jQuery('.productTeaser').find('a[href$=#'+hash+']');
				productItem = jQuery('#' + hash);
			} else {
				productToHighlight = jQuery('.productTeaser').find('a').first();
				productItem = jQuery('.productSet').first();
			}
			setActiveProductSlider(productToHighlight, productItem);
		});
	}

	if(jQuery('#yourRecipeResultsList').length > 0){
		initRecipeSlider(false);
		jQuery('body').bind('recipeSearchExecuted', function(event, data){
			var lis = new Array;
			if (data.length > 0) {
				lis = jQuery(data).filter(function(){ return $(this).is('li') });
			}
				// trigger loading of first search result
			if (lis.length > 0) {
				jQuery('#yourRecipeResultsListWrap').removeClass('hidden');
				jQuery('#noRecipeSearchResultsWrap').addClass('hidden');

				var alias = jQuery(lis[0]).find('a:first-child').attr('recipeAlias');
				if (alias) {
					jQuery.history.load(alias);
				}

				if(jQuery('#yourRecipeResultsListWrap').children('div').length > 0) {
					jQuery('#yourRecipeResultsListWrap').children('div').remove();
				} else {
					jQuery('#yourRecipeResultsList').remove();
				}
				jQuery('#yourRecipeResultsListWrap').append('<ul id="yourRecipeResultsList"></ul>');
				storeRecipeSliderElements(lis);
//				lis.each(function(index){
//					jQuery('#yourRecipeResultsList').append(this);
//				})
				initRecipeSlider(true);
			} else {
				triggerRecipeError();
			}
		});

			// new content was loaded? make sure to show it then
		jQuery('body').bind('contentChanged', function(event){
			jQuery('#resultDetailWrap').removeClass('hidden');
		});
	}

	// default values from title
	inputDefaultText();

    // onSubmit
    jQuery('form').submit(function() {
		jQuery(this).find('input[type="text"]').each(function(){
			var defaultValue = jQuery(this).attr('title');
			if (jQuery(this).val() == defaultValue) {
				jQuery(this).val('');
			}
		});
    });

    // tabBox in the productSet
    if(jQuery('.productTabBox').length > 0){
	    jQuery('.productTabBox').each(function(){
		    var singleTab = jQuery(this).find('.tabContent .singleTab');
		    var tabNav = jQuery(this).find('.tabNav li');

		    singleTab.hide();
		    tabNav.first().addClass('active');
		    singleTab.first().show();
		    tabNav.click(function() {
			    tabNav.removeClass('active');
			    jQuery(this).addClass('active');
			    singleTab.hide();
			    var openTab = jQuery(this).find('a').attr('href').split('#').pop();
			    jQuery('#' + openTab).show();
			    return false;
		    });

			// if on page 19 = einmachen und gelieren, set third tab active
			if (jQuery('body#page-19').length === 1) {
				var newActiveTab = jQuery(this).find('.tabNav li.additionalTab:first');
				if (newActiveTab.length === 1) {
					tabNav.removeClass('active');
					newActiveTab.addClass('active');
					singleTab.hide();
					var openTab = jQuery(newActiveTab).find('a').attr('href').split('#').pop();
					jQuery('#' + openTab).show();
				}
			}
	    });
    }

    // styled formElements
    jQuery('.selectWrap select').styledSelect({
	zIndexApply: false,
	zIndexStart: 1000,
	deactiveOnBackgroundClick: true
    });
    jQuery('.checkboxWrap input').customInput();

    // start IntroTeaser
    if(jQuery('.teaserSlide').length > 0){
		cycleIntroTeaser();
    }

	// init all functions
	initNordzucker();
	jQuery('body').bind('contentChanged', function(){
		initNordzucker();
	});

	jQuery('.uploadWrap input[type=file]').filestyle({
	    image: 'fileadmin/be_user/templates/img/icon/formhandler_image_upload.gif',
	    imageheight : 22,
	    imagewidth : 88,
	    width : 109
	});

	jQuery('#recipePreparation textarea').autoResize({
	    onResize : function() {},
	    animateCallback : function() {},
	    animateDuration : 300,
	    extraSpace : 20
	});

	jQuery('#recipePreparation textarea').each(function(){
	    var defaultTextareaText = jQuery(this).html();
	    if(defaultTextareaText) {
			// check if defaultValue or not
			if(jQuery(this).html() == '') {
				jQuery(this).html(defaultTextareaText);
			} else if (jQuery(this).html() != defaultTextareaText) {
				jQuery(this).addClass('notDefault');
			}
			// change the value and class on focus
			jQuery(this).focus(function(){
				if (jQuery(this).html() == defaultTextareaText) {
					jQuery(this).html('').removeClass('notDefault').addClass('focused');
				}
				if (jQuery(this).html() != defaultTextareaText) {
					jQuery(this).addClass('focused notDefault');
				}
			});
			// change the value and class on blur
			jQuery(this).blur(function(){
				if (jQuery(this).html() == '') {
					jQuery(this).html(defaultTextareaText).removeClass('focused notDefault');
				} else {
					jQuery(this).removeClass('focused').addClass('notDefault');
				}
			});
		}
	});
});

function triggerRecipeError() {
	// no recipe found -> add error class to body
	jQuery('#yourRecipeResultsListWrap').addClass('hidden');
	jQuery('#resultDetailWrap').addClass('hidden');
	jQuery('#noRecipeSearchResultsWrap').removeClass('hidden');
}


// -------- Cufon --------
if(typeof Cufon != "undefined") {
	Cufon.replace('.corporateText, #recipeSend h2, .tipContent h1, .productDescription h2', {
		fontFamily: 'lt_wiesbaden_swing_com'
	});
}

function tryLog(param) {
	if (console) {
		console.log(param)
	}
}


/***********************************************************************
 *
 * Javascript for the recipe pages
 *
 ************************************************************************/
function initRecipeRating() {
	var recipeRatingContainer = jQuery('#recipeRating').css('display', 'block');
	var forRecipe = parseInt(jQuery('#recipeRatingForRecipe').val());
	if (!hasUserAlreadyVotedForRecipe(forRecipe, false)) {
		jQuery('#recipeRating-step1').addClass('visible');
	} else {
		jQuery('#recipeRating-alreadyVoted').addClass('visible');
	}


	jQuery("#starify").stars({
		cancelShow: false,
//		oneVoteOnly: true,
		callback: function(ui, type, value){
		}
	});
}

	// bind events to init the recipe rating
jQuery('document').ready(function(){
	initRecipes();
	initRecipeRating();
	jQuery('body').bind('contentChanged', function(){
		initRecipeRating();
		Cufon.refresh();
	});

	jQuery('.sendRecipe span').live('click', function() {
		if(jQuery('#recipeRecommendWrap').length == 0) {
			var iframeWidth = "100%";
			var iframeHeight = parseInt(jQuery('#resultDetailWrap').height()) -44;
			var href = jQuery(this).attr('data-href');
			var iframeHtml = '<div id="recipeRecommendWrap"><iframe style="border: medium none; overflow-x: hidden; background: none repeat scroll 0% 0% transparent;" border="0" allowtransparency="true" frameborder="0" src="'+href+'" width="'+iframeWidth+'" height="'+iframeHeight+'">Your browser does not support iframes.</iframe><div id="recipeRecommendClose">Schließen</div></div>';
			jQuery('#resultDetail').append(iframeHtml);
			jQuery('#recipeRecommendClose').click(function(){
				jQuery('#recipeRecommendWrap').remove();
			});
		}
	});

	initVideoSlider();

});

function rateRecipe(forRecipe) {
	var selectedValue = jQuery('input[name=recipeRatingValue-radio]').val();

	if (isNaN(selectedValue) || selectedValue < 1 || selectedValue > 5) {
		alert("please select a valid value");
	} else {

		var alreadyVoted = hasUserAlreadyVotedForRecipe(forRecipe, true);

		if (alreadyVoted === true) {
			alert("already voted for that recipe")
		} else {
			jQuery.post('index.php?eID=tx_nzrecipesandproducts_ajax_rating',
			{ recipe: forRecipe, rank: selectedValue},
			function(data){
				updateRecipeRating(data);
				gotoNextRatingStep();
			});
		}
	}
}

function updateRecipeRating(data) {
//	jQuery('body').trigger('updatedRecipeRating', data)
	var recipeInfo = jQuery('#userRating');
	recipeInfo.removeClass().addClass(data.cssClass);
	recipeInfo.find('.ratingCount').text('(' + data.ratingCount + ')');
}

function initRecipes() {
	// Only do something, if we can display the result.
	// Otherwise the form just submits a regular request and hopefully the target page can display the result.
	var $resultList = jQuery('#yourRecipeResultsListWrap');
	if ($resultList.length === 1) {
		var $form = jQuery('#findYourRecipeForm');
		var $ajaxTarget = ajaxRecipeSearchAction;

		if ($ajaxTarget != '') {
			$form.submit(function(event) {

					// stop form from submitting normally
				event.preventDefault();
				var formValues = $form.serialize();
				formValues = formValues.replace(/%5B/gi, '[');
				formValues = formValues.replace(/%5D/gi, ']');
				// Send the data using post and put the results in a div
				jQuery.get($ajaxTarget, formValues,
					function(data) {
						jQuery('body').trigger('recipeSearchExecuted', data);
						return;
					}
				);
			})
		}

		jQuery.history.init(function(hash){
			if(hash == "") {
			} else {
				var detailPage = ajaxRecipeDetailPage;
				var params = { 'tx_nzrecipesandproducts_recipes[alias]': hash };
				jQuery('#resultDetailWrap').load(detailPage, params,  function(responseText, textStatus, XMLHttpRequest) {
					if (responseText !== '') {
						jQuery('body').trigger('contentChanged');
					} else {
						triggerRecipeError();
					}
				});
			}
		},
		{ unescape: ",/" });

			// attach click events to fetch detail view for recipe
		$resultList.delegate('a', 'click', function(event){
			event.preventDefault();
			var alias = jQuery(this).attr('recipeAlias');
			setActiveRecipeSlider(this);
			jQuery.history.load(alias);
			return false;
		});
		jQuery('#gotoRatingStep2').live('click', function(){
			gotoNextRatingStep();
		});
	}
}

function gotoNextRatingStep() {
	var ratingBox = jQuery('#recipeRating');
	var activeStep = ratingBox.find('.visible');
	activeStep.removeClass('visible').next().addClass('visible');
}

function hasUserAlreadyVotedForRecipe(forRecipe, updateCookie) {
	var votedRecipes = jQuery.cookie('votedRecipes');
	var alreadyVoted = false;

	if (votedRecipes != '' && votedRecipes != null) {
		votedRecipes = votedRecipes.split(',');
	} else {
		votedRecipes = new Array();
	}

	jQuery.each(votedRecipes, function(index, value) {
		if (value == forRecipe) {
			alreadyVoted = true;
				// this breaks the each loop
			return false;
		}
	});

		// update the cookie with the new recipe uid
	if (alreadyVoted === false && updateCookie === true) {
		votedRecipes.push(forRecipe);
		jQuery.cookie('votedRecipes', votedRecipes.join(','));
	}
	return alreadyVoted;
}
