﻿
jQuery.noConflict();

var $j = jQuery.noConflict();
$j(document).ready(function() {

	/* Apply x-forms classes */
	$j('#content .form input:radio').addClass('radioInput').next('label').addClass('radioLabel');
	$j('#content .form input:checkbox').addClass('checkboxInput').next('label').addClass('checkboxLabel');
	$j('#content .form input:submit').addClass('submitInput');


	/* Align portlets on section page */
	function frontpagePortletHeights() {
		$j('#page #frontpage #ctrlPageLowerContent .x-portlet:nth-child(2n)').addClass('x-portlet-even').each(function() {
			var maxHeight = $j(this).height();
			var prevHeight = $j(this).prev('.x-portlet').height();
			maxHeight = (prevHeight > maxHeight) ? prevHeight : maxHeight;
			if (maxHeight > 0) {
				$j(this).height(maxHeight).find('> .brandingBox .content').height(maxHeight - 26);
				$j(this).prev('.x-portlet').height(maxHeight).find('> .brandingBox .content').height(maxHeight - 26);
			}
		});
	}

	frontpagePortletHeights();
	// Webkit browsers don't know image sizes on DOM load:
	if ($j("#page #frontpage #ctrlPageLowerContent div.right img:first").height() == 0) {
		$j("#page #frontpage #ctrlPageLowerContent div.right img").load(function() {
			$j('#page #frontpage #ctrlPageLowerContent .x-portlet').removeAttr("style");
			$j('#page #frontpage #ctrlPageLowerContent .brandingBox .content').removeAttr("style");
			frontpagePortletHeights();
		});
	}


	/* Check for Calibri, add class on top menu if not (smaller Arial).  */
	if (typeof (isEditMode) != 'function') {
		if ($j('.hasCalibri').width() == $j('.hasArial').width()) {
			// MENU resizing. Fixed font size.
			$j('#header ul#nav li').addClass('noCalibri');
			$j('#header div.service ul li').addClass('noCalibri');
			// General header resize
			$j("h1, h2, h3, h4, h5, h6, p.instructions, div.pagingLeft a, div.pagingRight a, div.searchAssistantSv p, div.searchAssistantDa p").each(function(i) {
				if ($j(this).css("font-family")) {
					if (($j(this).css("font-family").toLowerCase()).search("calibri") != -1) {
						$j(this).wrap('<span class="noCalibri"></span>');
					}
				}

			});
		}
	}

	//external link
	$j('A[rel="external"]').click(function() {
		window.open($j(this).attr('href'));
		return false;
	});

	$j('.hidden').hide();

	/* Related column toggle */
	$j('div.relatedBox a.expand').live('click', function() {
		$j(this).parents('p').children('span').show();
		$j(this).attr('class', 'contract');
		return false;
	});
	$j('div.relatedBox a.contract').live('click', function() {
		$j(this).parents('p').children('span').hide();
		$j(this).attr('class', 'expand');
		return false;
	});
	/***********************************************
	Print
	***********************************************/
	$j('ul.toolBar .printOption .printWrapper ul li.picture img.tips ').hide();

	$j('.printWrapper a.close').click(function() {
		$j('.printWrapper').hide();
	});

	$j('.print').click(function() {
		$j('.printWrapper').show('fast');
	});

	var htmlHeadline = $j('h1').clone();
	$j('.printWrapper ul li.picture').prepend(htmlHeadline);

	$j('#showPicture').click(function() {
		var checkedPicture = $j("#showPicture").attr("checked");

		if (checkedPicture == true) {
			$j('img.dish').addClass('print');
			$j('img.dish').removeClass('hideforprint');
			$j('.printWrapper img.dish').show();
		} else {
			$j('img.dish').addClass('hideforprint');
			$j('img.dish').removeClass('print');
			$j('.printWrapper img.dish').hide();
		}
	});
	$j('#showTips').click(function() {
		var checkedTips = $j("#showTips").attr("checked");

		if (checkedTips == true) {
			$j('#commentBox').addClass('print');
			$j('#commentBox').removeClass('hideforprint');
			$j('#commentBox ol.comments li').removeClass('hide');
			$j('ul.toolBar .printOption .printWrapper ul li.picture img.tips ').show();
		} else {
			$j('#commentBox').addClass('hideforprint');
			$j('#commentBox').removeClass('print');
			$j('#commentBox ol.comments li').addClass('hide');
			$j('ul.toolBar .printOption .printWrapper ul li.picture img.tips ').hide();
		}
	});
	if ($j('#commentBox ol.comments li').hasClass('noComments')) {
		$j('ul li.tipWrapper').hide();
	}
	if ($j('.themePageTopContent .dish').length < 1) {
		$j('ul li.tipWrapper').prev().hide();
	}
	$j('div.recipeOptions ul.toolBar .printOption .printWrapper ul li a.printButton').click(function() {
		$j('.printWrapper').hide();
	});
	/* end print */
	/***********************************************
	Frontpage
	***********************************************/

	/* Four Dishes Box */
	$j('.fourDishesBox ul.buttons li a:first').addClass('selected');
	$j('.fourDishesBox .content .teaserLink').hide(); //fix for ie6
	$j('.fourDishesBox .content .teaserLink:first').show(); //fix for ie6

	$j('.fourDishesBox ul.buttons li a').click(function() {
		elmId = $j(this).attr('rel');
		elm = $j('.fourDishesBox #recipe' + elmId);
		if (elm.is(':visible')) { }
		else {
			$j('.fourDishesBox ul.buttons li a').removeClass('selected');
			$j(this).addClass('selected');
			// toggle recipes
			$j('.fourDishesBox .dishList').hide();
			elm.show();
			// toggle link more recipes
			$j('.fourDishesBox .content .teaserLink').hide();
			elm.next().show();
		}
	});

	/* Inspirational module, no flash */

	if ($j('#noFlashInspiration').is(':visible')) {
		var serviceUrl = "/Services/InspirationModulService.asmx/GetNoFlashContent";
		var postData = { dataUrlForContent: dataUrl, searchUrl: searchUrl, language: lang }
		$j.ajax({
			type: "POST",
			data: postData,
			url: serviceUrl,
			success:
		       function(html) {
		       	// Initial
		       	$j('#flashPromo').addClass('hide');
		       	$j('#flashPromo').html($j('string', html).text());
		       	$j('#flashPromo').slideDown();
		       	$j('.nfInspiration ul li:not(".right") a').click(function() {
		       		// Selected tab
		       		$j('.nfInspiration ul li.sel').removeClass('sel');
		       		$j(this).parent().addClass('sel');
		       		// Change content
		       		nfTabContent = $j(this).parent().attr('id') + '_data';
		       		$j('.nfInspiration .content:visible').hide();
		       		$j('.nfInspiration #' + nfTabContent).fadeIn();
		       	});
		       },
			error:
		       function(html) {
		       	//document.getElementById('<%= uiDivNoFlash.ClientID%>').innerHTML = "ERROR in no flash service";
		       }
		});
	}

	/* Product landing page, no flash */

	if ($j('#uiDivNoFlash').is(':visible')) {

		var serviceUrl = "/Services/ProductNewsService.asmx/GetCarouselNoFlashContent";
		var postData = { dataUrlForContent: carouselDataUrl }
		$j.ajax({
			type: "POST",
			data: postData,
			url: serviceUrl,
			success:
		       function(html) {
		       	// Initial
		       	$j('#uiDivNoFlash').addClass('hide');
		       	$j('#uiDivNoFlash').html($j('string', html).text());
		       	$j('#uiDivNoFlash').slideDown();
		       	$j(".nfProducts .dropDown p").click(function() {
		       		$j(".nfProducts .items").toggle();
		       		if ($j(".nfProducts .dropDown").hasClass("sel")) {
		       			$j(".nfProducts .dropDown,.nfProducts .dropDown p").removeClass("sel");
		       		} else {
		       			$j(".nfProducts .dropDown,.nfProducts .dropDown p").addClass("sel");
		       		}
		       	});
		       	$j(".nfProducts .dropDown ul li").click(function() {
		       		$j(".nfProducts .items").hide();
		       		$j(".nfProducts .dropDown p").text($j(this).text());
		       		$j(".nfProducts .dropDown,.nfProducts .dropDown p").removeClass("sel");
		       	});
		       },
			error:
		       function(html) {

		       }
		});
	}

	/***********************************************
	FOOD CALENDAR
	***********************************************/
	$j("#foodCalendar #calendar .month:last").addClass('last');


	/***********************************************
	FAQ
	***********************************************/
	//$j('#forum ol.faq li .answerJqueryWrapper').hide();
	// XForms
	$j('#staticXForm input:radio, #staticXForm input:checkbox').each(function() {
		$j(this).addClass('radio');
		$j(this).next("label").addClass("noBlock");
	});
	$j('#staticXForm input:submit').addClass("submit");

	/* Popup for rosa */
	$j('.rosaBottom span input').click(function() {
		window.open('http://customer.humany.com/arla/assistant.asp?entry=' + $j(".rosaBottom #rosaQuestion").val());
	});
	// Contact portlet: Position relative when hovering contact link

	/* Popup for office phone */
	$j('.contact a.officePhone').bind("mouseenter", function() {
		$j('#PageRelatedArea .contact').css('position', 'relative');
		$j(this).siblings('.officePhonePopup').fadeIn('fast');
	}).bind("mouseleave", function() {
		$j(this).siblings('.officePhonePopup').fadeOut('fast', function() {
			$j('#PageRelatedArea .contact').css('position', 'static');
		});
	});



	/***********************************************
	MY Pages
	***********************************************/
	$j('.ownRecipeBox input').live('keydown', function(e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			e.preventDefault();
		}
	})

	/* add own recipe */
	$j('p.ownRecipe input').click(function(e) {

		if ($j('.ownRecipeBoxWrapper').is(':visible') && !$j('.ownRecipeBoxWrapper').hasClass('ownRecipeEditMode') && !$j('.ownRecipeBoxWrapper').hasClass('ownRecipeSuccesMode')) {
			$j('.ownRecipeBoxWrapper').fadeOut('medium');
		} else {
			$j('.ownRecipeBoxWrapper').removeClass('ownRecipeEditMode ownRecipeSuccesMode').find('.ownRecipeBox').removeClass('getUserCreatedRecipeLoaderError savingUserCreatedRecipeSucces').html('<div class="getUserCreatedRecipeLoaderAnim"> </div>');
			$j('.ownRecipeBoxWrapper').fadeIn('medium');
			var data = {
				itemID: 0
			};
			getUserCreatedRecipe(e, data);
			TrackLinkSimple(this, '', ownRecipeTrackingTextCreationBegun, 'event19');
		}
	});
	$j('.ownRecipeBox div.buttons span.cancel input').livequery('click', function() {
		$j('.ownRecipeBoxWrapper').fadeOut('medium');
	});
	$j('.ownRecipeBox div.buttons span.submit input').livequery('click', function(e) {
		var data = {
			$recipeForm: $j(this).closest('.ownRecipeBox')
		};
		saveUserCreatedRecipe(e, data);
	});


	// Special styled dropdown
	$j(".ownRecipeBox #dishSelector p, .ownRecipeBox #dishSelector span.submit input").livequery('click', function() {

		if ($j(".ownRecipeBox #dishSelector").hasClass("dropDownSel")) {
			$j(".ownRecipeBox #dishSelector, .ownRecipeBox #dishSelector p").removeClass("dropDownSel");
			$j(".ownRecipeBox #dishSelector .items").slideUp('medium');
			showSelectedCategories();
		} else {
			$j(".ownRecipeBox #dishSelector, .ownRecipeBox #dishSelector p").addClass("dropDownSel");
			$j(".ownRecipeBox #dishSelector .items").slideDown('medium');
		}
		return false;
	});

	function showSelectedCategories() {
		// Output selected items to DOM
		catSelected = "";
		lastMainCategory = "";
		count = 0;
		$j(".ownRecipeBox .items li").each(function() {
			if ($j(this).attr("class") == "checked") {
				actMainCategory = $j(this).parent("ul").prev("h3").text();
				if (actMainCategory != lastMainCategory) {
					if (count > 0) {
						catSelected += "<br />";
						count = 0;
					}
					catSelected += actMainCategory + ": ";
					lastMainCategory = actMainCategory;
				}
				if (count > 0) {
					catSelected += ", ";
				}
				count++;
				catSelected += $j(this).text();
			}

		});
		$j(".ownRecipeBox #dishSelector").parent().children('div.selectedCategories').html(catSelected);

	}

	$j(".ownRecipeBox #dishSelector .items, .ownRecipeBox #unit").livequery('click', function(e) {
		e.stopPropagation();
	});
	$j(document).livequery('click', function(e) {
		e.stopPropagation();
		$j('.ownRecipeBox #dishSelector .items').slideUp('fast');
		$j(".ownRecipeBox #dishSelector, .ownRecipeBox #dishSelector p").removeClass("dropDownSel");
		showSelectedCategories();
		$j('.inputSelector .items').slideUp('fast');
		$j(".inputSelector, .ownRecipeBox #unit").removeClass("dropDownSel");

	});
	/*
	When ESC is pressed:
	$j(document).keyup(function(e) {
	if (e.keyCode == 27) {
	$j('.ownRecipeBox #dishSelector .items').slideUp('fast');
	$j(".ownRecipeBox #dishSelector, .ownRecipeBox #dishSelector p").removeClass("dropDownSel");
	$j('.ownRecipeBox #unit .items').slideUp('fast');
	$j(".ownRecipeBox #unit, .ownRecipeBox #unit p").removeClass("dropDownSel");         
	}
	});
	*/


	$j(".ownRecipeBox #dishSelector a").livequery('click', function() {
		$j(this).parent('li').toggleClass('checked');
	});



	// Special styled unit dropdown


	$j(".inputSelector .fieldContainer img.arrow").livequery('click', function(e) {
		if ($j(this).parent().parent().hasClass("dropDownSel")) {
			inputSelectorList("hide", $j(this).parent().parent(".inputSelector"));
		} else {
			inputSelectorList("show", $j(this).parent().parent(".inputSelector"));

		}
		e.stopPropagation();
	});
	$j(".inputSelector .fieldContainer input").livequery('click', function(e) {
		inputSelectorList("show", $j(this).parent().parent(".inputSelector"));
		e.stopPropagation();
	});

	$j(".inputSelector .fieldContainer input").livequery('keydown', function(e) {
		$elm = $j(this).parent().parent(".inputSelector");

		enterkey = false;
		tabkey = false;
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			enterkey = true;
		}
		if ((e.which && e.which == 9) || (e.keyCode && e.keyCode == 9)) {
			tabkey = true;
		}
		if (e.keyCode == 27) {
			// ESC pressed
			inputSelectorList('hide', $elm);
		}
		if (enterkey || tabkey) {
			if ($elm.find(".items li.sel:first").text() != "") {
				$j(this).val($elm.children(".items li.sel:first").text());
				if ($j(this).hasClass("fixedVal")) {
					$j(this).removeClass("error");
				}
			} else {
				if ($j(this).hasClass("fixedVal")) {
					$j(this).addClass("error");
				}
			}
			inputSelectorList('hide', $elm);
			// Exception for add/edit recipe ingredient list
			if ($j(this).attr("id") == "unit") {
				$j(".ownRecipeBox input#ingredient").focus();
				if ($j(this).val() == "") {
					validateThis($j(this));
				}
			}
			return false;
		}
	});
	$j(".inputSelector .fieldContainer input").livequery('keyup', function(e) {
		$elm = $j(this).parent().parent(".inputSelector");
		thisVal = $j(this).val();
		//thisOrigVal = $j(this).val();
		thisLength = $j(this).val().length;
		arrowUp = false;
		arrowDown = false;
		if ((e.which && e.which == 38) || (e.keyCode && e.keyCode == 38)) {
			arrowUp = true;
		}
		if ((e.which && e.which == 40) || (e.keyCode && e.keyCode == 40)) {
			arrowDown = true;
		}
		inputSelectorList('show', $elm);
		if (arrowDown == false && arrowUp == false) {
			$elm.find(".items li").removeClass('sel');
			$elm.find(".items li").each(function() {
				liVal = $j(this).children('a').text();
				if (liVal.substring(0, thisLength).toLowerCase() == thisVal.toLowerCase()) {
					liWhere = 0;
					origVal = liVal.substring(0, thisLength);
				} else {
					liWhere = -1;
				}
				$j(this).children('a').html(liVal.replace('<strong>', ''));
				$j(this).children('a').html(liVal.replace('</strong>', ''));
				$j(this).removeClass('sel');
				if (liWhere != -1 && thisLength > 0) {
					$elm.children(".items ul").scrollTop(parseInt($j(this).position().top) - 21);
					$j(this).children('a').html(liVal.replace(origVal, '<strong>' + origVal + '</strong>'));
					$j(this).addClass('sel');
					if (arrowDown == false && arrowUp == false) {
						currentSelection = $elm.find(".items li").index($j(this));
					}
				}
			});
		}
		if (arrowDown) {
			navigateList('down', $elm);
		}
		if (arrowUp) {
			navigateList('up', $elm);

		}
	});
	$j(".inputSelector .items li").livequery('click', function(e) {
		var curEl = $j(this);
		$elm = curEl.closest(".inputSelector");
		curEl.siblings('li').removeClass('sel');
		curEl.addClass('sel');
		$elm.find(".fieldContainer input").val(curEl.text());
		inputSelectorList('hide', $elm);
		// Exception for add/edit recipe ingredient list
		if (curEl.attr("id") == "unit") {
			$j(".ownRecipeBox #ingredient").focus();
		}
	});
	var currentSelection = 0;

	function navigateList(direction, $elm) {
		// Check if any of the menu items is selected
		if ($elm.find(".items li.sel").size() == 0) {
			currentSelection = 0;
		}

		if (direction == 'up' && currentSelection != -1) {
			if (currentSelection != 0) {
				currentSelection--;
			}
		} else if (direction == 'down') {
			if (currentSelection != $elm.find("ul li").size() - 1) {
				currentSelection++;
			}
		}
		if (currentSelection != 0) {
			$elm.find(".items ul").scrollTop(parseInt($elm.find(".items li").eq(currentSelection).position().top - 21));

		}
		setSelectedListItem(currentSelection, $elm);
	}
	function setSelectedListItem(menuitem, $elm) {
		$elm.find(".items li").removeClass("sel");
		$elm.find(".items li").eq(menuitem).addClass("sel");
		//currentUrl = $j(".inputSelector .items li").eq(menuitem).attr("href");
	}

	function inputSelectorList(mode, $elm) {

		$elm.find('.fieldContainer > input').focus();
		if (!$elm) {
			//$elm = $j(".inputSelector:first");
		}
		if ($elm.hasClass("dropDownSel") == false || mode == "show") {
			if ($elm.children(".items").is(":visible") == false) {
				$elm.children(".items").slideDown('fast');
				$elm.addClass("dropDownSel");
				// IE doesn't understand max-height. Hack:
				if ($elm.children(".items").height() >= 200) {
					$elm.children(".items").addClass("longList");
				}
				if ($elm.find(".items li.sel").length == 0) {
					$elm.find(".items li:first").addClass("sel");
					currentSelection = 0;
				}
			}
		} else {
			if (mode != "show") {
				$elm.children(".items").slideUp('fast');
				$elm.removeClass("dropDownSel");
			}
		}
	}
	// Validate on blur
	$j('.inputSelector input.fixedVal').livequery('blur', function() {
		$elm = $j(this).closest('.inputSelector');
		if ($elm.find(".items li.sel:first").text() != "") {
			$j(this).val($elm.children(".items li.sel:first").text());
			if ($j(this).hasClass("fixedVal")) {
				$j(this).removeClass("error");
			}
		} else {
			if ($j(this).hasClass("fixedVal")) {
				$j(this).addClass("error");
			}
		}
	});

	// END: Special styled unit dropdown

	// Default button for enterclick on folder mover adder, as general default button function doesn't work on added DOM obj
	$j(".moveMyItem .inputSelector input").livequery("keyup", function(e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$j(".moveMyItem .submit input").trigger("click");
			return false;
		}

	});

	// Default button for enterclick on ingredient adder, as general default button function doesn't work on added DOM obj
	$j(".ownRecipeBox #amount, .ownRecipeBox #ingredient").livequery("keydown", function(e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$j(".ownRecipeBox .ingredients .submit input").trigger("click");
			return false;
		}

	});
	$j(".ownRecipeBox #ingredient").livequery('keydown', function(e) {
		if ((e.which && e.which == 9) || (e.keyCode && e.keyCode == 9)) {
			$j(".ownRecipeBox .ingredients .submit input").trigger("focus");
			validateThis($j(this));
			return false;
		}
	});

	// Portions and preparation time scaler
	$j('.ownRecipeBox .portions a, .ownRecipeBox .preptime a').livequery('click', function() {
		if ($j(this).parent('li').hasClass('preptime')) {
			intervalVal = 5;
			maxVal = 995;
			minVal = 5;
		} else {
			intervalVal = 1;
			maxVal = 99;
			minVal = 1;
		}
		if ($j(this).hasClass("plus")) {
			addVal = +intervalVal;
		} else {
			addVal = -intervalVal;
		}
		val = $j(this).parent('li').find('input.number').val();
		val = parseInt(val) + addVal;
		val = Math.round(parseInt(val) / intervalVal) * intervalVal; // Rounds to nearest interval
		if (val >= minVal && val <= maxVal) {
			$j(this).parent('li').find('input.number').val(val);
		}
	});
	// Add ingredient
	$j('.ownRecipeBox input#ingredient, .ownRecipeBox input#amount').livequery('blur', function() {
		validateThis($j(this));
	});

	function validateThis($elm) {
		if ($elm.val() != "") {
			$elm.removeClass('error');
		} else {
			$elm.addClass('error');
		}
	}
	$j('.ownRecipeBox #unitList .items li').livequery('click', function() {
		if ($j(this).html() != "") {
			$j('.ownRecipeBox #unit').removeClass('error');
		}
	});
	$j('.ownRecipeBox ul.addIngredient span.submit input').livequery('click', function() {
		$j('.ownRecipeBox ul.addIngredient input[type="text"]').blur();
		ingIng = $j('.ownRecipeBox ul.addIngredient input#ingredient');
		var reg = new RegExp("[^A-Za-z0-9 ~;,._()æøåÆØÅ]*", "g");
		var ingIngVal = ingIng.val().replace(reg, "");
		ingAmnt = $j('.ownRecipeBox ul.addIngredient input#amount');
		ingUnit = $j('.ownRecipeBox ul.addIngredient input#unit');
		validIng = true;

		if (ingIng.val() == "") {
			ingIng.addClass('error');
			validIng = false;
		} else {
			ingIng.removeClass('error');
		}
		if (ingAmnt.val() == "") {
			ingAmnt.addClass('error');
			validIng = false;
		} else {
			ingAmnt.removeClass('error');
		}

		if (ingUnit.val() == "") {
			ingUnit.addClass('error');
			validIng = false;
		}

		if (ingUnit.hasClass('error')) {
			validIng = false;
		}
		if (validIng) {
			ingredientHTML = '<li><p class="text"><span class="ingAmount">' + ingAmnt.val() + '</span> <span class="ingUnit">' + ingUnit.val() + '</span> <span class="ingIng">' + ingIngVal + '</span></p>';
			ingredientHTML += '<a href="javascript:void(0);" class="delete"><img src="/css/gfx/icons/ownrecipeDelete.gif" /></a>';
			ingredientHTML += '<span class="move"><a href="javascript:void(0);" class="up"><span class="accessibility">up</span></a><a href="javascript:void(0);" class="down"><span class="accessibility">down</span></a></span>';
			ingredientHTML += '</li>';
			$j('.ownRecipeBox ul.ingredientList').append(ingredientHTML);

			ingIng.val('');
			ingAmnt.val('');
			ingUnit.val('');
			setTimeout("ingIng.removeClass('error');", 10); /*IE HACK*/
			ingredientArrows();
			$j(".ownRecipeBox #amount").focus();
			ingUnit.removeClass('error');
		}
	});

	// Remove ingredient
	$j('.ownRecipeBox ul.ingredientList a.delete').livequery('click', function() {
		$j(this).parent('li').remove();
		ingredientArrows();
	});

	// Move ingredient
	// 2 different events: IE6 hack
	$j('.ownRecipeBox ul.ingredientList li:not(:first-child) a.up').livequery('mousedown', function() {
		var $row = $j(this).parents("li:first");
		$row.insertBefore($row.prev()).fadeOut('medium').fadeIn('fast');
	});
	$j('.ownRecipeBox ul.ingredientList li:not(:last-child) a.down').livequery('mousedown', function() {
		var $row = $j(this).parents("li:first");
		$row.insertAfter($row.next()).fadeOut('medium').fadeIn('fast');
	});
	$j('.ownRecipeBox ul.ingredientList a.down').livequery('mouseup', function() {
		ingredientArrows();
	});
	$j('.ownRecipeBox ul.ingredientList a.up').livequery('mouseup', function() {
		ingredientArrows();
	});
	function ingredientArrows() {
		$j('.ownRecipeBox ul.ingredientList li').removeClass("first");
		$j('.ownRecipeBox ul.ingredientList li').removeClass("last");
		$j('.ownRecipeBox ul.ingredientList li:first').addClass("first");
		$j('.ownRecipeBox ul.ingredientList li:last').addClass("last");
	}

	// Save recipe
	//$j('.ownRecipeBox div.buttons span.submit input').click(function() {

	//});


	/* Add/edit own recipe end */




	/* Saves the changed password to the hidden field */
	jQuery.fn.setPasswordText = function(hiddenPasswordSelector) {
		if (this.size() > 0) {
			$j(this).keyup(function(e) {
				$j(hiddenPasswordSelector).val($j(this).val());
			})
		}
	};

	$j('div.settingsBox input.settingPasswordText').setPasswordText(".hiddenPassword");
	$j('div.settingsBox input.settingPassword').setPasswordText(".hiddenPassword");
	/* end */

	defaultButton($j(".mySettings fieldset input:not(.submit input)"), $j(".mySettings fieldset .submit input"));


	/* Switch between type=password and type=text */
	$j('.showPass').click(function() {
		var password = $j('.settingPassword').val();
		var text = $j('.settingPasswordText').val();

		if ($j('div.settingsBox input').hasClass('settingPassword')) {
			$j('.settingPassword').replaceWith('<input type="text" name="password" value="' + password + '" class="settingPasswordText">');
			$j('div.settingsBox input.settingPasswordText').setPasswordText(".hiddenPassword");
		} else {
			$j('.settingPasswordText').replaceWith('<input type="password" value="' + text + '" name="password" class="settingPassword">');
			$j('div.settingsBox input.settingPassword').setPasswordText(".hiddenPassword");
		}
	});
	/* end */


	/* My Item Toolbar */
	/*
	$j('.myMealPlans .weeklyMealPlaning > li, .myPagesMenues .recipeControl > li, .myThemes .recipeControl > li, .myRecipes .recipeControl > li').bind('mouseenter mouseleave', function(e) {
	if (!$j(this).hasClass('toolActive')) {
	$j(this).find('.myItemToolbar').toggle('fast');
	}

	});
	*/
	$j('.myMealPlans .weeklyMealPlaning > li, .myPagesMenues .recipeListControl > li, .myThemes .recipeControl > li, .myRecipes .recipeControl > li, .otherRecipes .recipeControl > li').hoverIntent(
		function(e) {
			if (!$j(this).hasClass('toolActive')) {
				$j(this).find('.myItemToolbar').show('fast');
			}
		},
		function(e) {
			if (!$j(this).hasClass('toolActive')) {
				$j(this).find('.myItemToolbar').hide('fast');
			}
		}
    );


	$j('.myMealPlans, .myPagesMenues .recipeListControl, .myThemes, .myRecipes .recipeControl, .otherRecipes .recipeControl').live('click', function(e) {
		var $tgt = $j(e.target);
		e.stopImmediatePropagation(); //cancel bubble and parent events (noticed some conflicts)
		if ($tgt.is('.myItemToolbar .edit')) {
			var $editRecipeForm = $j('.ownRecipeBoxWrapper');
			var yPos = $j('p.ownRecipe').offset().top + 26;
			var data = {
				itemID: $tgt.closest('.myItemToolbar').find('.delMyItemId').val()
			};
			$editRecipeForm.addClass('ownRecipeEditMode').removeClass('ownRecipeSuccesMode');
			$editRecipeForm.find('.ownRecipeBox').removeClass('getUserCreatedRecipeLoaderError savingUserCreatedRecipeSucces').html('<div class="getUserCreatedRecipeLoaderAnim"> </div>');
			$j('html, body').scrollTop(yPos);
			$editRecipeForm.fadeIn('medium');
			getUserCreatedRecipe(e, data);
		}
		else if ($tgt.is('.myItemToolbar .delete')) {
			$j('.toolActive').not($tgt.closest('li')).removeClass('toolActive').find('.myItemToolbar').hide().find('.popup').hide();
			$tgt.closest('li').addClass('toolActive');
			$tgt.parent().children('.moveMyItem').hide();
			$tgt.parent().children('.delMyItem').slideToggle('fast');
		}
		else if ($tgt.is('.recipeControl:not(.tema) li .positionMyItemToolbar .myItemToolbar .delMyItem .submit input')) {

			var folderId = $j('.hdnFolderId', $tgt.parents('.moreRecipes').parent().children('.folderMenu')).val();
			var pageNumber;
			if (folderId == null) {
				folderId = 0;
				pageNumber = $tgt.parents('.otherRecipes').find('.pages .selected').attr('rel');
			}
			else {
				pageNumber = $tgt.parents('.moreRecipes').find('.pages .selected').attr('rel');
			}
			if (pageNumber == null) {
				pageNumber = 1;
			}
			var data = {
				recipeId: $tgt.closest('.delMyItem').find('.delMyItemId').val(),
				folderId: folderId,
				pageNumber: pageNumber,
				pageId: $j('#hiddenNumber').val(),
				pageSize: $j('#hdnPageSize').val(),
				rowSize: $j('#hdnRowSize').val()
			};
			deleteRecipeItem(e, data);
		}
		else if ($tgt.is('.myItemToolbar .delMyItem .submit input')) {
			var data = {
				typeID: $tgt.closest('.delMyItem').find('.delMyItemType').val(),
				itemID: $tgt.closest('.delMyItem').find('.delMyItemId').val()
			};
			deleteMyPagesItem(e, data);
		}
		else if ($tgt.is('.myItemToolbar .delMyItem .cancel input, .myItemToolbar .delMyItem .close')) {
			$tgt.closest('li').removeClass('toolActive');
			$tgt.closest('.delMyItem').slideUp('fast', function() {
				$tgt.closest('.myItemToolbar').hide('fast');
			});
		}
		else if ($tgt.is('.myItemToolbar .move')) {
			$j('.toolActive').not($tgt.closest('li')).removeClass('toolActive').find('.myItemToolbar').hide().find('.popup').hide();
			$tgt.closest('li').addClass('toolActive');
			$tgt.parent().children('.delMyItem').hide();
			$tgt.parent().children('.moveMyItem').slideToggle('fast');
			var curFolderName = $tgt.parents('.moreRecipes').parent('li').children('.togglelink').text();

			var items = $tgt.parent().find('.items');
			var htmlForEnter = "<ul>"
			$j('.myFolders .togglelink').each(function() {
				var itemName = $j(this).text();
				if (curFolderName != itemName) {
					htmlForEnter += '<li><a href="javascript:void(0);">' + itemName + '</a></li>';
				}
			});

			if (curFolderName != '') {
				htmlForEnter += '<li><a href="javascript:void(0);">' + $j('#otherText').val() + '</a></li>';
			}
			htmlForEnter += "</ul>";
			items.html(htmlForEnter);
			items.hide();
		}
		else if ($tgt.is('.myItemToolbar .moveMyItem .close')) {
			$tgt.closest('li').removeClass('toolActive');
			$tgt.closest('.moveMyItem').slideUp('fast', function() {
				$tgt.closest('.myItemToolbar').hide('fast');
			});
		}
		else if ($tgt.is('.myItemToolbar .moveMyItem .submit input')) {

			var FolderName = $j('.currentFolderName', $tgt.parent().parent()).val();
			var FolderId = -1;
			if (FolderName == $j('#otherText').val()) {
				FolderId = 0;
			}
			else {
				$j('.myFolders .togglelink').each(function() {
					if ($j(this).text() == FolderName) {
						FolderId = $j('.hdnFolderId', $j(this).parent()).val();
					}
				});
			}

			if (FolderId == -1 && $j.trim(FolderName) == '') {
				return;
			}

			var PageNumberPrev = 1;
			if (FolderId == 0) {

				PageNumberPrev = $tgt.parents('.otherRecipes').find('.pages .selected').attr('rel');
			}
			else {
				PageNumberPrev = $tgt.parents('.moreRecipes').find('.pages .selected').attr('rel');
			}
			if (PageNumberPrev == null) {
				PageNumberPrev = 1;
			}

			var data = {
				recipeId: $tgt.parents('.myItemToolbar').find('.delMyItemId').val(),
				folderId: FolderId,
				folderName: FolderName,
				pageId: $j('#hiddenNumber').val(),
				pageNumberPrev: PageNumberPrev,
				pageSize: $j('#hdnPageSize').val(),
				rowSize: $j('#hdnRowSize').val()
			};
			moveMyRecipeItem(e, data);
		}
	});

	$j('.saveItemPopup .recipeIsSaved .moveSavedRecipeToFolder').click(function() {
		$j(this).toggleClass('selected');
		$j(this).parent().find('.moveRecipe').slideToggle('fast');
	});


	$j('.saveItemPopup .recipeIsSaved .moveRecipe .submit input').live('click', function(e) {
		var parent = $j(this).parent().parent();
		var FolderName = parent.find('.currentFolderName').val();
		var FolderId = -1;
		if (FolderName == $j('#otherText').val()) {
			FolderId = 0;
		}
		else {
			FolderId = parent.find('li.sel > input').val();
			if (FolderId == undefined) {
				FolderId = -1;
			}
			else {
				FolderId = parseInt(FolderId);
			}
		}

		if (FolderId == -1 && $j.trim(FolderName) == '') {
			return;
		}

		var data = {
			recipeId: parseInt($j('.recipeId').val()),
			folderId: FolderId,
			folderName: FolderName
		};

		saveMyRecipeItemToFolder(e, data);

	});



	/*
	
	$j('.addComment .content fieldset a.submitWhite').click(function() {
	$j(this).parent('fieldset').parent('div').parent('.addComment').parent('.myItemToolbar').fadeOut('fast');
	$j(this).parent('fieldset').parent('div').parent('.addComment').fadeOut('fast', function() {
	if ($j.browser.msie) {
	$j(this).attr("style", "");
	}
	});
	$j(this).siblings('textarea').val('');
	$j(this).parent('fieldset').parent('div').parent('.addComment').parent('.myItemToolbar').removeClass('open');
	});
	$j('.addComment .content a.close').click(function() {
	$j(this).parent('div').parent('.addComment').parent('.myItemToolbar').removeClass('open');
	$j(this).parent('div').parent('.addComment').parent('.myItemToolbar').parent('.hoverDiv').removeClass('index');
	});
	
	
	$j('.weeklyMealPlaning li').bind("mouseenter", function() {
	if (!$j(this).children('.myItemToolbar').hasClass('no_comment')) {
	$j(this).children('.myItemToolbar').fadeIn('fast');
	}
	}).bind("mouseleave", function() {
	if (!$j(this).children('.myItemToolbar').hasClass('open')) {
	$j(this).children('.myItemToolbar').fadeOut('fast');
	}
	});

	$j('.myItemToolbar a.comment').click(function() {
	if ($j(this).parent('.myItemToolbar').hasClass('open')) {
	$j(this).siblings('.myItemToolbar .addComment').fadeOut('fast');
	$j(this).parent('.myItemToolbar').removeClass('open');
	} else {
	$j(this).siblings('.myItemToolbar .addComment').fadeIn('fast');
	$j(this).siblings('.addComment').find('textarea').focus();
	$j(this).parent('.myItemToolbar').addClass('open');
	$j(this).parent('.myItemToolbar').parent('.hoverDiv').addClass('index');
	}
	});
	*/

	/* Save My Pages Items */





	/* Save My Pages Items */

	var $saveItemPopup = $j('div.saveItemPopup');

	$saveItemPopup.each(function(e) {
		$j(this).find('a.close').click(function(e) {
			$j(this).slideDown('fast');
		});
		$j(this).find('input.passWord').bind('focus blur', function() {
			if ($j(this).val() == '') {
				$j(this).toggleClass("passWordBlank");
			}
		});
		$j(this).find('a.checkbox').click(function() {
			$j('div.saveItemPopup a.checkbox').toggleClass("checked");
		});
		ResetFormfield($j(this).find('input.userName'), "");
		defaultButton($j(this).find('fieldset.promptForUserName input.clearOnFocus'), $j(this).find('fieldset.promptForUserName span.submit:first input'));
		defaultButton($j(this).find('fieldset.promptForPassword input.clearOnFocus'), $j(this).find('fieldset.promptForPassword span.submit:first input'));
	});

	$j(document).bind('SHOW_SAVE_ITEM_POPUP', function(e, data) {
		showSaveItemPopup(e, data);
	});
	$j(document).bind('HIDE_SAVE_ITEM_POPUP', function(e, data) {
		hideSaveItemPopup(e, data);
	});
	$j(document).bind('PROMPT_FOR_USERNAME', function(e, data) {
		promptForUsername(e, data);
	});
	$j(document).bind('PROMPT_FOR_PASSWORD', function(e, data) {
		promptForPassword(e, data);
	});
	$j(document).bind('GET_USER_STATUS', function(e, data) {
		getUserStatus(e, data);
	});
	$j(document).bind('AUTHENTICATE_USER', function(e, data) {
		authenticateUser(e, data);
	});
	$j(document).bind('LOG_OUT_USER', function(e, data) {
		logOutUser(e, data);
	});
	$j(document).bind('UPDATE_AUTHENTICITY', function(e, data) {
		updateAuthenticity(e, data);
	});
	$j(document).bind('SUBSCRIBE_USER', function(e, data) {
		subscribeUser(e, data);
	});
	$j(document).bind('GET_SUBSCRIPTION_STATUS', function(e, data) {
		getSubscriptionStatus(e, data);
	});
	getSubscriptionStatus
	$j(document).bind('SHOW_SUBSCRIPTION_MESSAGE', function(e, data) {
		showSubscriptionMessage(e, data);
	});
	$j(document).bind('SHOW_MESSAGE', function(e, data) {
		showMessage(e, data);
	});
	$j(document).bind('CLEAR_CONTENT', function(e, data) {
		clearContent(e, data);
	});
	$j(document).bind('CLEAR_SAVE_ITEM_POPUP', function(e, data) {
		clearSaveItemPopup(e, data);
	});
	$j(document).bind('SEND_PASSWORD_REMINDER', function(e, data) {
		sendPasswordReminder(e, data);
	});
	$j(document).bind('REGISTER_USER', function(e, data) {
		registerUser(e, data);
	});
	$j(document).bind('SAVE_ITEM', function(e, data) {
		saveMyPagesItem(e, data);
	});

	SaveItemFlow = new EventFlow();

	$j("#pageContent .toolBar a.authenticateUserAndSaveItem").live('click', function() {
		$j(this).preventDefault;
		if ($j("#page #theme #pageContent").length > 0) {
			// Theme
			loginContainer = $j(this).parents().find('div.themeOptions').children('div.saveItemPopup');
		} else {
			loginContainer = $j(this).parents().find('div.recipeOptions').children('div.saveItemPopup');
		}

		loginContainerName = "." + $j(loginContainer).attr('class').split(' ')[1];
		$popup = $j(loginContainer);

		$j('#pageRelated .myPagesLogin .loginLinks a.login').removeClass('selected');

		SaveItemFlow.clear();
		SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(loginContainerName + ' div.recipeIsSaved'), popup: $popup });
		SaveItemFlow.add('UPDATE_AUTHENTICITY', { authenticity: true, reload: ($popup.find('.reloadOnLogin').val() == 1), popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('SAVE_ITEM', { typeID: $saveItemPopup.find('input.saveItemTypeID').val(), itemID: $saveItemPopup.find('input.saveItemID').val(), itemSavedText: $saveItemPopup.find('input.itemSavedText').val(), link: $j(this), popup: $j('#pageContent div.saveItemPopup') });
		SaveItemFlow.add('PROMPT_FOR_USERNAME', { registerIfAvailable: true, signupOnly: false, popup: $popup });
		SaveItemFlow.add('SHOW_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.next();
	});
	$j("#pageContent .toolBar a.saveItem").live('click', function() {
		$j(this).preventDefault;
		if ($j("#page #theme #pageContent").length > 0) {
			// Theme
			loginContainer = $j(this).parents().find('div.themeOptions').children('div.saveItemPopup');
		} else {
			loginContainer = $j(this).parents().find('div.recipeOptions').children('div.saveItemPopup');
		}

		loginContainerName = "." + $j(loginContainer).attr('class').split(' ')[1];
		$popup = $j(loginContainer);

		$j('#pageRelated .myPagesLogin .loginLinks a.login').removeClass('selected');

		SaveItemFlow.clear();
		SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(loginContainerName + ' div.recipeIsSaved'), popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('SAVE_ITEM', { typeID: $saveItemPopup.find('input.saveItemTypeID').val(), itemID: $saveItemPopup.find('input.saveItemID').val(), itemSavedText: $saveItemPopup.find('input.itemSavedText').val(), link: $j(this), popup: $popup });
		SaveItemFlow.add('SHOW_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.next();
	});

	$j('#pageRelated .myPagesLogin .loginLinks a.login:first').click(function(e) {
		$j(this).preventDefault;
		$j(this).addClass('selected');

		loginContainer = $j(this).parents().find('div.loginWrapper').children('div.saveItemPopup');
		$popup = $j(loginContainer);
		loginContainerName = "." + $j(loginContainer).attr('class');

		$j(this).parent().find('a.login:last').removeClass('selected');
		$j(loginContainerName + ' fieldset.promptForUserName').addClass('signUpState');
		$j(loginContainerName + ' fieldset.promptForUserName a.checkbox').hide();

		SaveItemFlow.clear();
		SaveItemFlow.add('SHOW_MESSAGE', { msg: $j('#pageRelated .myPagesLogin div.saveItemPopup div.userIsRegistered'), popup: $popup });
		SaveItemFlow.add('UPDATE_AUTHENTICITY', { authenticity: true, reload: false, popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('PROMPT_FOR_USERNAME', { registerIfAvailable: true, signupOnly: true, popup: $popup });
		SaveItemFlow.add('SHOW_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.next();
	});
	$j('#pageRelated .myPagesLogin .loginLinks a.login:last').click(function(e) {
		$j(this).preventDefault;
		$j(this).addClass('selected');

		loginContainer = $j(this).parents().find('div.loginWrapper').children('div.saveItemPopup');
		$popup = $j(loginContainer);
		loginContainerName = "." + $j(loginContainer).attr('class');

		$j(this).parent().find('a.login:first').removeClass('selected');
		$j(loginContainerName + ' fieldset.promptForUserName').removeClass('signUpState');
		$j(loginContainerName + ' fieldset.promptForUserName a.checkbox').show();

		SaveItemFlow.clear();
		SaveItemFlow.add('UPDATE_AUTHENTICITY', { authenticity: true, reload: ($j('#pageRelated div.saveItemPopup').find('.reloadOnLogin').val() == 1), popup: $popup });
		SaveItemFlow.add('HIDE_SAVE_ITEM_POPUP', { popup: $j('#pageRelated div.saveItemPopup') });
		SaveItemFlow.add('PROMPT_FOR_USERNAME', { registerIfAvailable: false, signupOnly: false, popup: $popup });
		SaveItemFlow.add('SHOW_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.next();
	});



	// Subscription portlet
	ResetFormfield($j('.subscriptionPortlet input.clearOnFocus'), "");
	$j('.subscriptionPortlet').each(function() {
		defaultButton($j(this).find('input.userName'), $j(this).find('span.submit:first input'));
	});

	//show popup on hover the subscriptions
	showPopupOnHoverMouse('.subscriptionPortlet .checkboxList li a', 58, 85);

	$j('.subscriptionPortlet').find('a.checkbox').live('click', function() {
		$j(this).parents('fieldset').find('.error').hide();
		$j(this).toggleClass("checked");
	});

	$j("#pageRelated .subscriptionPortlet .submit input").live('click', function(e) {
		$j(this).preventDefault;
		e.stopImmediatePropagation();
		var $popup = $j(this).closest('.subscriptionPortlet');
		var userName = $popup.find('.userName');
		var subID = $popup.find('.content').attr('id');
		var loginContainer = $j('#pageRelated').find('div.loginWrapper').children('div.saveItemPopup:first');
		$j("#pageRelated .subscriptionPortlet .content").removeClass('active');
		$popup.find('.content').addClass('active');
		var multiSub = false;

		if ($j(this).parents('fieldset').find('ul').hasClass('checkboxList')) {
			var multiSub = true;
			SaveItemFlow.add('GET_SUBSCRIPTION_STATUS', { email: userName.val() });
			SaveItemFlow.add('SUBSCRIBE_USER', { popup: $popup, multiSubscription: multiSub });
			SaveItemFlow.next();
		}
		SaveItemFlow.clear();

		SaveItemFlow.add('UPDATE_AUTHENTICITY', { authenticity: true, reload: ($j('#pageRelated div.saveItemPopup').find('.reloadOnLogin').val() == 1), popup: loginContainer });
		SaveItemFlow.add('SUBSCRIBE_USER', { email: userName.val(), registerIfAvailable: true, signupOnly: false, subscriptionID: subID, popup: $popup, multiSubscription: multiSub });
		if ($j(this).closest('fieldset').hasClass('promptForUserName')) {
			SaveItemFlow.next();
		}
	});


	$j('#pageRelated .subscriptionPortlet a.authenticateUserAndSaveItem').click(function(e) {
		$j(this).preventDefault;
		//$j(this).addClass('selected');

		loginContainer = $j(this).parent().parent().find('div.saveItemPopup');
		$popup = $j(loginContainer);
		loginContainerName = "." + $j(loginContainer).attr('class');

		SaveItemFlow.clear();

		SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(loginContainerName + ' div.recipeIsSaved'), popup: $popup });
		SaveItemFlow.add('UPDATE_AUTHENTICITY', { authenticity: true, reload: ($popup.find('.reloadOnLogin').val() == 1), popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('SAVE_ITEM', { typeID: $j('#pageRelated .subscriptionPortlet input.typeId').val(), itemID: $j('#pageRelated .subscriptionPortlet input.newsletterId').val(), itemSavedText: $popup.find('input.itemSavedText').val(), link: $j(this), popup: $popup });
		SaveItemFlow.add('PROMPT_FOR_USERNAME', { registerIfAvailable: true, signupOnly: false, popup: $popup });
		SaveItemFlow.add('SHOW_SAVE_ITEM_POPUP', { popup: $popup });
		SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: $popup });


		SaveItemFlow.next();
	});
	$j('#pageRelated .myPagesLogin .logoutLinks a.logout').click(function(e) {
		$j(this).preventDefault;
		SaveItemFlow.clear();
		SaveItemFlow.add('LOG_OUT_USER', { popup: $j('#pageRelated div.saveItemPopup') });
		SaveItemFlow.next();
	});

	/* My settings (newsletter)*/
	$mySettings = $j('div.mySettings div.sections');

	$mySettings.find('dt strong').click(function(e) {
		$j(this).closest('dl').find('dd:visible').slideToggle('medium');
		var $dd = $j(this).parent().next()
		if ($dd.is(':hidden')) {
			$dd.slideToggle('medium');
		}
	});
	$mySettings.find('a.checkbox').click(function(e) {
		var isActive = $j(this).parent().prev('dt').find('strong.active').length > 0;
		if (isActive) {
			var data = {
				id: $j(this).parent().find('input.newsletterID').val(),
				asHtml: !$j(this).hasClass('checked'),
				subscribe: true
			};
			updateSubscriptionSettings(e, data);
		} else {
			$j(this).toggleClass("checked");
		}
	});
	$mySettings.find('dt input:button').click(function(e) {
		var $dd = $j(this).closest('dt').next();
		var data = {
			id: $dd.find('input.newsletterID').val(),
			asHtml: $dd.find('a.checkbox').hasClass('checked'),
			subscribe: $j(this).parent().hasClass('submit')
		};
		updateSubscriptionSettings(e, data);
	});


	/* My folders */

	var ajaxEvent = false;
	var ajaxHtml = '<img src="/css/gfx/icons/ajaxAnimBig.gif" class="loader" alt="Loading..." />';


	// Shows corresponding popup when clicking a link
	$j('.myRecipes a.popuplink').live('click', function() {
		var popup = $j(this).next(".popup");
		if (popup.is(":visible")) {
			popup.hide();
		} else {
			$j('.myFolders .popup:visible').hide();
			popup.fadeIn("medium");
			if ($j(this).hasClass("renameFolder")) {
				$j(".folderName", popup).val($j('.hdnFolderName', $j(this).parent()).val()).focus();
			}
			if ($j(this).hasClass("createNewFolder")) {
				$j(".folderName", popup).focus();
			}
		}
	});

	$j('.myFolders .popup .cancel input, .myFolders .popup .close').live('click', function() {
		$j(this).parents(".popup").hide();
	});

	// Newfolder AJAX functions
	$j('.myRecipes .newFolder .submit input').live('click', function() {
		var input = $j(this).parent().parent().children(".folderName");
		var curVal = $j.trim(input.val());
		if (curVal != '') {
			$j(this).parents(".popup").fadeOut("medium");
			var serviceUrl = "/Services/FoldersService.asmx/AddFolder";
			var postData = { folderName: curVal };

			$j.ajax({
				type: "POST",
				data: $j.toJSON(postData),
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				url: serviceUrl,
				success: function(result, userContext, methodName) {
					if (result.d != null) {
						addMyFolder(result.d);
					}
				},
				error:
                    function() {

                    }
			});
			input.val('');
		}
	});



	// Rename folder AJAX functions
	$j('.folderMenu .renameFolder .submit input').live('click', function() {
		var menuFolder = $j(this).parents(".folderMenu");
		var input = $j("input.folderName", menuFolder);
		var curFolderId = $j('.hdnFolderId', menuFolder).val();
		var curFolderName = $j('.hdnFolderName', menuFolder).val();
		var curVal = $j.trim(input.val());
		if (curVal != '' && curVal != '') {
			if (ajaxEvent == true) {
				return false;
			}
			else {
				ajaxEvent = true;
			}

			$j(this).parents(".popup").fadeOut("medium");
			if (curFolderName == curVal) {
				ajaxEvent = false;
				return;
			}
			var serviceUrl = "/Services/FoldersService.asmx/RenameFolder";
			var postData = { folderId: curFolderId, folderName: curVal };
			$j.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				data: $j.toJSON(postData),
				url: serviceUrl,
				success:
                    function(result, userContext, methodName) {
                    	if (result.d != null) {
                    		var hdnFolderId = $j('.hdnFolderId[value="' + result.d.ID + '"]');
                    		hdnFolderId.siblings('.hdnFolderName').val(result.d.Name);
                    		hdnFolderId.parent().parent().children(".togglelink").text(result.d.Name);
                    	}
                    	ajaxEvent = false;
                    },
				error:
                    function() {
                    	ajaxEvent = false;
                    }

			});
		}
	});

	// Delete folder AJAX functions
	$j('.folderMenu .delMyItem .submit input').live('click', function() {

		var menuFolder = $j(this).parents(".folderMenu");
		var curVal = $j('.hdnFolderId', menuFolder).val();
		if ($j.trim(curVal) != '') {
			if (ajaxEvent == true) {
				return false;
			}
			else {
				ajaxEvent = true;
			}
			$j(this).parents(".popup").fadeOut("medium");
			var serviceUrl = "/Services/FoldersService.asmx/RemoveFolder";
			var postData = { folderId: curVal };
			$j.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				data: $j.toJSON(postData),
				url: serviceUrl,
				success:
                    function(result, userContext, methodName) {
                    	if (result.d > -1) {
                    		$j('.hdnFolderId[value="' + result.d + '"]').parent().parent().remove();
                    	}

                    	if ($j(".myFolders > li").length == 0) {
                    		$j(".myFolders").remove();
                    		$j('.addFolder').remove();
                    		var serviceUrl2 = "/Services/FoldersService.asmx/GetNoFolderControl";
                    		$j.ajax({
                    			type: "POST",
                    			contentType: "application/json; charset=utf-8",
                    			dataType: "json",
                    			data: "{}",
                    			url: serviceUrl2,
                    			success:
                                    function(result2, userContext2, methodName2) {

                                    	if (($j('ul.noFolder')).length == 0) {
                                    		$j("<ul class='myFolders noFolder'></ul>").insertAfter('#otherRecipesText');
                                    		$j(".myRecipes > .noCalibri").remove();
                                    	}

                                    	$j('ul.noFolder').append($j(result2.d).html());
                                    	if (($j('.otherRecipes')).length == 0) {
                                    		$j("<div class='otherRecipes'>" + $j('#emptyFolder').val() + "</div>").insertAfter(".noFolder");
                                    		$j('<span class="noCalibri"><h2 class="myFolders">' + $j('#otherRecipesText').val() + '</h2></span>').insertBefore('.otherRecipes');
                                    	}
                                    	defaultButton($j(".newFolder input.folderName"), $j(".newFolder .submit input"));
                                    	ajaxEvent = false;
                                    },
                    			error:
                                    function() {
                                    	ajaxEvent = false;
                                    }
                    		});
                    	}
                    	else {
                    		ajaxEvent = false;
                    	}
                    }
			});
		}
	});

	//Open-Close folder
	$j('.myFolders li a.togglelink').live('click', function() {
		var curElement = $j(this);

		if (curElement.hasClass('selected')) {
			curElement.removeClass('selected');
			curElement.siblings('.moreRecipes').slideUp('fast');

		} else {
			if (!curElement.siblings('.moreRecipes').hasClass('filled')) {
				var curVal = $j('.hdnFolderId', curElement.parent()).val();
				getPageForFolder(1, curVal);
			}
			else {
				curElement.addClass('selected');
				curElement.siblings('.moreRecipes').slideDown('fast');
			}
		}
	});

	function getPageForFolder(pageNumber, folderId) {
		var rowSize = $j('#hdnRowSize').val();
		var pageSize = $j('#hdnPageSize').val();
		var serviceUrl = "/Services/FoldersService.asmx/GetRecipesForFolderControl";
		var pageId = -1;
		if ($j('#hiddenNumber').length > 0) {
			pageId = $j('#hiddenNumber').val();
		}
		var postData = "{pageNumber: " + pageNumber + ", folderId:" + folderId + ", pageId: " + pageId + ", pageSize: " + pageSize + ", rowSize: " + rowSize + "}";
		if (folderId != null) {
			var li = $j('.hdnFolderId[value="' + folderId + '"]').parent().parent();
			$j('.moreRecipes', li).html(ajaxHtml).slideDown('fast');
		}
		else {
			$j('.otherRecipes').html('<img src="/css/gfx/icons/ajaxAnimBig.gif" class="loader" alt="Loading..." />')
		}
		$j.ajax({
			type: "POST",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			data: postData,
			url: serviceUrl,
			success:
                    function(result, userContext, methodName) {
                    	if (result.d != null && result.d.ControlHtml != '') {
                    		renderFolder(result.d);
                    		updateUserDot();

                    	}
                    },
			error:
                    function() {

                    }
		});
	}

	//Paging ForMyFolders
	$j('.myRecipes .paging a:not(.selected), div.userFolder .paging a:not(.selected)').live('click', function() {


		var curElement = $j(this);
		var pageNumber = curElement.attr('rel');

		if (curElement.closest('.otherRecipes').length > 0) {

			/* Set height so the page doesnt jump */
			curElement.closest('.otherRecipes').addClass('fixedPagingHeight');

			getPageForFolder(pageNumber, null);
		}
		else if (curElement.closest('div.userFolder').length > 0) {
			/* Set height so the page doesnt jump */
			curElement.closest('div.userFolder').addClass('fixedPagingHeight');

			getPageForFolder(pageNumber, $j('.hdnFolderId').val());
		}
		else {
			var parentLi = $j(this).closest('.myFolders li');
			var curVal = parentLi.find('.hdnFolderId').val();

			/* Set height so the page doesnt jump */
			parentLi.find('.moreRecipes').addClass('fixedPagingHeight');

			getPageForFolder(pageNumber, curVal);
		}

	});

	// Submit button on enter
	defaultButton($j(".newFolder input.folderName"), $j(".newFolder .submit input"));
	$j('div.renameFolder').each(function() {
		var current = $j(this);
		defaultButton($j("input.folderName", current), $j(".submit input", current));
	});




	/*///////////////////////////////////////////////*/
	//		/MYPAGES
	/*///////////////////////////////////////////////*/


	/***************************************************
	Add this
	***************************************************/
	hover($j('.addthis_toolbox'))
	/***********************************************
	RECIPE 
	***********************************************/

	/* Heading resize if it's too long */

	if ($j("#recipe").length > 0) {
		recipeHeadingSelector = $j("#recipe #content h1");
		recipeMaxWidth = parseInt($j("#recipe .threeColumn").css("width"));
		if ($j(".recipeDkSpecial").length > 0) {
			// on recipeDkSpecial, jQuery only gets h1 width when .left class is defined.
			recipeHeadingSelector = $j("#recipe #content .left h1");
			recipeMaxWidth = parseInt($j("#recipe .threeColumn").css("width")) - parseInt($j("#recipe .right").css("width")) - 20; // padding
		}
		if ($j(recipeHeadingSelector).width() >= recipeMaxWidth) {
			fontSize = 31;
			while ($j(recipeHeadingSelector).width() > recipeMaxWidth) {
				fontSize -= 1;
				if (fontSize < 11) {
					break;  // prevents infinite loop and stops before txt becomes unreadable
				}
				$j(recipeHeadingSelector).css('font-size', fontSize + 'px');
			}
		}
	}

	/* Message for disabling favorite*/
	if ($j('.recipeOptions').is(':visible')) {

		if (disablingText[0] == 'undefined') {
			var disablingMessage = ''
		}
		else {
			var disablingMessage = disablingText[0];
		}


		$j("<div class='popup disablingBox'><div class='content'><p></p></div></div>").prependTo('div.recipeActions');
		$j('a.addToPurchaseList').hover(function() {
			$j('div.recipeActions .disablingBox').fadeIn('fast');
			$j('div.recipeActions .disablingBox p').text(disablingMessage);
		}, function() {
			$j('div.recipeActions .disablingBox').fadeOut('fast');
			$j('div.recipeActions .disablingBox p').text();
		});
	}
	$j('.newRecipe ul.recipeControl div.ingredients').hover(function() {
		$j(this).parent('li').addClass('index');
	}, function() {
		$j(this).parent('li').removeClass('index');
	});

	/* Toolbar hover */
	hover('ul.toolBar li:not(.persons)');

	/* show share recipe */
	$j('div.recipeActions .shareRecipe').mouseover(function() {
		$j('.shareLinks').fadeIn('fast');
	});
	$j('div.recipeActions').mouseout(function() {
		$j('.shareLinks').fadeOut('fast');
	});

	/* Hover on share links */
	hoverWhite('ul.recipeActions > li');

	/* Hover captchaHelpTrigger */
	hoverWhite('.captchaHelpTrigger');


	/* Rating Tips on recipe page */
	$j("<div class='popup ratingTips'><div class='content'><p></p></div></div>").appendTo('div.voting ul.rating');
	$j('ul.rating li a').each(function() {
		var tipsVal = $j(this).attr('class');

		$j(this).one('click', function() {
			RateRecipe(tipsVal);
		})
		var tipsTextHeading = $j(this).attr('title');
		var tipsTextDescription = $j(this).text();

		$j(this).hover(function() {
			var $ratePopup = $j(this).parent().parent();

			var posX = (-1 * ($ratePopup.find('a').index($j(this)) * 14) + 22);

			$j('.ratingTips').css({ right: posX });
			$j('.ratingTips').show();
			$j('.ratingTips p').html('<strong>' + tipsTextHeading + '</strong><br/><span class="description">' + tipsTextDescription + '</span>');
			$j(this).attr('title', '');
		}, function() {
			$j('.ratingTips').hide();
			$j('.ratingTips p').text();
			$j(this).attr('title', tipsTextHeading);
		});
	});
	$j('ul.rating').hover(function() {
		$j(this).css({ 'background-image': 'none' });
	}, function() {
		$j(this).css({ 'background-image': 'url(/css/gfx/icons/star-rating.gif)' });
	});


	/* Ingredients scale on recipepage */
	$j('div.ingredients span.portionDisclaimer').hide();
	$j('div.portionController a').click(function() {
		var pieces = $j('div.ingredients strong.pieces').text();
		if ($j(this).attr('class') == 'left') {
			pieces--;
			$j('div.ingredients strong.pieces').text(pieces)
		} else {
			pieces++;
			$j('div.ingredients strong.pieces').text(pieces)
		}
		if ($j('div.ingredients strong.pieces').text() == '12') {
			$j('div.ingredients span.portionDisclaimer').hide();
		} else {
			$j('div.ingredients span.portionDisclaimer').show();
		}
	});

	/* Open loginReminder for favorite link on recipe page */
	$j("div.loginReminder a.closeLogin").livequery(function() {
		$j(this).click(function() {
			$j(document).trigger("cluetip.close");
			$j('div.recipeOptions a.favorite').parent().parent().toggleClass("selected");
			return false;
		});
	});

	/* captcha Help hover */
	$j('.captchaHelpTrigger').hover(function() {
		$j('.captchaHelp').fadeIn('fast');
	}, function() {
		$j('.captchaHelp').fadeOut('fast');
	});

	/* Facebook */
	$j('.facebook').click(fbs_click);

	/* Add to blogger */
	$j('.blog').click(AddToBlogger);

	/* autogrow textarea */
	$j('textarea.expanding').autogrow();

	/* Recipe Comment */
	if ($j('ol.comments').is(':visible')) {
		ShowHideComments();
	}


	// default buttons
	defaultButton('#commentBox input', '.createComment');
	if ($j(".tellAFriendOfUserRecipeTrigger").length > 0) {
		defaultButton('.tellAFriend input', '.tellAFriendOfUserRecipeTrigger');
	}

	// TEMP Tell A Friend of Campaign
	else if ($j(".tellAFriendOfCampaignTrigger").length > 0) {
		defaultButton('.tellAFriend input', '.tellAFriendOfCampaignTrigger');
	}

	else {
		defaultButton('.tellAFriend input', '.tellAFriendTrigger');
	}

	$j('a.showHideComments').one('click', ToggleComments);
	/* Share links hover */
	showPopupOnHover('.shareRecipeTrigger');

	/* Comment */
	if ($j('ol.comments').is(':visible')) {
		ShowHideComments();
	}
	$j('a.showHideComments').live('click', ToggleComments);

	//creating errormessage wrapper
	$j("<div class='errorMessage'><div class='arrow'></div></div>").insertAfter('.val');
	$j('input.createComment').click(CreateComment);

	$j('.commentLink').bind('click', function() { ToggleCommentForm() });
	$j('#commentCaptcha').numeric();
	$j('#commentForm .cancel').bind('click', function() {
		$j('#commentCaptcha').val('');
		$j('#commentName').val('');
		$j('#commentBody').val('');
		$j('.errorBox').remove();
		$j('.commentLink').trigger('click');
	});

	if ($j('#recipe #commentBox').is(':visible')) {

		var pageHash = location.hash;
		if (location.hash == "#WriteACommentAndExpand") {
			commentsLocation = parseInt($j("#commentBox").offset().top);
			$j(".commentLink").trigger("click");
			$j("body,html").animate({ scrollTop: commentsLocation }, 500);
		}
	}
	if ($j('#recipe li.printOption').is(':visible')) {
		var pageHash = location.hash;
		var printLocation = parseInt($j("div.recipeOptions").offset().top - 200);
		if (location.hash == "#PrintRecipe") {
			$j("li.printOption a.print").trigger("click");
			$j("body,html").animate({ scrollTop: printLocation }, 500);
		}
	}

	/*Reset form in tell a friend*/
	ResetFormfield(".tellAFriend #uiToEmail", "");
	ResetFormfield(".tellAFriend #uiFromName", "");
	ResetFormfield(".tellAFriend #uiFromEmail", "");
	ResetFormfield(".tellAFriend #uiText", "");

	/*close popup*/
	$j('.popup .close').click(function() { $j(this).parents('.popup').hide() });

	/*close confirm tell a friend*/
	$j('.tellAFriend .confirm input').click(closeTellAFriend);

	/* Validate and click Tell A Friend */
	$j('.tellAFriendTrigger').click(TellAFriend);
	$j('.tellAFriendOfUserRecipeTrigger').click(TellAFriendOfUserRecipe);
	$j('.tellAFriendOfCampaignTrigger').click(TellAFriendOfCampaign);


	/* Show Tell A Friend popup */
	$j('.recipeActions .mail').click(function() {
		$j('.tellAFriend').fadeIn('300');
		$j('.tellAFriend #focusElement').focus();
	});

	/*Tip again tell a friend*/
	$j('.tellAFriend .confirm a').click(function() {
		resetTellAFriend();
	});

	/*cancel TellAFriend popup*/
	$j('.tellAFriend .cancel').click(function() {
		$j('.popup .close').trigger('click');
		resetTellAFriend();
	});
	$j('.tellAFriend .close').click(function() {
		$j(this).parents('.popup').hide();
		resetTellAFriend();
	});
	/* ------ Recipe Dk Special ------ */
	popupPos = $j('.recipeDkSpecial .recipeActions li:first').width();
	$j('.recipeDkSpecial div.recipeActions .tellAFriend').css({ 'left': popupPos })

	/* ------ Expand comments when click anchor ------ */
	$j('.toolBar a.comments').live('click', function() {
		if ($j('a.showHideComments').text() != msgComments[0]) {
			ToggleComments();
			ShowHideComments(this);
		}
	});

	/***********************************************
	SEARCH 
	***********************************************/
	if ($j('.searchForm').length > 0) {
		ResetFormfield(".searchFieldContainer input.searchField", searchDefaultValue[0]);
		defaultButton(".searchFieldContainer input.searchField", "#searchButton input");
	}
	if ($j('#search').length > 0) {

		if (searchDefaultValue[0] != $j('input.searchField').val()) {
			$j('input.searchField').addClass('focus');
		}

	}
	/* More searchresult (related portlet), no border on last item, IE fix */
	$j('div.moreSearchResults li:last').addClass('last-child');

	if ($j('div.searchFilter').is(':visible')) {
		searchFilterTrigger();
		searchPagingTrigger();

	}

	if ($j('#search .searchResults').hasClass('noHits')) {
		$j('.searchFilter').hide();
	}
	if ($j('.searchFilter ul.refine').length < 1) {
		$j('.searchFilter .moreFilters:first').hide();
	}
	// toggle all filters
	$j('.searchFilter .heading .moreFilters').click(function() {
		if ($j(this).find('.moreFiltersIcon').hasClass('fewer')) {
			$j(this).find('.moreFiltersText').text(msgSearchFilters[1]);
			$j(this).find('.moreFiltersIcon').removeClass('fewer');
			$j('ul.refine li.hide').slideUp().parent('ul').removeClass('e'); ;
			$j('#searchFilters h4 a').removeClass('fewer');
		}
		else {
			$j(this).find('.moreFiltersText').text(msgSearchFilters[0]);
			$j(this).find('.moreFiltersIcon').addClass('fewer');
			$j('ul.refine li.hide').slideDown().parent('ul').addClass('e');
			$j('#searchFilters h4 a').addClass('fewer');

		}
	});

	/********************************************
	Selector for themes and menus
	/********************************************/
	var PageNavigationErrorText = "Der er sket en fejl"
	if (typeof (languageBranch) != "undefined") {
		var langBranch = languageBranch;
	}
	else {
		var langBranch = 'da';
	}
	//themeSelector trigger
	$j('#selector .menu a').live('click', function() {
		if ($j(this).parent('li').hasClass('sel') == false) {
			pagerNo = 1;
			$j(document).trigger('updateElements', { caching: $j(this).attr('rel'), post_languageBranch: langBranch, post_placement: $j('body').find('#page').children().attr('id'), post_itemsCategory: $j(this).attr('rel'), post_pagerNo: pagerNo, output: ['#selector .items .itemsList', '.items .paging', '.items h2'], webservice: ['/Services/PageNavigationService.asmx/PagerContent', '/Services/PageNavigationService.asmx/PagerNav', '/Services/PageNavigationService.asmx/PagerContentHeader'], error: ['<p class="errorBox">' + PageNavigationErrorText + '</p>'], fade: ['true', 'false', 'false'] });
			$j('#selector li').removeClass('sel');
			$j(this).parent('li').addClass('sel');
		}

	});

	//themeSelector Paging trigger
	$j('#selector .paging .pages a, #selector .paging .pagingLeft a, #selector .paging .pagingRight a').live('click', function() {
		if ($j(this).hasClass('selected') == false) {
			var itemsCategory = $j(this).parents('#selector').find('.menu li.sel a').attr('rel');
			$j(document).trigger('updateElements', { caching: itemsCategory + $j(this).attr('rel'), post_languageBranch: languageBranch, post_placement: $j('body').find('#page').children().attr('id'), post_itemsCategory: itemsCategory, post_pagerNo: $j(this).attr('rel'), output: ['#selector .items .itemsList', '.items .paging', '.items h2'], webservice: ['/Services/PageNavigationService.asmx/PagerContent', '/Services/PageNavigationService.asmx/PagerNav', '/Services/PageNavigationService.asmx/PagerContentHeader'], error: ['<p class="errorBox">' + PageNavigationErrorText + '</p>'], fade: ['true', 'false', 'false'] });
			$j('#footer').focus();
		}
	});




	/********************************************
	Products				
	/********************************************/

	//Product Paging trigger
	$j('.otherProducts .paging .pages a, .otherProducts .paging .pagingLeft a, .otherProducts .paging .pagingRight a').live('click', function() {
		if ($j(this).hasClass('selected') == false) {
			$j(document).trigger('updateElements', { post_languageBranch: languageBranch, caching: $j(this).attr('rel'), post_placement: $j('body').find('#page').children().attr('id'), post_itemsCategory: $j('.otherProducts .paging').attr('rel'), post_pagerNo: $j(this).attr('rel'), output: ['.otherProducts ul', '.otherProducts .paging'], webservice: ['/Services/PageNavigationService.asmx/PagerContent', '/Services/PageNavigationService.asmx/PagerNav'], error: ['<p class="errorBox">' + PageNavigationErrorText + '</p>', '<p class="errorBox">' + PageNavigationErrorText + '</p>'], fade: ['true', 'false'] });
		}
	});

	hidePaging();

	//Setting hover class on other product listing
	$j('div.otherProducts div.wrapper li.product').hover(function() {
		$j(this).addClass("over");
	},
		function() {
			$j(this).removeClass("over");
		});

	//productCarousel trigger
	$j('#productCarousel a').click(function() {
		if ($j(this).parent('li').hasClass('sel') == false) {
			$j(document).trigger('updateElements', { post_languageBranch: languageBranch, caching: $j(this).attr('rel'), post_pageRefId: $j(this).attr('rel'), output: ['.productCarousel .content:first', '.productRelatedRecipes', '.relatedProducts .content'], webservice: ['/Services/ProductNewsService.asmx/ProductCarousel', '/Services/ProductNewsService.asmx/SearchHits', '/Services/ProductNewsService.asmx/OtherProducts'], error: ['<div class="text"><p class="errorBox">' + ProductNewsErrorText + '</p></div>', '<div class="content"><p class="errorBox">' + ProductNewsErrorText + '</p></div>', '<div class="relatedBox relatedProducts"><div class="content"><p class="errorBox">' + ProductNewsErrorText + '</p></div>'], fade: ['true', 'true', 'true'] });
		}
	});

	/* Product carousel*/
	$j('#productCarousel li:first').addClass('sel');

	$j('#productCarousel').jcarousel();

	/* jCAROUSEL has a problem to get width for ul in edit mode therefore we are setting this in edit mode */
	if (typeof (isEditMode) == 'function') {
		if (isEditMode()) {
			carouselItems = $j('ul#productCarousel li').length;
			carouselWidth = carouselItems * '78';
			jQuery('ul#productCarousel').css("width", carouselWidth);
		}
	}
	$j('.productCarousel .slide .prevButton').remove();
	$j('.productCarousel .slide ul li:last').addClass('last');

	$j('.productCarousel .slide ul li a').click(function() {
		$j('.productCarousel .slide ul li').removeClass('sel');
		$j(this).parents('li').addClass('sel');
		$j(this).attr('href', 'javascript:void(0)');
	});

	tooltip();


	//Recipe Paging trigger
	$j('.topRecipesNavigation .paging .pages a, .topRecipesNavigation .paging .pagingLeft a, .topRecipesNavigation .paging .pagingRight a').live('click', function() {
		if ($j(this).hasClass('selected') == false) {
			$j(document).trigger('updateElements', { caching: $j(this).attr('rel'), post_placement: $j('body').find('#page').children().attr('id'), post_itemsCategory: $j('.topRecipesNavigation .paging').attr('rel'), post_pagerNo: $j(this).attr('rel'), output: ['.topRecipesNavigation div#topListRecipeItems', '.topRecipesNavigation .paging'], webservice: ['/Services/PageNavigationService.asmx/PagerContent', '/Services/PageNavigationService.asmx/PagerNav'], error: ['<p class="errorBox">' + PageNavigationErrorText + '</p>', '<p class="errorBox">' + PageNavigationErrorText + '</p>'], fade: ['true', 'false'] });
		}
	});

	$j('#topList #pageContent #content .paging .pages a,#topList #pageContent #content .paging .pagingLeft a,#topList #pageContent #content .paging .pagingRight a').live('click', function() {
		if ($j(this).hasClass('selected') == false) {
			window.location = "?p=" + $j(this).attr('rel');
		}
	});



	/* No Flash product carousel */

	$j(".nfProducts .dropDown p").click(function() {
		$j(".nfProducts .items").toggle();
		if ($j(".nfProducts .dropDown").hasClass("sel")) {
			$j(".nfProducts .dropDown,.nfProducts .dropDown p").removeClass("sel");
		} else {
			$j(".nfProducts .dropDown,.nfProducts .dropDown p").addClass("sel");
		}
	});
	$j(".nfProducts .dropDown ul li").click(function() {
		$j(".nfProducts .items").hide();
		$j(".nfProducts .dropDown p").text($j(this).text());
		$j(".nfProducts .dropDown,.nfProducts .dropDown p").removeClass("sel");
	});

	/* Non-Calibri IE6 fix for products page */
	if ($j(".productPage .productPresentation").is(":visible")) {
		$j(".productPage .productHeader").addClass("withText");
	}



	/********************************************
	Top lists			
	/********************************************/
	// IE hack: prevents popup to appear under other recipes.
	$j('#topList .ingredients a.showIng').click(function() {
		$j(this).parent().parent().css('z-index', '1000');
	});
	$j('#topList .ingredients a.close').click(function() {
		$j(this).parent().parent().parent().parent().css('z-index', '');

	});


	/********************************************
	Global functions				
	/********************************************/


	/* Hover on ingredientslist*/
	$j('ul.hover li').hover(function() {
		if ($j(this).children('.ingredients').children('.popup').is(':visible')) { }
		else {
			$j(this).addClass('hoverState');
		}
	},
		function() {
			$j(this).removeClass('hoverState');
		});
	hoverDisabled($j('ul.hover li ul li'));

	$j('body').bind('showIngredientsList', function() {
		ShowIngredientsList();
	});
	$j('body').trigger('showIngredientsList');

	// Global Bindings
	$j(document).bind('updateElements', function(e, data) {
		UpdateElements(data);
	});

	// reset defaultvalue for subscribe field
	if ($j('fieldset.subscribe').length > 0) {
		ResetFormfield($j('fieldset.subscribe input.textfield'), $j('fieldset.subscribe input.textfield').val());
	}

	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	if ($j('div.recipeSearch').is(':visible')) {
		jQuery.historyInit(callback);
	}


	$j('.fileUpload input').uploadify({
		'uploader': '/flash/uploadify.swf',
		'script': '/Services/RecipeService.asmx/UploadOwnRecipeImage',
		'cancelImg': '/css/gfx/elements/btnCloseLogin.gif',
		'auto': true,
		'multi': false,
		'fileExt': '*.png;*.jpg;*.jpeg;*.gif',
		'fileDesc': '*.png;*.jpg;*.jpeg;*.gif',
		'sizeLimit': '1024000',
		'folder': '/uploads',
		'buttonText': 'fileUploadText',
		'width': 296,
		'height': 21,
		'wmode': 'transparent',
		'onComplete': function(event, queueID, fileObj) {
			$j(event.target).uploadifySettings('buttonText', fileObj.name);
			$j(event.target).closest('ul').next('.fileUploadPreview').fadeIn();
		}
	});
	$j('.fileUploadPreview a.delFileUpload').click(function() {
		$j(this).closest('.fileUploadPreview').fadeOut();
		$j(this).closest('.fileUploadPreview').prev('ul').find('.fileUpload input').uploadifySettings('buttonText', 'fileUploadText');
	});

	//DOM ready end 
});

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Functions
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */



//Toogle ingredients on hover
function ShowIngredientsList() {
    //add attributes

    $j('.recipeControl .showIng').livequery(function() {
        $j(this).each(function(index) {
            $j(this).attr('href', "javascript:void(0)");
            $j(this).next('.popup').addClass('toShow');
        });

        $j(this).hoverIntent(function() {
            var elm = $j(this).next('.popup');
            $j('.recipeControl .showIng').next('.popup').hide();
            $j('.ingredients').removeClass('active');
            elm.parents('.ingredients').addClass('active');
            // IE Z-index hack:
            if ($j(this).closest('ul').css('position') == 'relative' && $j(this).closest("ul").children("li.activeRecipe").length == 0) {
                $j(this).closest('ul').css('position', 'static');
                $j(this).closest('ul').addClass('wasRelative');
            }
            if (elm.hasClass('clicked')) {
                elm.show();
            }
            else {
                elm.fadeIn('fast');
                $j('.recipeControl .showIng').next('.popup').removeClass('clicked');
                $j(this).css('position', 'relative');
                $j(this).parent().css('position', 'relative');
                elm.find('.close').hide();
            }
        },
		function() {
		    var elm = $j(this).next('.popup');

		    if (elm.hasClass('clicked')) {
		        elm.show();
		    }
		    else {
		        elm.fadeOut('fast');
		        elm.parents('.ingredients').removeClass('active');
		        setTimeout("$j(this).css('position','static')", 500);
		        setTimeout("$j(this).parent().css('position','static')", 500);
		        // IE Z-index hack:
		        if ($j(this).closest('ul').hasClass('wasRelative')) {
		            $j(this).closest('ul').css('position', 'relative');
		            $j(this).closest('ul').removeClass('wasRelative');
		        }
		    }
		});
    });

    //add click for ingredientslist
    $j('.recipeControl .showIng, .recipeControl .popup .close').live('click', function() {
        var elm = $j(this).next('.popup');
        var allElm = $j('.recipeControl .popup');
        if ($j(this).hasClass('close')) {
            var elm = $j(this).parents('.popup');
        }
        if (elm.hasClass('clicked')) {
            elm.parents('.ingredients').removeClass('active');
            elm.removeClass('clicked');
            elm.find('.close').hide();
            elm.hide();
        }
        else {
            elm.addClass('clicked');
            elm.show();
            elm.parents('.shoeIng').css('position', 'relative');
            elm.find('.close').show();
        }
    });
}



//Updating elements with ajax
function UpdateElements(data) {
    jQuery.each(data.output, function(index) {
        if ($j(data.output[index]).length > 0) {

            var newPostData = {};

            for (prop in data) {
                if (prop.indexOf('post_') != -1) {
                    var propName = prop.replace(/post_/, '');
                    newPostData[propName] = data[prop];
                }
            }

            if (typeof (data.pageDefinition) != "undefined") {
                var pageDefinition = data.pageDefinition[index];
            }

            var d = new Date();
            var caching = data.caching;
            if (caching == null) {
                var caching = d.toUTCString();
            }
            $j.Tache.Get({
                type: "POST",
                data: newPostData,
                url: data.webservice[index],
                cacheKey: data.webservice[index] + "?" + caching,
                cache: false,
                success: function(html) {
                    elementHTML = $j('string', html).text();
                    if (data.fade[index] == "true") {
                        UpdateFading(data.output[index], elementHTML);
                    } else {
                        UpdateNoFX(data.output[index], elementHTML);
                    }
                    if (pageDefinition == "search") {
                        searchFilterTrigger();
                        searchPagingTrigger();
                        updateTitle($j('.paging .selected').attr('title'));
                    }
                    else if (pageDefinition == "searchPaging") {
                        searchPagingTrigger();
                        updateTitle($j('.paging .selected').attr('title'));
                    }
                },
                error: function(html) {
                    elementErrorHTML = data.error[index];
                    UpdateFading(data.output[index], elementErrorHTML);
                }

            });
        }
    });
    return false;
}

// Update html with fadeIn/fadeOut
function UpdateFading(elm, html) {
    $j(elm).fadeOut(400, function() {
        $j(this).html(html);
    });
    $j(elm).fadeIn(400);
}

// Update html without efx
function UpdateNoFX(elm, html) {
    $j(elm).html(html);
}

// Get Position for Popup
function getPopupPos(e, $popup) {
    posX = e.pageX - $popup.width() / 2;
    posY = e.pageY - $popup.height() - 20;
    return [posX, posY]
}
// Facebook link
function fbs_click() { u = location.href; t = document.title; window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436'); return false; }

// Add to blogger
function AddToBlogger() { var sCode = "undefined"; self.location.href = 'http://beta.blogger.com/add-widget?widget.title=&widget.content=' + sCode; }

//function to toggle text 
function textToggle(element, text1, text2) {
    if (jQuery.trim($j(element).text()) == text1)
        $j(element).text(text2);
    else $j(element).text(text1);
}
/* Reset form fields on focus*/
function ResetFormfield(elm, defaultValue) {
    $j(elm).focus(function() {
        if (defaultValue != "") {
            if (this.value == defaultValue) {
                this.value = "";
                $j(this).addClass('focus');
            }
        }
        else {
            if (this.value == this.defaultValue) {
                this.value = "";
                $j(this).addClass('focus');
            }
        }
    }).blur(function() {
        if (defaultValue != "") {
            if (!this.value.length) {
                this.value = defaultValue;
                $j(this).removeClass('focus');
            }
        }
        else {
            if (!this.value.length) {
                this.value = this.defaultValue;
                $j(this).removeClass('focus');
            }
        }


    });
}

// default button for form
function defaultButton(elm, btn) {
    $j(elm).keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $j(btn).trigger('click');
            return false;
        } else {
            return true;
        }
    });
}

//Global hover function
function hover(elm) {
    $j(elm).hover(function() {
        $j(this).addClass('hoverState');
    },
	function() {
	    $j(this).removeClass('hoverState');
	});
}

//Global hover white box function
function hoverWhite(elm) {
    if ($j(elm).next().attr('class') != 'hoverWhiteRight') {
        $j('<span class="hoverWhiteRight"></span>').prependTo($j(elm));
    }
    $j(elm).hover(function() {
        $j(this).addClass('hoverWhite');

    },
	function() {
	    $j(this).removeClass('hoverWhite');
	});
}

//Disabling hover
function hoverDisabled(elm) {
    $j(elm).hover(function() {
        $j(this).removeClass('hoverState');
    },
	function() {
	});
}

//show popup on hover
function showPopupOnHover(elm) {
    $j(elm).hoverIntent(function() {
        $j(this).next('.popup').fadeIn('fast');
    },
	function() {
	    $j(this).next('.popup').fadeOut('fast');
	});
}

//show popup on hover that follow the cursor
function showPopupOnHoverMouse(elm, xPadding, yPadding) {
    $j(elm).each(function() {
        $j(this).hoverIntent(function(e) {
            var elmWidth = ($j(this).next('.popup').width() + xPadding) / 2;
            var elmHeight = $j(this).next('.popup').height() - yPadding;
            $j(this).next('.popup').css("top", (e.pageY - xOffset - elmHeight) + "px").css("left", (e.pageX + yOffset - elmWidth) + "px");

            $j(this).next('.popup').fadeIn('fast');
        }, function() {
            $j(this).next('.popup').fadeOut('fast');
        });
        $j(this).mousemove(function(e) {
            var elmWidth = ($j(this).next('.popup').width() + xPadding) / 2;
            var elmHeight = $j(this).next('.popup').height() - yPadding;
            $j(this).next('.popup').css("top", (e.pageY - xOffset - elmHeight) + "px").css("left", (e.pageX + yOffset - elmWidth) + "px");
        });
    });
}

/***************************************************
Search functions
***************************************************/
function callback(hash) {
    hash = hash.replace(/^.*#/, '');
    updateSearchElements(hash);
    return false;
}
function searchFilterTrigger() {
    // set onlick event for searchfilter buttons
    $j('#searchFilters li span a, .searchNav p.left a').one('click', function() {
        var hash = this.href;
        hash = hash.replace(/^.*#/, '');
        jQuery.historyLoad(hash);

        clicked = $j(this).attr('rel');
        if ($j(this).parents('li:first').hasClass('selected')) {
            $j('.searchNav p.left a').each(function(index) {
                if (clicked == $j(this).attr('rel')) {
                    $j(this).trigger('click');
                }
            });
        }
        else {
            // Remove filter from post array
            if ($j(this).parents('div:first').hasClass('searchNav')) {
                $j(this).removeClass('include');
                $j(this).removeClass('exclude');
            }
            $j(this).parents('#searchFilters').find('li').addClass('disabled');
        }
        return false;
    });
    hover($j('#searchFilters h4'));
    hover($j('#searchFilters ul li'));

    // toggle single filter
    $j('h3.allergy a, #searchFilters h4 a').click(function() {
        if ($j(this).hasClass('fewer')) {
            $j(this).removeClass('fewer').parent().next('ul').removeClass('e');
            $j(this).parent().next().children('.hide').slideUp();
            return false;
        }
        else {
            $j(this).addClass('fewer').parent().next('ul').addClass('e');
            $j(this).parent().next().children('.hide').slideDown();
            return false;
        }
    });

}

// function for update searchelements (searchnavigation, searchresult, searchpaging and searchfilter)
function updateSearchElements(hash) {
    // define search query
    var qs = new Querystring();
    var q = qs.get("q");

    if (hash) {
        // define search hash
        var qsh = new Querystring(hash);
        var paging = qsh.get("p");
        var pagingTrigger = $j('#content .paging').hasClass('clicked');


        //define totalArray for navigatores
        var totalArrayExclude = qsh.get('e') ? qsh.get('e') : '';
        var totalArrayInclude = qsh.get('i') ? qsh.get('i') : '';

        // restore ajax loaded state
        if ($j.browser.msie) {
            // jquery's $.load() function does't work when hash include special characters like åäö.
            hash = encodeURIComponent(hash);
        }
        // call updateSearchPaging
        if (pagingTrigger == true) {
            updateSearchPaging(paging, totalArrayExclude, totalArrayInclude, q);
        }
        else {
            UpdateSearchResult(paging, totalArrayExclude, totalArrayInclude, q);
        }
    } else {
        //if hash is empty (clean search)
        UpdateSearchResult('1', "", "", q);
    }
}

function UpdateSearchResult(pageNr, totalArrayExclude, totalArrayInclude, q) {
    // Remove single toggle function
    $j('ul.refine').each(function() {
        if ($j(this).find('li.hide').length < 1) {
            $j(this).prev().find('a').removeAttr('href');
        }
    });

    // hide show all link 
    var hideShowAll = true;
    $j('.searchFilter ul.refine').each(function(e) {
        if ($j(this).children('li:last').hasClass('hide')) { hideShowAll = false; }
    });
    hideShowAll ? $j('.searchFilter .moreFilters:first').hide() : $j('.searchFilter .moreFilters:first').show();

    // define state for expand/collapse
    var arrayToggleState = [];
    $j('#searchFilters ul.e').each(function() {
        var categoriString = $j(this).find('a:first').attr('rel');
        var categoriArray = categoriString.split(":");
        arrayToggleState[arrayToggleState.length] = categoriArray[0];
    });
    var arrayToggleState = arrayToggleState.join();
    // create caching ajax url

    //remove special characters from the string
    totalArrayIncludeCaching = totalArrayInclude.replace(/[^a-zA-Z 0-9]+/g, '');
    totalArrayExcludeCaching = totalArrayExclude.replace(/[^a-zA-Z 0-9]+/g, '');

    // create caching ajax url
    var caching = q + pageNr + totalArrayExcludeCaching + totalArrayIncludeCaching + arrayToggleState;

    // trigger ajax post
    $j(document).trigger('updateElements', { caching: caching, post_toggleState: arrayToggleState, post_languageBranch: languageBranch, post_paging: pageNr, post_area: $j('#search').attr('class'), post_q: q, post_include: totalArrayInclude, post_exclude: totalArrayExclude, pageDefinition: ['', '', '', "search"], output: ['#recipeResults', '.searchNav p.left', '#content .paging', '#searchFilters'], webservice: ['/Services/SearchService.asmx/RecipeResult', '/Services/SearchService.asmx/SearchNavigation', '/Services/SearchService.asmx/SearchPaging', '/Services/SearchService.asmx/SearchFilter'], error: ['<div class="text"><p class="errorBox">' + msgSearchFilters[3] + '</p></div>', '', '', ''], fade: ['false', 'false', 'false', 'false'] });
    $j('html, body').animate({ scrollTop: 180 }, 'medium');
}

// SEARCHPAGING
function searchPagingTrigger() {
    // set onlick event for paging buttons
    $j('#content .paging .pages a, #content .paging .pagingLeft a, #content .paging .pagingRight a').one('click', function() {
        var hash = this.href;
        hash = hash.replace(/^.*#/, '');
        $j(this).parents('.paging').addClass('clicked');
        jQuery.historyLoad(hash);
        $j(this).parents('.paging').removeClass('clicked');
        return false;
    });
}
// function for update searchpaging and searchresult
function updateSearchPaging(pageNr, totalArrayExcludePaging, totalArrayIncludePaging, q) {
    // create caching ajax url
    var caching = q + pageNr + totalArrayExcludePaging + totalArrayIncludePaging;

    $j(document).trigger('updateElements', { caching: caching, post_languageBranch: languageBranch, post_paging: pageNr, post_area: $j('#search').attr('class'), post_q: q, post_include: totalArrayIncludePaging, post_exclude: totalArrayExcludePaging, pageDefinition: ['', 'searchPaging'], output: ['#recipeResults', '#content .paging'], webservice: ['/Services/SearchService.asmx/RecipeResult', '/Services/SearchService.asmx/SearchPaging'], error: ['<div class="text"><p class="errorBox">' + msgSearchFilters[3] + '</p></div>', ''], fade: ['false', 'false'] });
    $j('html, body').animate({ scrollTop: 180 }, 'medium');
}

// function for update title on searchpage
function updateTitle(paging) {
    var title1 = $j('.searchNav p.left').text();
    if (paging == undefined) {
        var title2 = msgSearchFilters[4];
    }
    else {
        var title2 = msgSearchFilters[5] + paging + msgSearchFilters[4];
    }
    title1 = jQuery.trim(title1);
    //title = title1+title2;
    document.title = title1 + title2;
}

//// function for exclude navigators
//function excludeNavigators(elm){
//    //array for exclude filters
//    var arrayExclude = [];
//    $j('.searchNav .exclude').each(function(){
//        arrayExclude[arrayExclude.length] = $j(this).attr('rel');
//    });
//    if($j(elm).parents('ul:first').hasClass('exclude')){
//        var excludefilterTrigger = $j(elm).attr('rel');
//        var arrayItems = arrayExclude.length;
//        arrayExclude.splice(arrayItems,0,excludefilterTrigger);
//    }
//    var ArrayExclude = arrayExclude.join('\u00A3');   
//    return ArrayExclude;
//}
//// function for include navigators
//function includeNavigators(elm){
//    //array for include filters
//    var arrayInclude = [];
//    $j('.searchNav .include').each(function(){
//        arrayInclude[arrayInclude.length] = $j(this).attr('rel');
//    });
//     if($j(elm).parents('ul:first').hasClass('include')){
//        var includeFilterTrigger = $j(elm).attr('rel');
//        var arrayItems = arrayInclude.length;
//        arrayInclude.splice(arrayItems,0,includeFilterTrigger);
//    }
//    var ArrayInclude = arrayInclude.join('\u00A3');
//    return ArrayInclude;
//}

// get querystring parameters
function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};

    if (qs == null) {
        qs = location.search.substring(1, location.search.length);
        hash = false;
    }
    else {
        hash = true;
    }
    if (qs.length == 0) return;

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');

    if (hash == true) {
        var args = qs.split('$'); // parse out name/value pairs separated via &
    }
    else if (hash == false) {
        var args = qs.split('&'); // parse out name/value pairs separated via &

    }

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);

        var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;

        this.params[name] = value;
    }
}

Querystring.prototype.get = function(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
    var value = this.params[key];
    return (value != null);
}




/***************************************************
Products functions
***************************************************/
//Tooltip
function tooltip() {
    /* CONFIG */
    xOffset = 95;
    yOffset = 30;
    /* END CONFIG */

    $j(".productCarousel ul li a").hover(function(e) {

        $j(this).parent('li').addClass('hoverState');
        elmPos = $j(this).offset();
        posContainer = $j(".productCarousel .slide").offset();
        posConX = posContainer.left;
        posX = elmPos.left;
        posY = elmPos.top;
        this.t = this.title;
        title_array = this.t.split("/");
        $j(".productCarouselPopup .content").html('<h4><span>' + title_array[0] + '</span></h4><span>' + title_array[1] + '</span>');
        $j(".productCarouselPopup").css("bottom", (xOffset) + "px").css("left", (posX - posConX - yOffset) + "px").show();
        this.title = "";

    },
	function(e) {
	    $j(".productCarouselPopup").hide();
	    this.title = this.t;
	    $j(".productCarouselPopup h4 span").remove();
	    $j(".productCarouselPopup .content span").remove();
	    $j(this).parent('li').removeClass('hoverState');
	});
};

/* ------ Hide the paging container if empty ------*/
function hidePaging() {
    if ($j('.otherProducts .paging div').length < 1) {
        $j('.otherProducts .paging').hide();
    }
}
/***************************************************
My Pages
***************************************************/
// Call tip a friend (used from flash)

function callFlashTellAFriend(e) {
    var $popup = $j('.flashTellAFriend .popup');
    if (!$popup.length) { return; }
    $popup.toggle('fast');    
}

// START INLINE RECIPE

// Function for toggling inline recipe
$j("ul.recipeControl a.toggleRecipe, .myRecipes ul.recipeControl li div.hoverDiv a, .myRecipes ul.recipeControl li h2 a").live("click", function(e) {
    // Show if no active class, hide if active
    $j(this).addClass("toggleRecipe");
    e.preventDefault();
    // Add container if it doesn't exist
    if ($j(this).closest("li").children("div.recipeContainer").length == 0) {
        $j(this).closest("li").append('<div class="recipeContainer hide"></div>');
    }

    if ($j(this).closest("li").hasClass("activeRecipe")) {
        hideInlineRecipe($j(this));
    } else {
        showInlineRecipe($j(this));
    }

});
inlineprogress = false;
function showInlineRecipe($elm) {
    if (inlineprogress == false) {
        inlineprogress = true;

        // "Reset" attributes and classes
        $j("ul.recipeControl div.ingredients.active div.popup").hide(); // Hide open ingredient popups
        // UL must be relative if not
        if ($elm.closest("ul").css("position") != "relative") {
            $elm.closest("ul").css("position", "relative");
        }
        $j("ul.recipeControl div.recipeContainer").not($elm.closest("li").children("div.recipeContainer")).remove();
        $j("ul.recipeControl li.activeRecipe").removeClass("activeRecipe");
        $j("ul.recipeControl li").css("height", "auto");

        // Toggle visibility to retrieve height of hidden element
        $elm.closest("li").children("div.recipeContainer").css("visibility", "hidden");
        $elm.closest("li").children("div.recipeContainer").css("display", "block");

        // AJAX
        sendData = "{recipeId:" + $elm.attr("rel") + "}";

        $j.ajax({
            contentType: "application/json; charset=utf-8",
            // MOCKUP:
            //cache: false,
            //url: "/mockups/Creuna/pages/09 My cookbook/webservices/inlineRecipe.html",
            // PROD:
            type: "POST",
            url: "/Services/FoldersService.asmx/GetRecipeFolderView",
            dataType: "json",
            data: sendData,

            success: function(data) {
                // Start by scrolling to clicked recipe
                recipeLocation = parseInt($elm.closest("li").offset().top - 10);
                $j("html,body").animate({
                    scrollTop: recipeLocation
                }, 400, function() {
                    // Get height of elements and populate
                    $elm.closest("li").children("div.recipeContainer").html(data.d);
                    slideHeight = $elm.closest("li").children("div.recipeContainer").height();
                    origLiHeight = $elm.closest("li").height();
                    origUlHeight = $elm.closest("ul").height();
                    if (origUlHeight > 174) {
                        // Adjust positioning when recipe LI's with many lines
                        $elm.closest("li").find("div.recipeContainer").css("top", parseInt(origUlHeight + 5) + "px");
                    }
                    // Hide in order to prepare fadein
                    $elm.closest("li").find("div.recipeContainer div.content").hide();
                    slideHeight += 180;
                    //Animated fadein of recipe content
                    $elm.closest("li").animate({
                        height: slideHeight
                    }, 400, function() {
                        // Show elements
                        $elm.closest("li").children("div.recipeContainer").css("visibility", "visible");
                        $elm.closest("li").find("div.recipeContainer div.content").fadeIn();
                        $elm.closest("li").addClass("activeRecipe");
                        // Handle comments expanding: Enable comments toogler, make comments overflow / scrollbar
                        ShowHideComments();
                        commentsHeight = $elm.closest("li").find("div.recipeContainer ol.comments").height();
                        $elm.closest("li").find("div.recipeContainer ol.comments").css("height", commentsHeight);
                        // Bug fix
                        slideHeight = $elm.closest("li").children("div.recipeContainer").height();
                        if (parseInt($elm.closest("li").css("height")) < parseInt(slideHeight + 180)) {
                            //console.log("Gl height: " + parseInt($elm.closest("li").css("height")) + ", ny height: " + parseInt(slideHeight + 180));
                            $elm.closest("li").height(slideHeight + 180);
                        }
                        inlineprogress = false;
                        $j("html,body").stop();

                        //IE positioning fix
                        $elm.closest(".hoverDiv").css("position", "static").css("position", "relative");
                        
                    });
                });
                $elm.closest("li").stop();
            }
        });
    }
}
function hideInlineRecipe($elm) {
    if (inlineprogress == false) {
        // Animated fadeout
        $elm.closest("li").find("div.recipeContainer div.content").animate({ opacity: 0 }, 300, function() {
            // Hide/toggle elements
            $elm.closest("li").children("div.recipeContainer").hide();
            $elm.closest("li").children("div.recipeContainer").css("visibility", "hidden");
            //$elm.closest("li").parent("ul").css("position", "static");
            $elm.closest("li").removeClass("activeRecipe");
            // Slide up to original height
            $elm.closest("li").animate({
                height: origLiHeight
            }, 500, function() {
                // Scroll to top/recipe. (Eg when clicked close on bottom)
                recipeLocation = parseInt($elm.closest("li").offset().top - 20);
                $j("html,body").animate({
                    scrollTop: recipeLocation
                }, 500);
            });
        });
        $j("html,body").stop();
    }

}

$j("ul.recipeControl div.recipeContainer a.showHideComments").live("click", function() {
    if ($j(this).hasClass("exploder")) {
        // Scroll to next comments when expanding
        commentsHeight = $j("div.recipeContainer ol.comments").height();
    } else {
        // Scroll to top when collapsing
        commentsHeight = 0;
    }
    $j("div.recipeContainer ol.comments").animate({ scrollTop: commentsHeight }, 800);

});

// Print inline
/*
$j("div.recipeContainer a.print").live("click", function() {
    //$j(this).parents("li").find(".printFrame").remove();
    $j(this).parents("li").find("div.recipeContainer").append('<iframe class="printFrame" name="printFrame" width="1" height="1"></iframe>');
    $j(".printFrame").attr("src", $j(this).parents("li").find("div.actionLinks a:first").attr("href"));
    //window.printFrame.onload = printIFrame(window.printFrame);
    $j(".printFrame").load(function() {
        printIFrame(window.printFrame);
    });
});
function printIFrame(which) {
    which.focus();
    which.print();
}
*/


// END INLINE RECIPE

function restackMyPagesItems($li) {
    restack($li.parent());
    restack($li.parent().nextAll('ul.recipeControl, ul.weeklyMealPlaning'));
    function restack($ul) {
        $ul.each(function() {
            $j(this).append($j(this).next('ul.recipeControl, ul.weeklyMealPlaning').children()[0]);
            $j(this).children().attr('class', '').find('.myItemToolbar, .delMyItem').hide();
            $j(this).children(':first').attr('class', 'first-child');
        });
    }
    $li.next().addClass($li.attr('class'));
    $li.remove();
}
function promptForUsername(e, data) {
    var $popup = data.popup;
    $popup.find('fieldset, div.confirmation').hide();
    $popup.find('fieldset.promptForUserName').fadeIn('medium');
    $popup = $popup.find('fieldset.promptForUserName');
    $popup.find('span.submit input').unbind();
    $popup.find('span.submit input').click(function(e) {
        $j(this).preventDefault;
        SaveItemFlow.add('GET_USER_STATUS', { email: $popup.find('input.userName').val(), registerIfAvailable: data.registerIfAvailable, signupOnly: data.signupOnly, popup: data.popup });
        SaveItemFlow.next();
    });
}
function promptForPassword(e, data) {
    var $popup = data.popup;
    var $username = $popup.find('fieldset.promptForUserName input.userName');
    $popup.find('fieldset, div.confirmation').hide();
    $popup.find('fieldset.promptForPassword').fadeIn('medium');
    $popup = $popup.find('fieldset.promptForPassword');
    $popup.find('span.submit input').unbind();
    $popup.find('span.submit input').click(function(e) {
        $j(this).preventDefault;
        SaveItemFlow.add('AUTHENTICATE_USER', { email: $username.val(), password: $popup.find('input.passWord').val(), cookie: ($popup.find('a.checked').length > 0), popup: data.popup });
        SaveItemFlow.next();
    });
    $popup.find('a.forgotPassWord').click(function(e) {
        $j(this).preventDefault;
        SaveItemFlow.add('SEND_PASSWORD_REMINDER', { email: $username.val(), link: $j(this), msg: $popup.find('p.passWordSent'), popup: data.popup });
        SaveItemFlow.next();
    });
}
function showSaveItemPopup(e, data) {
    $j('div.saveItemPopup').not(data.popup).hide('fast');
    data.popup.show('fast');
    //if(data.popup.is(':hidden')){
    //var posX = (data.link.offsetLeft + $j(data.link).width()/2) - $popup.width()/2;
    //var posY = $j(data.link).height() + 15;
    //data.popup.css({ left: posX, bottom: posY});
    //data.popup.show('fast');
    //}
    SaveItemFlow.next();
}
function hideSaveItemPopup(e, data) {
    data.popup.hide();
    SaveItemFlow.next();
}
function showMessage(e, data) {
    $msg = data.msg;
    if ($msg.is(':hidden')) {
        $msg.fadeIn('medium');
    } else {
        $msg.fadeOut('medium').fadeIn('medium').fadeOut('medium').fadeIn('medium');
    }
}
function showSubscriptionMessage(e, data) {
    var $msg = data.msg;
    var $popup = data.popup;
    $popup.find('.content fieldset').hide();
    $popup.find('.content .innerContent').fadeOut('slow').html('<p>' + $msg + '</p>').fadeIn('slow');
    //show popup on hover the subscriptions
    showPopupOnHoverMouse('.subscriptionPortlet .checkboxList li a', 58, 85);
    SaveItemFlow.next();
}
function clearSaveItemPopup(e, data) {
    var $popup = data.popup; //$j('div.saveItemPopup');
    $popup.find('fieldset, div.confirmation, span.error, p.passWordSent').hide();
    $popup.find('a.forgotPassWord').show();
    $popup.find('input.passWord').val('').removeClass('passWordBlank');
    SaveItemFlow.next();
}
function clearContent(e, data) {
    data.popup.find('.content .innerContent').hide();
    SaveItemFlow.next();
}
function updateAuthenticity(e, data) {
    if (data.authenticity) {
        if (data.reload) {
            location.reload(true);
        } else {
            $j('#pageContent .toolBar a.favorite').removeClass('authenticateUserAndSaveItem').addClass('saveItem');
            $j('#pageRelated .myPagesLogin .topIntroText, #pageRelated .myPagesLogin .loginWrapper').addClass('isAuthenticated');
        }

    }
    SaveItemFlow.next();
}

// function for subscribe user for subscription portlet
function subscribeUser(e, data) {
    if (data.multiSubscription == true) {
        var arrayMultiSub = [];
        if ($j(data.popup).find('.checkboxList li a.checked').length > 0) {
            $j(data.popup).find('.checkboxList li a.checked').each(function(index) {
                var multiSubString = $j(this).attr('id');
                var multiSubArray = multiSubString.split(":");
                arrayMultiSub[arrayMultiSub.length] = multiSubArray[0];
            });
        }
        else {
            $j(data.popup).find('.error').show();
            return false;
        }


        var arrayMultiSub = arrayMultiSub.join();
        var serviceUrl = "/Services/UserActionService.asmx/SubscribeNewsletters";
        var postData =
		{
		    subscriptionID: arrayMultiSub,
		    languageBranch: languageBranch
		}
    }
    else {
        var serviceUrl = "/Services/AuthenticationService.asmx/SubscribeUser";
        var postData =
		{
		    userName: data.email,
		    subscriptionID: data.subscriptionID,
		    languageBranch: languageBranch
		}
    }
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
				function(result, userContext, methodName) {
				    if (result == null) {
				        SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
				        SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
				        SaveItemFlow.next();
				    }
				    else {
				        result = eval('(' + $j('string', result).text() + ')');

				        switch (result.Code) {
				            case -1: //no such user
				                SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('fieldset.promptForUserName span.error'), popup: data.popup });
				                SaveItemFlow.next();
				                break;
				            case 0: //user without password is logged in and subscribed.
				                SaveItemFlow.add('GET_SUBSCRIPTION_STATUS', { email: data.email });

				                SaveItemFlow.add('SHOW_SUBSCRIPTION_MESSAGE', { msg: result.Text, popup: data.popup });
				                SaveItemFlow.next();
				                break;
				            case 1: //user is password protected

				                SaveItemFlow.add('PROMPT_FOR_PASSWORD', { popup: data.popup });
				                defaultButton(data.popup.find('input.passWord'), data.popup.find('.promptForPassword span.submit input'));
				                data.popup.find('input.passWord').focus();
				                SaveItemFlow.add('CLEAR_CONTENT', { popup: data.popup });
				                SaveItemFlow.next();
				                break;
				        }
				    }
				},
        error:
				function(XMLHttpRequest, errorHeading, errorText) {
				    SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
				    SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
				    SaveItemFlow.next();
				}
    });
}

function getUserStatus(e, data) {
    var serviceUrl = "/Services/AuthenticationService.asmx/GetUserStatus";
    var postData = { userName: data.email }
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
				function(result, userContext, methodName) {
				    if (result == null) {
				        SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
				        SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
				        SaveItemFlow.next();
				    }
				    else {
				        result = eval('(' + $j('string', result).text() + ')');

				        if (data.signupOnly) {
				            if (result.Code < 3) {
				                result.Code = -1;
				            }
				        }

				        switch (result.Code) {
				            case -1: //no such user
				                SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('fieldset.promptForUserName span.error'), popup: data.popup });
				                SaveItemFlow.next();
				                break;
				            case 0: //user without password
				                SaveItemFlow.add('AUTHENTICATE_USER', { email: data.email, password: '', cookie: ($j(data.popup).find('fieldset.promptForUserName a.checked').length > 0), popup: data.popup });
				                SaveItemFlow.next();
				                break;
				            case 1: //user is password protected
				                SaveItemFlow.add('PROMPT_FOR_PASSWORD', { popup: data.popup });
				                SaveItemFlow.next();
				                break;
				            case 2: //user is not yet activated
				                SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.notActivated'), popup: data.popup });
				                SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
				                SaveItemFlow.next();
				                break;
				            case 3: //usename valid and available
				                if (data.registerIfAvailable) {
				                    SaveItemFlow.add('REGISTER_USER', { email: data.email, popup: data.popup });
				                    SaveItemFlow.next();
				                } else {
				                    SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('fieldset.promptForUserName span.error'), popup: data.popup });
				                    SaveItemFlow.next();
				                }
				                break;
				        }
				    }
				},
        error:
				function(XMLHttpRequest, errorHeading, errorText) {
				    SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
				    SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
				    SaveItemFlow.next();
				}
    });

}
function authenticateUser(e, data) {
    var serviceUrl = "/Services/AuthenticationService.asmx/TryLogin";
    var postData =
		{
		    userName: data.email,
		    password: data.password,
		    saveCookie: data.cookie

		}
    Creuna.Tracking.Instance.SetPending("LOGIN", function() { TrackLogin(data.email); });
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,

        success:
				function(result, userContext, methodName) {
				    if (result == null) {
				        SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
				        SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
				        SaveItemFlow.next();
				    } else {
				        var isAuthenticated = $j('boolean', result).text();
				        switch (isAuthenticated) {
				            case 'false': //not authenticated
				                SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('fieldset.promptForPassword span.error'), popup: data.popup });
				                SaveItemFlow.next();
				                break;
				            case 'true': //authenticated
				                SaveItemFlow.add('GET_SUBSCRIPTION_STATUS', { email: data.email });
				                Creuna.Tracking.Instance.FirePending("LOGIN");
				                SaveItemFlow.next();
				                break;
				        }
				    }
				},
        error:
				function(XMLHttpRequest, errorHeading, errorText) {
				    SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
				    SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
				    SaveItemFlow.next();
				}
    });
}

function getSubscriptionStatus(e, data) {

    $j('.subscriptionPortlet').each(function(index) {
        var elm = $j(this);
        var subID = $j(this).find('.content').attr('id');
        var serviceUrl = "/Services/UserActionService.asmx/GetSubscriptionStatus";
        var postData = { userName: data.email, subscriptionID: subID, languageBranch: languageBranch };
        var activeSubID = $j('#pageRelated .subscriptionPortlet .active').attr('id');
        if (activeSubID != subID) {
            $j.ajax({
                type: "POST",
                data: postData,
                url: serviceUrl,
                success:

			    function(result, userContext, methodName) {
			        if (result == null) {
			            SaveItemFlow.next();
			        }
			        else {
			            result = eval('(' + $j('string', result).text() + ')');
			            switch (result.Code) {

			                case 0: //not subscribed
			                    elm.find('.userName').removeClass('clearOnFocus').addClass('focus').val(data.email);
			                    SaveItemFlow.next();
			                    break;
			                case 1: //subscribed
			                    SaveItemFlow.add('SHOW_SUBSCRIPTION_MESSAGE', { msg: result.Text, popup: elm });
			                    SaveItemFlow.next();
			                    break;
			            }
			        }
			    },
                error:
			    function(XMLHttpRequest, errorHeading, errorText) {
			        SaveItemFlow.next();
			    }
            });
        }
    });
    SaveItemFlow.next();

}

function fillFolderNames() {

    var serviceUrl = "/Services/FoldersService.asmx/GetCurrentUserFoldersNames";
    $j.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result.d != null) {
			        var items = $j('.moveRecipe').find('.items');
			        var htmlForEnter = "<ul>";

			        for (var i = 0; i < result.d.length; i++) {
			            htmlForEnter += '<li><a href="javascript:void(0);">' + result.d[i].FolderName + '</a><input type="hidden" value="' + result.d[i].FolderID + '"/></li>';
			        }

			        htmlForEnter += '<li><a href="javascript:void(0);">' + $j('#otherText').val() + '</a><input type="hidden" value="-1"/></li>';
			        htmlForEnter += "</ul>";
			        items.html(htmlForEnter);
			        items.hide();
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {

			}
    });
}

function saveMyPagesItem(e, data) {
    var serviceUrl = "/Services/UserActionService.asmx/SaveItem";
    var postData = { itemType: data.typeID, id: data.itemID };
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
			        SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
			        SaveItemFlow.next();
			    } else {
			        data.link.attr('class', 'favoriteSaved').unbind().parent().parent().unbind().attr('class', '');
			        $j("#pageRelated .subscriptionPortlet").each(function() {
			            $j(this).children("div:first").addClass("content");
			        });
			        if (data.itemSavedText != '') {
			            data.link.html(data.itemSavedText);
			        }
			        /* Track that the item was saved */
			        Creuna.Tracking.Instance.FirePending('SAVE');
			        SaveItemFlow.next();


			        var isSavedId = parseInt($j('int', result).text()); //(-1) - false, (0) - true, else id number
			        if (isSavedId > 0) {
			            $j('.recipeId').val(isSavedId);
			            fillFolderNames();
			            //saveMyRecipeItemToFolder(e, data);

			        }
			        
			        /*switch(isSaved) {
			        case 'false': //not saved
							
						break;
			        case 'true': //saved
							
						break;
			        }*/

			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
			    SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
			    SaveItemFlow.next();
			}
    });

}



function deleteMyPagesItem(e, data) {
    var serviceUrl = "/Services/UserActionService.asmx/RemoveItem";
    var postData = { itemType: data.typeID, id: data.itemID };
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        var $c = $j(e.target).closest('.content');
			        $c.children('p:first').hide();
			        $c.children('p.delError').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			    } else {
			        var isDeleted = $j('boolean', result).text();
			        switch (isDeleted) {
			            case 'false': //not deleted
			                var $c = $j(e.target).closest('.content');
			                $c.children('p:first').hide();
			                $c.children('p.delError').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			                break;
			            case 'true': //deleted
			                var $li = $j(e.target).closest('li');
			                $li.fadeOut('slow', function() {
			                    restackMyPagesItems($li);
			                });

			                break;
			        }
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    var $c = $j(e.target).closest('.content');
			    $c.children('p:first').hide();
			    $c.children('p.delError').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			}
    });

}

function deleteRecipeItem(e, data) {
    var serviceUrl = "/Services/FoldersService.asmx/DeleteRecipe";
    $j.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: $j.toJSON(data),
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result.d == null) {
			        var $c = $j(e.target).closest('.content');
			        $c.children('p:first').hide();
			        $c.children('p.delError').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			    } else {
			        $j(e.target).closest('li').fadeOut('slow');
			        renderFolder(result.d);
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    var $c = $j(e.target).closest('.content');
			    $c.children('p:first').hide();
			    $c.children('p.delError').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			}
    });

}


$j(".folderMenu a.popuplink").livequery("click", function() {
    if ($j(this).parent(".folderMenu").css("position") != "relative") {
        $j(this).parent(".folderMenu").css("position", "relative");
    } else {
        if ($j(this).next('div.popup').is(':visible')) {
            $j(this).parent(".folderMenu").css("position", "static");
        }
    }
});
$j(".folderMenu .popup a.close").livequery("click", function() {
    $j(this).parent().parent().parent(".folderMenu").css("position", "static");
});



var FolderMenuControl = null;

function addMyFolder(html) {
    if (FolderMenuControl == null) {
        var serviceUrl2 = "/Services/FoldersService.asmx/GetMenuControl";
        var postedData = "{pageId : "+ $j('#hiddenNumber').val() +"}";
        $j.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: postedData,
            url: serviceUrl2,
            success: function(result2, userContext2, methodName2) {
                if (result2.d != null) {
                    FolderMenuControl = result2.d;
                    addMyFolderHtml(html);
                }
            },
            error:
                    function() {
                    }
        });
    }
    else {
        addMyFolderHtml(html);
    }
}

function addMyFolderHtml(folderObject) {
    $j(".myRecipes > .myPagesIntro").remove();
    if ($j('.addFolder').length == 0) {
        var innerhtml = $j("ul.myFolders .folderMenu").html();
        $j('<div class="addFolder">' + innerhtml + '</div>').insertAfter('.ownRecipeBoxWrapper');
        $j('.addFolder .popup').css("opacity", "").hide();
        defaultButton($j(".newFolder input.folderName"), $j(".newFolder .submit input"));
        $j("ul.noFolder").remove();
    }
    var folderstr = 'folder=' + folderObject.ID;
    var currentFolderMenuControl = FolderMenuControl.replace(/folder=0/g, folderstr);
    var folderMenu = $j('<div>' + currentFolderMenuControl + '</div>');
    $j('.hdnFolderId', folderMenu).val(folderObject.ID);
    $j('.hdnFolderName', folderMenu).val(folderObject.Name);

    if (($j("ul.myFolders:not(.noFolder)")).length == 0) {
        $j("<ul class='myFolders'></ul>").insertAfter("#emptyFolder");
        $j(".myRecipes > .noCalibri").remove();
        
        //$j('<span class="noCalibri"><h2 class="myFolders">' + $j('#otherRecipesText').val() + '</h2></span>').insertBefore('.otherRecipes');
    }

    if (($j('.myRecipes > .otherRecipes > .recipeControl')).length == 0) {
        $j(".myRecipes > .otherRecipes").remove();
    }
    
    $j("ul.myFolders:not(.noFolder)").prepend('<li><a class="togglelink">' + folderObject.Name + '</a>' + folderMenu.html() + '<div class="moreRecipes clearfix hide">&nbsp;</div></li>');

    $j('div.renameFolder').each(function() {
        var current = $j(this);
        defaultButton($j("input.folderName", current), $j(".submit input", current));
    });

    if (window.addthis) {
        window.addthis = null;
    }
    $j.getScript("http://s7.addthis.com/js/250/addthis_widget.js#username=arla");
    $j("ul.myFolders .noFolders").remove();

}

function saveMyRecipeItemToFolder(e, data) {
    var serviceUrl = "/Services/FoldersService.asmx/SaveRecipeToFolder";
    $j.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: $j.toJSON(data),
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result.d != null) {
			        $j('.recipeOptions > .saveItemPopup').fadeOut('fast');

			    }

			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {

			}
    });
}

function moveMyRecipeItem(e, postData) {
    var serviceUrl = "/Services/FoldersService.asmx/MoveRecipeToFolder";
    $j.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: $j.toJSON(postData),
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result.d != null) {
			        var $li = $j(e.target).closest('li');
			        $li.fadeOut('slow');
			        if (result.d.IsNew) {
			            addMyFolder(result.d.NewFolder.Folder);
			        }

			        renderFolder(result.d.NewFolder);
			        renderFolder(result.d.OldFolder);
			        var curElement = $j('.hdnFolderId[value="' + result.d.NewFolder.Folder.ID + '"]').parent().parent().find('.togglelink');
			        curElement.siblings('.moreRecipes').slideDown('fast');
			        var $tgt = $j(e.target);
			        $tgt.closest('li').removeClass('toolActive');
			        $tgt.closest('.moveMyItem').slideUp('fast', function() {
			            $tgt.closest('.myItemToolbar').hide('fast');
			        });
			    }
			    else {
			        var $c = $j(e.target).closest('.content');
			        $c.children('p:first').hide();
			        $c.children('p.moveError').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    var $c = $j(e.target).closest('.content');
			    $c.children('p:first').hide();
			    $c.children('p.moveError').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			}
    });

}

function getUserCreatedRecipe(e, data) {
    var serviceUrl = "/Services/UserActionService.asmx/GetUserCreatedRecipe";
    var postData = { recipeId: data.itemID };

    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        cache: false,
        success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        $j('.ownRecipeBoxWrapper .ownRecipeBox').addClass('getUserCreatedRecipeLoaderError').html($j('<div class="getUserCreatedRecipeLoaderErrorMessage">' + res.Text + '</div>'));
			    } else {
			        var res = eval("(" + $j('string', result).text() + ")");

			        switch (res.Code) {
			            case -1: //Recipe can not be edited
			                $j('.ownRecipeBoxWrapper .ownRecipeBox').addClass('getUserCreatedRecipeLoaderError').html($j('<div class="getUserCreatedRecipeLoaderErrorMessage">' + res.Text + '</div>'));
			                break;
			            case 0: //Recipe can be edited
			                $j('.ownRecipeBoxWrapper .ownRecipeBox').replaceWith($j(res.Text));
			                break;
			        }
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    $j('.ownRecipeBoxWrapper .ownRecipeBox').addClass('getUserCreatedRecipeLoaderError').html($j('<div class="getUserCreatedRecipeLoaderErrorMessage">' + XMLHttpRequest + ', ' + errorHeading + ', ' + errorText + '</div>'));
			}
    });

}


function renderFolder(obj) {
    var panel;
    if (obj.Folder == null) {
        if (($j('.otherRecipes')).length == 0) {
            $j("<div class='otherRecipes'></div>").insertAfter("#otherRecipesText");
            $j('<span class="noCalibri"><h2 class="myFolders">' + $j('#otherRecipesText').val() + '</h2></span>').insertBefore('.otherRecipes');
        }
        panel = $j('.otherRecipes');
        
        var readyHtml = obj.ControlHtml;
        if (obj.PagerHtml != null && $j.trim(obj.PagerHtml) != '') {
            readyHtml += "<div class='paging'>" + obj.PagerHtml + "</div>";
        }
        if ($j.trim(readyHtml.replace("\n", "").replace("\r", "")) == '') {
            panel.remove();
            $j(".myRecipes > .noCalibri").remove();
            if (($j('.myFolders:not(.noFolder)')).length == 0) {
                $j("<div class='otherRecipes'>" + $j('#emptyFolder').val() + "</div>").insertAfter("#emptyFolder");
                $j('<span class="noCalibri"><h2 class="myFolders">' + $j('#otherRecipesText').val() + '</h2></span>').insertBefore('.otherRecipes');
            }
        }
        
        
        panel.html(readyHtml);
        $j("img[src$='.png']", panel).ifixpng();
    }

    else {
       
        panel = $j('.hdnFolderId[value="' + obj.Folder.ID + '"]').closest('.myFolders li');
        if (panel.length > 0) {
            $j('.togglelink', panel).addClass('selected');
            var readyHtml = obj.ControlHtml;
            if (obj.PagerHtml != null && $j.trim(obj.PagerHtml) != '') {
                readyHtml += "<div class='paging'>" + obj.PagerHtml + "</div>";
            }
            $j('.moreRecipes', panel).addClass('filled').html(readyHtml);
        }
        else {
            panel = $j('div.userFolder');
            var readyHtml = obj.ControlHtml;
            if (obj.PagerHtml != null && $j.trim(obj.PagerHtml) != '') {
                readyHtml += "<div class='paging'>" + obj.PagerHtml + "</div>";
            }
            panel.html(readyHtml);
        }
    }
    panel.removeClass('fixedPagingHeight');
    $j('.recipeControl > li', panel).hoverIntent(
	                                function(e) {
	                                    if (!$j(this).hasClass('toolActive')) {
	                                        $j(this).find('.myItemToolbar').show('fast');
	                                    }
	                                },
	                                function(e) {
	                                    if (!$j(this).hasClass('toolActive')) {
	                                        $j(this).find('.myItemToolbar').hide('fast');
	                                    }
	                                });
}

function saveUserCreatedRecipe(e, data) {
    var serviceUrl = "/Services/UserActionService.asmx/AddUserCreatedRecipe";
    var postData = {
        id: data.$recipeForm.find('.left ul li:first input#recipeId').val(),
        folderId: data.$recipeForm.find('.left ul li:first input#folderId').val(),
        title: data.$recipeForm.find('.left ul li:first input#title').val(),
        categories: function() {
            var $cats = data.$recipeForm.find('.left #dishSelector .items li.checked a');
            var catsArr = [];
            $cats.each(function(idx) {
                catsArr[idx] = $j(this).attr('rel');
            });
            return catsArr.join('~#~');
        } (),

        portions: data.$recipeForm.find('.left li.portions input#dish').val(),
        prepTime: data.$recipeForm.find('.left li.preptime input#preptime').val(),

        ingredients: function() {
            var $ings = data.$recipeForm.find('.left ul.ingredientList li > p');
            var ingsArr = [];
            $ings.each(function(idx) {
                ingsArr[idx] = $j(this).find('.ingAmount').text() + '~;~' + $j(this).find('.ingUnit').text() + '~;~' + $j(this).find('.ingIng').text();
            });
            return ingsArr.join('~#~');
        } (),

        description: data.$recipeForm.find('.right #howto').val(),
        pageId: $j('#hiddenNumber').val(),
        pageSize: $j('#hdnPageSize').val(),
        rowSize: $j('#hdnRowSize').val()
    };

    //validation
    var validRecipe = true;

    if (jQuery.trim(postData.title).length <= 0) {
        data.$recipeForm.find('.titleOfRecipeError').show();
        validRecipe = false;
    } else {
        data.$recipeForm.find('.titleOfRecipeError').hide();
    }
    if (postData.categories.length <= 0) {
        data.$recipeForm.find('.typeOfRecipeError').show();
        validRecipe = false;
    } else {
        data.$recipeForm.find('.typeOfRecipeError').hide();
    }
    if (postData.ingredients.length <= 0) {
        data.$recipeForm.find('.ingrediensError').show();
        validRecipe = false;
    } else {
        data.$recipeForm.find('.ingrediensError').hide();
    }
    if (jQuery.trim(postData.description).length <= 0) {
        data.$recipeForm.find('.cookingstepsError').show();
        validRecipe = false;
    } else {
        data.$recipeForm.find('.cookingstepsError').hide();
    }

    if (validRecipe) {
        data.$recipeForm.find('.error').hide();
        $j(e.target).parent().width($j(e.target).width()).addClass('savingUserCreatedRecipeAnim');

        $j.ajax({
            type: "POST",
            data: $j.toJSON(postData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: serviceUrl,
            cache: false,
            success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        $j(e.target).parent().removeClass('savingUserCreatedRecipeAnim');
			    } else {
			        var res = result.d;
			        switch (res.Message.Code) {
			            case -1: //Recipe can not be saved
			                $j(e.target).parent().width('auto').removeClass('savingUserCreatedRecipeAnim');
			                $j(e.target).closest('.buttons').after($j('<div class="savingUserCreatedRecipeError">' + res.Message.Text + '</div>'));
			                break;
			            case 0: //Recipe can be saved
			                $j(e.target).parent().width('auto').removeClass('savingUserCreatedRecipeAnim');
			                $j(e.target).closest('.ownRecipeBoxWrapper').addClass('ownRecipeSuccesMode').find('.ownRecipeBox').addClass('savingUserCreatedRecipeSucces').html($j('<div class="savingUserCreatedRecipeSuccesMessage">' + res.Message.Text + '</div>'));

			                //track creation of new recipe
			                if (postData.id == "" || postData.id == 0) {
			                    TrackLinkSimple(this, '', ownRecipeTrackingTextCreationDone, 'event16');
			                }
			                renderFolder(res.UpdatedInfo);
			                break;
			        }

			    }
			},
            error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    $j(e.target).closest('.buttons').after($j('<div class="savingUserCreatedRecipeError">' + XMLHttpRequest + ', ' + errorHeading + ', ' + errorText + '</div>'));
			}
        });

    }

}

function sendPasswordReminder(e, data) {
    var serviceUrl = "/Services/AuthenticationService.asmx/SendPasswordReminder";
    var postData = { email: data.email };
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        /* Show error */
			    } else {
			        var isSent = $j('boolean', result).text();
			        switch (isSent) {
			            case 'false': //not sent

			                break;
			            case 'true': //sent
			                data.link.hide();
			                data.msg.fadeIn('medium');
			                break;
			        }
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			}
    });
}
function registerUser(e, data) {
    var serviceUrl = "/Services/AuthenticationService.asmx/RegisterUser";
    var postData =
	{
	    userName: data.email
	}
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
			        SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
			        SaveItemFlow.next();
			    } else {
			        var isCreated = $j('boolean', result).text();
			        switch (isCreated) {
			            case 'false': //not created
			                SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
			                SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
			                SaveItemFlow.next();
			                break;
			            case 'true': //created
			                $j(data.popup).find('div.recipeIsSaved p.addInfo').show();
			                /* Track that a new user has been created */
			                TrackNewUser();
			                SaveItemFlow.next();
			                break;
			        }
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    SaveItemFlow.add('SHOW_MESSAGE', { msg: $j(data.popup).find('div.serverError'), popup: data.popup });
			    SaveItemFlow.add('CLEAR_SAVE_ITEM_POPUP', { popup: data.popup });
			    SaveItemFlow.next();
			}
    });
}
function logOutUser(e, data) {
    var serviceUrl = "/Services/AuthenticationService.asmx/Logout";
    var postData = {};
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        /* Show error */
			    } else {
			        location.reload(true);
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			}
    });
}

function updateSubscriptionSettings(e, data) {
    var serviceUrl = "/Services/UserActionService.asmx/SetNewsletterSubscription";
    var postData = {
        newsletterId: data.id,
        subscribe: data.subscribe,
        sendAsHtml: data.asHtml
    };
    $j.ajax({
        type: "POST",
        data: postData,
        url: serviceUrl,
        success:
			function(result, userContext, methodName) {
			    if (result == null) {
			        $j(e.target).text('Server error!');
			    } else {
			        var isUpdated = $j('boolean', result).text();
			        switch (isUpdated) {
			            case 'false': //not updated
			                $j(e.target).text('Server error!');

			                break;
			            case 'true': //updated
			                if ($j(e.target).is('a.checkbox')) {
			                    $j(e.target).toggleClass('checked');
			                    $j(e.target).fadeOut('medium').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			                } else {
			                    var $dt = $j(e.target).closest('dt');
			                    var $but = $dt.find('span');
			                    var submitText = $dt.next('dd').find('input.subscribeText').val();

			                    if ($but.hasClass('submit')) {
			                        $but.attr('class', 'cancel');
			                        submitText = $dt.next('dd').find('input.unsubscribeText').val();
			                    } else {
			                        $but.attr('class', 'submit');
			                    }

			                    $j(e.target).val(submitText);
			                    $dt.find('strong').toggleClass('active');
			                    $dt.find('strong').fadeOut('medium').fadeIn('medium').fadeOut('medium').fadeIn('medium');
			                }

			                break;
			        }
			    }
			},
        error:
			function(XMLHttpRequest, errorHeading, errorText) {
			    $j(e.target).text('Server error!');
			}
    });
}

/***************************************************
Comment functions
***************************************************/
// Comment expand/collapsed comment form
function ToggleCommentForm() {
    if ($j('#commentForm').is(':visible')) {
        $j('#commentForm').hide();
        $j('#commentForm .submit').hide(); //ie hack to prevent margin on input buttons
        $j('#commentForm .cancel').hide();

    } else {
        $j('#commentForm .submit').show();
        $j('#commentForm .cancel').show();
        $j('#commentForm').show();
        $j('#commentName').focus();
        $j('#commentBox .confirm').remove();
    }
}

//Show-hide user comment
function ShowHideComments() {
    defaultToShow = 2;
    commentBuffer = 1;
    nrComments = (totalComments - defaultToShow);
    uc = $j('ol.comments li');
    if (uc >= 1) { $j('ol.comments li.noComments').remove(); }
    if (nrComments >= (defaultToShow + commentBuffer)) {
        uc.livequery(function() { uc.not(':gt(' + (defaultToShow - 1) + ')').show(); });
        $j('a.showHideComments').show();
        $j('.showHideComments .text1').text(msgComments[1]);
        $j('.showHideComments .text2').text(msgComments[2]);
        $j('.numberOfComments').text(nrComments);
    }
    else {
        uc.show();
    }
}

//toggle comments
function ToggleComments() {
    if ($j('a.showHideComments').text() == msgComments[0]) {
        uc.livequery(function() { uc.not(':lt(' + defaultToShow + ')').hide() });
    }
    else {
        uc.show();
    }
    $j('a.showHideComments').toggleClass('exploder');
    textToggle($j('a.showHideComments'), msgComments[0], msgComments[1] + nrComments + msgComments[2]);
}

//Create a new comment
function CreateComment() {
    if ($j('.createComment').hasClass('clicked')) { }
    else {
        var valSum = null;
        var valid = ValReq('#commentName', errorMsgComments[0], valSum) +
					ValReqMultiLine('#commentBody', errorMsgComments[1], valSum) +
					ValReq('#commentCaptcha', errorMsgComments[2], valSum);

        if (valid == 3) {
            var serviceUrl = "/Services/UserActionService.asmx/CreateComment";
            var postData =
		{
		    captcha: $j('#commentCaptcha').val(),
		    captchaHash: currentCaptchaHash,
		    itemId: currentId,
		    author: $j('#commentName').val(),
		    comment: $j('#commentBody').val()
		}
            var submitDefaultValue = $j('.createComment').attr('value');
            $j('.createComment').addClass('clicked').attr('value', msgComments[4]);

            $j.ajax({
                type: "POST",
                data: postData,
                url: serviceUrl,
                success:
			   function(result, userContext, methodName) {
			       if (result == null) {
			           /* Show error */
			       }
			       else {
			           var c = eval('(' + $j(result).find('string').text() + ')');

			           if (c.ErrorHeading) {
			               if ($j('.errorBox').is(':visible')) { }
			               else {/* Show error */
			                   $j("<p class='errorBox'></p>").insertAfter(".captcha");
			                   $j('.errorBox').html(c.ErrorHeading + '<br/>' + c.ErrorText);
			                   $j('#commentCaptcha').focus();
			                   //remove errorBox on keypress in captcha field
			                   $j('#commentCaptcha').live('keypress', function(event) {
			                       $j('.errorBox').remove();
			                   });
			                   $j('.createComment').removeClass('clicked').attr('value', submitDefaultValue);
			               }
			           }
			           else {
			               $j('#commentCaptcha').val('');
			               currentCaptchaHash = c.NewCaptchaHash;
			               $j('#captchaPrompt').html(c.NewCaptchaPrompt + ':');
			               $j('#commentName').val('');
			               $j('#commentBody').val('');

			               /* Updating UI */
			               var newComment = "<li><span><strong>" + c.Author + "</strong> - " + c.CreatedDateTime + "</span><p>" + c.Comment + "</p></li>";
			               $j(newComment).prependTo('ol.comments');
			               uc.not(':lt(' + (defaultToShow - 1) + ')').hide();
			               totalComments = totalComments + 1;
			               $j('.comments .noOfVotes').text(totalComments);
			               ShowHideComments(this);
			               if ($j('a.showHideComments').text() == msgComments[0]) {
			                   ToggleComments();
			               }
			               $j('#commentForm').fadeOut('slow');
			               $j('ol.comments li.noComments').remove();
			               $j('<p class="confirm" style="display: none"><br/>' + msgComments[3] + '<br/><br/></p>').insertAfter('#commentBox .innerBot p');
			               $j('#commentBox .confirm').fadeIn('slow');
			               $j('.createComment').removeClass('clicked').attr('value', submitDefaultValue);
			           }
			       }
			   },
                error:
			   function(XMLHttpRequest, errorHeading, errorText) {
			       $j("<p class='errorBox'><strong>" + errorMsgComments[4] + "</strong><br/>" + errorMsgComments[5] + "</p>").insertAfter(".captcha");
			       $j('.createComment').live('click', function(event) {
			           $j('.errorBox').remove();
			       });
			       $j('.createComment').removeClass('clicked').attr('value', submitDefaultValue);
			   }
            });
        }
    } 
}

/***************************************************
Rate recipe functions
***************************************************/
/* Set text after number of rating */
function numberOfRatingText(currentRatings) {
    $j('.voting .numberOfVotesTxt').text(textAfterRating[0]);
}

/* function for rating recipe */
function RateRecipe(tipsVal) {
    if ($j.cookie('RecipeRating') != currentId) {
        var serviceUrl = "/Services/UserActionService.asmx/RateRecipe";
        var postData =
		{
		    recipeId: currentId,
		    value: tipsVal
		}
        $j.ajax({
            type: "POST",
            data: postData,
            url: serviceUrl,
            success:
			   function(result, userContext, methodName) {
			       if (result == null) {
			           /* Show error */
			       }
			       else {
			           var c = eval('(' + $j(result).find('string').text() + ')');


			           if (c.ErrorHeading) {
			               alert(msgRating[2]);
			           }
			           else {
			               /* Updating UI */
			               $j('.ratingTips p').text(msgRating[0]);
			               setTimeout("$j('.ratingTips').fadeOut('slow')", 1500);
			               numberOfRatingText(c.NumberOfRatings);
			               $j('.numberOfVotes').text(c.NumberOfRatings);
			               $j('.voting ul.rating').removeAttr('class').attr('class', 'rating rating' + c.AverageRating + '');
			               $j('.noOfVotesBg').fadeIn('200').fadeOut('100');
			               $j.cookie('RecipeRating', currentId);
			           }
			       }
			   },
            error:
			   function(XMLHttpRequest, errorHeading, errorText) {
			       $j('.ratingTips p').text(msgRating[2]);
			       $j('ratingTips').show();
			   }
        });
    }
    else {
        $j('.ratingTips p').text(msgRating[1]);
    }
}

/***************************************************
Tell A Friend functions
***************************************************/
/* reset Tell A Friend fields */
function resetTellAFriend() {
    $j(".tellAFriend .errorMessage").hide();
    $j(".tellAFriend #uiToEmail").val(msgTellAFriend[2]).removeClass('focus');
    $j(".tellAFriend #uiFromName").val(msgTellAFriend[3]).removeClass('focus');
    $j(".tellAFriend #uiFromEmail").val(msgTellAFriend[4]).removeClass('focus');
    $j(".tellAFriend #uiText").val(msgTellAFriend[5]).removeClass('focus');
    $j(".tellAFriend #mailCopy").attr('checked', '')
    $j('.tellAFriend .confirm').hide();
    $j('.tellAFriend fieldset').show();
}

// Close TellAFriend
function closeTellAFriend() {
    $j('.tellAFriend').fadeOut('fast	');
    setTimeout("$j('.tellAFriend fieldset').show()", 1000);
    $j('.tellAFriend .confirm').hide();
}

/* function for Tell A Friend*/
function TellAFriend() {
    return SendTellAFriend(false);
}

function TellAFriendOfUserRecipe() {
    return SendTellAFriend(true);
}

function TellAFriendOfCampaign() {
    return SendTellAFriend("campaign");
}

function SendTellAFriend(sendUserRecipe) {
    var valSum = null;
    var valid = ValReqEmail('#uiToEmail', errorMsgTellAFriend[0], valSum) +
					ValReq('#uiFromName', errorMsgTellAFriend[1], valSum) +
					ValReqEmail('#uiFromEmail', errorMsgTellAFriend[2], valSum);
    if (valid == 3) {
        var serviceUrl;
        if (sendUserRecipe) {
            serviceUrl = "/Services/UserActionService.asmx/TellAFriendOfUserRecipe";
        }
        else {
            serviceUrl = "/Services/UserActionService.asmx/TellAFriend";
        }
        var postData =
		{
		    toEmail: $j(".tellAFriend #uiToEmail").val(),
		    fromName: $j(".tellAFriend #uiFromName").val(),
		    fromEmail: $j(".tellAFriend #uiFromEmail").val(),
		    text: $j(".tellAFriend #uiText").val(),
		    refId: currentId,
		    mailCopy: $j(".tellAFriend #mailCopy").attr('checked')
		}

		// TEMP TellAFriendCampaign
		if (sendUserRecipe == "campaign") {
		    serviceUrl = "/Services/UserActionService.asmx/TellAFriendOekoDag";
		}
		
		
        $j.ajax({
            type: "POST",
            data: postData,
            url: serviceUrl,

            success:

			   function(result, userContext, methodName) {
			       if (result == null) {
			           /* Show error */
			       }
			       else {
			           var c = eval('(' + $j(result).find('string').text() + ')');

			           if (c.ErrorHeading) {
			               alert(msgRating[2]);
			           }
			           else {
			               /* Updating UI */
			               $j('.tellAFriend .confirm p').text(msgTellAFriend[0]);
			               $j('.tellAFriend .confirm a').text(msgTellAFriend[1]);
			               $j('.tellAFriend fieldset').fadeOut('fast');
			               $j('.tellAFriend .confirm').fadeIn('fast');
			               /* Track that the recipe was sent by email */
			               Creuna.Tracking.Instance.FirePending();
			           }
			       }
			   },
            error:
			   function(XMLHttpRequest, errorHeading, errorText) {
			       $j('.ratingTips p').text(msgRating[2]);
			       $j('ratingTips').show();
			   }
        });
    }
}

/***************************************************
Validation methods
***************************************************/

function ValReqMultiLine(ctrlId, msg, valsum) {
    return ValReq(ctrlId, msg, valsum, 'm');
}

function ValReq(ctrlId, msg, valsum, flags) {
    if (flags) {
        return Val(ctrlId, /.+/, msg, valsum, flags)
    }
    else {
        return Val(ctrlId, /^.+$/, msg, valsum)
    }
}

function ValReqDigits(ctrlId, msg, valsum) {
    return Val(ctrlId, /^\d+$/, msg, valsum)
}

function ValReqEmail(ctrlId, msg, valsum) {
    return Val(ctrlId, /^[A-Za-z0-9](([\_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/, msg, valsum)
}

function Val(ctrlId, regex, msg, valsum, flags) {
    var val = jQuery.trim($j(ctrlId).val());
    var isMatch = false;
    if (flags) {
        isMatch = val.match(regex, flags);
    }
    else {
        isMatch = val.match(regex);
    }

    if (!isMatch) {
        $j(ctrlId).next('.errorMessage').html("<div class='arrow'></div>" + msg);
        $j(ctrlId).next('.errorMessage').show();
        $j(ctrlId).change(function() { $j(ctrlId).next('.errorMessage').hide() });
        return false;
    }
    else {
        $j(ctrlId).next('.errorMessage').html("<div class='arrow'></div>");
        $j(ctrlId).next('.errorMessage').hide();
        return true;
    }
}
/***************************************************
Constructor for setting up event flows
***************************************************/

//Event Flow
function EventFlow() {
    this.flow = [];
    this.add = function(evt, data) {
        this.flow.insertAt(new EventEntry(evt, data), 0);
    }
    this.clear = function() {
        this.flow = [];
    }
    this.next = function() {
        if (this.flow.length > 0) {
            entry = this.flow.shift(0);
            $j(document).trigger(entry.evt, entry.data);
            return true;
        } else {
            return false;
        }
    }
    return true;
}
function EventEntry(evt, data) {

    this.evt = evt;
    this.data = data;
}

//Array properties
Array.prototype.insertAt = function(o, index) {
    if (index > -1 && index <= this.length) {
        this.splice(index, 0, o);
        return true;
    }
    return false;
}

function updateUserDot() {
    // placeholder for IE6 fix, don't delete
}
/***************************************************
Site Catalyst tracking helper methods
***************************************************/
function TrackLink(lnk, rs, title, pArr, events) {
    if (typeof (tracking_suite) == "undefined") {
        return false;
    }
    var suite = rs;
    if (suite == null || suite == '') { suite = tracking_suite; }
    var s = s_gi(suite);
    s.charSet = "ISO-8859-1";
    s.linkTrackVars = '';
    for (var i = 0; i < pArr.length; i++) {
        s[pArr[i].k] = pArr[i].v;
        if (i > 0) { s.linkTrackVars += ','; }
        s.linkTrackVars += pArr[i].k;
    }
    if (events) { s.events = events; s.linkTrackEvents = events; s.linkTrackVars += ',events'; }
    s.tl(lnk, 'o', title);
}

function TrackLinkSimple(lnk, rs, title, events) {
    if (typeof (tracking_suite) == "undefined") {
        return false;
    }
    var suite = rs;
    if (suite == null || suite == '') { suite = tracking_suite; }
    var s = s_gi(suite);
    s.charSet = "ISO-8859-1";
    if (events) { s.events = events; s.linkTrackEvents = events; s.linkTrackVars += ',events'; }
    s.tl(lnk, 'o', title);
}

function TrackPage(pn, dd) {
    if (typeof (tracking_suite) == "undefined") {
        return false;
    }
    var suite = tracking_suite;
    var s = s_gi(suite);
    s.charSet = "ISO-8859-1";
    s.pageName = pn;
    s.channel = tracking_channel;
    s.hier1 = dd;
    s.server = location.hostname;
    s.t();
}

function TrackLogin(email) {
    if (typeof (tracking_suite) == "undefined") {
        return false;
    }
    var suite = tracking_suite;
    var s = s_gi(suite);
    s.charSet = "ISO-8859-1";
    s.linkTrackVars = 'prop14,prop15,eVar6,eVar7,events';
    s.linkTrackEvents = 'event14';
    s.prop14 = email;
    s.eVar6 = email;
    s.prop15 = tracking_loginText;
    s.eVar7 = tracking_loginText;
    s.events = 'event14';
    s.tl(this, 'o', 'Login');
}

function TrackNewUser() {
    if (typeof (tracking_suite) == "undefined") {
        return false;
    }
    var suite = tracking_suite;
    var s = s_gi(suite);
    s.charSet = "ISO-8859-1";
    s.linkTrackVars = 'events';
    s.linkTrackEvents = 'event17';
    s.events = 'event17';
    s.tl(this, 'o', 'Ny bruger');
}

if (Creuna == null) {
    var Creuna = {};
}

function DecodeHTML(str) {
    return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}
function htmlEncode(value) {
    return $j('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $j('<div/>').html(value).text();
}


Creuna.Tracking = function() {

    this.pendingCalls = new Object();

    this.SetPending = function(key, func) {
        var k = key;
        if (k == null || k == '') { k = 'DEFAULT'; }
        this.pendingCalls[k] = func;
    }

    this.FirePending = function(key) {
        var k = key;
        if (k == null || k == '') { k = 'DEFAULT'; }
        if (this.pendingCalls[k] != null && this.pendingCalls[k] != 'undefined') {
            this.pendingCalls[k]();
            this.pendingCalls[k] = null;
        }
    }
}

Creuna.Tracking.Instance = new Creuna.Tracking();

/***************************************************
function for cache ajax calls
***************************************************/
// 
(function($) {

    // define public plugin contents
    $.Tache = {
        Data: [],
        Delete: function(a) { Delete(a) },
        DeleteAll: function() { DeleteAll() },
        Get: function(a) { Get(a) },
        SetTimeout: function(a) { SetTimeout(a) },
        Timeout: 600   // 600 seconds = 10 minutes
    };

    // PRIVATE: create a unique identifier
    function CreateID(oAJAX) {
        var sIdentifier = oAJAX.cacheKey;
        if (sIdentifier == 'undefined') {
            sIdentifier = oAJAX.url;
            sIdentifier += ((typeof oAJAX.data == "string") ? oAJAX.data : "");
            sIdentifier += ((typeof oAJAX.dataType == "string") ? oAJAX.dataType : "");
            sIdentifier += ((typeof oAJAX.type == "string") ? oAJAX.type : "");
        }
        return sIdentifier;
    }

    // PUBLIC: delete a single data item
    function Delete(oAJAX) {
        // exit now if we haven't been passed a URL
        if (typeof oAJAX.url != "string") {
            alert("No AJAX URL passed");
            return;
        }

        // delete expired and
        var sIdentifier = CreateID(oAJAX);
        var dtNow = new Date();
        for (var i = $.Tache.Data.length; i > 0; i--) {
            if ((((dtNow.valueOf() - $.Tache.Data[i - 1].dtAge.valueOf()) / 1000) > $.Tache.Timeout) || ($.Tache.Data[i - 1].sIdentifier == sIdentifier)) {
                $.Tache.Data.splice(i - 1, 1);
            }
        }
    }

    // PUBLIC: delete all cached data
    function DeleteAll() {
        $.Tache.Data = [];
    }

    // PUBLIC: return the data of ajax call either directly from the server or from memory if pre-loaded
    function Get(oAJAX) {
        // exit now if we haven't been passed a URL
        if (typeof oAJAX.url != "string") {
            alert("No AJAX URL passed");
            return;
        }

        // find if the data has been cached has already been called, deleting expired requests as we go
        var sIdentifier = CreateID(oAJAX);
        var dtNow = new Date();
        for (var i = $.Tache.Data.length; i > 0; i--) {
            if (((dtNow.valueOf() - $.Tache.Data[i - 1].dtAge.valueOf()) / 1000) > $.Tache.Timeout) {
                // delete expired request
                $.Tache.Data.splice(i - 1, 1);
            } else if ($.Tache.Data[i - 1].sIdentifier == sIdentifier) {
                oAJAX.success($.Tache.Data[i - 1].oData);
                return;
            }
        }

        // the data wasn't found; alter the callback to insert the soon-to-be requested data into the cache
        var oCallback = oAJAX.success;
        oAJAX.success = function(oNewData) {
            $.Tache.Data.push({ sIdentifier: sIdentifier, oData: oNewData, dtAge: new Date() });
            oCallback(oNewData);
        }
        $.ajax(oAJAX);
    }

    // PUBLIC: set the timeout value
    function SetTimeout(iSeconds) {
        $.Tache.Timeout = iSeconds;
    }

})(jQuery);

