var baseUrl = "http://" + window.location.hostname;

/**
 * VARS SHOPPINGLIST
 */
var cookieNameShoppingList = "shoppingList";	// Prefix for cookies
var cookieNameMain = "shoppingListMainSettings";	// Cookie name for settings
var cookieNameCurrent = "shoppingListCurrent";	// Cookie name for current shoppinglist
var cookieNamePrint = "shoppingListPrint";	// Cookie name for printing shoppinglist
var cookieTime = 5;	// How many days a cookie should exist
var cookiesMax= 12; // How many cookies can we create?
var cookieLength = 800; // Max size of cookie, * 3 = 2400 (of 4000)
var menyCookieName = "mpCurrent"; // Cookie name for "uke meny"
var shoppingListUrl = "/oppskrifter/handleliste"; // URL for handleliste
var shoppingListPrintUrl = shoppingListUrl + "/print"; // URL for printing handleliste
var wsShoppingListUrl	= baseUrl + "/shoppinglist";
var urlKokebok = "/oppskrifter/min-kokebok"; // URL for kokebok
var urlUkemeny = "/oppskrifter/ukemeny"; // URL for ukemeny
var urlSok = "/oppskrifter/oppskriftssok"; // URL for oppskrift sok
var urlSendMail = baseUrl + "/system-pages/handleliste-mail-xml"; // URL mail
var noRecipiesInList = "Ingen oppskrifter"; 
var noIngridientsInList = "Ingen ingredienser på din handleliste<br />Hent oppskrifter fra din <a href='" + urlKokebok + "'>kokebok</a>, <a href='" + urlUkemeny + "'>ukemeny</a> eller <a href='" + urlSok + "'>s&oslash;k</a>";
var fullShoppingList = new ShoppingList(); // Global stuff...
var tmpVar = "";
var recipeAddedText = "<span class='added'>Lagt til i <a href='" + shoppingListUrl + "'>handleliste</a></span>";
var orginalPrefix = ['beger', 'blad', 'boks', 'bunt', 'fedd', 
                     'klase', 'kurv', 'litt', 'noe', 'noen', 
                     'pakke', 'porsjon', 'pose', 'potte', 'skiver', 
                     'stykk', 'barneskje', 'teskje', 'spiseskje', 'milliliter', 
                     'centiliter', 'desiliter', 'liter', 'mikrogram', 'milligram', 
                     'gram', 'hektogram', 'kilogram', 'plate', 'plater', 
                     'stilk', 'stilker', 'båt', 'båter'];

var printoutPrefix = ['beger', 'blad', 'boks', 'bunt', 'fedd', 
                      'klase', 'kurv', 'litt', 'noe', 'noen', 
                      'pakke', 'porsjon', 'pose', 'potte', 'skiver', 
                      'stk', 'bs', 'ts', 'ss', 'ml', 
                      'cl', 'dl', 'l', 'ug', 'mg', 
                      'g', 'hg', 'kg', 'plate', 'plater', 
                      'stilk', 'stilker', 'båt', 'båter'];	



/**
 * VARS KOKEBOK
 */
var wsListTineUrl 					= baseUrl + "/cookbook";
var wsListMyUrl 					= baseUrl + "/recipe";
var kokebokUrl 					= "/oppskrifter/min-kokebok";
var privateRecipeUrl				= kokebokUrl + "/oppskrift";
var oppskrifterUrl 					= "/oppskrifter";
var oppskrifterXmlUrl 			= "/system-pages/kokebok-my-xml";
var oppskrifterCookieXmlUrl 	= "/system-pages/kokebok-xml";
var cookieNameKokebok = "kokebok";
var cookieNameKokebokSynced = "kokebokSync";
var cookieTime = 5;	// How many days a cookie should exist
var noOppskrifterInListLoggedIn = "<div class='noIngridientsInList' style='margin-bottom: 30px;'>Ingen oppskrifter i din kokebok<br />Finn en <a href='" + oppskrifterUrl + "'>oppskrift</a> og legg den i kokeboken, eller lag din <a href='#' class='leggTillOppskriftLink'>egen oppskrift</a></div>";
var noOppskrifterInListLoggedOut = "<div class='noIngridientsInList' style='margin-bottom: 30px;'>Ingen oppskrifter i din kokebok<br />Finn en <a href='" + oppskrifterUrl + "'>oppskrift</a> og legg den i kokeboken<br />Hvis du registrerer deg får du muligheten til å legge inn dine egne oppskrifter</div>";
/* Keeping track of all the filters */
var pageSettings = {
		section 	: "all",
		filterName	: "",
		filterSort	: "",
		subsection	: new Array()
};
var itemsPerPage = 9;
var kokebokAddedText = "<span class='added'>Lagt til i <a href='" + kokebokUrl + "'>kokebok</a></span>";



/**
 * VARS PRODUKTKARUELL
 */
/* Speed for scrolling */
var scrollSpeed = 4;
var overlayId = "#logokarusellOverlay";
var showNumberOfLinks = 10;

/* Do not change, used for the links */
var multiplier = 1;
var bgColor;



/**
 * VARS SEARCH
 */
/* Good to have urls */
var searchButton = "http://webfiles.tine.no/tine.no_v2/images/search_button.png";
var searchButtonHover = "http://webfiles.tine.no/tine.no_v2/images/search_button_hover.png";
var searchUrl = "/system-pages/sok-ajax?q=";

var paginOmTINE;
var paginErnaring;
var paginOppskrifter;
var paginProdukter;
var thinkingFlag = false;




/**
 * READY PAGE
 */
$("document").ready(function() {
	
	/**
	* ALL
	*/
	/*$(".body table").each(function() {
		if (!$(this).hasClass('noGrey')){
			$(this).find('tbody tr:odd').addClass('odd');
			//$(this).find("tbody tr:odd").addClass("odd");
		}
	}); */
	$(".body table:not(.noGrey) tbody tr:odd").addClass('odd');
	$(".body table tbody tr td").addClass('bottomBorder');
	
	$(".body table tbody tr, .body table thead tr").each(function(){
		$(this).find("th:gt(0)").addClass("tableBorder");
		$(this).find("td:gt(0)").addClass("tableBorder");
	});
	
	if ($(".formName").size() > 0) {
		Cufon.replace('h1,h2');
	}
	
	/**
	 * SEARCH PAGE
	 */
	if ($("#searchInput").size() == 1) {
		
		/* AutoSuggest */
		  var options = {
				  suggestionsDiv: $("#seachPageAutoComplete"),
				  //autoCompleteURL: baseUrl + '/searchblox61/servlet/AutoSuggest',
				  autoCompleteURL: baseUrl + '/webproxy',
				  searchResultsURL: baseUrl + '/searchblox61/servlet/SearchServlet',
				  params: '&col=3&col=4&col=7&col=8',
				  site: "&urlnum=1"
		  };
		  $('#searchInput').searchbloxAutoComplete(options);
		
		/* Something */
		var value = "";
		$('input[name="q"]').each(function() {
			if ($(this).val() != "") {
				value = $(this).val();
			}
		});
		if (value != "") {
			$('input[name="q"]').val(value);
		}
		
		/* Checking site */
		if ($("#searchInput").size() == 1) {
			
			/* Check if first time to page (or no section selected) then select them all */
			if (!$("#for1").is(':checked') &&
					!$("#for2").is(':checked') &&
					!$("#for3").is(':checked') &&
					!$("#for4").is(':checked')) {
				$("#for1").click();
				$("#for2").click();
				$("#for3").click();
				$("#for4").click();
			} else {
				if (!$("#for1").is(':checked')) {
					$("div.searchOmTINE").hide();
					$("div.searchOmTINE").next().hide();
				}
				if (!$("#for2").is(':checked')) {
					$("div.searchErnaring").hide();
					$("div.searchErnaring").next().hide();
				}
				if (!$("#for3").is(':checked')) {
					$("div.searchOppskrifter").hide();
					$("div.searchOppskrifter").next().hide();
				}
				if (!$("#for4").is(':checked')) {
					$("div.searchProdukter").hide();
					$("div.searchProdukter").next().hide();
				}
			}
			
			/* For show and hide sections */
			$('input:checkbox').bind($.browser.msie ? 'click' : 'change', function() {
				fixHiddenDivs();
			});
			
			countResults();
			$("div.result div.text").highlight($("#searchInput").val());
		}
	}
	
	/**
	 * VACANCY PAGE
	 */
	if ($("#vacancyDiv").size() == 1) {
		// TODO Fix rounded corners in IE bug.
		if (navigator.userAgent.indexOf('MSIE') != -1) {
			$("#vacancyDiv *").removeClass("rounded_top_left").removeClass("rounded_buttom_right");
		}
	}
	
	
	
	/**
	 * PLANT PAGE
	 */
	/*if ($("#plantInfobox").size() == 1) {
		$("#plantInfobox").find(".address").each(function() {
			var currentText = $(this).text();
			var newText = currentText.replace('\n', '<br />');
			$(this).html(newText);
		});
	}*/

	/**
	 * RECIPE PAGE
	 */
	if ($("#ownIngredientsList").size() == 1) {

		/* Needed regexps */
		var regexSteps = /(<br\/?>)+|\*+/i;
		var regexIngredients = /,|<br\/?>/i;
		var regexIngredientsHeadline = /:$/m;
		var regexIngredientsRemove = /\*/;

		/* Split all ingredients */
		var ingredients = new Array();
		var tmp = $("#ownIngredientsList span").html();
		ingredients = tmp.split(regexIngredients);
		
		/* Create a list */
		$("#ownIngredientsList").append($("<ul></ul>"));

		/* For each ingredient, print it */
		for ( var i = 0; i < ingredients.length; i++) {
			var ingredient = $.trim(ingredients[i]);
			var flag = false;

			/* Remove all stars */
			ingredient = ingredient.replace('*','');

			/* If headline */
			if (ingredient.match(regexIngredientsHeadline)) {
				flag = true;
			}

			/* Add empty row before lines that ends with ':' */
			if (i > 0 && ingredient.match(regexIngredientsHeadline)) {
				$("#ownIngredientsList ul").append("<li>&nbsp;</li>");
			}

			/* Print ingredient if not empty */
			if (ingredient != "") {
				if (flag) {
					$("#ownIngredientsList ul").append("<li class='headline'>" + ingredient + "</li>");
				} else {
					$("#ownIngredientsList ul").append("<li>" + ingredient + "</li>");
				}
			}
		}

		/* Remove orginal ingredients */
		$("#ownIngredientsList span").remove();


		/* Split all steps */
		var steps = $("#ownStepsList span").html().split(regexSteps);

		/* Create a list */
		$("#ownStepsList").append($("<ul></ul>"));

		/* For each step, print it */
		for ( var i = 0; i < steps.length; ) {
			var step = $.trim(steps[i]);

			/* If empty row, remove it and continue to next */
			if (step.match(regexSteps)) {
				steps.splice(i,1);
				continue;
			}

			/* If not empty row, create step */
			if (step != "") {
				$("#ownStepsList ul").append(
						"<li>" +
						"<div class='stepnumber'>" + parseInt(i+1) + "</div>" +
						"<div>" + step + "</div><div class='cleardiv'></div>" + 
				"</li>");
			}
			i++;
		}

		/* Remove orginal steps */
		$("#ownStepsList span").remove();
	}



	/**
	 * KOKEBOK PAGE
	 */
	if ($("#kokebok").size() == 1) {

		if (getLoggedInUser() != false) {
			$(".userservice-notice").hide();
			$(".userservice-notice").next().hide();
		}
		
		$(".usercreatebutton").live('click', function() {
			showLogin();
			return false;
		});
		
		$('.facebookbutton').bind('click',function(e) {
			showLogin();
			return false;
		}); 
		
		var recipeIds;
		
		/* Sync */
		var synced = syncCookieAndDb(true);
		
		/* Cookie or websevice? */
		if (!getLoggedInUser()) {
			recipeIds = cookieListTineItems();
		} else {
			recipeIds = wsListTineItems(getLoggedInUser().email);
		}
		var queryCorrect 	= createQueryFromIds(recipeIds);
		var queryInUrl		= getQueryInUrl();

		/* Checking so url matches rest service */
		if (queryCorrect != queryInUrl) {
			if (synced !== undefined && synced != false) {
				window.location.href = kokebokUrl + "?query=" + queryCorrect + "&synced="+synced;
			} else {
				window.location.href = kokebokUrl + "?query=" + queryCorrect;
			}
			
			return;
		}
	
		$(".leggTillOppskriftButton").show();
		
		
		/* Activate tab */
		makeActive("alle");

		/* Fix inputs */
		$("input.textThing, textarea.textThing").each(function() {
			$(this).attr("value",$(this).attr("title"));
			$(this).addClass("greyInput");
		});

		/* Set created date on stuff from EVS (for sorting) */
		$("#kokebok ul li.mosaic_recipe div.created").each(function () {
			var id = $(this).text();
			for ( var i = 0; i < recipeIds.length; i++) {
				var recipe = recipeIds[i];
				if (recipe.recipeid == id) {
					$(this).text(recipe.created);
					break;
				}
			}
		});

		/* Print my recipes */
		var myRecipes;
		if (getLoggedInUser()) {
			myRecipes = wsListMyItems(getLoggedInUser().email);

			for ( var i = 0; i < myRecipes.length; i++) {
				var recipe = myRecipes[i];

				var theLi = 
					"<li class='mosaic_recipe recipe_my " + recipe.category + " itemKey-" + recipe.id + "'>" +
					"<div class='created'>" + recipe.created + "</div>" +
					"<div class='images'>" +
					"<img class='add_rounded_image' src='http://www.tine.no/imageresize/recipe/" + recipe.image + "/220_125.jpg' alt='" + recipe.title + "'/>" +
					"<img src='http://webfiles.tine.no/tine.no_v2/images/shadow_220px.jpg'/>" +
					"</div>" +
					"<a class='linkbullet' href='" + privateRecipeUrl + "?hash=" + recipe.hash + "'>" +
					"<p class='title'>" + recipe.title + "</p>" +
					"<div class='extrainfo'>"+
					"<p></p>" +
					"</div>" +
					"</a>" +
					"<div class='buttons'>" +
					"<div class='box1Own'>" +
					"<img src='http://webfiles.tine.no/tine.no_v2/images/shoppinglist_icon.gif'/>" +
					"Legg til i <br />handleliste" +
					"</div>" +
					"<div class='box2'>" +
					"<img src='http://webfiles.tine.no/tine.no_v2/images/button_delete.png' />" +
					"Fjern oppskrift" +
					"</div>" +
					"</div>" +
					"</li>";

				$("#kokbokRecipes").find("ul").append(theLi);
			}
		} 

		/* Fix all dates (for sorting) */
		fixDates();

		/* Sets sorting */
		fixSorting();

		$("#kokebok ul li:lt(" + (itemsPerPage+1) + ")").show();
		$("#kokebok ul li:gt(" + (itemsPerPage-1) + ")").hide();
		
		/* Fix logged in/not logged in  text */
		fixLayout();
		
		/* Mark latest added */
		markLatest();
		
		/* Set synced text */
		//fixSyncedText();

		/* Add pager */
		$("#kokbokRecipes").pagingNew({
			'items'			: "li.mosaic_recipe", 
			'prev'			: $("#prevPage"), 
			'next'			: $("#nextPage"), 
			'prevDisabled'	: $("#prevPageDisabled"), 
			'nextDisabled'	: $("#nextPageDisabled"),
			'countPerPage'	: itemsPerPage
		});
		
		fixPagingLinks();

		/* Show result */
		$(".loading").hide();
		$(".viewTypeThumbs").show();
	
		$("#menuKey-alle").click();
	}
	
	
	/**
	 * PRODUCTKARUSELL PAGE
	 */
	if ($("#logokarusell").size() == 1) {
		/* Add close buttons to products */
		$("#logokarusell .product").prepend("<img src='http://webfiles.tine.no/tine.no_v2/images/logokarusell_close.png' alt='Steng' class='close' />");

		/* Hide some links */
		$("#logokarusell .product").each(function() {
			$(this).find("a.link:gt(" + (showNumberOfLinks - 1) + ")").hide();
		});
	}
	
	
	/**
	 * SHOPPINGLIST PAGE
	 */
	if ($("#handlelisteVarerDiv").size() == 1) {	
		if (getLoggedInUser() != false) { 
			$(".userservice-notice").hide();
			$(".userservice-notice").next().hide();
		} else {
			$(".usercreatebutton").live('click', function() {
				showLogin();
				return false;
			});

			$('.facebookbutton').live('click', function(e) {
				showLogin();
				return false;
			});
			
		}

		/* Checking so url matches cookie */
		var shoppingList = getShoppingList();
		shoppingList.cleanShoppinglist();
		saveShoppingList(shoppingList);
		
		var keysInQueryAsString = getKeysInUrl();
		var keysInQuery = getKeysInQuery(keysInQueryAsString);
		var keysInShoppingLists = shoppingList.getRecipeKeys();

		/* Security check */
		if (keysInQuery.length == 0) {
			window.location.href = shoppingListUrl + "?key=" + shoppingList.getQuery();
		} else if(keysInQuery.length == 1 && keysInQuery[0] == -1 && keysInShoppingLists.length == 0){
			// It's OK
		} else if (!keysAreSame(keysInQuery, keysInShoppingLists)) {
			window.location.href = shoppingListUrl + "?key=" + shoppingList.getQuery();
		}
		// It's OK

		/* Gets all info from the hidden div on the page */
		fullShoppingList = loadAllRecipesIntoJS();
		
		

		/* Fix all the portion ratios */
		fixPortionPrintout();

		/* Prints out all the ingredients */
		printAllIngredientsToTable(true);

		/* Prints own recipes */
		printOwnRecipesToTable();

		/* Fix calsses */
		setupTableClasses();

		/* Fix rounded corner on first image */
		fixRoundedCorner();

		/* Fix some text */
		fixOutputTextForRecipes();
		fixOutputTextForIngredints();
		fixSaveShoppingList();

		/* Show it all */
		$("#handlelisteVarerDiv").show();
		$("#handlelisteOppskrifterDiv").show();
	}
	
	/**
	* COMPLIENT PAGE 
	*/
	if ($("#WebProduct").size() == 1) {
		var names = [];
		var classes = [];
		
		var i = 0;
		$("#WebProductDD option").each(function() {
			var text = $(this).text();
			var imageClass = $(this).attr("class");
			
			names[i] = text;
			classes[i] = imageClass;
			i++;
		});
		
		$("#WebProduct").autocomplete(names, {
			matchContains: true,
			selectFirst: false,
			max: 200
		});
		
		$("#WebProduct").live('blur', function() {
			var value = $(this).val();
			var selectedClass = "";
			for(j = 0; j < names.length; j++) {
				var name = names[j];
				if (name == value) {
					selectedClass = classes[j];
					break;
				}
			}
			if (selectedClass !=  "" && $(this).val() != "") {
				$(".infoButton").show();
				$("#HoldbarhetDatoInfo, #ProductionCodeInfo").unbind();
				$("#HoldbarhetDatoInfo, #ProductionCodeInfo").bind('click', function() {
					var imgUrl = "http://webfiles.tine.no/Tine.no/images/produktholdbarhet/";
					var imgId = selectedClass;
					
					if ($.trim(imgId) == "") {
						return;
					}
					imgId = imgId.substring(3);
					imgUrl = imgUrl + imgId + ".jpg";
					
					//Get the screen height and width
					var maskHeight = $(document).height();
					var maskWidth = $(window).width();

					//Set heigth and width to mask to fill up the whole screen
					$('#mask').css({'width':maskWidth,'height':maskHeight});

					//Get the window height and width
					var winH = $(window).height();
					var winW = $(window).width();
					  
					//Get scroll
					var pos = getScrollXY();
					
					//Set the popup window to center
					$('#HoldbarhetDatoInfoBox').css('top',  (winH/2-$('#HoldbarhetDatoInfoBox').height()/2) + pos.y);
					$('#HoldbarhetDatoInfoBox').css('left', (winW/2-$('#HoldbarhetDatoInfoBox').width()/2) + pos.x);
					
					$('#HoldbarhetDatoInfoBox').find("img:not(.closeLogin)").remove();
					$('#HoldbarhetDatoInfoBox').append("<img src='" + imgUrl + "' title='Hjelpbilde' class='rounded'></img>");
					
					$("#mask").show();
					$("#HoldbarhetDatoInfoBox").show();
				});
			} else {
				$(".infoButton").hide();
				$(".infoButtonShow").show();
				$("#HoldbarhetDatoInfo, #ProductionCodeInfo").unbind();
			}
		});
	}
});


/**
 * KEY BINDINGS
 */
$(document).keyup(function(e) {
	if (e.keyCode == 27) {
		$("#logokarusell .product .close").click();
		$(".closeDialog").click(); 
		$(".closeLogin").click();
	}
});



/**
 * BINDING SEARCH
 */
/* When the user goes over the search button with the mouse (hover effect) */
$("#searchSubmit").live('mouseover', function() {
	$(this).attr("src", searchButtonHover);
});
$("#searchSubmit").live('mouseout', function() {
	if (!$("#searchInput").is(":focus")) {
		$(this).attr("src", searchButton);
	}
});

$("#searchForm").live('submit', function() {
	thinking();
});

$("#searchSubmit").live('click', function() {
	$("#searchForm").submit();
});


$("#searchSorting").live("blur change", function() {
	$("#searchSubmit").click();
});

$(".nextLink, .prevLink").live('click', function() {
	
	/* Get section */
	var section = $(this).closest(".section");
	if (section.length == 0) {
		section = $(this).parent().parent().parent().prev();
	}
	
	/* Create url */
	var url;
	if ($(this).hasClass("nextLink")) {
		url = $(section).find(".links .next").text();
	} else {
		url = $(section).find(".links .prev").text();
	}
	
	/* Rysshaxx */
	url = decodeURIComponent(url);
	url = url.replace(/&/g, '%26','g');
	url = url.replace(/\//g, '%2F','g');
	url = url.replace(/\?/g, '%3F','g');
	url = url.replace(/=/g, '%3D','g');
	url = searchUrl + url;
	
	/* Hide current result */
	$(section).find(".result").hide();
	
	/* Add loading image */
	$(section).find(".loading").attr('style', 'display : block;');
	
	/* Where we want the data */
	var result = null;
	
	/* If it was updated */
	if (url != searchUrl) {
		result = wsGetResult(url)
	}
	
	/* If we have a result else reset view */
	if (result != null) {
		
		/* Some vars */
		var start = $(result).find("results").attr("start");
		var end = $(result).find("results").attr("end");
		var hits = $(result).find("results").attr("hits");
		var nextUrl = "";
		var prevUrl = "";
		if ($(result).find("link[page=prev]").size() > 0) {
			prevUrl = $(result).find("link[page=prev]").attr("url");
		}
		if ($(result).find("link[page=next]").size() > 0) {
			nextUrl = $(result).find("link[page=next]").attr("url");
		}
		
		/* Remove, not hide current result on page */
		$(section).find(".result ").remove();
		
		/* Update counter(s) */
		$(section).find(".counter").text(start + "-" + end + " av " + hits);
		$(section).next().find(".theCounter").text(start + "-" + end + " av " + hits);
		
		/* Update prev and next links */
		$(section).find(".links .prev").text(prevUrl);
		$(section).find(".links .next").text(nextUrl);
		$(section).next().find(".links .prev").text(prevUrl);
		$(section).next().find(".links .next").text(nextUrl);
		
		/* Disable buttons if needed */
		if (prevUrl == "") {
			$(section).find(".prevLink").addClass("disabled");
			$(section).next().find(".prevLink").addClass("disabled");
		} else {
			$(section).find(".prevLink").removeClass("disabled");
			$(section).next().find(".prevLink").removeClass("disabled");
		}
		if (nextUrl == "") {
			$(section).find(".nextLink").addClass("disabled");
			$(section).next().find(".nextLink").addClass("disabled");
		} else {
			$(section).find(".nextLink").removeClass("disabled");
			$(section).next().find(".nextLink").removeClass("disabled");
		}
		
		/* Show the result */
		addResult(section, $(result).find("results"));
		
	} else {
		
		/* Show current result due to error (trying to go out of range) */
		$(section).find(".result").show();
	}
	
	/* Remove loading image */
	$(section).find(".loading").hide();
	
});


/* Toggle search result */
$(".showResult").live('click', function() {
	
	/* Get everything we need */
	var section = $(this).closest(".section");
	if (section.length == 0) {
		section = $(this).parent().prev();
	}
	var childs = $(section).children(".result");
	var text = $(section).next().children("a");
	var visibleSize = $(section).children(".result:visible").length;
	
	var titleClone = $(section).find(".head").clone();	
	var title = $(titleClone).find(".title").text();
	$(titleClone).children().remove();
	
	/* If we are hiding else showing */
	if (visibleSize > 2) {
		
		/* Hide/show paging if needed */
		$(section).find(".navigationLinks").hide();
		$(section).next().find(".navigationLinks").hide();
		$(section).find(".theCounter").hide();
		
		/* Show the first two */
		$(childs).hide();
		$(childs).slice(0,2).show();
		
		/* Fix text */
		$(text).html("Vis flere resultater fra " + title);
		
	} else {
		
		/* Fix text */
		$(text).html("Skjul resultater fra " + title);
		
		/* Hide other sections */
		if ($(section).hasClass("searchOmTINE")) {
			hideAllExcept("omtine");
		} else if ($(section).hasClass("searchErnaring")) {
			hideAllExcept("ernaring");
		} else if ($(section).hasClass("searchOppskrifter")) {
			hideAllExcept("oppskrifter");
		} else if ($(section).hasClass("searchProdukter")) {
			hideAllExcept("produkter");
		} 
		
		/* Hide/show paging if needed */
		$(section).find(".navigationLinks").show();
		$(section).next().find(".navigationLinks").show();
		$(section).find(".theCounter").show();
		
		/* Show first 10 */
		$(childs).slice(0,10).show();
	}
});

/**
 * BINDINGS PRODUKTKARUELL
 */
/* Mouse over on left arrow, moves it to the left */
$("#logokarusell .right").live("mouseover", function() {
	this.iid = setInterval(function() {
		var position = $("#logokarusell .logos").scrollLeft();
		$("#logokarusell .logos").scrollLeft(position + scrollSpeed);
		$(this).mouseover();
	}, 25);
}).live("mouseout", function() {
	this.iid && clearInterval(this.iid);
});

/* Mouse over on right arrow, moves it to the right */
$("#logokarusell .left").live("mouseover", function() {
	this.iid = setInterval(function() {
		var position = $("#logokarusell .logos").scrollLeft();
		$("#logokarusell .logos").scrollLeft(position - scrollSpeed);
		$(this).mouseover();
	}, 25);
}).live("mouseout", function() {
	this.iid && clearInterval(this.iid);
});

$("#logokarusell .logos a").live("click", function() {
	var product = $("img", this).attr("alt");
	product = product.replace(/ /g, "").replace(/'/g, "").toLowerCase();

	_gaq.push(['_trackEvent', 'Logokarusell', 'Åpnet', product]);
});

/* Clicking on a product */
/*
$("#logokarusell .logos img").live("click", function() {

	// If closing current (clicking on active) 
	if ($(this).hasClass("active")) {

		// Close
		$("#logokarusell .product .close").click();
	} else {

		// If no one is active, open it - else switch to the new one 
		if ($("#logokarusell .logos img.active").size() == 0) {
			
			
			// Adds layer to all other buttons, so the still will be pressible 
			$("#logokarusell .logos img:not(:hidden)").wrap("<span class='imageLayer' /> ");

			// Open 
			$(this).prev().hide();
			$(this).show().addClass("active").wrap("<span class='imageLayer active' /> ");
			$("img.active").before("<img src='http://webfiles.tine.no/tine.no_v2/images/logokarusell_shadow_left.png' class='shadow' />");
			$("img.active").after("<img src='http://webfiles.tine.no/tine.no_v2/images/logokarusell_shadow_right.png' class='shadow' />");

			// Get div name to open 
			var product = $(this).attr("alt");
			product = product.replace(/ /g, "").replace(/'/g, "").toLowerCase();

			// Hide all product layers, except the one that should be open 
			$("#logokarusell .product:not(." + product + ")").hide();

			// Show information + overlay 
			$("." + product + "").show();
			$(overlayId).show();
			
			_gaq.push(['_trackEvent', 'Logokarusell', 'Åpnet', product]);

		} else {

			// Switch the the new layer 
			$(this).hide();
			$(this).parent().next().addClass("clickMe");
			$("#logokarusell .product .close").click();
			$(".clickMe").click();
			$(".clickMe").removeClass("clickMe");
			
		}
		
		// Reset links 
		multiplier = 1;
		
		// Hide some links 
		$("#logokarusell .product:visible").find("a.link:gt(" + (showNumberOfLinks - 1) + ")").hide();
		
		// Setup the 'Forrige' and 'Neste' buttons 
		showAndHideLinksSetup();
	}
});
*/

/* Clicking on the overlay closes it */
$("#logokarusellOverlay").live('click', function() {
	$("#logokarusell .product .close").click();
});


/* Closing products */
$("#logokarusell .product .close").live('click', function() {

	/* Remove all hidden image buttons */
	$("#logokarusell .logos span.imageLayer").each(function() {
		var innerData = $(this).html();
		$(this).before(innerData);
		$(this).remove();
	});

	/* Remove active class and Change image to none active one */
	$("#logokarusell .logos img:hidden").show();
	$("#logokarusell .logos img.hoverImage").hide();
	$("#logokarusell .logos img.active").prev().remove();
	$("#logokarusell .logos img.active").next().remove();
	$("#logokarusell .logos img.active").removeClass("active");

	/* Hide products */
	$("#logokarusell .product").hide();

	/* Hide overlay */
	$(overlayId).hide();
});

/* Hovering effect for logos */
$(".logos img").live("mouseover", function() {
	if ($(this).hasClass("hoverImage") || $(this).parent().hasClass("imageLayer") || $(this).hasClass("active")) {
		// Do nothing, why not invert the if? Because, all your base are belong to us! Muhaha
	} else {
		$(".hoverImage:visible").each(function() {
			// Old: $(this).prev().show();
			$(this).parent().prev().find("img").show();
			$(this).hide();
		});
		// Old: $(this).next().show();
		$(this).parent().next().find("img").show();
		$(this).hide();
	}
});
$(".logos img").live("mouseout", function() {
	if ($(this).hasClass("hoverImage") && $("#logokarusell .logos img.active").size() == 0) {
		// Old: $(this).prev().show();
		$(this).parent().prev().find("img").show();
		$(this).hide();
	} else {

	}
});

/* Hovering effect for logos (when grayed out) */
$(".imageLayer").live("mouseover", function() {
	$(this).addClass("hover");
});
$(".imageLayer").live("mouseout", function() {
	$(this).removeClass("hover");
});

/* Show previous / next links */
$(".prevProducts").live('click', function() {
	showAndHideLinks(-1);
});
$(".nextProducts").live('click', function() {
	showAndHideLinks(1);
});

/* For rounded corners on product link */
$("#productPage").live("mouseover", function() {
	bgColor = $(this).attr("style");
	$(this).attr("style", "background-color: #F00000");
});
$("#productPage").live("mouseout", function() {
	$(this).attr("style", bgColor);
});


/**
 * BINDINGS KOKEBOK
 */
/* MEIRIER Button */
$("#plantAllProductsButton").live('click', function(e) {
	$("#plant .product:gt(2)").toggle();
	if ($("#plant .product:visible").size() > 3) {
			$("#plantAllProductsButton").text("Vis færre produkter");
	} else {
		$("#plantAllProductsButton").text("Vis alle produkter");
	}
	e.preventDefault();
});

$("#plantAllRelatedButton").live('click', function(e) {
	$("#plant .product:gt(3)").toggle();
	if ($("#plant .product:visible").size() > 3) {
			$("#plantAllRelatedButton").text("Vis færre meierier");
	} else {
		$("#plantAllRelatedButton").text("Vis alle meierier");
	}
	e.preventDefault();
});

/* Mouse overs */
/*Removed .mosiac_recipe and replaced it with .kokebokRecipe*/
$(".kokebokRecipe").live('mouseover', function() {
	$(".buttons").hide();
	$(this).find(".buttons").show();
});

$(".kokebokRecipe").live('mouseout', function() {
	$(this).find(".buttons").hide();
});

/* Links */
$(".mosaic_recipe .buttons div").live('mouseover', function(e) {
	$(this).addClass("link");
});
$(".mosaic_recipe .buttons div").live('mouseout', function(e) {
	$(this).removeClass("link");
});

/* Add to handleliste */
$(".mosaic_recipe .box1").live('click', function(e) {
	var key =  getItemKey($(this).parent().parent());
	var name = $(this).parent().parent().find(".title").text();
	if (key) {
		_gaq.push(['_trackEvent', 'Handleliste', 'Legg til', name + ' (' + key + ')']);
		addRecipeKeyAndGoToShoppingList(key);
	}
	e.preventDefault();
	return false;
});

/* Add to handleliste */
$(".mosaic_recipe .box1Own").live('click', function(e) {
	var key =  getItemKey($(this).parent().parent());
	var name = $(this).parent().parent().find(".title").text();
	if (key) {
		var data;
		if (getLoggedInUser()) {
			data = wsGetMyItem(getLoggedInUser().email, key);
		} else {
			alert("Login first 1");
		}
		_gaq.push(['_trackEvent', 'Handleliste', 'Legg til', name + ' (' + key + ')']);
		addRecipeIngredientsAndGoToShoppingList(data);
	}
	e.preventDefault();
	return false;
});

/* Remove from kokebok */
$(".mosaic_recipe .box2").live('click', function(e) {
	var key =  getItemKey($(this).parent().parent());
	var name = $(this).parent().parent().find(".title").text();
	var id = getIdFromKey(key);
	$(this).parent().parent().remove();
	
	/* If tine item, else user created */
	if (id) {
		_gaq.push(['_trackEvent', 'Kokebok', 'Fjern fra', name + ' (' + id + ')']);
		if (!getLoggedInUser()) {
			cookieDeleteTineItem(id);
		} else {
			wsDeleteTineItem(getLoggedInUser().email, id);
			cookieDeleteTineItem(id);
		}
	} else {
		if (getLoggedInUser()) {
			_gaq.push(['_trackEvent', 'Kokebok', 'Slett egen oppskrift']);
			wsDeleteMyItem(getLoggedInUser().email, key);
		}
	}
	
	/* Update paging childs */
	$("#kokbokRecipes").pagingNew('updateChilds', createFilter());
	//$("#kokbokRecipes").pagingNew('setFilter', createFilter());
	
	/* Get first hidden one (that's matches the filter) and show it last. */
	var all = $("ul.viewTypeThumbs li").filter(createFilter());
	if (all.length > 8) {
		for(i = 8; i < all.length; i++){
			var current = all[i];
			var prev = all[i-1];
			if ($(prev).is(":visible") && $(current).is(":hidden")) {
				$(current).show();
				break;
			}
		}
	}
	
	//fixPagingLinks();
	e.preventDefault();
	return false;
});

/* Close */
$("#kokebokAddRecipe .close").live('click', function() {
	$("#addRecipeBoxMask").click();
});


/* Reset inputs */
$("#resetKokebokRecipe").live('click', function(e) {
	$("#kokebokAddRecipeForm input, #kokebokAddRecipeForm textarea").each(function() {
		if ($(this).attr('title') != "") {
			$(this).val($(this).attr('title'));
		}
	});
	$("#kokebokAddRecipeForm select").each(function() {
		$(this).val($(this).children("option:first").val());
	});
	e.preventDefault();
	return false;
});

/* Submit form */
$("#addKokebokRecipe").live('click', function(e) {
	if (!getLoggedInUser()) {
		return false;
	}
	$("#kokebokAddRecipeForm").attr("action", wsListMyUrl + "/"+ getLoggedInUser().email +"/");
	$("#kokebokAddRecipeForm").append("<input type='hidden' name='email' value='" + getLoggedInUser().email + "'/>");
	$("#kokebokAddRecipeForm").append("<input type='hidden' name='token' value='" + getUserToken() + "'/>");
	$("#kokebokAddRecipeForm").submit();
	e.preventDefault();
	return false;
});


/* For 'Bakst, Dessert, Drikker, Kaker, Frokost og nistemat, Middag' */
$("#kokebokMenu div").live('click', function() {

	/* Get elements id */
	var id = $(this).attr('id');

	/* Get place of it (Not in use, only when multiple subsection is allowed) */
	var place = pageSettings.subsection.indexOf(id);

	/* Activate subsection else deactivate subsection */
	if (place == -1) {

		/* Deactivate other subsections */
		for ( var i = 0; i < pageSettings.subsection.length; i++) {
			var element = pageSettings.subsection[i];
			makeMenuActive($("#"+element), false);
		}
		pageSettings.subsection = new Array();

		/* Add active button to array */
		pageSettings.subsection.push(id);
		makeMenuActive($(this), true);
	} else {

		/* Remove active button to array */
		pageSettings.subsection.splice(place,1);
		makeMenuActive($(this), false);
	}

	/* Set new filter */
	$("#kokbokRecipes").pagingNew('setFilter', createFilter());

	/* Reset pager */
	$("#kokbokRecipes").pagingNew('reset');
});


/* For 'Alle, Mine, Tine' */
$("#kokebok div.labels img").live('click', function() {
	var buttonName = getButton($(this));
	if (!isButtonActive($(this))) {

		/* Activate button */
		makeActive(buttonName);

		/* Set new section filter value */
		if (buttonName == "mine") {
			pageSettings.section = "my";
		} else if (buttonName == "kategorier") {
			pageSettings.section = "category";
		} else {
			pageSettings.section = "all";
		}

		/* Set new filter */
		$("#kokbokRecipes").pagingNew('setFilter', createFilter());

		/* Reset pager */
		$("#kokbokRecipes").pagingNew('reset');
	}
});


/* For 'Legg til egen oppskrift' */
$("#kokebok div.labels a.leggTillOppskriftButton, a.leggTillOppskriftLink").live('click', function() {
	if(getLoggedInUser()) {
		showAddRecipe();
	} else {
		_gaq.push(['_trackEvent', 'Kokebok', 'Klikk Opprett egen oppskrift uten innlogging']);
		if ($(".labels").find("span").size() == 0) {
			$("a.leggTillOppskriftButton").parent().append("<span class='small'>(Krever <span class='usercreatebutton'>innlogging</span>)</span>");
		}
	}
	return false;
});

/* For edit recipe */
$("a.endreOppskriftButton").live('click', function(e) {

	var loaded = function() {

		/* Values */
		var id = $("#recipeId").text();;
		var email = "";
		var title = $.trim($("#recipeTitle").text());
		var category = $("#recipeCategory").text();
		var description = $.trim($("#recipeDescription").html().replace(/<br>/g, "\n"));
		var ingredients = ""; // Comes after
		var steps = ""; // Comes after
		var file = "";

		/* Regex */
		var regexFix = /\s{2,1000}/g; 

		/* Ingredients */
		$("#ownIngredientsList ul li").each(function(index) {
			if (index != 0) {
				ingredients += "\n";
			}
			ingredients += $.trim($(this).text().replace(regexFix,' '));
		});

		/* Steps */
		$("#ownStepsList ul li div:not(.stepnumber)").each(function(index) {
			if (index != 0) {
				steps += "\n";
			}
			steps += $.trim($(this).text().replace(regexFix,' '));
		});
		steps = $.trim(steps.replace(/\n\n/g, "\n"));

		/* Set values */
		$("#kokebokAddRecipeName").val(title);
		$("#kokebokAddRecipeDescription").val(description);
		$("#kokebokAddRecipeCategory").val(category);
		$("#kokebokAddRecipeIngredients").val(ingredients);
		$("#kokebokAddRecipeSteps").val(steps);

		/* Fix text */
		$("#addKokebokRecipe").attr("style", "background-position: 79px center;").text("Oppdatere");
		$("#kokebokAddRecipe h2").text("Oppdatere egen oppskrift");

		/* Add id for update */
		$("#kokebokAddRecipeForm").append("<input name='id' value='" + id + "' type='hidden' />");

		/* Fix inputs */
		$(".greyInput").removeClass("greyInput");
		$("input.textThing, textarea.textThing").each(function() {
			if ($.trim($(this).val()) == "" || $(this).attr("title") == $.trim($(this).val())) {
				$(this).attr("value",$(this).attr("title"));
				$(this).addClass("greyInput");
			}
		});
	};

	/* Show everything */
	showEditRecipe(loaded);
	e.preventDefault();
	return false;
});


/* Sorting */
$("#kokebokSort").live("blur", function() {
	fixSorting();

	/* Reset pager */
	$("#kokbokRecipes").pagingNew('reset');
});


/* Filter */
$("#kokebokFilter").live("keyup blur", function() {

	/* Sets new filter value */
	pageSettings.filterName = $(this).val();

	/* Set new filter */
	$("#kokbokRecipes").pagingNew('setFilter', createFilter());

	/* Reset pager */
	$("#kokbokRecipes").pagingNew('reset');
});


/* When post */
$("#kokebokAddRecipeForm").live('submit', function() {
	document.getElementById('kokebokAddRecipeForm').target = 'upload_target';
	$("#upload_target").load(uploadDone);
});


/* For the inputs, should be in common */
$("input.textThing, textarea.textThing").live('focus', function() {
	if ($(this).val() == $(this).attr('title')) {
		$(this).val("");
		$(this).removeClass("greyInput");
	}
});
$("input.textThing, textarea.textThing").live('blur', function() {
	if ($.trim($(this).val()) == "") {
		$(this).val($(this).attr("title"));
		$(this).addClass("greyInput");
	}
});



/**
 * BINDINGS SHOPPINGLIST
 */
/* Load an saved shoppinglist */
$("span.load").live('click', function() {
	var name = $(this).parent().find("span.load").text();
	if (!confirm("Endringer som ikke er lagret vil bli overskrevet. Er du sikker?")) {
		return;
	}
	var id = $(this).parent().find("span.id").text();
	loadShoppingList(id, name);
});

/* Delete an saved shoppinglist */
$("span.delete").live('click', function() {
	var name = $(this).parent().find("span.load").text();
	if (!confirm("Sikker på att du vil fjerne " + name + "?")) {
		return;
	}

	var loggedInUser = getLoggedInUser();

	var id = $(this).parent().find("span.id").text();
	var status = wsRemoveShoppingList(loggedInUser.email, id);

	if (status == "deleted") {
		_gaq.push(['_trackEvent', 'Handleliste', 'Slett']);
		$("#savedShoppingLists").find("li").each(function() {
			var tmpId = $.trim($(this).find("span.id").text());

			/* Same id = remove */
			if (id == tmpId) {
				$(this).fadeOut('fast', function() {
					$(this).remove();
					fixSavedShoppingListsText();
				});
				fixSaveShoppingList();
				setCurrentShoppingList("");
			}
		});

	} else {
		// TODO What to do with other codes?
	}

});

/* Pressing esc */
$("#txtShoppingListName").live('keypress', function(e) {
	var code = (e.keyCode ? e.keyCode : e.which);
	if(code == 13) {
		$("#btnSaveShoppingList").click();
	}
});

/* Sends a shoppinglist */
$("#btnSendShoppingList").live('click', function(e) {
	sendTheMail();
	e.preventDefault();
	return false;
});

/* Saves a shoppinglist */
$("#btnSaveShoppingList").live('click', function(e) {
	var name = $.trim($("#txtShoppingListName").val());
	name = name.replace("<", "");
	name = name.replace(">", "");
	name = name.replace("=", "");	
	
	var id = "";

	// TODO If not logged in?
	var loggedInUser = getLoggedInUser();
	if (loggedInUser == null) {
		return false;
	}

	// TODO How to handle errors?
	if (name == "") {
		return false;
	}

	/* If it already exists */
	$("#savedShoppingLists").find("li").each(function() {
		var tmpName = $.trim($(this).find("span.load").text());

		/* Same name = update */
		if (name == tmpName) {
			id = $(this).find("span.id").text();
		}
	});

	/* Make it as a string */
	var data = JSON.stringify(fullShoppingList, '');

	/* Save/update it */
	var status = wsAddShoppingList(loggedInUser.email, data, name, id);

	/* Text after input */
	var feedback = "";
	var errorFlag = false;
	
	/* If it was saved, updated or unknown status */
	if (status.status == "created") {
	
		_gaq.push(['_trackEvent', 'Handleliste', 'Lagre handleliste']);

		/* New active list */
		$("li.active").removeClass("active");
		setCurrentShoppingList(name);

		/* Add it to list */
		$("#savedShoppingLists").append(
				"<li class='active'>" +
				"<span class='id'>" + status.id + "</span>" +
				"<span class='load'>" + name + "</span>" +
				" " +
				"<span class='delete'><img class='deleteMenuPlan' src='http://webfiles.tine.no/Tine.no_v2/images/icon_delete.png'></span>" +
		"</li>");

		/* Update text */
		fixSaveShoppingList();
		$("#txtShoppingListName").val("").focus();
		
		feedback = "Handleliste lagret";

	} else if (status.status == "updated") {
	
		_gaq.push(['_trackEvent', 'Handleliste', 'Oppdatert handleliste']);

		/* New active list */
		$("li.active").removeClass("active");
		setCurrentShoppingList(name);
		$("#savedShoppingLists li").each(function() {
			var tmpName = $(this).find("span.load").text();
			if (tmpName == name) {
				$(this).addClass("active");
			}
		});

		feedback = "Handleliste oppdatert";
	} else {
		//error
		errorFlag = true;
		if (status.message == "length") {
			feedback = "Maks lengde er på 30 tegn";
		} else {
			feedback = "Unsupported error";
		}
		
	}
	
	if (errorFlag) {
		$("#txtShoppingListNameStatus").attr("style", "color : #F00000;");
	}
	$("#txtShoppingListNameStatus").text(feedback);
	$("#txtShoppingListNameStatus").show(function() {
		setTimeout(function() {
			$("#txtShoppingListNameStatus").fadeOut('2000');
		}, 2000);
		
	});
	

	fixSavedShoppingListsText();

	/* My work is done here now */
	e.preventDefault();
	return false;
});

/* Send shoppinglist to mail */
$("#handlelisteToMail").live('click', function(e) {
	var loggedInUser = getLoggedInUser();
	if (!loggedInUser) {
		_gaq.push(['_trackEvent', 'Handleliste', 'Send som epost uten innlogging']);
		var text = $("#handlelisteToMail").text();
		$("#handlelisteToMail").parent().html(
				"<div class='mail'>" +
				"<span class='fontFix'>" + text + "</span> " +
				"<span class='small'>(Krever <span class='usercreatebutton'>innlogging</span>)</span>" +
				"</div>"
		);
	} else {
		_gaq.push(['_trackEvent', 'Handleliste', 'Send som epost']);
		sendTheMail();
		if ($(this).siblings().size() == 0) {
			var tmp = $(this); 
			$(this).after(" <span class='small' style='vertical-align: 2px; color: green'>(E-post sendt)</span>");
			setTimeout(function() {
				$(tmp).next().fadeOut(2000, function(){
					$(tmp).next().remove();
				});
			}, 2000);
		
		}
	}	
	e.preventDefault();
	return false;
});

$(".portionsLower").live('click', function() {
	var input = $(this).next();
	var value = $(input).val();
	tmpVar = value;
	value = parseInt(value) - 1;
	$(input).val(value);
	$(input).blur();
});

$(".portionsHigher").live('click', function() {
	var input = $(this).prev();
	var value = $(input).val();
	tmpVar = value;
	value = parseInt(value) + 1;
	$(input).val(value);
	$(input).blur();
});


/* Print */
$("#printShoppinglist").live('click', function() {
	_gaq.push(['_trackPageview', '/print/handleliste']);
	var param1 = allIngredientsToJSON();

	if (supportsLocalStorage()) {
		localStorage.setItem(cookieNamePrint, param1);
	} else {
		$.cookie(cookieNamePrint, param1, {
			expires: cookieTime, 
			path: '/'
		});
	}

	window.open(shoppingListPrintUrl, '_blank', 'height=800, width=600, toolbar=0, location=0, menubar=0, scrollbars=1');
	return false;
});


/* So user can't change input for portions (input should also be disabled) */
$(".recipePortions").live("focus", function(e) {
	tmpVar = $(this).val();
});


$(".recipePortions").live("blur", function(e) {
	var ok = updatePortionsInRecipe($(this).parent().parent().find(".recipeName").text(), $(this).val());
	if (!ok) {
		$(this).val(tmpVar);
	}
});


$(".removeIngredient").live("click", function() {
	var name = $(this).parent().prev().text();
	$(this).parent().parent().remove();
	removeIngredient(name);	
	updateIngredientTable();
	fixOutputTextForIngredints();
	
	
	window.scrollBy(0,1)
	window.scrollBy(0,-1)
});

$("#extraIngredientAdd").live("click", function() {

	/* Validate inputs */
	if (amount = parseFloat($("#extraIngredientAmount").val().replace(',','.'))) {
		if ($("#extraIngredientName").val() == "") {
			$("#extraIngredientName").focus();
			return;
		}
	} else {
		$("#extraIngredientAmount").focus();
		return;
	}

	/* Create new ingredient */
	var ingredient = new Ingredient();
	ingredient.setAmount($("#extraIngredientAmount").val());
	ingredient.setName($("#extraIngredientName").val());
	ingredient.setPrefix($("#extraIngredientPrefix").val());

	/* Add it, save it, print it */
	fullShoppingList.addExtraIngredients(ingredient);
	saveShoppingList(fullShoppingList);
	rewriteIngredientsTable();

	/* User feedback */
	var feedbackString = ingredient.getAmount() + " " + ingredient.getPrefix() + " " + ingredient.getName() + " er lagt til."; 
	$(".addedDiv").text(feedbackString);
	$(".addedDiv").show();
	setTimeout(function() {
		$(".addedDiv").fadeOut(1000);
	}, 4500);

	/* Reset inputs */
	$("#extraIngredientAmount").val("");
	$("#extraIngredientName").val($("#extraIngredientName").attr("title"));
	$("#extraIngredientPrefix").val("");
	$("#extraIngredientAmount").focus();
});

$("#extraIngredientAddNew").live("click", function() {
	var data = $.trim($("#extraIngredient").val());
	data = data.replace("<", "");
	data = data.replace(">", "");
	data = data.replace("=", "");
	if (data == "" || data == $("#extraIngredient").attr("title")) {
		return;
	}
	data = getNewIngredientData(data);

	if ($.trim(data.name) == "") {
		return;
	}
	
	if (data != null) {
		var ingredient = new Ingredient();
		ingredient.setAmount(data.amount);
		ingredient.setPrefix(data.prefix);
		ingredient.setName(data.name);

		/* Add it, save it, print it */
		fullShoppingList.addExtraIngredients(ingredient);
		saveShoppingList(fullShoppingList);
		rewriteIngredientsTable();
		fixOutputTextForIngredints();

		/* User feedback */
		var feedbackString = ingredient.getAmount() + " " + ingredient.getPrefix() + " " + ingredient.getName() + " er lagt til."; 
		$(".addedDiv").text(feedbackString);
		$(".addedDiv").show();
		setTimeout(function() {
			$(".addedDiv").fadeOut(1000);
		}, 3000);

		/* Reset */
		$("#extraIngredient").val($("#extraIngredient").attr("title"));
		$("#extraIngredient").blur();
		$("#extraIngredient").addClass("greyInput");
	}
});



$("#extraIngredientAmount, #extraIngredientName, #extraIngredient").live('focus', function() {
	if ($(this).val() == $(this).attr('title')) {
		$(this).val("");
		$(this).removeClass("greyInput");
	}
});

$("#extraIngredientAmount, #extraIngredientName, #extraIngredient").live('blur', function() {
	if ($.trim($(this).val()) == "") {
		$(this).val($(this).attr("title"));
		$(this).addClass("greyInput");
	}
});

$("#extraIngredientAmount, #extraIngredientName").live('keypress', function(e) {
	var code = (e.keyCode ? e.keyCode : e.which);
	if(code == 13) {
		$("#extraIngredientAdd").click();
	}
});
$("#extraIngredient").live('keypress', function(e) {
	var code = (e.keyCode ? e.keyCode : e.which);
	if(code == 13) {
		$("#extraIngredientAddNew").click();
	}
});

$("span.multipliable select").live('blur click change', function() {
	var href = $("#addAmountToShoopingList").attr('href');
	var lastIndex = href.lastIndexOf(',');
	var tmpHref = href.substring(0, lastIndex);
	var value = $("span.multipliable select").val(); 
	var newHref = tmpHref + "," + value + ")";
	$("#addAmountToShoopingList").attr('href', newHref);
});


/**
 * FUNCTIONS SEARCH
 */

/** 
* Returns the version of Internet Explorer or a -1
* (indicating the use of another browser).
*/
function getInternetExplorerVersion() {
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

function thinking() {
	if (!thinkingFlag) {
		$(".text:not(input)").remove();
		$(".section").remove();
		$(".extra").remove();
		$('.mainColumn').append("<img src='http://webfiles.tine.no/tine.no_v2/images/ajax-loader.gif' alt='Loading...' class='loading' style='display: block;'/>");
		thinkingFlag = true;
	}
}

function addResult(section, results) {
	
	for ( var i = 0; i < $(results).find("result").size(); i++) {
		var result = $(results).find("result:eq("+i+")");
		
		/* Crop title */
		var title = $(result).find("title").text();

		var url = $(result).find("url").text();
		var place = title.lastIndexOf("|");
		if (place != -1) {
			title = title.substring(0, place-1);
		}
		
		/* Create GUI */
		var tmp =
			"<div class='result'>" +
				"<div class='text'>" +
					"<h2><a href='" + url + "'>" + title + "</a></h2>" +
					$(result).find("description").text() +
				"</div>" +
			"</div>";
			
		/* Add in right order */
		if ($(section).find(".result").size() > 0) {
		    $(section).find(".result:last").after(tmp);
		} else {
		    $(section).find(".navigationLinks").after(tmp);
		}
	}
}

function hideAllExcept(notToHide) {
	if (notToHide == "omtine") {
		if ($("#for2").is(":checked")) {
			$("#for2").click();
		}
		if ($("#for3").is(":checked")) {
			$("#for3").click();
		}
		if ($("#for4").is(":checked")) {
			$("#for4").click();
		}
	} else if (notToHide == "ernaring") {
		if ($("#for1").is(":checked")) {
			$("#for1").click();
		}
		if ($("#for3").is(":checked")) {
			$("#for3").click();
		}
		if ($("#for4").is(":checked")) {
			$("#for4").click();
		}
	} else if (notToHide == "oppskrifter") {
		if ($("#for1").is(":checked")) {
			$("#for1").click();
		}
		if ($("#for2").is(":checked")) {
			$("#for2").click();
		}
		if ($("#for4").is(":checked")) {
			$("#for4").click();
		}
	} else if (notToHide == "produkter") {
		if ($("#for1").is(":checked")) {
			$("#for1").click();
		}
		if ($("#for2").is(":checked")) {
			$("#for2").click();
		}
		if ($("#for3").is(":checked")) {
			$("#for3").click();
		}
	}
	
	notToHide == "omtine" ? $("#navigationLinksOmTINE").show() : $("#navigationLinksOmTINE").hide();
	notToHide == "ernaring" ? $("#navigationLinksErnaring").show() : $("#navigationLinksErnaring").hide();
	notToHide == "oppskrifter" ? $("#navigationLinksOppskrifter").show() : $("#navigationLinksOppskrifter").hide();
	notToHide == "produkter" ? $("#navigationLinksProdukter").show() : $("#navigationLinksProdukter").hide();
	
	notToHide == "omtine" ? $(".counterOmTINE").show() : $(".counterOmTINE").hide();
	notToHide == "ernaring" ? $(".counterErnaring").show() : $(".counterErnaring").hide();
	notToHide == "oppskrifter" ? $(".counterOppskrifter").show() : $(".counterOppskrifter").hide();
	notToHide == "produkter" ? $(".counterProdukter").show() : $(".counterProdukter").hide();
	
	
	fixHiddenDivs();
}



function countResults() {
	var numberOfResults = 0;
	$("span.numberOfResults:not(:hidden)").each(function() {
		numberOfResults += parseInt($(this).text());
	});
	$(".totalNumberOfResults").text(numberOfResults);
}


function fixHiddenDivs(){
	
	/* If more than one checkbox is checked */
	if ($("input[type='checkbox']:checked").length > 1) {
		
		/* Hide some stuff */
		$(".result").hide();
		$(".navigationLinks").hide();
		$(".theCounter").hide();
		
		/* Show 2 of everyone */
		$(".section").each(function() {
			$(this).children(".result").slice(0,2).show();
		});
	}
	
	if ($("#for1").is(':checked') ) {
		$("div.searchOmTINE").show();
		$("div.searchOmTINE").next().show();
	} else {
		$("div.searchOmTINE").hide();
		$("div.searchOmTINE").next().hide();
	}

	if ($("#for2").is(':checked') ) {
		$("div.searchErnaring").show();
		$("div.searchErnaring").next().show();
	} else {
		$("div.searchErnaring").hide();
		$("div.searchErnaring").next().hide();
	}

	if ($("#for3").is(':checked') ) {
		$("div.searchOppskrifter").show();
		$("div.searchOppskrifter").next().show();
	} else {
		$("div.searchOppskrifter").hide();
		$("div.searchOppskrifter").next().hide();
	}
	
	if ($("#for4").is(':checked') ) {
		$("div.searchProdukter").show();
		$("div.searchProdukter").next().show();
	} else {
		$("div.searchProdukter").hide();
		$("div.searchProdukter").next().hide();
	}
	countResults();
}


function wsGetResult(link) {
	var returnResult;
	$.ajax({
		type: "GET",
		url: link + "&r=" + Math.random(),
		dataType: "xml",
		async: false,
		success: function(data) {
			returnResult = data;
		},
		error: function(data) {
			alert("connection lost, try again.");
		}
	});
	return returnResult;
}




/**
 * FUNCTIONS PRODUKTKARUELL
 */
/**
 * Setup the 'Forrige' and 'Neste' buttons.
 */
function showAndHideLinksSetup() {
	
	/* Check if we are in the beginning */
	if ($("#logokarusell .product:visible .links a.link:first").is(":visible")) {
		$(".prevProducts").hide();
	} else {
		$(".prevProducts").show();
	}

	/* Check if we are in the end */
	if ($("#logokarusell .product:visible .links a.link:last").is(":visible")) {
		$(".nextProducts").hide();
	} else {
		$(".nextProducts").show();
	}

	if ($(".prevProducts").is(":hidden") && $(".nextProducts").is(":hidden")) {
		$("#logokarusell .product:visible .links div.prevAndNext").hide();
	}
}

/**
 * Show previous / next links to the right in 'logokarusell'
 * 
 * @param page >
 *            0 if next page, else previous page.
 */
function showAndHideLinks(page) {
	var numberOfLinks = ($("#logokarusell .product:visible .links a.link").size());
	var rangeLower;
	var rangeHigher;

	/* If next X link(s) */
	if (page > 0) {

		/* Check so there is more links to show */
		if (numberOfLinks < showNumberOfLinks * multiplier) {
			return;
		}

		/* Calculating range to show */
		rangeLower = showNumberOfLinks * multiplier++;
		rangeHigher = showNumberOfLinks * multiplier;

	} else {

		/* Check so there is more links to show */
		if (multiplier <= 1) {
			return;
		}

		/* Calculating range to show */
		rangeHigher = showNumberOfLinks * --multiplier;
		rangeLower = (showNumberOfLinks * multiplier - showNumberOfLinks);
	}

	/* Show all */
	$("#logokarusell .links a").show();

	/* Remove everything outside the range */
	$("#logokarusell .product:visible .links a.link:lt(" + rangeLower + ")").toggle();
	$("#logokarusell .product:visible .links a.link:gt(" + (rangeHigher - 1) + ")").toggle();

	/* Setup the 'Forrige' and 'Neste' buttons */
	showAndHideLinksSetup();
}



/**
 * FUNCTIONS KOKEBOK
 */
function fixPagingLinks() {
	if ($(".viewTypeThumbs").children().filter(createFilter()).size() < 10) {
		$(".pagingLinks").hide();
	} else {
		$(".pagingLinks").show();
	}
}

function fixSyncedText() {
	var num = "";
	var vars = getUrlVars();
	num = parseInt(vars['synced']);
	
	if (num != "" && num > 0) {
		$("#syncedText").html("Har nå synkronisert " + num + " oppskrifter.").show();
	}
}

function markLatest() {
	var latest = getLatestInUrl();
	if (latest == null || latest == "") {
		return;
	}
	$(".itemKey-" + latest + " a.linkbullet").animate({'backgroundColor': 'yellow'}, 1000).animate({ 'backgroundColor': 'white'}, 1000);
}

function addOwnRecipeKeyAndGoToShoppingList(id, name, hash) {
	var ingredients;
	if (getLoggedInUser()) {
		ingredients = wsGetMyItem(getLoggedInUser().email, id);
	} else {
		alert("Login first 4");
	}
	_gaq.push(['_trackEvent', 'Handleliste', 'Legg til', name + ' (' + hash + ')']);
	addRecipeIngredientsAndGoToShoppingList(ingredients);
	return false;
}

function createFilter() {
	return function() {

		/* First sort out all by category */
		if (pageSettings.section == "my" && !$(this).hasClass("recipe_my")) {
			return false;
		} else if (pageSettings.section == "category" && !$(this).hasClass("recipe_categories")) {
			return false;
		} 

		/* Now sort out all by filter text (Not case sensitive) */
		if ($(this).find("p").text().toLowerCase().indexOf(pageSettings.filterName.toLowerCase()) == -1) {
			return false;
		}

		/* If any subsections selected */
		if(pageSettings.subsection[0] == 'menuKey-alle'){
			return true;
		} else if (pageSettings.subsection.length > 0 && !hasAnyClass($(this), pageSettings.subsection)) {
			return false;
		}

		/* The recipe is OK */
		return true;
	};
}


function hasAnyClass(node, array) {
	for ( var i = 0; i < array.length; i++) {
		var value = array[i];
		if ($(node).is("." + value)) {
			return true;
		}
	}
	return false;
}


function uploadDone() { 
	var xml = "";
	
	/* Need correct xml */
	if (getInternetExplorerVersion() == 8){ 
		var apa = $.trim($("#upload_target").contents().text()).replace(/-/g,"");
		xml = $.parseXML(apa);
	} else {
		xml = $("#upload_target").contents();
	}
	
	/* Get current status */
	var status = $(xml).find("status").text();
	

	/* If no status... we have errors, else everything is ok */
	if (!status) {
	
		/* Get all errors */
		var errors = $(xml).find("error");

		/* If any errors, else 'something' is kidding with us */
		if (errors.length > 0) {

			/* Remove all prev error messages */
			$("span.errorMessage").remove();
			$(".error").removeClass("error");

			/* Let us print all errors */
			for ( var i = 0; i < errors.length; i++) {
				var error = errors[i];
				var type =  $(error).find("name").text();
				var message =  $(error).find("value").text();

				/* Translate message */
				if (message == "length") {
					message = "Du må fylle inn dette feltet";
				} else if (message == "missing") {
					message = "Mangler felt";
				} else if (message == "size") {
					message = "For stort bilde";
				} else if (message == "contenttype") {
					message = "Feil filformat";
				}

				/* Find input where error should be placed */
				if (type == "email") {
					// TODO Some special stuff here I guess.
					alert("Email error, try to login again.");
				} else if (type == "title") {
					var element = $("#kokebokAddRecipeName");
				} else if (type == "category") {
					var element = $("#kokebokAddRecipeCategory");
				} else if (type == "ingredients") {
					var element = $("#kokebokAddRecipeIngredients");
				} else if (type == "description") {
					var element = $("#kokebokAddRecipeDescription");
				} else if (type == "steps") {
					var element = $("#kokebokAddRecipeSteps");
				} else if (type == "image") {
					var element = $("#kokebokAddRecipeImage");
				} else {
					// TODO Error type not added
					alert("An unsupported error has occurred.");
				}
				$(element).parent().prev().children("label").addClass("error");
				if ($(element).next("span").length > 0) {
					$(element).after("<span class='errorMessage'>" + message + ", </span>");
				} else {
					$(element).after("<span class='errorMessage'>" + message + "</span>");
				}
			}
		}
	} else {
		var oldHash = $("#recipeHash").text();
		var hash = $(xml).find("status").attr("hash");
		var url = privateRecipeUrl + "?hash=" + hash + "&r=" + Math.random();

		if (status == "created") {
			_gaq.push(['_trackEvent', 'Kokebok', 'Opprett egen oppskrift']);
			window.location.href = url;
		} else if (status == "updated"){
			_gaq.push(['_trackEvent', 'Kokebok', 'Endre egen oppskrift']);
			updateOwnRecipeInShoppinglist(oldHash, hash);
			window.location.href = url;
		} else {
			alert("none supported status");
		}
	}
}


function createQueryFromIds(array) {
	var returnString = "@key%20IN%20(";
	for ( var i = 0; i < array.length; i++) {
		var key = array[i].recipeid;
		returnString += key;
		if (i != array.length-1) {
			returnString += ",";
		}
	}
	returnString += ")";
	return returnString;
}


function getQueryInUrl(){
	var vars = getUrlVars();
	return vars['query']; 
}

function getLatestInUrl(){
	var vars = getUrlVars();
	return vars['latest']; 
}


function makeMenuActive(div, activate) {

	/* If activate else deactivate button */
	if (activate) {
		$(div).addClass('active');

		/* If element is not the first one */
		if ($(div).prev().length > 0) {
			$(div).prev().addClass('prevActive');
		} else {
			$(div).addClass("firstButton");
		}
	} else {
		$(div).removeClass('active');

		/* If element is not the first one */
		if ($(div).prev().length > 0) {
			$(div).prev().removeClass('prevActive');
		} else {
			$(div).removeClass("firstButton");
		}
	}
}

/* Not in use? */
function getMenuKey(obj) {
	var classes = $(obj).attr("class").split(" ");
	for ( var i = 0; i < classes.length; i++) {
		var theClass = classes[i];
		if (theClass.indexOf('menuKey') != -1) {
			return theClass.substr(8);
		}
	}
	return false;
}
function getItemKey(obj) {
	var classes = $(obj).attr("class").split(" ");
	for ( var i = 0; i < classes.length; i++) {
		var theClass = classes[i];
		if (theClass.indexOf('itemKey') != -1) {
			return theClass.substr(8);
		}
	}
	return false;
}
function getIdFromKey(key) {
	var list;
	if (!getLoggedInUser()) {
		list = cookieListTineItems();
	} else {
		list = wsListTineItems(getLoggedInUser().email);
	}

	for ( var i = 0; i < list.length; i++) {
		var element = list[i];
		if (element.recipeid == key) {
			return element.id;
		}
	}
	return false;
}

function getButton(button) {
	var classes = $(button).attr("class").split(" ");
	return classes[0];
}


function isButtonActive(button) {
	if ($(button).hasClass("active")) {
		return true;
	}
	return false;
}


function makeActive(buttonName) {
	var images = $("#kokebok div.labels img."+buttonName);

	$("#kokebok div.labels img.active:visible").prev().show();
	$("#kokebok div.labels img.active:visible").hide();
	$(images[0]).next().show();
	$(images[0]).hide();


	$("#kokbokRecipes").find("li").hide();
	if (buttonName == "mine") {
		$("#kokbokRecipes").find(".recipe_my").show();
	} else if (buttonName == "kategorier") {
		$("#kokbokRecipes").find(".recipe_categories").show();
	} else {
		$("#kokbokRecipes").find(".recipe_my").show();
		$("#kokbokRecipes").find(".recipe_categories").show();
	}
}


function fixDates() {

	// 14.03.2011 14:23:50 ---> 2011-03-14 14:23:50
	$("#kokbokRecipes").find(".created").each(function() {
		var orginalDate = $(this).text();
		var day 	= orginalDate.substr(0,2);
		var month 	= orginalDate.substr(3,2);
		var year	= orginalDate.substr(6,4);
		var time	= orginalDate.substr(11,8);
		var newDate	= year + "-" + month + "-" + day + " " + time;
		$(this).text(newDate);
	});
}


function fixSorting() {
	var sortOn = $("#kokebokSort").val();

	var newOrder;
	if (sortOn == "alphabetic") {
		newOrder = $("#kokbokRecipes ul li").sort(recipeSortingByName);
	} else {
		newOrder = $("#kokbokRecipes ul li").sort(recipeSortingByDate);
	}

	$("#kokbokRecipes ul li").remove();
	$("#kokbokRecipes ul").append(newOrder);
}

function recipeSortingByDate(a, b) {
	var aText = $(a).find(".created").text().toLowerCase(); 
	var bText = $(b).find(".created").text().toLowerCase();

	if (aText < bText) {
		return 1;
	}
	else if (aText > bText) {
		return -1;
	}
	return 0;
}

function recipeSortingByName(a, b) {
	var aText = $(a).find(".title").text().toLowerCase(); 
	var bText = $(b).find(".title").text().toLowerCase();

	if (aText < bText) {
		return -1;
	}
	else if (aText > bText) {
		return 1;
	}
	return 0;
}


function fixLayout() {

	if ($("#kokebok ul li").size() <= 0) {
	
		if($(".noIngridientsInList").size() <= 0) {
			if (!getLoggedInUser()) {
				$("#kokbokRecipes").append(noOppskrifterInListLoggedOut);
			} else {
				$("#kokbokRecipes").append(noOppskrifterInListLoggedIn);
			}
		}
	} else {
		$(".noIngridientsInList").remove();
	}

	/*if (onlyVisible) {
		$("#kokebok ul li.removeMargin").removeClass("removeMargin");
		//$("#kokebok ul li:gt(" + (itemsPerPage-1) + ")").hide();
		$('#kokebok ul li:visible').each(function (i) {
			if ((i+1) % 3 == 0) $(this).addClass("removeMargin");   
		});
		
		
	} else {
		$("#kokebok ul li.removeMargin").removeClass("removeMargin");
		//$("#kokebok ul li:gt(" + (itemsPerPage-1) + ")").hide();
		$('#kokebok ul li').each(function (i) {
			if ((i+1) % 3 == 0) $(this).addClass("removeMargin");   
		});
	}*/
}



function showAddRecipe() {

	_gaq.push(['_trackEvent', 'Kokebok', 'Klikk Opprett egen oppskrift']);
	
	// Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	// Set heigth and width to mask to fill up the whole screen
	$('#addRecipeBoxMask').css({'width':maskWidth,'height':maskHeight});

	// Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();

	// Set the popup window to center
	$('#addRecipeBox').css('top',  winH/2-$('#addRecipeBox').height()/2);
	$('#addRecipeBox').css('left', winW/2-$('#addRecipeBox').width()/2);

	$('#addRecipeBoxMask').show();
	$('#addRecipeBox').show();

	$('#addRecipeBoxMask').bind('click', function() {
		$("#addRecipeBoxMask").hide();
		$("#addRecipeBox").hide();
	});

	var url = '/system-pages/kokebok-oppskrift-leggtil';

	$('#addRecipeBox').load(url, function() {
		Cufon.replace('h1,h2');
	});
}

function showEditRecipe(loaded) {
	// Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	// Set heigth and width to mask to fill up the whole screen
	$('#addRecipeBoxMask').css({'width':maskWidth,'height':maskHeight});

	// Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();

	// Set the popup window to center
	$('#addRecipeBox').css('top',  winH/2-$('#addRecipeBox').height()/2);
	$('#addRecipeBox').css('left', winW/2-$('#addRecipeBox').width()/2);

	$('#addRecipeBoxMask').show();
	$('#addRecipeBox').show();

	$('#addRecipeBoxMask').bind('click', function() {
		$("#addRecipeBoxMask").hide();
		$("#addRecipeBox").hide();
	});

	var url = '/system-pages/kokebok-oppskrift-leggtil';

	$('#addRecipeBox').load(url, function() {
		loaded();
		Cufon.replace('h1,h2');
	});
}

function addToKokebokAndGoToKokebok(key, name) {
	var recipeIds;

	/* Sync */
	syncCookieAndDb(true);

	/* Cookie or websevice? */
	if (!getLoggedInUser()) {
		cookieAddTineItem(key, null);
		recipeIds = cookieListTineItems();
	} else {
		wsAddTineItem(getLoggedInUser().email, key);
		cookieAddTineItem(key, null);
		recipeIds = wsListTineItems(getLoggedInUser().email);
	}
	var queryCorrect 	= createQueryFromIds(recipeIds);
	_gaq.push(['_trackEvent', 'Kokebok', 'Legg til', name + ' (' + key +')']);

	/* Checking so url matches rest service */
	window.location.href = kokebokUrl + "?query=" + queryCorrect + "&latest=" + key;
	return false;
}

function addToKokebok(key) {
	if (!getLoggedInUser()) {
		cookieAddTineItem(key, null);
	} else {
		wsAddTineItem(getLoggedInUser().email, key);
		cookieAddTineItem(key, null);
	}
	$("#addToKokebok").after(kokebokAddedText);
}


function cookieListTineItems() {
	var returnArray = new Array();
	if (supportsLocalStorage()) {
		var items = localStorage.getItem(cookieNameKokebok);
		items = JSON.parse(items);
		if (items != null) {
			returnArray = items;
		}
	} else {
		var items = $.cookie(cookieNameKokebok);
		items = JSON.parse(items);
		if (items != null) {
			returnArray = items;
		}
	}
	return returnArray;
}
function wsListTineItems(email) {
	var returnArray = new Array();
	var token = getUserToken();
	var dataInput = {
			"token" : token,
			"r" : Math.random()
	};
	$.ajax({
		type: "GET",
		url: wsListTineUrl + "/" + email + "/",
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(data) {
			$(data).find("cookbook").each(function() {
				var cookbook = {
						id 	: $(this).find("id").text(),
						recipeid 	: $(this).find("recipeid").text(),
						created 	: $(this).find("created").text()
				};
				returnArray.push(cookbook);
			});
		}
	});
	return returnArray;
}





function cookieDeleteTineItem(id) {
	if (supportsLocalStorage()) {
		var items = localStorage.getItem(cookieNameKokebok);
		items = JSON.parse(items);
		if (items != null) {
			for ( var i = 0; i < items.length; i++) {
				var item = items[i];
				if (item.id == id) {
					items.splice(i,1);
					break;
				}
			}
		}
		localStorage.setItem(cookieNameKokebok, JSON.stringify(items));
	} else {
		var items = $.cookie(cookieNameKokebok);
		items = JSON.parse(items);
		if (items != null) {
			for ( var i = 0; i < items.length; i++) {
				var item = items[i];
				if (item.id == id) {
					items.splice(i,1);
					break;
				}
			}
		}
		$.cookie(cookieNameKokebok, JSON.stringify(items), {
			expires: cookieTime, 
			path: '/'
		});
	}
}
function wsDeleteTineItem(email, id) {
	var token = getUserToken();
	var dataInput = {
			"token" : token
	};
	$.ajax({
		type: "POST",
		async: false,
		url: wsListTineUrl + "/remove/" + email + "/" + id + "/",
		data : dataInput,
		success: function(data) {},
		error: function(error) {}
	});
}




function cookieAddTineItem(recipeid, id) {
	var items = cookieListTineItems();
	var last = items[items.length-1];
	if (last == null) {
		lastId = 0;
	} else {
		lastId = last.id;
	}
	if (lastId == null || lastId == "") {
		lastId = 0;
	}

	// Add check if exists.
	for ( var i = 0; i < items.length; i++) {
		var item = items[i];
		if (item.recipeid == recipeid) {
			return false;
		}
	}

	var item = {
			"id" 		: id != null ? id : parseInt(lastId+1),
					"recipeid" 	: recipeid, 
					"created" 	: "" // TODO
	};

	if (supportsLocalStorage()) {
		var items = localStorage.getItem(cookieNameKokebok);
		items = JSON.parse(items);
		if (items == null) {
			items = new Array();
		}
		items.push(item);
		localStorage.setItem(cookieNameKokebok, JSON.stringify(items));
	} else {
		var items = $.cookie(cookieNameKokebok);
		items = JSON.parse(items);
		if (items == null) {
			items = new Array();
		}
		items.push(item);
		$.cookie(cookieNameKokebok, JSON.stringify(items), {
			expires: cookieTime, 
			path: '/'
		});
	}

}
function wsAddTineItem(email, id) {
	var token = getUserToken();
	var dataInput = {
			"token" : token,
			"recipeid" : id
	};
	$.ajax({
		type: "POST",
		async: false,
		url: wsListTineUrl + "/" + email + "/",
		data : dataInput,
		success: function(data) {},
		error: function(error) {}
	});
}



function wsDeleteMyItem(email, id) {
	var token = getUserToken();
	var dataInput = {
			"token" : token
	};
	$.ajax({
		type: "POST",
		async: false,
		url: wsListMyUrl + "/remove/" + email + "/" + id + "/?r=" + Math.random(),
		data : dataInput,
		success: function(data) {},
		error: function(error) {}
	});
}




function wsListMyItems(email) {
	var returnArray = new Array();
	var token = getUserToken();
	var dataInput = {
			"token" : token
	};
	$.ajax({
		type: "GET",
		url: wsListMyUrl + "/" + email + "/?r=" + Math.random(),
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(data) {
			$(data).find("recipe").each(function() {
				var recipe = {
						id : 			$(this).find("id").text(),
						hash : 			$(this).find("hash").text(),
						image : 			$(this).find("imagehash").text(),
						email : 		$(this).find("email").text(),
						title : 		$(this).find("title").text(),
						ingredients : 	$(this).find("ingredients").text(),
						category : 		$(this).find("category").text(),
						description : 	$(this).find("description").text(),
						steps :		 	$(this).find("steps").text(),
						created :	 	$(this).find("created").text(),
						updated :	 	$(this).find("updated").text()
				};
				returnArray.push(recipe);
			});
		}
	});
	return returnArray;
}





function wsGetMyItem(email, key) {
	var returnData;
	var token = getUserToken();
	var dataInput = {
			"token" : token
	};
	$.ajax({
		type: "GET",
		url: wsListMyUrl + "/" + email + "/" + key + "/?r=" + Math.random(),
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(data) {
			returnData = {
					"hash"			: $(data).find("hash").text(),
					"image"			: $(data).find("imagehash").text(),
					"title"			: $(data).find("title").text(),
					"ingredients" 	: $(data).find("ingredients").text()
			};
		}
	});
	return returnData;
}

function wsGetItem(hash) {
	var returnData;
	
	$.ajax({
		type: "GET",
		url: wsListMyUrl + "/hash/" + hash+ "?r=" + Math.random(),
		dataType: "xml",
		async: false,
		success: function(data) {
			returnData = {
					"hash"			: $(data).find("hash").text(),
					"image"			: $(data).find("imagehash").text(),
					"title"			: $(data).find("title").text(),
					"ingredients" 	: $(data).find("ingredients").text()
			};
		}
	});
	return returnData;
}

function syncCookieAndDb(setCookie) {

	/* Security */
	if (supportsSessionStorage()) {
		var synced = sessionStorage.getItem(cookieNameKokebokSynced);
		if (synced && synced == "true") {
			return;
		}
	} else {
		var synced = $.cookie(cookieNameKokebokSynced);
		if (synced && synced == "true") {
			return;
		}
	}

	/* Security */
	var loggedInUser = getLoggedInUser();
	if (!loggedInUser) {
		return false;
	}

	var listDb = wsListTineItems(loggedInUser.email);
	
	/* Add all to db */
	var listCookie = cookieListTineItems();
	for ( var i = 0; i < listCookie.length; i++) {
		var item = listCookie[i];
		
		/* Check befor adding */
		if(item && item!= undefined && !idInList(item.recipeid, listDb)){
			wsAddTineItem(loggedInUser.email, item.recipeid);
		}
	}
	var listDbAfter = wsListTineItems(loggedInUser.email);
	var diffOne = listDbAfter.length - listDb.length;
	
	/* Clear cookie */
	if (supportsLocalStorage()) {
		localStorage.removeItem(cookieNameKokebok);
	} else {
		$.cookie(cookieNameKokebok, null, {path: '/'});
	}

	/* Create new cookie from db */
	for ( var i = 0; i < listDbAfter.length; i++) {
		var item = listDb[i];
		if (item && item!= undefined) {
			cookieAddTineItem(item.recipeid, item.id);
		}
	}
	var listCookieAfter = cookieListTineItems();
	var diffTwo = listCookieAfter.length - listCookie.length;
	//var diffThree = wsListMyItems(loggedInUser.email).length;
	
	/* Set cookie */
	if (setCookie) {
		if (supportsSessionStorage()) {
			sessionStorage.setItem(cookieNameKokebokSynced, "true");
		} else {
			$.cookie(cookieNameKokebokSynced, "true");
		}
	}
	
	return diffOne + diffTwo;
}

function idInList(id, list) {
	for ( var i = 0; i < list.length; i++) {
		var val = list[i];
		if (id == val.recipeId) {
			return true;
		}
	}
	return false;
}



/**
 * FUNCTIONS SHOPPINGLIST
 */
function sendTheMail() {
	var message = "<h2>Varer</h2>";
	message += "<table>";

	var ingredients = fullShoppingList.getAllNoneDeletedIngredients();
	var ownRecipes = fullShoppingList.getAllOwnRecipes();
	var recipes = fullShoppingList.getRecipes();
	
	/* Security */
	if (ingredients.length == 0 && ownRecipes.length == 0 && recipes.length == 0) {
		return;
	}
	
	/* Sort them */
	ingredientsSort(ingredients);
	
	/* Ingredients */	
	if (ingredients != null) {
		for ( var i = 0; i < ingredients.length; i++) {
			var ingredient = ingredients[i];
			message = addIngredientToMessage(message, ingredient.getAmount(), ingredient.getPrintoutPrefix(), ingredient.getName());
		}
	}

	message += "</table>";
	
	/* Safty */
	if (ownRecipes.length != 0 || recipes.length != 0) {
		
		message += "<br /><br />";
		message += "<h2>Oppskrifter</h2>";
		message += "<table>";

		/* Own Recipes */
		for (var i = 0; i < ownRecipes.length; i++) {
			var recipe = ownRecipes[i];
			var name = recipe.getName();
			var url = "http://www.tine.no/oppskrifter/min-kokebok/oppskrift?hash=" + recipe.getKey();
			message = addRecipeToMessage(message, name, url);
		}
		
		/* Tine Recipes */	
		var dataInput = {
				"key" : fullShoppingList.getQuery()
		};

		$.ajax({
			type: "POST",
			url: urlSendMail + "?r=" + Math.random(),
			data : dataInput,
			dataType: "xml",
			async: false,
			success: function(dataResult) {
				$(dataResult).find("recipe").each(function() {
					message = addRecipeToMessage(message, $(this).find("name").text(), $(this).find("url").text());
				});
			}
		});
		message += "</table>";
	}
	
	var loggedInUser = getLoggedInUser();
	var mail = loggedInUser.email;
	sendToMail(mail, message);
	
}

function addRecipeToMessage(message, name, link) {
	var row = 
		"<tr>" +
			"<td style='padding-top: 2px;'><a href='" + $.trim(link) + "'>" + $.trim(name) + "</a></td>" +
		"</tr>";
	message += row;
	return message;
}


function addIngredientToMessage(message, amount, prefix, name) {
	if($.trim(prefix) == '') {
		prefix = "stykk";
	}
	var row = 
		"<tr>" +
			"<td style='padding-top: 2px;'>" + (amount == 0 ? '' : amount) + " " + (amount == 0 ? '' : prefix)+ "</td>" +
			"<td style='padding-top: 2px; padding-left: 7px;'>" + name + "</td>" +
		"</tr>";
	message += row;
	return message;
}




function fixSavedShoppingListsText() {
	if ($("#savedShoppingLists li").size() <= 0) {
		if ($(".noSavedShoppingLists").size() == 0) {
			$("#savedShoppingLists").after("<div class='noSavedShoppingLists'>Ingen lagrede handlelister</div>");
		} else {
			$(".noSavedShoppingLists").show();
		}
	} else {
		$(".noSavedShoppingLists").hide();
	}
}


function getCurrentShoppingList() {
	var name = "";
	if (supportsLocalStorage()) {
		var currentShoppingList = localStorage.getItem(cookieNameCurrent);
		if (currentShoppingList != null) {
			name = currentShoppingList;
		}
	} else {
		var currentShoppingList = $.cookie(cookieNameCurrent);
		if (currentShoppingList != null) {
			name = currentShoppingList;
		}
	}
	return name;
}

function setCurrentShoppingList(name) {
	if (supportsLocalStorage()) {
		localStorage.setItem(cookieNameCurrent, name);
	} else {
		$.cookie(cookieNameCurrent, name, {
			expires: cookieTime, 
			path: '/'
		});
	}
	return name;
}

function fixSaveShoppingList() {
	var loggedInUser = getLoggedInUser();
	if(loggedInUser != null && loggedInUser != false) {
		$("#saveShoppingList").text("Lagre handleliste [" + wsGetShoppingListCollectionByEmail(loggedInUser.email).length + "]");
	}
}

function updateOwnRecipeInShoppinglist(oldHash, newHash) {
	var shoppingList = getShoppingList();
	shoppingList.updateOwnRecipe(oldHash, newHash);
	saveShoppingList(shoppingList);
}


function keysAreSame(keys1, keys2) {
	if (keys1.length != keys2.length) {
		return false;
	}
	for ( var i = 0; i < keys1.length; i++) {
		var key = keys1[i];
		if (keys2.indexOf(key) == -1) {
			return false;
		}
	}
	return true;
}

function getNewIngredientData(data) {

	/* Return values */
	var returnValue = {
			"amount" 	: "",
			"prefix" 	: "",
			"name" 		: ""
	};

	/* Regexps */
	var regExpAmount = /(^\d+\s\d+[,\.\/]\d+)|(^\d+[,\.\/]\d+)|(^\d+)/;	

	/* Amount */
	var amount = "";
	amount = data.match(regExpAmount);

	/* If no amount found, else */
	if (!amount) {
		returnValue.amount = "1";
		returnValue.prefix = "stykk";
		returnValue.name = data;
	} else {

		/* Set amount value */
		returnValue.amount = amount[0];

		/* Prefix */
		var regExpPrefix = new RegExp(amount[0] + "\\s?(\\w+)");
		var prefix = data.match(regExpPrefix);

		/* If prefix found via regexp AND it's accepted by cms, else */
		if (prefix && (orginalPrefix.indexOf(prefix[1]) != -1 || printoutPrefix.indexOf(prefix[1]) != -1)) {

			/* Find correct prefix and set it */
			if (orginalPrefix.indexOf(prefix[1]) == -1) {
				returnValue.prefix = orginalPrefix[printoutPrefix.indexOf(prefix[1])];
			} else {
				returnValue.prefix = prefix[1];
			}

			/* Find rest of the data as name */
			var regExpName = new RegExp(amount[0] + "\\s?" + prefix[1] + "\\s+(.*)");
			var name = data.match(regExpName);
			returnValue.name = name[1];
		} else {

			/* Find rest of the data as name */
			var regExpName = new RegExp(amount[0] + "\\s?(.*)");
			var name = data.match(regExpName);
			returnValue.prefix = "stykk";
			returnValue.name = name[1];
		}

	}

	/* Set amount correct */
	returnValue.amount = getAsDecimal(returnValue.amount); 

	/* Return it all */
	return returnValue;
}

function getAsDecimal(value) {
	value = value.replace(" ","+"); 
	if (value.indexOf(",") != -1) {
		value = value.replace(",","."); 
	}
	return eval(value);
}


function fixPortionPrintout() {
	$(".recipePortions").each(function() {
		var recipePortion = fullShoppingList.getRecipePortion($(this).parent().parent().find(".recipeName").text());
		$(this).val(recipePortion.getNewPortions());
	});
}

function updatePortionsInRecipe(recipeName, newPortions) {
	var recipePortion = fullShoppingList.getRecipePortion(recipeName);

	/* Safty */
	if (!recipePortion.getMultible()) {
		return false;
	}

	/* Safty */
	newPortions = parseInt(newPortions);
	if (newPortions <= 0 || newPortions >= 100) {
		return false;
	}

	// Berækna ut ny amount
	recipePortion.setNewPortions(newPortions);

	// Skriv ut uppdaterad tabell
	rewriteIngredientsTable();

	// Sett reverse value = new portions
	recipePortion.setReverseValue(recipePortion.getNewPortions());

	// Spara
	saveShoppingList(fullShoppingList);
	
	var recipie = fullShoppingList.getRecipe(recipeName);
	var key = recipie.key;
	_gaq.push(['_trackEvent', 'Handleliste', 'Endre antall porsjoner', recipeName +  ' (' + key + ')']);

	return true;
}

function fixRoundedCorner() {
	$("#handlelisteOppskrifterDiv div.row:first div:first img").wrap(function() {

		/* No need for many spans */
		if ($(this).parent().is("span")) {
			return;
		}

		/* Add rounded corner span */
		if ($(this).height() > 0 && $(this).width() > 0) {
			return '<span style="background-image:url(' + $(this).attr('src') + '); height: '+ $(this).height() + 'px; width: '+ $(this).width() + 'px;" class="roundedTopLeft" />';
		} else if ($(this).height() > 0) {
			return '<span style="background-image:url(' + $(this).attr('src') + '); height: '+ $(this).height() + 'px;" class="roundedTopLeft" />';
		} else if ($(this).width() > 0) {
			return '<span style="background-image:url(' + $(this).attr('src') + '); width: '+ $(this).width() + 'px;" class="roundedTopLeft" />';
		} else {
			return '<span style="background-image:url(' + $(this).attr('src') + ');" class="roundedTopLeft" />';
		}
	});
}

function rewriteIngredientsTable() {
	printAllIngredientsToTable(false);
	setupTableClasses();
}

function ingredientsSort(ingredients) {
	ingredients.sort(sortIngredients);

	/* For all ingredients */
	for ( var i = 0; i < ingredients.length; i++) {
		var ing1 = ingredients[i];

		/* Match it with all other ingredients AFTER in the array */
		for ( var j = i+1; j < ingredients.length;) {

			/* Security */
			if (j >= ingredients.length) {
				break;
			}
			var ing2 = ingredients[j];

			/* If they have the same name */
			if (ing1.getName().toLowerCase() == ing2.getName().toLowerCase()){

				/* And same prefix */
				if (ing1.getPrefix() == ing2.getPrefix()) {

					/* Add it to a total in the first one */
					ing1.setAmount(parseFloat(ing1.getAmount()) + parseFloat(ing2.getAmount()));

					/* Remove the last one */
					ingredients.splice(j, 1);
					continue;
				} 

				/* Or can we do something with the prefixes so they will be merged? */
				else {
					var convert1 = shouldBeConverted(ing1.getAmount(), ing1.getPrefix());
					var convert2 = shouldBeConverted(ing2.getAmount(), ing2.getPrefix());

					/* If both can be converted */
					if (convert1.convert && convert2.convert) {

						/* And same prefix */
						if (convert1.prefix == convert2.prefix) {

							/* Add it to a total in the first one */
							ing1.setAmount(parseFloat(convert1.amount) + parseFloat(convert2.amount));
							ing1.setPrefix(convert1.prefix);

							/* Remove the last one */
							ingredients.splice(j, 1);
							continue;
						}

					} else if (convert1.convert) {

						/* And same prefix */
						if (convert1.prefix == ing2.getPrefix()) {

							/* Add it to a total in the first one */
							ing1.setAmount(parseFloat(convert1.amount) + parseFloat(ing2.getAmount()));
							ing1.setPrefix(convert1.prefix);

							/* Remove the last one */
							ingredients.splice(j, 1);
							continue;
						} 
					} else if (convert2.convert) {

						/* And same prefix */
						if (convert2.prefix == ing1.getPrefix()) {

							/* Add it to a total in the first one */
							ing1.setAmount(parseFloat(convert2.amount) + parseFloat(ing1.getAmount()));

							/* Remove the last one */
							ingredients.splice(j, 1);
							continue;
						} 
					}
				}
			}
			j++;	
		}

		var conv = shouldBeConverted(ing1.getAmount(), ing1.getPrefix());
		if (conv.convert) {
			ing1.setAmount(conv.amount);
			ing1.setPrefix(conv.prefix);
		}
	}
}

/**
 * Tells if anything should be converted to somerhing other.
 * 
 * @param amount
 * @param prefix
 * @returns {obj}
 */
function shouldBeConverted(amount, prefix) {
	var returnArray = {
			"convert" 	: false,
			"amount"	: 0,
			"prefix"	: ''
	};

	/* Volym inc */
	if (prefix == 'milliliter' && amount >= 10) {
		returnArray.prefix = 'centiliter';
		returnArray.amount = amount / 10;
	} 
	if (prefix == 'centiliter' && amount >= 10) {
		returnArray.prefix = 'desiliter';
		returnArray.amount = amount / 10;
	} 
	if (prefix == 'desiliter' && amount >= 10) {
		returnArray.prefix = 'liter';
		returnArray.amount = amount / 10;
	} 

	/* Weight inc */
	if (prefix == 'mikrogram' && amount >= 1000) {
		returnArray.prefix = 'milligram';
		returnArray.amount = amount / 1000;
	} 
	if (prefix == 'milligram' && amount >= 1000) {
		returnArray.prefix = 'gram';
		returnArray.amount = amount / 1000;
	} 
	if (prefix == 'gram' && amount >= 100) {
		returnArray.prefix = 'hektogram';
		returnArray.amount = amount / 100;
	} 
	if (prefix == 'hektogram' && amount >= 10) {
		returnArray.prefix = 'kilogram';
		returnArray.amount = amount / 10;
	} 


	/* Volym dec */
	if (prefix == 'liter' && amount < 1) {
		returnArray.prefix = 'desiliter';
		returnArray.amount = amount * 10;
	} 
	/*if (prefix == 'desiliter' && amount < 1) {
		returnArray.prefix = 'centiliter';
		returnArray.amount = amount * 10;
	} */
	
	if (prefix == 'centiliter' && amount < 1) {
		returnArray.prefix = 'milliliter';
		returnArray.amount = amount * 10;
	} 

	/* Weight dec */
	if (prefix == 'kilogram' && amount < 1) {
		returnArray.prefix = 'hektogram';
		returnArray.amount = amount * 10;
	} 
	if (prefix == 'hektogram' && amount < 1) {
		returnArray.prefix = 'gram';
		returnArray.amount = amount * 100;
	} 
	if (prefix == 'gram' && amount < 1) {
		returnArray.prefix = 'milligram';
		returnArray.amount = amount * 1000;
	} 
	if (prefix == 'milligram' && amount < 1) {
		returnArray.prefix = 'mikrogram';
		returnArray.amount = amount * 1000;
	} 

	if (prefix == '') {
		returnArray.amount = amount;
		returnArray.prefix = 'stykk';
	}

	if (returnArray.amount != 0) {
		returnArray.convert = true;
	}

	return returnArray;
}

function printOwnRecipesToTable() {

	/* Check if table is created */
	if (fullShoppingList.getRecipeKeys() <= 0) {
		var html = 
			"<div id='handleListePortions'>porsjoner</div>" +
			"<div class='handleListeTitle'>Oppskrifter p&#229; din handleliste</div>" +
			"<div id='handlelisteOppskrifterDiv' class='tableStyle shadow440' style='display: none;'></div>";
		$("#jsSetup").before(html);
	}

	/* Get all recipes */
	var recipes = fullShoppingList.getAllOwnRecipes();

	/* Print them */
	for ( var i = 0; i < recipes.length; i++) {
		var recipe = recipes[i];
		var test = wsGetItem(recipe.getKey());
		if (test.hash != recipe.getKey()){
			removeRecipe(recipe.getKey());
			continue;
		}
		var html = 
			"<div>" +
				"<div><img src='http://www.tine.no/imageresize/recipe/" + test.image + "/64_35.jpg' alt='" + recipe.getName() + "' /></div>" +
				"<div>" +
				"<a href='" + urlKokebok + "/oppskrift?hash=" + recipe.getKey() + "' class='arrow recipeName'>" + recipe.getName() + "</a>" +
				"<xsl:text> </xsl:text>" +
				"<div class='recipePortionsDiv'></div>" +
				"</div>" +
				"<div><a href='javascript:void(0);' onclick='removeRecipeInDesign(\"" + recipe.getKey() + "\", \"" + recipe.getName() + "\", this);' class='slet'>Slett</a></div>" +
			"</div>";
		$("#handlelisteOppskrifterDiv").append(html);
	}
}


function printAllIngredientsToTable(firstTime) {

	/* Removes old stuff */
	var oldRows = $("#handlelisteVarerDiv").children().remove();

	/* Get all none deleted ingredients */
	var allIngredients = fullShoppingList.getAllNoneDeletedIngredients();

	/* Add them to a new array (cloning) */
	var printedIngredients = new Array();
	for ( var i = 0; i < allIngredients.length; i++) {
		var ingredient = allIngredients[i];
		var tmpIngredient = new Ingredient();
		tmpIngredient.setAmount(ingredient.getAmount());
		tmpIngredient.setName(ingredient.getName());
		tmpIngredient.setPrefix(ingredient.getPrefix());
		printedIngredients.push(tmpIngredient);
	}

	/* Sort the clone, don't want to edit the original array */
	ingredientsSort(printedIngredients);

	/* Print the clone */
	for ( var int = 0; int < printedIngredients.length; int++) {
		var ingredient = printedIngredients[int];
		addIngredientToTable(ingredient, oldRows, firstTime);
	};
}

function allIngredientsToJSON() {

	/* Get all none deleted ingredients */
	var allIngredients = fullShoppingList.getAllNoneDeletedIngredients();

	/* Add them to a new array (cloning) */
	var printedIngredients = new Array();
	for ( var i = 0; i < allIngredients.length; i++) {
		var ingredient = allIngredients[i];
		var tmpIngredient = new Ingredient();
		tmpIngredient.setAmount(ingredient.getAmount());
		tmpIngredient.setName(ingredient.getName());
		tmpIngredient.setPrefix(ingredient.getPrefix());
		printedIngredients.push(tmpIngredient);
	}

	/* Sort the clone, don't want to edit the original array */
	ingredientsSort(printedIngredients);

	/* Create json */
	var jsonObj = JSON.stringify(printedIngredients);

	/* Return to base commander */
	return jsonObj;
}


function sortIngredients(a, b) {
	if (a.getName().toLowerCase() < b.getName().toLowerCase()) {
		return -1;
	}
	else if (a.getName().toLowerCase() > b.getName().toLowerCase()) {
		return 1;
	}
	return 0;
}


function removeIngredient(name) {
	fullShoppingList.removeIngredient(name);
	saveShoppingList(fullShoppingList);
}


function addIngredientToTable(ingredient, oldTable, firstTime) {
	var style = "";
	if (!firstTime && isIngredientUpdated(ingredient, oldTable)) {
		style = "style='background-color: lightgreen;'";
	}
	//$('<span>').text(ingredient.getName()).html()
	var name = ingredient.getName(); //.replace("<", "&lt;");
	//name = name.replace(">", "&gt;");

	var valuetext = "" + ingredient.getAmount();

	if(ingredient.getAmount() == 0.5) {
			valuetext = '½';
	}

	if(ingredient.getAmount() == 0.33) {
			valuetext = '⅓';
	}

	if(ingredient.getAmount() == 0.75) {
			valuetext = '¾';
	}

	if(ingredient.getAmount() == 0.25) {
			valuetext = '¼';
	}

	if(ingredient.getAmount() == 0) {
			valuetext = '';
	}

	valuetext = valuetext.replace('.25',' ¼');
	valuetext = valuetext.replace('.5',' ½');
	valuetext = valuetext.replace('.75',' ¾');
	valuetext = valuetext.replace('.33',' ⅓');

	var recipeDiv = (
			"<div>" +
			"<div " + style + ">" + valuetext + " " + ingredient.getPrintoutPrefix() + "</div>" + 
			"<div " + style + ">" + name + "</div>" + 
			"<div " + style + "><a href='javascript:void(0);' class='slet removeIngredient'>Slett</a></div>" + 
			"</div>"
	);
	$("#handlelisteVarerDiv").append(recipeDiv);
}

function isIngredientUpdated(ingredient, oldTable) {
	var returnValue = false;
	var ingredientNames = new Array();
	var ingredientNamesWithPrefix = new Array();
	var regExpAmount 	= /^\d+(\.\d+)?/g;
	var regExpPrefix 	= /\s[a-zåæøA-ZÅÆØ ]*/g;

	/* Compare with all ingredient rows */
	$(oldTable).each(function() {
		var name = $(this).find(".middle").text();

		/* Add to array for later use */
		ingredientNames.push(name);

		/* If ingredients name is the same as the one on the row */
		if (name == ingredient.getName()) {

			/* Get data */
			var amount = $(this).find(".first").text().match(regExpAmount);
			var prefix = $(this).find(".first").text().match(regExpPrefix);
			prefix = $.trim(prefix);

			/* Save with prefix */
			var tmpValue = {
					"name": $.trim(name),
					"prefix": $.trim(prefix)
			};
			ingredientNamesWithPrefix.push(tmpValue);

			/* And if same prefix */
			if (prefix == ingredient.getPrintoutPrefix() || prefix == ingredient.getPrefix()) {

				/* And if the value has changed */
				if (amount != null && amount.length != null && amount.length > 0 && amount[0] != ingredient.getAmount()) {
					returnValue = true;
				} 
				return;
			}
		}
	});

	/* If updated, return true */
	if (returnValue) {
		return true;
	}

	/* If totaly new one */
	if (ingredientNames.indexOf(ingredient.getName()) == -1) {
		return true;
	} 

	/* If new one with just new prefix */
	var inListFlag = false;
	for ( var i = 0; i < ingredientNamesWithPrefix.length; i++) {
		var tmp = ingredientNamesWithPrefix[i];

		if ($.trim(ingredient.getName()) == tmp.name && ($.trim(ingredient.getPrefix()) == tmp.prefix || $.trim(ingredient.getPrintoutPrefix()) == tmp.prefix)) {
			inListFlag = true;
			break;
		}
	}
	return !inListFlag;
}


function setupTableClasses() {
	$("div.tableStyle > div").addClass("row");
	$("div.tableStyle > div > div:nth-child(1)").addClass("first");
	$("div.tableStyle > div > div:nth-child(2)").addClass("middle");
	$("div.tableStyle > div > div:nth-child(3)").addClass("last");
	$("div.tableStyle > div > div:nth-child(1) > img").addClass("rounded2");

	// TODO fix IE bug with rounded corners in 'table'.
	if (navigator.userAgent.indexOf('MSIE') ==-1) {
		$("div.tableStyle *").removeClass("rounded_top_left").removeClass("rounded_buttom_right");
		$("div.tableStyle > div:nth-child(1) > div:nth-child(1)").addClass("rounded_top_left");
		$("div.tableStyle > div:last-child > div:last-child").addClass("rounded_buttom_right");
	}
	updateRecipeTable();
	updateIngredientTable();
}


function clearCookie() {

	/* If newer browser, else use cookies :'( */
	if (supportsLocalStorage()) {
		localStorage.setItem(cookieNameShoppingList, null);
	} else {

		/* For all cookies create a long string */
		for ( var i = 0; i < parseInt(cookiesMax); i++) {
			var cookieName = cookieNameShoppingList + i;
			$.cookie(cookieName, null, {
				path: '/'
			});
		}

		$.cookie(cookieNameMain, null, {
			path: '/'
		});
	}
	setCurrentShoppingList("");
	//window.location.reload(false);
}


function addRecipeKey(key) {
	var shoppingList = getShoppingList();
	shoppingList.addRecipeKey(key);
	saveShoppingList(shoppingList);
	$("#addAmountToShoopingListLink").append(recipeAddedText);
}


function addRecipeKeys(list) {
	var shoppingList = getShoppingList();
	for ( var i = 0; i < list.length; i++) {
		var key = list[i];
		if (key == "-1") {
			continue;
		}
		shoppingList.addRecipeKey(key);
	}
	saveShoppingList(shoppingList);
}

function addRecipeKeysAndGoToShoppingList(list) {
	for ( var i = 0; i < list.length; i++) {
		var key = list[i];
		if (key == "-1") {
			continue;
		}

		/* Key is my own recipe else it's a vs one */
		var patt=/^u_?.*/g;
		var privateRecipe = patt.test(key);

		if (privateRecipe) {
			var data = wsGetItem(key.substring(2));
			addRecipeToShoppingList(data);
		} else {
			var shoppingList = getShoppingList();
			shoppingList.addRecipeKey(key);
			saveShoppingList(shoppingList);
		}
	}

	window.location.href = shoppingListUrl + "?key=" + shoppingList.getQuery();
}

function addRecipeKeyAndGoToShoppingList(key, name) {
	_gaq.push(['_trackEvent', 'Handleliste', 'Legg til', name + ' (' + key + ')']);
	var shoppingList = getShoppingList();
	shoppingList.addRecipeKey(key);
	saveShoppingList(shoppingList);
	window.location.href = shoppingListUrl + "?key=" + shoppingList.getQuery();
}

function addRecipeIngredientsAndGoToShoppingList(data) {
	var shoppingList = getShoppingList();
	addRecipeToShoppingList(data);
	window.location.href = shoppingListUrl + "?key=" + shoppingList.getQuery();
}

function addRecipeToShoppingList(data) {
	var shoppingList = getShoppingList();
	var ingredients = data.ingredients.split(/[,]|<br\/>/);

	var regexIngredientsHeadline = /:$/m;

	var recipe = new Recipe;
	recipe.setName(data.title);
	recipe.setImage(data.image);
	recipe.setKey(data.hash);

	for ( var i = 0; i < ingredients.length; i++) {
		var ingredient = $.trim(ingredients[i]);

		/* Safty */
		if (ingredient.match(regexIngredientsHeadline) || $.trim(ingredient) == "") {
			continue;
		}

		var data = getNewIngredientData(ingredient);

		if (data != null) {
			var ingredient = new Ingredient();
			ingredient.setAmount(data.amount);
			ingredient.setPrefix(data.prefix);
			ingredient.setName(data.name);

			/* Add it, save it, print it */
			recipe.addIngredient(ingredient);
		}
	}
	shoppingList.addRecipe(recipe);
	saveShoppingList(shoppingList);
}


function addRecipeKeyAndChangePortions(key, orginalAmount, newAmount) {
	var shoppingList = getShoppingList();
	var recipePortion = new RecipePortion();
	recipePortion.setMultible(true);
	recipePortion.setNewPortions(newAmount);
	recipePortion.setOrginalPortions(orginalAmount);
	recipePortion.setRecipeKey(key);
	shoppingList.addRecipePortion(recipePortion);
	shoppingList.addRecipeKey(key);
	saveShoppingList(shoppingList);
	$("#addAmountToShoopingListLink").after(recipeAddedText);
}

function addRecipeKeyAndChangePortionsAndGoToShoppingList(key, name, orginalAmount, newAmount) {
	_gaq.push(['_trackEvent', 'Handleliste', 'Legg til', name + ' (' + key + ')']);
	var shoppingList = getShoppingList();
	var recipePortion = new RecipePortion();
	recipePortion.setMultible(true);
	recipePortion.setNewPortions(newAmount);
	recipePortion.setOrginalPortions(orginalAmount);
	recipePortion.setRecipeKey(key);
	recipePortion.setReverseValue(newAmount);
	shoppingList.addRecipePortion(recipePortion);
	shoppingList.addRecipeKey(key);
	saveShoppingList(shoppingList);
	window.location.href = shoppingListUrl + "?key=" + shoppingList.getQuery();
}

function addRecipeFromMenu() {

	var keys;

	if (supportsLocalStorage()) {
		keys = localStorage.getItem(menyCookieName);
	} else {
		keys = $.cookie(menyCookieName);
	}

	keys = JSON.parse(keys);
	addRecipeKeysAndGoToShoppingList(keys);
}

function loadAllRecipesIntoJS() {
	var shoppingList = getShoppingList();

	$("#jsSetup > div.recipe").each(function() {
		var recipe = new Recipe();
		var recipePortion = new RecipePortion();
		var recipeName = $(this).find("> div.name").text();
		var recipeImage = $(this).find("> div.image").text();
		var recipeKey = $(this).find("> div.key").text();
		var recipePortions = $(this).find("> div.portions").text();
		var recipeMultible = $(this).find("> div.multible").text();

		recipePortions = recipePortions == "" ? 1 : recipePortions;
		recipePortions = parseInt(recipePortions);
		recipePortions = recipePortions <= 0 ? 1 : recipePortions;

		recipe.setImage(recipeImage);
		recipe.setKey(recipeKey);
		recipe.setName(recipeName);

		recipePortion.setMultible(recipeMultible);
		recipePortion.setOrginalPortions(recipePortions);
		recipePortion.setReverseValue(recipePortions);
		recipePortion.setRecipeKey(recipeKey);

		$(this).find("> div.ingredients > div.ingredient").each(function() {
			var ingredient = new Ingredient;
			var ingredientName = $(this).find("> div.name").text();
			var ingredientAmount = $(this).find("> div.amount").text();
			var ingredientPrefix = $(this).find("> div.prefix").text();

			ingredient.setAmount(ingredientAmount);
			ingredient.setName(ingredientName);
			ingredient.setPrefix(ingredientPrefix);

			recipe.addIngredient(ingredient);
		});
		shoppingList.addRecipe(recipe);

		var recipePortionInCookie = shoppingList.getRecipePortion(recipeName);
		if (recipePortionInCookie != null && recipePortion.getNewPortions() != recipePortionInCookie.getNewPortions()) {
			fixIngredientsAmount(recipe.getIngredients(), recipePortions, recipePortionInCookie.getNewPortions());
		} else {
			shoppingList.addRecipePortion(recipePortion);
		}

	});

	return shoppingList;
}


/**
 * Updates the Recipe tables style.
 */
function updateRecipeTable() {
	$("#handlelisteOppskrifterDiv > div:even > div").removeClass("odd").addClass("even");
	$("#handlelisteOppskrifterDiv > div:odd > div").removeClass("even").addClass("odd");
}


/**
 * Updates the Ingredient tables style.
 */
function updateIngredientTable() {
	$("#handlelisteVarerDiv > div:even > div").removeClass("odd").addClass("even");
	$("#handlelisteVarerDiv > div:odd > div").removeClass("even").addClass("odd");
}


/**
 * Gets the shoppinglist from the cookie
 * 
 * @returns {ShoppingList}
 */
function getShoppingList() {
	var shoppingList = new ShoppingList();

	/* If newer browser, else use cookies :'( */
	if (supportsLocalStorage()) {

		/* Get it */
		var tmp = localStorage.getItem(cookieNameShoppingList);

		/* Create the shopping list */
		if (tmp == null || tmp  == "") {
			shoppingList = new ShoppingList();
		} else {
			var shoppingListString = JSON.parse(tmp);
			shoppingList = new ShoppingList(shoppingListString);
		}
		
		

	} else {

		/* Get settings from main cookie */
		var settingsCookie = $.cookie(cookieNameMain);

		/* If no shoppinglist saved */
		if (settingsCookie == null) {
			return new ShoppingList();
		}

		/* Parse settings */
		var settings = JSON.parse(settingsCookie);

		/* For all cookies create a long string */
		var shoppingListString = "";
		for ( var i = 0; i < parseInt(settings.numberOfCookies); i++) {

			var cookieName = cookieNameShoppingList + i;
			var cookieString = $.cookie(cookieName);

			if (cookieString != null) {
				shoppingListString += cookieString;
			}
		}

		/* Create the shopping list */
		var shoppingListString = JSON.parse(shoppingListString);
		shoppingList = new ShoppingList(shoppingListString);
	}

	/* Return it */
	return shoppingList;
}

function supportsLocalStorage() {
	try {
		return 'localStorage' in window && window['localStorage'] !== null;
	} catch(e){
		return false;
	}
}
function supportsSessionStorage() {
	try {
		return 'sessionStorage' in window && window['sessionStorage'] !== null;
	} catch(e){
		return false;
	}
}

/**
 * Saves the shoppinglist to the cookie
 * 
 * @param shoppingList
 */
function saveShoppingList(shoppingList) {

	/* If newer browser, else use cookies :'( */
	if (supportsLocalStorage()) {
		var shoppingListLocalStorage = JSON.stringify(shoppingList, '');
		localStorage.setItem(cookieNameShoppingList, shoppingListLocalStorage);
	} else {

		/* Backup */
		var recipes = shoppingList.getRecipes();

		/* No need to save all recipes in the cookie (one cookie max size = 4096 bytes) */
		shoppingList.setRecipes(new Array());

		/* Serialize shopping list */
		var shoppingListCookie = JSON.stringify(shoppingList, '');

		/* How many cookies do we need? */
		var numberOfCookies = parseInt(shoppingListCookie.length) / parseInt(cookieLength);
		numberOfCookies = parseInt(numberOfCookies) + 1;

		/* Create a settings variable for the main cookie so we know how many cookies we need */
		var cookieSettings = {
				"numberOfCookies" : numberOfCookies
		};

		/* Safty, I hope it will never alert anything */
		if (numberOfCookies > cookiesMax) {
			alert("Cookie size soon out of memory!");
		}

		/* Time for some magic, create all the needed strigs */
		for ( var i = 0; i < numberOfCookies; i++) {
			var lower = i * cookieLength;
			var higher = cookieLength;

			var cookieString = shoppingListCookie.substr(lower, higher);
			var cookieName = cookieNameShoppingList + i;

			$.cookie(cookieName, cookieString, {
				expires: cookieTime, 
				path: '/'
			});
		}

		/* Create the string */
		cookieSettings = JSON.stringify(cookieSettings, '');

		/* Save main cookie */
		$.cookie(cookieNameMain, cookieSettings, {
			expires: cookieTime, 
			path: '/'
		});

		/* Restore deleted stuff */
		shoppingList.setRecipes(recipes);
	}

	/* No active shoppinglist anymore */
	//setCurrentShoppingList("");
}

function saveCurrentShoppingList() {
	if(getLoggedInUser() == false) {
		_gaq.push(['_trackEvent', 'Handleliste', 'Lagre handleliste uten innlogging']);
		$("#saveShoppingList").parent().parent().html(
			"<div class='gem'>" +
			"<span class='fontFix'>Lagre handleliste</span> " +
			"<span class='small'>(Krever <span class='usercreatebutton'>innlogging</span>)</span>" +
			"</div>"
		);
	} else {
		showSavedShoppingListWindow();
	}
	return false;
}

function showSavedShoppingListWindow() {
	$("#mask").show();

	var loggedInUser = getLoggedInUser();
	if (loggedInUser != null) {

		var shoppingLists = wsGetShoppingListCollectionByEmail(loggedInUser.email);
		var currentShoppingList = getCurrentShoppingList();
		$("#savedShoppingLists li").remove();
		$("#txtShoppingListName").val(currentShoppingList);
		if (shoppingLists.length == 0) {
			$("#saveShoppingListDialog").append("<span>Inge lagrede handlelister</span>");
		} else {
			for ( var i = 0; i < shoppingLists.length; i++) {
				var shoppingList = shoppingLists[i];
				var active = "";
				if (currentShoppingList == shoppingList.name) {
					active = "active";
				}
				$("#savedShoppingLists").append(
						"<li class='" + active + "'>" +
						"<span class='id'>" + shoppingList.id + "</span>" +
						"<span class='load'>" + shoppingList.name + "</span>" +
						" " +
						"<span class='delete'><img class='deleteMenuPlan' src='http://webfiles.tine.no/Tine.no_v2/images/icon_delete.png'></span>" +
				"</li>");
			}
		}
		fixSavedShoppingListsText();
	}
	$(".saveShoppingListDialog").show();
	$("#txtShoppingListName").focus();
}



function loadShoppingList(id, name) {
	var loggedInUser = getLoggedInUser();

	/* Security */
	if (loggedInUser == null) {
		return false;
	}

	clearCookie();
	var shoppinglistObj = wsGetShoppingListByID(loggedInUser.email, id);
	var shoppingListString = JSON.parse(shoppinglistObj.data);
	shoppingList = new ShoppingList(shoppingListString);
	saveShoppingList(shoppingList);
	setCurrentShoppingList(name);
	window.location.reload(false);
}

function hideSavedShoppingListsWindow() {
	$("#mask").hide();
	$(".saveShoppingListDialog").hide();
}

function hideSendShoppingListsWindow() {
	$("#mask").hide();
	$(".sendShoppingListDialog").hide();
}

$(".closeDialog, #mask").live('click', function() {
	if($(".sendShoppingListDialog").size() > 0 || $(".saveShoppingListDialog").size() > 0) {
		hideSavedShoppingListsWindow();
		hideSendShoppingListsWindow();
	}
	return false;
});
/**
 * Read a page's GET URL variables and return them as an associative array.
 */
function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

	for ( var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}



function getKeysInUrl(){
	var vars = getUrlVars();
	return vars['key']; 
}


function getKeysInQuery(query) {
	if (query === undefined) {
		return new Array();
	}
	var keys = query.split(',');
	return keys;
}


function getCurrentUrl() {
	return window.location.href.split("?")[0];
}


/**
 * Removing a recipe
 * 
 * @param key
 *            The EVS key to the recipe that should be removed
 */
function removeRecipeInDesign(key, name, link) {
	fullShoppingList.removeRecipe(key);
	saveShoppingList(fullShoppingList);
	$(link).parent().parent().remove();
	
	_gaq.push(['_trackEvent', 'Handleliste', 'Fjern fra', name + ' (' + key + ')']);

	/* If last one */
	if ($("#handlelisteOppskrifterDiv").find(".row").size() <= 0) {
		$("#handlelisteOppskrifterDiv").remove();
		$("#handleListePortions").next().remove();
		$("#handleListePortions").remove();
	}

	rewriteIngredientsTable();
	fixRoundedCorner();
	fixOutputTextForRecipes();
	fixOutputTextForIngredints();
	window.scrollBy(0,1)
	window.scrollBy(0,-1)
}

function fixOutputTextForRecipes() {
	var count =  $("#handlelisteOppskrifterDiv").children().length;

	/* If show recipies, else show text */
	if (count > 0) {
		$("#handleListePortions").show();
		$("#handleListePortions").next().show();
	} else {
		$("#handleListePortions").hide();
		$("#handleListePortions").next().hide();
	}
}

function fixOutputTextForIngredints() {
	var count =  $("#handlelisteVarerDiv").children().length;

	/* Hide text if visible */
	if ($("#handlelisteVarerDiv").next(".noIngridientsInList").length > 0) {
		$("#handlelisteVarerDiv").next().remove();
	}

	/* Show text */
	if (count == 0) {

		/* Design */
		var toShow = "<div class='noIngridientsInList'>" + noIngridientsInList + "</div>";

		/* Show text if not visible */
		$("#handlelisteVarerDiv").after(toShow);
	}
}

function removeRecipe(key) {
	var shoppingList = getShoppingList();
	shoppingList.removeRecipe(key);
	saveShoppingList(fullShoppingList);
}


function recipesHasDeletedIngredients(deletedIngredients, key) {
	for ( var i = 0; i < deletedIngredients.length; i++) {
		var deletedIngredient = deletedIngredients[i];
		if (deletedIngredient.getRecipeKey() == key) {
			return true;
		}
	}
	return false;
}

function getNoneDeletedIngredients(deletedIngredients, recipe) {
	var returnIngredients = new Array();

	/* Loop over all recipes that have ingredients marked 'deleted' */
	for ( var i = 0; i < deletedIngredients.length; i++) {
		var deletedIngredient = deletedIngredients[i];

		/* Find correct recipe */
		if (deletedIngredient.getRecipeKey() == recipe.getKey()) {

			/* For all ingredients in recipe */
			for ( var j = 0; j < recipe.getIngredients().length; j++) {
				var ingredient = recipe.getIngredients()[j];

				/* If ingredient is Not marked as 'deleted' */
				if (!isIngredientInList(deletedIngredient.getIngredients(), ingredient)) {

					/* Add it to the return list */
					returnIngredients.push(ingredient);
				} 
			}
		}
	}
	return returnIngredients;
}

function isIngredientInList(ingredients, ingredient) {
	for ( var i = 0; i < ingredients.length; i++) {
		var ing = ingredients[i];
		if (ing.getName() == ingredient.getName() && ing.getPrefix() == ingredient.getPrefix()) {
			return true;
		}
	}
	return false;
}

function fixIngredientsAmount(ingredients, orginalPortions, newPortions) {
	for ( var i = 0; i < ingredients.length; i++) {
		var ingredient = ingredients[i];
		ingredient.setAmount(ingredient.getAmount() / orginalPortions * newPortions);
	}
}

function changeAmountOfIngridents(ingredients, orginalPortions, newPortions, reverseValue) {

	/* Convertion */
	orginalPortions = parseInt(orginalPortions);
	newPortions = parseInt(newPortions);
	reverseValue = parseInt(reverseValue);

	/* Safty */
	if (orginalPortions <= 0 || newPortions <= 0 || reverseValue <= 0) {
		return false;
	}

	/* Now let's reslace all ingridents */
	for ( var i = 0; i < ingredients.length; i++) {

		/* Get the ingrident */
		var ingredient = ingredients[i];

		/* Convertion */
		var ingredientAmount = ingredient.getAmount();
		ingredientAmount = parseFloat(ingredientAmount);

		/* Amount for 1 portion */
		var amountOnePortion = ingredientAmount / reverseValue;

		/* New amount for X portions */
		var newAmount = amountOnePortion * newPortions; 

		/* Set the new amount */
		ingredient.setAmount(newAmount);
	}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function isNumeric(input) {
	return (input - 0) == input && input.length > 0;
}



function sendToMail(mail, message) {
	var returnList = "";
	var token = getUserToken();
	var url = wsShoppingListUrl + "/send/email/";
	var dataInput = {
			"email" : mail,
			"message" : message,
			"token" : token,
			"r" : Math.random()
	};

	$.ajax({
		type: "POST",
		url: url,
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(dataResult) {
			if ($(dataResult).find("status").size() > 0 ) {
				returnList = $(dataResult).find("status").text();
			} else {
				returnList = {
						an 		: $(dataResult).find("email").attr('an'),
						email 	: $(dataResult).find("email").text()
				};
			}
		}
	});
	return returnList;
}

function wsGetShoppingListByID(email, shoppingListId) {
	var returnList = "";
	var url = wsShoppingListUrl + "/id/"+email+"/"+shoppingListId;
	var token = getUserToken();
	var dataInput = {
			"token" : token,
			"r" : Math.random()
	};

	$.ajax({
		type: "GET",
		url: url,
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(dataResult) {
			if ($(dataResult).find("status").size() > 0 ) {
				returnList = $(dataResult).find("status").text();
			} else {
				returnList = {
						id 		: $(dataResult).find("id").text(),
						email 	: $(dataResult).find("email").text(),
						name 	: $(dataResult).find("name").text(),
						data 	: $(dataResult).find("data").text(),
						version : $(dataResult).find("version").text(),
						created : $(dataResult).find("created").text(),
						updated : $(dataResult).find("updated").text()
				};
			}
		}
	});
	return returnList;
}

function wsGetShoppingListCollectionByEmail(email) {
	var returnArray = new Array();
	var url = wsShoppingListUrl + "/" + email;
	var token = getUserToken();
	var dataInput = {
			"token" : token,
			"r" : Math.random()
	};

	$.ajax({
		type: "GET",
		url: url,
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(dataResult) {
			$(dataResult).find("shoppinglist").each(function() {
				var shoppinglist = {
						id 		: $(this).find("id").text(),
						email 	: $(this).find("email").text(),
						name 	: $(this).find("name").text(),
						data 	: $(this).find("data").text(),
						version : $(this).find("version").text(),
						created : $(this).find("created").text(),
						updated : $(this).find("updated").text()
				};
				returnArray.push(shoppinglist);
			});
		}
	});

	return returnArray;
}

function wsRemoveShoppingList(email, shoppingListId) {
	var returnValue = "";
	var url = wsShoppingListUrl + "/remove/"+email+"/"+shoppingListId+"/";
	var token = getUserToken();
	var dataInput = {
			"token" : token,
			"r" : Math.random()
	};

	$.ajax({
		type: "POST",
		url: url,
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(dataResult) {
			returnValue = $(dataResult).find("status").text();
		}
	});

	return returnValue;
}

function wsAddShoppingList(email, data, name, shoppingListId) {
	var returnValue = "";
	var url = wsShoppingListUrl + "/"+email;
	var token = getUserToken();
	var dataInput = {
			"token" : token,
			"data" : data,
			"name" : name,
			"id" : shoppingListId,
			"r" : Math.random()
	};

	$.ajax({
		type: "POST",
		url: url,
		data : dataInput,
		dataType: "xml",
		async: false,
		success: function(dataResult) {
			if ($(dataResult).find("status").size() > 0) {
				returnValue = {
					"status" : $(dataResult).find("status").text(),
					"id" : $(dataResult).find("status").attr("id")
				};
			} else {
				returnValue = {
					"status" : "error",
					"message" : $(dataResult).find("result").text()
				};
			}
			
		}
	});

	return returnValue;
}


/**
 * OBJECTS SHOPPINGLIST
 */
function ShoppingList(_obj) {
	this.key = "";
	this.recipeKeys = new Array();
	this.recipes = new Array();
	this.extraIngredients = new Array();
	this.deletedIngredients = new Array();
	this.recipePortions = new Array();

	if (_obj != undefined && _obj != null) {
		if (_obj.hasOwnProperty('recipes')) {
			for ( var int = 0; int < _obj.recipes.length; int++) {
				var element = _obj.recipes[int];
				var recipe = new Recipe(element);
				this.recipes.push(recipe);
			}
		}
		if (_obj.hasOwnProperty('key')) {
			this.key = _obj.key;
		}
		if (_obj.hasOwnProperty('recipeKeys')) {
			this.recipeKeys = _obj.recipeKeys;
		}
		if (_obj.hasOwnProperty('extraIngredients')) {
			for ( var int = 0; int < _obj.extraIngredients.length; int++) {
				var element = _obj.extraIngredients[int];
				var ingredient = new Ingredient(element);
				this.extraIngredients.push(ingredient);
			}
		}
		if (_obj.hasOwnProperty('deletedIngredients')) {
			for ( var int = 0; int < _obj.deletedIngredients.length; int++) {
				var element = _obj.deletedIngredients[int];
				var deletedIngredients = new DeletedIngredients(element);
				this.deletedIngredients.push(deletedIngredients);
			}
		}
		if (_obj.hasOwnProperty('recipePortions')) {
			for ( var int = 0; int < _obj.recipePortions.length; int++) {
				var element = _obj.recipePortions[int];
				var recipePortion = new RecipePortion(element);
				this.recipePortions.push(recipePortion);
			}
		}
	}

	ShoppingList.prototype.toString = function() {

		/* Header */
		var returnString = this.recipes.length + " recipes (" + this.key
		+ ")\n";
		returnString += "Query: " + this.getQuery() + "\n\n"; 
		returnString += "Keys: " + this.getRecipeKeys() + "\n\n"; 

		/* For all recipes */
		for ( var int = 0; int < this.recipes.length; int++) {
			var element = this.recipes[int];
			returnString += "(" + int + ") " + element.toString() + "\n";
		}

		/* All the extra ingredients */
		returnString += "- - Extra Ingredients - - \n";
		for ( var int = 0; int < this.extraIngredients.length; int++) {
			var element = this.extraIngredients[int];
			returnString += "\t (" + int + ") " + element.toString() + "\n";
		}

		/* All the deleted ingredients */
		returnString += "- - Deleted Ingredients - - \n";
		for ( var int = 0; int < this.deletedIngredients.length; int++) {
			var element = this.deletedIngredients[int];
			returnString += "\t (" + int + ") " + element.toString() + "\n";
		}

		/* All the deleted ingredients */
		returnString += "- - Portions - - \n";
		for ( var int = 0; int < this.recipePortions.length; int++) {
			var element = this.recipePortions[int];
			returnString += "\t (" + int + ") " + element.toString() + "\n";
		}

		return returnString;
	};

	ShoppingList.prototype.getRecipe = function(name) {
		for ( var i = 0; i < this.recipes.length; i++) {
			var recipe = this.recipes[i];
			if(recipe.getName() == name) {
				return recipe;
			}  
		}
	};

	ShoppingList.prototype.updateOwnRecipe = function(oldHash, newHash) {
		for ( var i = 0; i < this.recipes.length; i++) {
			var recipe = this.recipes[i];
			if(recipe.getKey() == oldHash) {
				recipe.setKey(newHash);
			}  
		}
	};

	ShoppingList.prototype.getRecipes = function() {
		return this.recipes;
	};

	ShoppingList.prototype.setRecipes = function(recipes) {
		this.recipes = recipes;
	};

	ShoppingList.prototype.getDeletedIngredients = function() {
		return this.deletedIngredients;
	};

	ShoppingList.prototype.setDeletedIngredients = function(deletedIngredients) {
		this.deletedIngredients = deletedIngredients;
	};

	ShoppingList.prototype.getKey = function() {
		return this.key;
	};

	ShoppingList.prototype.setKey = function(key) {
		this.key = key;
	};

	ShoppingList.prototype.getExtraIngredients = function() {
		return this.extraIngredients;
	};

	ShoppingList.prototype.getRecipesIngredients = function() {
		var ingredients = new Array();

		/* For all recipes in shopping list */
		for ( var int = 0; int < this.recipes.length; int++) {
			var element = this.recipes[int];
			ingredients = ingredients.concat(element.getIngredients());
		}
		return ingredients;
	};

	ShoppingList.prototype.getAllIngredients = function() {
		return this.getRecipesIngredients().concat(this.getExtraIngredients());
	};

	ShoppingList.prototype.getAllNoneDeletedIngredients = function() {
		var ingredients = new Array();

		for ( var i = 0; i < this.recipes.length; i++) {
			var recipe = this.recipes[i];			
			var tmpIngredients = new Array(); 

			/* Get all ingidients */
			if (recipesHasDeletedIngredients(this.deletedIngredients, recipe.getKey())) {
				tmpIngredients = getNoneDeletedIngredients(this.deletedIngredients, recipe);
			} else {
				tmpIngredients = recipe.getIngredients();
			}

			/* Time for some magic */
			for ( var j = 0; j < this.recipePortions.length; j++) {
				var recipePortion = this.recipePortions[j];

				/* Find right values */
				if (recipePortion.getRecipeKey() == recipe.getKey()) {
					changeAmountOfIngridents(tmpIngredients, recipePortion.getOrginalPortions(), recipePortion.getNewPortions(), recipePortion.getReverseValue());
					break;
				}
			}

			/* Adds ingredients to return array */
			ingredients = ingredients.concat(tmpIngredients);
		}

		/* Return all ingredients + all extra added by user */
		return ingredients.concat(this.getExtraIngredients());
	};
	
	ShoppingList.prototype.cleanShoppinglist = function() {

		for ( var i = 0; i < this.recipes.length;) {
			var recipe = this.recipes[i];
			var key = recipe.getKey();
			var test = wsGetItem(key);
			
			/* own recipe */
			if (key.length > 30) {
				if (test.hash != key){
					this.removeRecipe(key);
					continue;
				}
			}
			i++;
		}
	};

	ShoppingList.prototype.getAllOwnRecipes = function() {
		var returnArray = new Array();
		var recipes = this.getRecipes();
		for ( var i = 0; i < recipes.length; i++) {
			var recipe = recipes[i];
			if (!isNumeric(recipe.getKey())) {
				returnArray.push(recipe);
			}
		}
		return returnArray;
	};

	ShoppingList.prototype.addRecipe = function(recipe) {
		this.addRecipeKey(recipe.getKey());
		if (!this.hasRecipe(recipe)) {
			this.recipes.push(recipe);
		}
	};

	ShoppingList.prototype.addRecipePortion = function(recipePortion) {
		if (!this.hasRecipePortion(recipePortion)) {
			this.recipePortions.push(recipePortion);
		}
	};

	ShoppingList.prototype.updateRecipePortion = function(recipePortionInput) {
		for ( var i = 0; i < this.recipePortions.length; i++) {
			var recipePortion = this.recipePortions[i];
			if(recipePortion.getRecipeKey() == recipePortionInput.getRecipeKey()) {
				recipePortion.setNewPortions(recipePortionInput.setNewPortions());
				return true;
			}
		}
		return false;
	};

	ShoppingList.prototype.getRecipePortion = function(name) {
		var recipeKey = "";
		for ( var i = 0; i < this.recipes.length; i++) {
			var recipe = this.recipes[i];
			if (recipe.getName() == name) {
				recipeKey = recipe.getKey();
				break;
			}
		}

		if (recipeKey != "") {
			for ( var i = 0; i < this.recipePortions.length; i++) {
				var recipePortion = this.recipePortions[i];
				if (recipePortion.getRecipeKey() == recipeKey) {
					return recipePortion;
				}
			}
		}
		return null;
	};

	ShoppingList.prototype.hasRecipe = function(recipe) {
		for ( var int = 0; int < this.recipes.length; int++) {
			var element = this.recipes[int];
			if (element.getKey() == recipe.getKey()) {
				return true;
			}
		}
		return false;
	};

	ShoppingList.prototype.hasRecipePortion = function(recipePortion) {
		for ( var int = 0; int < this.recipePortions.length; int++) {
			var element = this.recipePortions[int];
			if (element.getRecipeKey() == recipePortion.getRecipeKey()) {
				return true;
			}
		}
		return false;
	};

	ShoppingList.prototype.addRecipeKey = function(key) {
		if (key != "" && this.recipeKeys.indexOf(key) == -1 && key != -1) {
			this.recipeKeys.push(key+'');
		}
	};

	ShoppingList.prototype.getQuery = function() {
		var returnString = "";
		var keys = this.getRecipeKeys();
		for ( var int = 0; int < keys.length; int++) {
			var key = keys[int];
			returnString += key;
			if (int != keys.length-1 && keys[int+1] != "") {
				returnString += ",";
			}
		}
		returnString = returnString != "" ? returnString : "-1";
		return returnString;

	};
	ShoppingList.prototype.getRecipeKeys = function() {
		var returnArray = new Array();
		var keys = this.recipeKeys;
		for ( var i = 0; i < keys.length; i++) {
			var key = keys[i];
			if (isNumeric(key)) {
				returnArray.push(key);
			}
		}

		return returnArray;
	};

	ShoppingList.prototype.addExtraIngredients = function(ingredient) {
		this.extraIngredients.push(ingredient);
	};

	ShoppingList.prototype.removeRecipe = function(key) {
		for ( var int = 0; int < this.recipes.length; int++) {
			var element = this.recipes[int];
			if ($.trim(element.getKey()) == $.trim(key)) {
				this.recipes.splice(int, 1);
				break;
			}
		}

		for ( var i = 0; i < this.recipeKeys.length; i++) {
			var element = this.recipeKeys[i];
			if ($.trim(element) == $.trim(key)) {
				this.recipeKeys.splice(i, 1);
				break;
			}
		}
	};

	ShoppingList.prototype.removeIngredient = function(name) {

		/* Ingredients in recipes */
		for ( var i = 0; i < this.recipes.length; i++) {
			var recipe = this.recipes[i];

			/* If a recipe has the ingredient */
			if (recipe.hasIngredient(name)) {
				var ingredients = recipe.getIngredientsByName(name);
				var addedFlag = false;

				/* Check if the recipe has any other removed ingreditens */
				for ( var j = 0; j < this.deletedIngredients.length; j++) {
					var deletedIngredient = this.deletedIngredients[j];
					if (deletedIngredient.getRecipeKey() == recipe.getKey()) {
						for ( var k = 0; k < ingredients.length; k++) {
							var tmpIngredient = ingredients[k];
							deletedIngredient.addIngredient(tmpIngredient);
						}
						addedFlag = true;
					}
				}

				/* Else we create a new post */
				if (!addedFlag) {
					var deletedIngredient = new DeletedIngredients();
					deletedIngredient.setRecipeKey(recipe.getKey());
					for ( var k = 0; k < ingredients.length; k++) {
						var tmpIngredient = ingredients[k];
						deletedIngredient.addIngredient(tmpIngredient);
					}
					this.deletedIngredients.push(deletedIngredient);
				}
			}
		}

		/* Ingredients in extra */
		for ( var i = 0; i < this.extraIngredients.length; ) {
			var element = this.extraIngredients[i];
			if (element.getName() == name) {
				this.extraIngredients.splice(i, 1);
				continue;
			} else {
				i++;
			}
		}
	};
}

function Recipe(_obj) {
	this.key = "";						// Key in evs
	this.name = "";						// Name
	this.image = "";					// Link to image
	this.ingredients = new Array();		// Array of all the ingredients

	if (_obj != undefined && _obj != null) {
		if (_obj.hasOwnProperty('image')) {
			this.image = _obj.image;
		}
		if (_obj.hasOwnProperty('key')) {
			this.key = _obj.key;
		}
		if (_obj.hasOwnProperty('name')) {
			this.name = _obj.name;
		}
		if (_obj.hasOwnProperty('ingredients')) {
			for ( var int = 0; int < _obj.ingredients.length; int++) {
				var element = _obj.ingredients[int];
				var ingredient = new Ingredient(element);
				this.ingredients.push(ingredient);
			}
		}
	}

	Recipe.prototype.toString = function() {
		var returnString = this.name + "(" + this.key + ")\t\t"
		+ this.ingredients.length + " ingredients\n";

		/* For all ingredients in the recipe */
		for ( var int = 0; int < this.ingredients.length; int++) {
			var element = this.ingredients[int];
			returnString += "\t (" + int + ") " + element.toString() + "\n";
		}
		return returnString;
	};

	Recipe.prototype.getIngredients = function() {
		return this.ingredients;
	};

	Recipe.prototype.getImage = function() {
		if (this.image == undefined) {
			this.image = "";
		}
		return this.image;
	};

	Recipe.prototype.getKey = function() {
		return this.key;
	};

	Recipe.prototype.getName = function() {
		return this.name;
	};

	Recipe.prototype.setKey = function(key) {
		this.key = key;
	};

	Recipe.prototype.setName = function(name) {
		this.name = name;
	};

	Recipe.prototype.setImage = function(image) {
		this.image = image;
	};

	Recipe.prototype.addIngredient = function(ingredient) {
		this.ingredients.push(ingredient);
	};

	Recipe.prototype.hasIngredient = function(name) {
		for ( var int = 0; int < this.ingredients.length; int++) {
			var ingredient = this.ingredients[int];
			if (ingredient.getName() == name) {
				return true;
			}
		}
		return false;
	};

	Recipe.prototype.removeIngredient = function(name) {
		for ( var int = 0; int < this.ingredients.length; int++) {
			var ingredient = this.ingredients[int];
			if (ingredient.getName() == name) {
				ingredients.splice(j, 1);
				break;
			}
		}
	};

	Recipe.prototype.getIngredient = function(name) {
		for ( var int = 0; int < this.ingredients.length; int++) {
			var ingredient = this.ingredients[int];
			if (ingredient.getName() == name) {
				return ingredient;
			}
		}
		return null;
	};

	Recipe.prototype.getIngredientsByName = function(name) {
		var returnList = new Array();

		for ( var int = 0; int < this.ingredients.length; int++) {
			var ingredient = this.ingredients[int];
			if (ingredient.getName() == name) {
				returnList.push(ingredient);
			}
		}
		return returnList;
	};
}


function Ingredient(_obj) {
	this.name = "";
	this.amount = "";
	this.prefix = "";

	if (_obj != undefined && _obj != null) {
		if (_obj.hasOwnProperty('name')) {
			this.name = _obj.name;
		}
		if (_obj.hasOwnProperty('amount')) {
			this.amount = _obj.amount;
		}
		if (_obj.hasOwnProperty('prefix')) {
			this.prefix = _obj.prefix;
		}
	}

	Ingredient.prototype.toString = function() {
		return (this.amount + "\t" + this.prefix + "\t" + this.name);
	};

	Ingredient.prototype.getAmount = function() {
		return roundNumber(this.amount, 2);
	};

	Ingredient.prototype.getName = function() {
		return this.name;
	};

	Ingredient.prototype.setAmount = function(amount) {
		if (typeof amount == "string") {
			if (amount.indexOf('/') > -1) {
				amount = parseFloat(eval(amount));
			} else if (amount.indexOf(',') > -1){
				amount = parseFloat(amount.replace(",","."));
			} else if (isNaN(parseFloat(amount))) {
				amount = 0;
			} else {
				amount = parseFloat(amount);
			}
		}
		this.amount = amount;
	};

	Ingredient.prototype.setName = function(name) {
		this.name = $.trim(name);
	};

	Ingredient.prototype.setPrefix = function(prefix) {
		this.prefix = prefix;
	};

	Ingredient.prototype.getPrefix = function() {
		return this.prefix;
	};

	Ingredient.prototype.getPrintoutPrefix = function() {
		var pos = orginalPrefix.indexOf(this.prefix);
		if (pos == -1) {
			return this.prefix;
		}
		return printoutPrefix[pos];
	};
}

function DeletedIngredients(_obj) {

	this.recipeKey = "";
	this.ingredients = new Array();

	if (_obj != undefined && _obj != null) {
		if (_obj.hasOwnProperty('recipeKey')) {
			this.recipeKey = _obj.recipeKey;
		}
		if (_obj.hasOwnProperty('ingredients')) {
			for ( var int = 0; int < _obj.ingredients.length; int++) {
				var element = _obj.ingredients[int];
				var ingredient = new Ingredient(element);
				this.ingredients.push(ingredient);
			}
		}
	}

	DeletedIngredients.prototype.toString = function() {
		var returnString = "recipekey " + this.recipeKey + "\n";

		/* For all ingredients in the recipe */
		for ( var int = 0; int < this.ingredients.length; int++) {
			var element = this.ingredients[int];
			returnString += "\t\t (" + int + ") " + element.toString() + "\n";
		}
		return returnString;
	};

	DeletedIngredients.prototype.setRecipeKey = function(key) {
		this.recipeKey = key;
	};

	DeletedIngredients.prototype.getRecipeKey = function() {
		return this.recipeKey;
	};

	DeletedIngredients.prototype.getIngredients = function() {
		return this.ingredients;
	};

	DeletedIngredients.prototype.addIngredient = function(ingredient) {
		this.ingredients.push(ingredient);
	};
}

function RecipePortion(_obj) {
	this.recipeKey = "";
	this.orginalPortions = "";
	this.newPortions = "";
	this.reverseValue = 1;
	this.multible = false;

	if (_obj != undefined && _obj != null) {
		if (_obj.hasOwnProperty('recipeKey')) {
			this.recipeKey = _obj.recipeKey;
		}
		if (_obj.hasOwnProperty('orginalPortions')) {
			this.orginalPortions = _obj.orginalPortions;
		}
		if (_obj.hasOwnProperty('newPortions')) {
			this.newPortions = _obj.newPortions;
		}
		if (_obj.hasOwnProperty('reverseValue')) {
			this.reverseValue = _obj.reverseValue;
		}
		if (_obj.hasOwnProperty('multible')) {
			this.multible = _obj.multible;
		}
	}

	RecipePortion.prototype.toString = function() {
		return (this.recipeKey + " " + this.orginalPortions + "/" + this.newPortions + " (" + this.multible + ")");
	};

	RecipePortion.prototype.setRecipeKey = function(key) {
		this.recipeKey = key;
	};

	RecipePortion.prototype.getRecipeKey = function() {
		return this.recipeKey;
	};

	RecipePortion.prototype.setOrginalPortions = function(portions) {
		portions = parseInt(portions);
		if (portions <= 0) {
			portions = 1;
		}
		this.orginalPortions = portions;
	};

	RecipePortion.prototype.getOrginalPortions = function() {
		if (this.orginalPortions == "" || parseInt(this.orginalPortions) <= 0) {
			this.orginalPortions = 1;
		}
		return this.orginalPortions;
	};

	RecipePortion.prototype.setNewPortions = function(portions) {
		portions = parseInt(portions);
		if (portions <= 0) {
			portions = 1;
		}
		this.newPortions = portions;
	};

	RecipePortion.prototype.getNewPortions = function() {
		if (this.newPortions == "" || parseInt(this.newPortions) <= 0){
			if (this.getOrginalPortions() == "" || parseInt(this.getOrginalPortions()) <= 0) {
				this.newPortions = 1;
			} else {
				this.newPortions = parseInt(this.getOrginalPortions());
			}
		}
		return this.newPortions;
	};

	RecipePortion.prototype.setMultible = function(multible) {
		if (multible == "true" || multible == true) {
			this.multible = true;
		} else {
			this.multible = false;
		}
	};

	RecipePortion.prototype.getMultible = function() {
		return this.multible;
	};

	RecipePortion.prototype.setReverseValue = function(reverseValue) {
		reverseValue = parseInt(reverseValue);
		if (reverseValue <= 0) {
			reverseValue = 1;
		}
		this.reverseValue = reverseValue;
	};

	RecipePortion.prototype.getReverseValue = function() {
		if (this.reverseValue == "" || parseInt(this.reverseValue) <= 0){
			if (this.getOrginalPortions() == "" || parseInt(this.getOrginalPortions()) <= 0) {
				this.reverseValue = 1;
			} else {
				this.reverseValue = parseInt(this.getOrginalPortions());
			}
		}
		return this.reverseValue;
	};
}

/**
 * PLUGINS
 */
/**
 * Paging plugin.
 */
(function($){
	
	/* All the methods in plugin */
	var methods = {
			
			/* Initialize method */
			init : function(settingsInput) {
				
				/* For each element */
				return this.each(function() {

					/* Saves this */
					$this = $(this);
					
					/* Extend all the parsed settings */
					var settings = $.extend($.fn.pagingNew.defaults, settingsInput);

					/* Create info for button */
					var data = {
							'items'			: 	$this.find(settings.items),
							'counter'		:	"1",
							'currentPage'	:	"1",
							'settings'		:	settings,
							'maxReached'	:	false
					};
					
					/* Fix maxResult */
					if (data.items.length > data.settings.maxResult) {
						$this.children(settings.items).slice(data.settings.maxResult).remove();
						data.items = $this.children(settings.items); // To update the counter
						data.maxReached = true;
					}
					
					/* Fix navigation */
					fixNavigation(data);
					
					/* Set counter correct */
					var higher = data.items.length > settings.countPerPage ? settings.countPerPage : data.items.length;
					updateCounter(0, higher, data);
					
					/* Saves data */
					$(this).data('data', data);
					
					
					/* - - - - - B i n d i n g s - - - - - */
					/* Binds the next button */
					$(settings.next).data('id', $this.attr('id'));
					$(settings.next).bind('click', function() {
						
						/* Get info */
						var dataFromId = $(this).data('id');
						var data = $("#"+dataFromId).data('data');
						
						/* Size */
						var size = data.items.length;
						
						/* Security */
						if (data.settings.countPerPage * data.currentPage > data.size) {
							return;
						}
						
						/* Range counting */
						var lower = data.settings.countPerPage * data.currentPage;
						var higher = data.settings.countPerPage * data.currentPage + data.settings.countPerPage;
						
						/* Hide current */
						$(data.items).hide(function() {
							
							/* Show next */
							setTimeout(function() {
								$(data.items).slice(lower, higher).show(function() {
									settings.nextFunction.apply($this);
								});
							},600);
							
						});
						
						/* Next page Pooh */
						data.currentPage++;
					
						/* Fix navigation */
						fixNavigation(data);
						
						/* Update counter */
						updateCounter(lower, higher, data);
						
						/* Save new values */
						$("#"+dataFromId).data('data', data);
						
						/* Runs nextFunction */
						//settings.nextFunction.apply($this);
						
					});
					
					/* Binds the prev button */
					$(settings.prev).data('id', $this.attr('id'));
					$(settings.prev).live('click', function() {
					
						/* Get info */
						var dataFromId = $(this).data('id');
						var data = $("#"+dataFromId).data('data');
						
						/* Security */
						if (data.currentPage <= 1) {
							return;
						}
						
						/* Prev page Piglet */
						data.currentPage--;
						
						/* Range counting */
						var lower = data.settings.countPerPage * data.currentPage - data.settings.countPerPage;
						var higher = data.settings.countPerPage * data.currentPage;
						
						/* Hide current */
						$(data.items).hide(function() {
							
							/* Show next */
							setTimeout(function() {
								$(data.items).slice(lower, higher).show(function() {
									settings.prevFunction.apply($this);
								});
							},600);
						});
						
						/* Fix navigation */
						fixNavigation(data);
						
						/* Update counter */
						updateCounter(lower, higher, data);
						
						/* Save new values */
						$("#"+dataFromId).data('data', data);
						
						/* Runs nextFunction */
						//settings.prevFunction.apply($this);

					});
				});
			}, 
			
			/* Reset the values */
			reset : function() {
				
				/* For each element */
				return this.each(function() {
					
					/* Saves this */
					$this = $(this);
					
					/* Data to be overwritten */
					var resetData = {
							'counter'		:	"1",
							'currentPage'	:	"1"
					};
					
					/* Get data */
					var data = $this.data('data');

					/* Overwrite it */
					data = $.extend(data, resetData);
					
					/* Hide current */
					$(data.items).hide();

					/* Range counting */
					var higher = data.items.length > data.settings.countPerPage ? data.settings.countPerPage : data.items.length;
					
					/* Show first ones */
					$(data.items).slice(0, higher).show();
					
					/* Fix navigation */
					fixNavigation(data);
					
					/* Set counter correct */
					updateCounter(0, higher, data);
					
					/* Saves this */
					$this.data('data', data);
				});
			},
			
			/* Filter out some values */
			setFilter: function(filter) {
				
				/* For each element */
				return this.each(function() {
					
					/* Saves this */
					$this = $(this);
					
					/* Get data */
					var data = $this.data('data');
					
					/* Hide 'em all */
					$this.find(data.settings.items).not(filter).hide();
					
					/* Overwrite items */
					data.items = $this.find(data.settings.items).filter(filter);
					
					/* Saves this */
					$this.data('data', data);
				});
			},
			
			/* Get current page */
			updateChilds: function(filter) {
				
				/* For each element */
				return this.each(function() {
					
					/* Saves this */
					$this = $(this);
					
					/* Get data */
					var data = $this.data('data');
								
					/* Overwrite items */		
					if (filter) {
						data.items = $this.find(data.settings.items).filter(filter);
					} else {
						data.items = $this.find(data.settings.items);
					}
					
					/* Updates navigation */
					fixNavigation(data);
					
					/* Saves this */
					$this.data('data', data);
				});
			}
		};
	
	function updateCounter(lower, higher, data) {
		var maxReachedText = "";
		if (data.maxReached && higher >= data.settings.maxResult) {
			maxReachedText = "<span class='pagerMaxReached'>" + data.settings.maxResultText + "</span>";
		}
		
		var tmpHigher = higher > data.items.length ? data.items.length : higher; 
		if (data.settings.counter != "") {
			data.settings.counter.html(lower+1 + " - " + tmpHigher + " av " + data.items.length + " "+ maxReachedText);
		}
	}
	
	function fixNavigation(data) {
		
		/* If there will be a next */
		fixNextLink(data);
		
		/* If there will be a previous */
		fixPrevLink(data);
	}
	
	function fixNextLink(data) {
		
		/* Enable or disable it */
		if (data.items.length > data.settings.countPerPage * data.currentPage) {
			nextLink("on", data);
		} else {
			nextLink("off", data);
		}
	}
	
	function fixPrevLink(data) {
		
		/* Enable or disable it */
		if (data.currentPage > 1) {
			prevLink("on", data);
		} else {
			prevLink("off", data);
		}
	}
	
	function prevLink(status, data) {
		
		/* Shows correct button */
		if (status == "on") {
			data.settings.prev.show();
			data.settings.prevDisabled.hide();
		} else {
			data.settings.prev.hide();
			data.settings.prevDisabled.show();
		}
	}
	
	function nextLink(status, data) {
		
		/* Shows correct button */
		if (status == "on") {
			data.settings.next.show();
			data.settings.nextDisabled.hide();
		} else {
			data.settings.next.hide();
			data.settings.nextDisabled.show();
		}
	}
	
	/* Main method */
	$.fn.pagingNew = function(method) {
	
		/* Setup default option values */
		$.fn.pagingNew.defaults = {
				'items'			: "", 
				'prev'			: "", 
				'next'			: "", 
				'prevDisabled'	: "", 
				'nextDisabled'	: "", 
				'counter'		: "", 
				'countPerPage'	: 10,
				'maxResult'		: 50,
				'maxResultText'	: "Prøv att førfina søket.",
				'nextFunction'	: function() {},
				'prevFunction'	: function() {}
			};
		
		/* Call right method... or initialize plugin... or error */
		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.pagingNew' );
		}  
	};
})( jQuery );


/**
 * SCRIPTS
 */
jQuery.fn.highlight = function(pat) {
	function innerHighlight(node, pat) {
		var skip = 0;
		if (node.nodeType == 3) {
			var pos = node.data.toUpperCase().indexOf(pat);
			if (pos >= 0) {
				var spannode = document.createElement('span');
				spannode.className = 'highlight';
				var middlebit = node.splitText(pos);
				var endbit = middlebit.splitText(pat.length);
				var middleclone = middlebit.cloneNode(true);
				spannode.appendChild(middleclone);
				middlebit.parentNode.replaceChild(spannode, middlebit);
				skip = 1;
			}
		} else if (node.nodeType == 1 && node.childNodes
				&& !/(script|style)/i.test(node.tagName)) {
			for ( var i = 0; i < node.childNodes.length; ++i) {
				i += innerHighlight(node.childNodes[i], pat);
			}
		}
		return skip;
	}
	return this.each(function() {
		innerHighlight(this, pat.toUpperCase());
	});
};


/**
 * IE FIXES
 */
if (!Array.indexOf) {
	Array.prototype.indexOf = function(_obj) {
		for (var i = 0; i < this.length; i++) {
			if (this[i] == _obj) {
				return i;
			}
		}
		return -1;
	};
}

/**
 * PROTOTYPE
 */
Array.prototype.find = function(searchStr) {
	var returnArray = false;
	for (i=0; i<this.length; i++) {
		if (typeof(searchStr) == 'function') {
			if (searchStr.test(this[i])) {
				if (!returnArray) { returnArray = []; }
				returnArray.push(i);
			}
		} else {
			if (this[i]===searchStr) {
				if (!returnArray) { returnArray = []; }
				returnArray.push(i);
			}
		}
	}
	return returnArray;
};

/**
 * Adds 'focus' attribute to jQuery
 */
jQuery.extend(jQuery.expr[':'], {
    focus: function(element) { 
    	
    	/* return true if the element is active, else false */
        return element == document.activeElement; 
    }
});

/**
* For animate background-color
*/
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(!g.colorInit){g.start=c(g.elem,e);g.end=b(g.end);g.colorInit=true}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}if(e=/rgba\(0, 0, 0, 0\)/.exec(f)){return a.transparent}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]}})(jQuery);




/*
 * jQuery Autocomplete plugin 1.1
 *
 * Copyright (c) 2009 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
 */;(function($){$.fn.extend({autocomplete:function(urlOrData,options){var isUrl=typeof urlOrData=="string";options=$.extend({},$.Autocompleter.defaults,{url:isUrl?urlOrData:null,data:isUrl?null:urlOrData,delay:isUrl?$.Autocompleter.defaults.delay:10,max:options&&!options.scroll?10:150},options);options.highlight=options.highlight||function(value){return value;};options.formatMatch=options.formatMatch||options.formatItem;return this.each(function(){new $.Autocompleter(this,options);});},result:function(handler){return this.bind("result",handler);},search:function(handler){return this.trigger("search",[handler]);},flushCache:function(){return this.trigger("flushCache");},setOptions:function(options){return this.trigger("setOptions",[options]);},unautocomplete:function(){return this.trigger("unautocomplete");}});$.Autocompleter=function(input,options){var KEY={UP:38,DOWN:40,DEL:46,TAB:9,RETURN:13,ESC:27,COMMA:188,PAGEUP:33,PAGEDOWN:34,BACKSPACE:8};var $input=$(input).attr("autocomplete","off").addClass(options.inputClass);var timeout;var previousValue="";var cache=$.Autocompleter.Cache(options);var hasFocus=0;var lastKeyPressCode;var config={mouseDownOnSelect:false};var select=$.Autocompleter.Select(options,input,selectCurrent,config);var blockSubmit;$.browser.opera&&$(input.form).bind("submit.autocomplete",function(){if(blockSubmit){blockSubmit=false;return false;}});$input.bind(($.browser.opera?"keypress":"keydown")+".autocomplete",function(event){hasFocus=1;lastKeyPressCode=event.keyCode;switch(event.keyCode){case KEY.UP:event.preventDefault();if(select.visible()){select.prev();}else{onChange(0,true);}break;case KEY.DOWN:event.preventDefault();if(select.visible()){select.next();}else{onChange(0,true);}break;case KEY.PAGEUP:event.preventDefault();if(select.visible()){select.pageUp();}else{onChange(0,true);}break;case KEY.PAGEDOWN:event.preventDefault();if(select.visible()){select.pageDown();}else{onChange(0,true);}break;case options.multiple&&$.trim(options.multipleSeparator)==","&&KEY.COMMA:case KEY.TAB:case KEY.RETURN:if(selectCurrent()){event.preventDefault();blockSubmit=true;return false;}break;case KEY.ESC:select.hide();break;default:clearTimeout(timeout);timeout=setTimeout(onChange,options.delay);break;}}).focus(function(){hasFocus++;}).blur(function(){hasFocus=0;if(!config.mouseDownOnSelect){hideResults();}}).click(function(){if(hasFocus++>1&&!select.visible()){onChange(0,true);}}).bind("search",function(){var fn=(arguments.length>1)?arguments[1]:null;function findValueCallback(q,data){var result;if(data&&data.length){for(var i=0;i<data.length;i++){if(data[i].result.toLowerCase()==q.toLowerCase()){result=data[i];break;}}}if(typeof fn=="function")fn(result);else $input.trigger("result",result&&[result.data,result.value]);}$.each(trimWords($input.val()),function(i,value){request(value,findValueCallback,findValueCallback);});}).bind("flushCache",function(){cache.flush();}).bind("setOptions",function(){$.extend(options,arguments[1]);if("data"in arguments[1])cache.populate();}).bind("unautocomplete",function(){select.unbind();$input.unbind();$(input.form).unbind(".autocomplete");});function selectCurrent(){var selected=select.selected();if(!selected)return false;var v=selected.result;previousValue=v;if(options.multiple){var words=trimWords($input.val());if(words.length>1){var seperator=options.multipleSeparator.length;var cursorAt=$(input).selection().start;var wordAt,progress=0;$.each(words,function(i,word){progress+=word.length;if(cursorAt<=progress){wordAt=i;return false;}progress+=seperator;});words[wordAt]=v;v=words.join(options.multipleSeparator);}v+=options.multipleSeparator;}$input.val(v);hideResultsNow();$input.trigger("result",[selected.data,selected.value]);return true;}function onChange(crap,skipPrevCheck){if(lastKeyPressCode==KEY.DEL){select.hide();return;}var currentValue=$input.val();if(!skipPrevCheck&&currentValue==previousValue)return;previousValue=currentValue;currentValue=lastWord(currentValue);if(currentValue.length>=options.minChars){$input.addClass(options.loadingClass);if(!options.matchCase)currentValue=currentValue.toLowerCase();request(currentValue,receiveData,hideResultsNow);}else{stopLoading();select.hide();}};function trimWords(value){if(!value)return[""];if(!options.multiple)return[$.trim(value)];return $.map(value.split(options.multipleSeparator),function(word){return $.trim(value).length?$.trim(word):null;});}function lastWord(value){if(!options.multiple)return value;var words=trimWords(value);if(words.length==1)return words[0];var cursorAt=$(input).selection().start;if(cursorAt==value.length){words=trimWords(value)}else{words=trimWords(value.replace(value.substring(cursorAt),""));}return words[words.length-1];}function autoFill(q,sValue){if(options.autoFill&&(lastWord($input.val()).toLowerCase()==q.toLowerCase())&&lastKeyPressCode!=KEY.BACKSPACE){$input.val($input.val()+sValue.substring(lastWord(previousValue).length));$(input).selection(previousValue.length,previousValue.length+sValue.length);}};function hideResults(){clearTimeout(timeout);timeout=setTimeout(hideResultsNow,200);};function hideResultsNow(){var wasVisible=select.visible();select.hide();clearTimeout(timeout);stopLoading();if(options.mustMatch){$input.search(function(result){if(!result){if(options.multiple){var words=trimWords($input.val()).slice(0,-1);$input.val(words.join(options.multipleSeparator)+(words.length?options.multipleSeparator:""));}else{$input.val("");$input.trigger("result",null);}}});}};function receiveData(q,data){if(data&&data.length&&hasFocus){stopLoading();select.display(data,q);autoFill(q,data[0].value);select.show();}else{hideResultsNow();}};function request(term,success,failure){if(!options.matchCase)term=term.toLowerCase();var data=cache.load(term);if(data&&data.length){success(term,data);}else if((typeof options.url=="string")&&(options.url.length>0)){var extraParams={timestamp:+new Date()};$.each(options.extraParams,function(key,param){extraParams[key]=typeof param=="function"?param():param;});$.ajax({mode:"abort",port:"autocomplete"+input.name,dataType:options.dataType,url:options.url,data:$.extend({q:lastWord(term),limit:options.max},extraParams),success:function(data){var parsed=options.parse&&options.parse(data)||parse(data);cache.add(term,parsed);success(term,parsed);}});}else{select.emptyList();failure(term);}};function parse(data){var parsed=[];var rows=data.split("\n");for(var i=0;i<rows.length;i++){var row=$.trim(rows[i]);if(row){row=row.split("|");parsed[parsed.length]={data:row,value:row[0],result:options.formatResult&&options.formatResult(row,row[0])||row[0]};}}return parsed;};function stopLoading(){$input.removeClass(options.loadingClass);};};$.Autocompleter.defaults={inputClass:"ac_input",resultsClass:"ac_results",loadingClass:"ac_loading",minChars:1,delay:400,matchCase:false,matchSubset:true,matchContains:false,cacheLength:10,max:100,mustMatch:false,extraParams:{},selectFirst:true,formatItem:function(row){return row[0];},formatMatch:null,autoFill:false,width:0,multiple:false,multipleSeparator:", ",highlight:function(value,term){return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)("+term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")+")(?![^<>]*>)(?![^&;]+;)","gi"),"<strong>$1</strong>");},scroll:true,scrollHeight:180};$.Autocompleter.Cache=function(options){var data={};var length=0;function matchSubset(s,sub){if(!options.matchCase)s=s.toLowerCase();var i=s.indexOf(sub);if(options.matchContains=="word"){i=s.toLowerCase().search("\\b"+sub.toLowerCase());}if(i==-1)return false;return i==0||options.matchContains;};function add(q,value){if(length>options.cacheLength){flush();}if(!data[q]){length++;}data[q]=value;}function populate(){if(!options.data)return false;var stMatchSets={},nullData=0;if(!options.url)options.cacheLength=1;stMatchSets[""]=[];for(var i=0,ol=options.data.length;i<ol;i++){var rawValue=options.data[i];rawValue=(typeof rawValue=="string")?[rawValue]:rawValue;var value=options.formatMatch(rawValue,i+1,options.data.length);if(value===false)continue;var firstChar=value.charAt(0).toLowerCase();if(!stMatchSets[firstChar])stMatchSets[firstChar]=[];var row={value:value,data:rawValue,result:options.formatResult&&options.formatResult(rawValue)||value};stMatchSets[firstChar].push(row);if(nullData++<options.max){stMatchSets[""].push(row);}};$.each(stMatchSets,function(i,value){options.cacheLength++;add(i,value);});}setTimeout(populate,25);function flush(){data={};length=0;}return{flush:flush,add:add,populate:populate,load:function(q){if(!options.cacheLength||!length)return null;if(!options.url&&options.matchContains){var csub=[];for(var k in data){if(k.length>0){var c=data[k];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub.push(x);}});}}return csub;}else
if(data[q]){return data[q];}else
if(options.matchSubset){for(var i=q.length-1;i>=options.minChars;i--){var c=data[q.substr(0,i)];if(c){var csub=[];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub[csub.length]=x;}});return csub;}}}return null;}};};$.Autocompleter.Select=function(options,input,select,config){var CLASSES={ACTIVE:"ac_over"};var listItems,active=-1,data,term="",needsInit=true,element,list;function init(){if(!needsInit)return;element=$("<div/>").hide().addClass(options.resultsClass).css("position","absolute").appendTo(document.body);list=$("<ul/>").appendTo(element).mouseover(function(event){if(target(event).nodeName&&target(event).nodeName.toUpperCase()=='LI'){active=$("li",list).removeClass(CLASSES.ACTIVE).index(target(event));$(target(event)).addClass(CLASSES.ACTIVE);}}).click(function(event){$(target(event)).addClass(CLASSES.ACTIVE);select();input.focus();return false;}).mousedown(function(){config.mouseDownOnSelect=true;}).mouseup(function(){config.mouseDownOnSelect=false;});if(options.width>0)element.css("width",options.width);needsInit=false;}function target(event){var element=event.target;while(element&&element.tagName!="LI")element=element.parentNode;if(!element)return[];return element;}function moveSelect(step){listItems.slice(active,active+1).removeClass(CLASSES.ACTIVE);movePosition(step);var activeItem=listItems.slice(active,active+1).addClass(CLASSES.ACTIVE);if(options.scroll){var offset=0;listItems.slice(0,active).each(function(){offset+=this.offsetHeight;});if((offset+activeItem[0].offsetHeight-list.scrollTop())>list[0].clientHeight){list.scrollTop(offset+activeItem[0].offsetHeight-list.innerHeight());}else if(offset<list.scrollTop()){list.scrollTop(offset);}}};function movePosition(step){active+=step;if(active<0){active=listItems.size()-1;}else if(active>=listItems.size()){active=0;}}function limitNumberOfItems(available){return options.max&&options.max<available?options.max:available;}function fillList(){list.empty();var max=limitNumberOfItems(data.length);for(var i=0;i<max;i++){if(!data[i])continue;var formatted=options.formatItem(data[i].data,i+1,max,data[i].value,term);if(formatted===false)continue;var li=$("<li/>").html(options.highlight(formatted,term)).addClass(i%2==0?"ac_even":"ac_odd").appendTo(list)[0];$.data(li,"ac_data",data[i]);}listItems=list.find("li");if(options.selectFirst){listItems.slice(0,1).addClass(CLASSES.ACTIVE);active=0;}if($.fn.bgiframe)list.bgiframe();}return{display:function(d,q){init();data=d;term=q;fillList();},next:function(){moveSelect(1);},prev:function(){moveSelect(-1);},pageUp:function(){if(active!=0&&active-8<0){moveSelect(-active);}else{moveSelect(-8);}},pageDown:function(){if(active!=listItems.size()-1&&active+8>listItems.size()){moveSelect(listItems.size()-1-active);}else{moveSelect(8);}},hide:function(){element&&element.hide();listItems&&listItems.removeClass(CLASSES.ACTIVE);active=-1;},visible:function(){return element&&element.is(":visible");},current:function(){return this.visible()&&(listItems.filter("."+CLASSES.ACTIVE)[0]||options.selectFirst&&listItems[0]);},show:function(){var offset=$(input).offset();element.css({width:typeof options.width=="string"||options.width>0?options.width:$(input).width(),top:offset.top+input.offsetHeight,left:offset.left}).show();if(options.scroll){list.scrollTop(0);list.css({maxHeight:options.scrollHeight,overflow:'auto'});if($.browser.msie&&typeof document.body.style.maxHeight==="undefined"){var listHeight=0;listItems.each(function(){listHeight+=this.offsetHeight;});var scrollbarsVisible=listHeight>options.scrollHeight;list.css('height',scrollbarsVisible?options.scrollHeight:listHeight);if(!scrollbarsVisible){listItems.width(list.width()-parseInt(listItems.css("padding-left"))-parseInt(listItems.css("padding-right")));}}}},selected:function(){var selected=listItems&&listItems.filter("."+CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);return selected&&selected.length&&$.data(selected[0],"ac_data");},emptyList:function(){list&&list.empty();},unbind:function(){element&&element.remove();}};};$.fn.selection=function(start,end){if(start!==undefined){return this.each(function(){if(this.createTextRange){var selRange=this.createTextRange();if(end===undefined||start==end){selRange.move("character",start);selRange.select();}else{selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}}else if(this.setSelectionRange){this.setSelectionRange(start,end);}else if(this.selectionStart){this.selectionStart=start;this.selectionEnd=end;}});}var field=this[0];if(field.createTextRange){var range=document.selection.createRange(),orig=field.value,teststring="<->",textLength=range.text.length;range.text=teststring;var caretAt=field.value.indexOf(teststring);field.value=orig;this.selection(caretAt,caretAt+textLength);return{start:caretAt,end:caretAt+textLength}}else if(field.selectionStart!==undefined){return{start:field.selectionStart,end:field.selectionEnd}}};})(jQuery);
