var dishTypes = ['appetizers', 'mainCourses', 'deserts', 'delicacies', 'newArticles', 'tryCourses', 'weekCourses', 'weekSuggestions']; /* All types to search for in XML, will also be used as a reference for the right DIV id */
//var dishTypes = ['appetizers']; /* All types to search for in XML, will also be used as a reference for the right DIV id */
//var contentURL = "http://localhost:8080/template/testdoc?jsoncallback=?";
//var contentURL = "http://93.175.178.192/tools/template/testdoc?doc=gerechten.xml&jsoncallback=?";
//var contentURL = "http://localhost:2000/newco/homepagetest/res/testdoc?doc=gerechten.xml&jsoncallback=?";
//var contentURL = "http://localhost:2000/newco/homepagetest/res/gerechten.xml";
//var contentURL = "http://localhost/newcoapi/homepagetest/res/gerechten.xml";

//Kookfabriek
var contentURL = "http://apps.newcofoodretail.com/tools/pricebutton?key=R910&affiliate=newco&jsoncallback=?";
var MEALS =  new Array();
var DISHES = new Array();
var SWITCH_SPEED = 300; // Milliseconds
var newco = {
		template : "",
		gerechten : [],
		templatedishes : {},
		shop : "culinaireversmarkt",
		affiliate : "newco",
		dataType : "full",
		special : null
};

function Meal(type, dishes) {
	var meal = this;
	
	this.type = type;
	this.dishes = dishes;
	var currentDish = 0;
	
	this.init = function(){
		$("#" + meal.type.toLowerCase()).find(".cvm-dish-next").click(function(){
			meal.nextDish();
		});
				
		$("#" + meal.type.toLowerCase()).find(".cvm-dish-previous").click(function(){
			meal.previousDish();
		});
	}
	
	this.nextDish = function(){
		currentDish++;
		if(currentDish > meal.dishes.length-1){
			currentDish = 0;
		}
		var dish = meal.dishes[currentDish];
		showDish(meal.type, dish);
	}
	
	this.previousDish = function(){
		currentDish--;
		if(currentDish < 0){
			currentDish = meal.dishes.length-1;
		}
		var dish = meal.dishes[currentDish];
		showDish(meal.type, dish);
	}
}

function Dish(dishName, image, link, per, price, subtitle, preparationtime, title, description, ingredients, instructions, cookingtime, dishtype, waardering, basicingredients, waarderingnumber, articleType, recipes, prevprice, features, show, orderable, unity){
	this.dishName = dishName;
	this.image = image;
	this.link = link;
	this.per = per;
	this.price = price;
	this.subtitle = subtitle;
	this.preparationtime = preparationtime;
	this.cookingtime = cookingtime;
	this.title = title;
	this.description = description ? description : null;
	this.ingredients = ingredients;
	this.basicingredients = basicingredients;
	this.instructions = instructions;
	this.dishtype = dishtype;
	this.waardering = waardering;
	this.waarderingnumber = waarderingnumber;
	this.articletype = articleType;
	this.recipes = recipes;
	this.prevprice = prevprice || 0.00;
	this.features = features;
	this.show = show;
	this.orderable = orderable;
	this.unity = unity;
}


function showDish(type, dish){
	var suggestion;
	if(type == "newArticles")suggestion=3;
	if(type == "tryCourses")suggestion=1;
	if(type == "weekCourses")suggestion=0;
	if(type == "weekSuggestions")suggestion=2;
	
	if (type == 'appetizers' || type == 'mainCourses' || type == 'deserts' || type == 'delicacies') {
		$("#" + type.toLowerCase()).children().children("#cvm-dish-link")[0].href = dish.link;
		$("#" + type.toLowerCase()).children("a")[0].href = dish.link;
		$("#" + type.toLowerCase()).children().children("#cvm-dish-link").children("#cvm-dish-image").fadeOut(SWITCH_SPEED, function(){
			$("#" + type.toLowerCase()).children().children("#cvm-dish-link").children("#cvm-dish-image")[0].src = dish.image;
			$("#" + type.toLowerCase()).children().children("#cvm-dish-link").children("#cvm-dish-image").fadeIn(SWITCH_SPEED);
		});
		$("#" + type.toLowerCase()).children(".cvm-dish-info")[0].innerHTML = dish.title + "<br>" + dish.sub + "<hr><img src='res/images/klok-icon.png' style='float:left;margin-right:5px;' alt='klok'><b>" + dish.time + "</b><b> " + dish.price + "<font size='1'></font></b>";
	}else{
		var suggestions = $(".cvm-suggestion");
		var extraText = dish.text ? dish.text : "<br>";
		$(suggestions[suggestion]).find("a").attr("href", dish.link);
		$(suggestions[suggestion]).find("a").find("img")[0].src = dish.image;
		$(suggestions[suggestion]).find(".cvm-suggestion-info").html(
			'<font size="3"><b>' + dish.title + '</b></font><br> <font size="2">' + dish.sub + '</font><p><font size="2">' + extraText  + '</font> </p>' 
			+ '<hr><img src="res/images/klok-icon.png" style="float:left;margin-right:5px;" alt="klok"><font size="2" style="float:left;margin-top:-5px;">'
			+ dish.time + " " + dish.price + '</font><a href="' + dish.link + '"><img style="margin:-5px 0 0 20px;" src="res/images/bekijk-button.png" alt="BEKIJK"></a>'
		);
	}
}


$(document).ready(function(){
	var dishesPlaces = $(".newcodish");
	if(!newco.gerechten)
		newco.gerechten = null;
	if(!newco.check)
		newco.check="check";
	if(!newco.ignoreContentRules)
		newco.ignoreContentRules = false;
	
	var searchdata = {};
	var testURLS = window.location.search.slice(1 , window.location.search.length).split("&");
	
	if (window.location.search.length != 0) {
		for (var i = 0; i < testURLS.length; i++) {
			searchdata[testURLS[i].split("=")[0]] = testURLS[i].split("=")[1];
			newco[testURLS[i].split("=")[0]] = testURLS[i].split("=")[1];
			//newco.persons = searchdata.persons;
			//newco.dish = searchdata.dish;
			//newco.template = searchdata.template;
		}
		if (newco.dish && newco.persons) {
			//loadPageDishes(searchdata);
			var quantity = "&num=" + (newco.persons ? newco.persons : 1) + "&ingrnum=" + (newco.ingrnum ? newco.ingrnum : (newco.persons ? newco.persons : 1));
			var contentURL = "http://apps.newcofoodretail.com/tools/pricebutton?key=" + newco.dish + "&affiliate=" + newco.affiliate + "&shop=" + newco.shop + "&check=" + newco.check + "&jsoncallback=?" + quantity + "&level=" +( newco.level || 3);
			var content = new Array();
			getContentDishes(contentURL);
		}
	}
	
	if (dishesPlaces && newco.gerechten) {
		if (dishesPlaces.length >= newco.gerechten.length) {
			loadPageDishes();
		}
		else {
			//console.log("ERROR: Not enough places");
			for (var i = 0; i < newco.gerechten.length - dishesPlaces.length; i++) {
				$(dishesPlaces[0]).clone().insertAfter(dishesPlaces[0]);
			}
			loadPageDishes();
		}
	}
	
	$('.newcodishimage').each(function(){
		$(this).css('display', 'none');
		this.src = "http://www.culinaireversmarkt.nl/placeholder.png";
		$(this).fadeIn(500);
	});
	
	getTemplate();
});

function getTemplate(){
	if(newco.template)
	if (newco.template.length > 0) {
		$.getJSON("http://apps.newcofoodretail.com/tools/pricebutton?jsoncallback=?&template=" + newco.template, function(data){
			
			if (data.msg == "template found") {
				newco.templatereturn = data.url;
				
				var coordString = data.url;
				var parameters = coordString.split("&");
				var object = {};
				var dishNames = "";
				for (var i = 0; i < parameters.length; i++) {
					var parameter = parameters[i].split("=");
					if (parameter[0] == "date") {
						newco.timerDate = parameter[1];
						setNewcoTimer();
					}
					else {
						var value = parameter[1];
						var m = /\[[^[]+\]/gi;
						value = value.replace(m, "");
						newco.templatedishes[parameter[0]] = value.split(",");
						newco.templateplaces[i] = parameter[0];
						
						for (var p = 0; p < parameter[1].split(",").length; p++) {
							var dishName = parameter[1].split(",")[p];
							dishName = dishName.replace(/[\[]/gi, ",");
							dishName = dishName.replace(/[\]]/gi, "");
							dishNames += dishName + ",";
						}
					}
				}
				dishNames = dishNames.substr(0, dishNames.length - 1);
				var quantity = "&num=" + (newco.persons ? newco.persons : 1) + "&ingrnum=" + (newco.ingrnum ? newco.ingrnum : (newco.persons ? newco.persons : 1));
				var contentURL = "http://apps.newcofoodretail.com/tools/pricebutton?key=" + dishNames + "&affiliate=" + newco.affiliate + "&shop=" + newco.shop + "&templatename=" + newco.template + "&check=" + newco.check + "&jsoncallback=?" + quantity + "&level=" +( newco.level || 3);
				getContentDishes(contentURL);
			}else{
				// Template is unknown or not found
				// console.log(data.msg);
				//alert("Op dit moment zijn er moeilijkheden en deze zorgen ervoor dat de wij niet de juiste inhoud kunnen tonen. \nKom alstublieft terug op een ander tijdstip.");
				//alert("We are currently having some issues, Which are causing our features to not work properly \n Please come back at a later time");
			}
		}, "application/json");
		/*
.error(function(){
			// We are currently having some issues 
			// Which are causing our features to not work properly
			// Please come back at a later time
			//alert("Op dit moment zijn er moeilijkheden en deze zorgen ervoor dat de wij niet de juiste inhoud kunnen tonen. \nKom alstublieft terug op een ander tijdstip.");
			
			
			// SEND MAIL TO ALAIN OR PAUL
		});
*/
	}
}

// private String articleCode;
// private double price;
// private double discountPrice;
// private Date discountDate;
// private String title;
// private String image;
// private boolean isBiologic;

function getFeature(feature, amount){
	$.getJSON("http://apps.newcofoodretail.com/tools/pricebutton?jsoncallback=?&feature=" + feature + "&amount=" + amount, function(data){
		var articles = data.articles;
		var places = $(".newcodish" + feature);
		
		for (var a = 0; a < articles.length; a++) {
			var article = articles[a];
			if(!newco.featureDishes[feature])
				newco.featureDishes[feature] = new Array();
				
			newco.featureDishes[feature].push(new Dish(article.articlekey, article.imageurl, article.shopurl, "", article.price, article.subtitle, article.preparationtime, article.title, article.description, article.ingredients, article.instructions, article.cookingtime, article.dishtype, article.waardering, article.basicingredients, article.waardering_no));
		}
		
		if (newco.featureDishes[feature].length > places.length) {
			for (var p = 0; p < newco.featureDishes[feature].length - places.length; p++) {
				$(places[0]).clone().insertAfter(places[places.length - 1]);
			}
			places = $(".newcodish" + templateplace);
		}
		placeContent(newco.featureDishes[feature], places, ".newcodish" + feature);
		
	}, "application/json").error(function(){
		
	});
}

function getCategory(category) {
	$.getJSON("http://apps.newcofoodretail.com/tools/category?name=" + category, function(data){
		var name = data.name;
		var grpid = data.grpid;
		var childgrps = data.childgrps;
	});
}

function splitUrl(url){
	
}

function placeContent(content, places, placename){
	var active;
	var positions = 0;
	var animated = true;
	//console.log([content, places, placename]);
	for (var i = 0; i < content.length; i++) {
		var article = content[i];
		var place = places[i];
		
		if(article.show == 0 && !newco.ignoreContentRules) {
			content.splice(i, 1);
			$(places[i]).remove();
			places.splice(i, 1);
			i--;
			continue;
		}
		
		//console.log(place);
		//console.log(article);
		if (article) {
			$(place).find(".newcodishimage").attr("src", article.image);
			$(place).find(".newcodishimage").css("opacity", "1");
		$(place).find(".newcodishurl").attr("href", article.link);
		if (article.dishtype != "") 
			$(place).find(".newcodishdishtype").html(article.dishtype);
		$(place).find(".newcodishwholetitle").html(article.title + " " + article.subtitle);
		$(place).find(".newcodishtitle").html(article.title);
		$(place).find(".newcodishshorttitle").html(article.title.split(" ")[0]);
		$(place).find(".newcodishsubtitle").html(article.subtitle);
		if (article.preparationtime) 
			$(place).find(".newcodishtime").html(article.preparationtime + " min.");
		if (article.cookingtime) 
			$(place).find(".newcodishcookingtime").html(article.cookingtime + " min.");
		$(place).find(".newcodishdescription").html(article.description);
		if(article.per.length = 0)
			$(place).find(".newcodishper").html(article.per);
		else{
			if(article.dishName.charAt(0) != "L")
				$(place).find(".newcodishper").html(" p.p.");
		}
		$(place).find(".newcodishpreparation").html(article.preparation);
		$(place).find(".newcodishingredients").html(article.ingredients);
		$(place).find(".newcodishbasicingredients").html(article.basicingredients);
		$(place).find(".newcodishinstructions").html(article.instructions);
		$(place).find(".newcodishdifficulty").html(article.waardering);
		$(place).find(".newcodishunity").html(article.unity);
		
		if (parseInt(article.waarderingnumber) > 0) 
			$(place).find(".newcodishdifficultynumber").html(article.waarderingnumber);
		
		if (article.price != 0.00) {
			$(place).find(".newcodishprice").html("&euro; " + article.price.toFixed(2).replace(".", ","));
		}
		else {
			$(place).find(".newcodishprice").html("&euro; " + article.price.toFixed(2).replace(".", ","));
		}
		
		if (article.prevprice != 0.00) {
			$(place).find(".newcodishpreviousprice").html("&euro; " + article.prevprice.toFixed(2).replace(".", ","));
		}
		
		if(getArticleFeature(article, "biologisch")){
			$(place).find(".newcodishbio").show();
		}
		
		if(getArticleFeature(article, "culinair")){
			$(place).find(".newcodishculinair").show();
		}
		
		if(newco.persons)
			$(".newcodishperson").html(newco.persons);
			
		var end = article.title.search(" ");
		if (end > 0) {
			var endtitle = article.title.slice(end, article.title.length);
			
			$(place).find(".newcodishshortendtitle").html(endtitle);
		}
		
		if ($(place).attr("newcolist") == "true") {
			active = places[0];
			$(place).find("#newcodishselectnext").click(function(){
				$(this).parent().hide();
				if ($(this).parent().next(placename).length > 0) 
					$(this).parent().next(placename).show();
				else {
					if ($(this).parent().siblings(placename).length > 0) 
						$($(this).parent().siblings(placename)[0]).show();
					else 
						$(this).parent().show();
				}
			});
			
			$(place).find("#newcodishselectprevious").click(function(){
				$(this).parent().hide();
				if ($(this).parent().prev(placename).length > 0) 
					$(this).parent().prev(placename).show();
				else {
					if ($(this).parent().siblings(placename).length > 0) 
						$($(this).parent().siblings(placename)[$(this).parent().siblings(placename).length - 1]).show();
					else 
						$(this).parent().show();
				}
			});
		}
		else 
			if (parseInt($(place).attr("newcolist"))) {
				if (positions < parseInt($(place).attr("newcolist"))) 
					positions++;
				else 
					$(place).hide();
				
				if (positions == 1) {
					$(place).parent().find("#newcodishselectnext").click(function(){
						//console.log("next!");
						var replace = $(placename).first();
						$(placename).last().after($(replace));
						$(replace).hide();
						$($(placename)[parseInt($(place).attr("newcolist")) - 1]).show();
						
					});
					
					$(place).parent().find("#newcodishselectprevious").click(function(){
						//console.log("prev!");
						var replace = $(placename).last();
						$(replace).show();
						$(placename).first().before($(replace));
						$($(placename)[parseInt($(place).attr("newcolist"))]).hide();
						
					});
				}
			}
	}
	}
	if (active) {
		$(places).css("display", "none");
		$(active).css("display", "block");
	}
}

function controlContentData(template){
	var dishesPlaces = $(".newcodish");
	
	if (template) {
		dishesPlaces = $(".newcodish" + template);
		if (newco.templatedishes[template].length > dishesPlaces.length) {
			for (var i = 0; i < newco.templatedishes[template].length - dishesPlaces.length; i++) {
				$(dishesPlaces[0]).clone().insertAfter(dishesPlaces[dishesPlaces.length - 1]);
			}
			dishesPlaces = $(".newcodish" + template);
		}
	}
	
	
//	$(".newcodish").each(function(){
//		if ($(this).attr("newcodish[]")) {
//			console.log($(this).attr("newcodish[]"));
//			for(var i = 0; i < DISHES.length; i++){
//				
//			}
//		}
//	});

		for (var i = 0; i < DISHES.length; i++) {
			var place = dishesPlaces[i];
			if (newco.gerechten) {
				for (var n = 0; n < newco.gerechten.length; n++) {
					if (newco.gerechten[n] == DISHES[i].dishName) {
						place = dishesPlaces[n];
					}
				}
				if(template)
					if(newco.templatedishes[template].length != 0)
						for (var n = 0; n < newco.templatedishes[template].length; n++) {
							if (newco.templatedishes[template][n] == DISHES[i].dishName) {
								place = dishesPlaces[n];
							}
						}
					else
						return;
			}
		
			$(place).find(".newcodishimage").attr("src", DISHES[i].image);
			$(place).find(".newcodishurl").attr("href", DISHES[i].link);
			$(place).find(".newcodishdishtype").html(DISHES[i].dishtype);
			$(place).find(".newcodishwholetitle").html(DISHES[i].title + " " + DISHES[i].subtitle);
			$(place).find(".newcodishtitle").html(DISHES[i].title);
			$(place).find(".newcodishshorttitle").html(DISHES[i].title.split(" ")[0]);
			$(place).find(".newcodishsubtitle").html(DISHES[i].subtitle);
			if(DISHES[i].preparationtime >= 0)
				$(place).find(".newcodishtime").html(DISHES[i].preparationtime + " min.");
			if(DISHES[i].cookingtime >= 0)
				$(place).find(".newcodishcookingtime").html(DISHES[i].cookingtime  + " min.");
			$(place).find(".newcodishdescription").html(DISHES[i].description);
			$(place).find(".newcodishper").html(DISHES[i].per);
			$(place).find(".newcodishpreparation").html(DISHES[i].preparation);
			$(place).find(".newcodishingredients").html(DISHES[i].ingredients);
			$(place).find(".newcodishbasicingredients").html(DISHES[i].basicingredients);
			$(place).find(".newcodishinstructions").html(DISHES[i].instructions);
			$(place).find(".newcodishdifficulty").html(DISHES[i].waardering);
			if(DISHES[i].waarderingnumber > 0)
				$(place).find(".newcodishdifficultynumber").html(DISHES[i].waarderingnumber);
			
			if (DISHES[i].price != 0.00) {
				$(place).find(".newcodishprice").html("&euro; " + DISHES[i].price.toFixed(2).replace(".", ","));
			}else{
				$(place).find(".newcodishprice").html("&euro; " + DISHES[i].price.toFixed(2).replace(".", ","));
			}
			
			
			var end = DISHES[i].title.search(" ");
			if (end > 0) {
				var endtitle = DISHES[i].title.slice(end, DISHES[i].title.length);
				
				$(place).find(".newcodishshortendtitle").html(endtitle);
			}
		}
		
		if(newco.persons)
			$(".newcodishperson").html(newco.persons);
			
		if(!template)
			if(newco.special)
				newco.special();
}

function loadPageDishes(searchdata){
	
	
	if(!newco.shop)
		newco.shop = "culinaireversmarkt";
	if(!newco.affiliate)
		newco.affiliate = "newco";
	
	if (!searchdata) {
		for (var i = 0; i < newco.gerechten.length; i++) {
			var dishName = newco.gerechten[i];
			//var contentURL = "http://93.175.178.192/tools/pricebutton?key=" + dishName + "&affiliate=kookfabriek&shop=" + newco.shop + "&jsoncallback=?";
			var contentURL = "http://apps.newcofoodretail.com/tools/pricebutton?key=" + dishName + "&shop=" + newco.shop + "&jsoncallback=?";
			getContentDish(dishName, contentURL);
		}
	}else{
		//var contentURL = "http://93.175.178.192/tools/pricebutton?key=" + searchdata.dish + "&affiliate=kookfabriek&num=" + parseInt(searchdata.persons) + "&shop=" + newco.shop + "&jsoncallback=?";
		var contentURL = "http://apps.newcofoodretail.com/tools/pricebutton?key=" + searchdata.dish + "&num=" + parseInt(searchdata.persons) + "&shop=" + newco.shop + "&jsoncallback=?";
		getContentDish(searchdata.dish, contentURL);
	}
}

// To make a small change in the content
function restartPageDishes(){
	DISHES = new Array();
	loadPageDishes(newco);
}

function getContentDish(contentURL, type) {
	var dish;
	
	$.ajaxSetup({async : false});
	$.getJSON(contentURL, function(data){
		for (var a = 0; a < data.articles.length; a++) {
			var article = data.articles[a];
			dish = new Dish(article.articlekey, article.imageurl, article.shopurl, "", article.price, article.subtitle, article.preparationtime, article.title, article.description, article.ingredients, article.instructions, article.cookingtime, article.dishtype, article.waardering, article.basicingredients, article.waardering_no, article.articletype, article.recipes, article.discountprice, article.features, article.show, article.orderable);
			DISHES.push(dish);
		}
		
		for (var e = 0; e < data.error.length; e++) {
			var error = data.error[e];
			for(var i = 0; i < newco.templateplaces.length; i++) {
				var place = newco.templateplaces[i];
				for (var t = 0; t < newco.templatedishes[place].length; t++) 
					if (error.articlekey == newco.templatedishes[place][t]) {
						newco.templatedishes[place].splice(t, 1);
						t--;
					}
			}
		}
		$.ajaxSetup({async : true});
	});
	return dish;
}

// The old getContentDish
/*
function getContentDish(dishName, contentURL, template){
	
	$.getJSON(contentURL, function(data){
		//console.log(data);
		for (var a = 0; a < data.articles.length; a++) {
			var article = data.articles[a];
			if (data.error.articles) 
				for (var i = 0; i < newco.templatedishes[template].length; i++) 
					if (data.error.articles.articleKey == newco.templatedishes[template][i]) {
						newco.templatedishes[template].splice(i, 1);
						checkTemplateDishes(template);
						return;
					}
			
			DISHES.push(new Dish(article.articlekey, article.imageurl, article.shopurl, "", article.price, article.subtitle, article.preparationtime, article.title, article.description, article.ingredients, article.instructions, article.cookingtime, article.dishtype, article.waardering, article.basicingredients, article.waardering_no, article.articletype, article.recipes, article.discountprice, article.features));
		}
	}, "application/json").success(function(){
		if (template) {
			checkTemplateDishes(template);
		}
		else {
			if (newco.gerechten.length > 0) {
				if (DISHES.length == newco.gerechten.length) 
					controlContentData();
			}
			else 
				controlContentData();
		}
	});
}
*/

function getContentDishesData(data){
		for (var a = 0; a < data.articles.length; a++) {
			var article = data.articles[a];
			DISHES.push(new Dish(article.articlekey, article.imageurl, article.shopurl, "", article.price, article.subtitle, article.preparationtime, article.title, article.description, article.ingredients, article.instructions, article.cookingtime, article.dishtype, article.waardering, article.basicingredients, article.waardering_no, article.articletype, article.recipes, article.discountprice, article.features, article.show, article.orderable, article.unity));
		}
		
		for (var e = 0; e < data.error.length; e++) {
			var error = data.error[e];
			for(var i = 0; i < newco.templateplaces.length; i++){
				var place = newco.templateplaces[i];
				for (var t = 0; t < newco.templatedishes[place].length; t++) 
					if (error.articlekey == newco.templatedishes[place][t]) {
						newco.templatedishes[place].splice(t, 1);
						t--;
					}
			}
		}
		getContentDishesSuccess();
}

function getContentDishesSync(contentURL){
	$.ajax({
		type: 'GET',
		url: contentURL,
		dataType: 'json',
		success: getContentDishesData,
		data: {},
		async: false
	});
}

function getContentDishes(contentURL, type){
	$.getJSON(contentURL, function(data){
		//console.log(data);
		for (var a = 0; a < data.articles.length; a++) {
			var article = data.articles[a];
			DISHES.push(new Dish(article.articlekey, article.imageurl, article.shopurl, "", article.price, article.subtitle, article.preparationtime, article.title, article.description, article.ingredients, article.instructions, article.cookingtime, article.dishtype, article.waardering, article.basicingredients, article.waardering_no, article.articletype, article.recipes, article.discountprice, article.features, article.show, article.orderable, article.unity));
		}
		
		for (var e = 0; e < data.error.length; e++) {
			var error = data.error[e];
			for(var i = 0; i < newco.templateplaces.length; i++){
				var place = newco.templateplaces[i];
				for (var t = 0; t < newco.templatedishes[place].length; t++) 
					if (error.articlekey == newco.templatedishes[place][t]) {
						newco.templatedishes[place].splice(t, 1);
						t--;
					}
			}
		}
		getContentDishesSuccess();
	});/*
.success(function(){
		for(var i = 0; i < newco.templateplaces.length; i++){
			var templateplace = newco.templateplaces[i];
			var content = new Array();
			var places = $(".newcodish" + templateplace);
			var placename = ".newcodish" + templateplace;
			if (newco.templatedishes[templateplace].length > places.length) {
				for (var p = 0; p < newco.templatedishes[templateplace].length - places.length; p++) {
					$(places[0]).clone().insertAfter(places[places.length - 1]);
				}
				places = $(".newcodish" + templateplace);
			}
			
			for (var t = 0; t < newco.templatedishes[templateplace].length; t++) {
				var articlecode = newco.templatedishes[templateplace][t];
				var dish = getDish(articlecode);
				content.push(dish);
				if (dish.articletype == "MENU") {
					if(!newco.menus)
						newco.menus = {};
					
					if(!newco.menus[templateplace])
						newco.menus[templateplace] = new Array();
					
					newco.menus[templateplace].push(dish.recipes);
				}
			}
			placeContent(content, places, placename);
		}
		if(newco.menus)
			setMenus();
		
		if(newco.special)
			newco.special();
		
	}).error(function(){
		//Stuff went wrong FIX IT!
		// SEND MAIL TO ALAIN OR PAUL
	});
*/
}

function getContentDishesSuccess() {
	if(newco.templateplaces)
		for(var i = 0; i < newco.templateplaces.length; i++) {
			var templateplace = newco.templateplaces[i];
			var content = new Array();
			var places = $(".newcodish" + templateplace);
			var placename = ".newcodish" + templateplace;
			if (newco.templatedishes[templateplace].length > places.length) {
				for (var p = 0; p < newco.templatedishes[templateplace].length - places.length; p++) {
					$(places[0]).clone().insertAfter(places[places.length - 1]);
				}
				places = $(".newcodish" + templateplace);
			}
			
			for (var t = 0; t < newco.templatedishes[templateplace].length; t++) {
				var articlecode = newco.templatedishes[templateplace][t];
				var dish = getDish(articlecode);
				content.push(dish);
				if (dish.articletype == "MENU") {
					if(!newco.menus)
						newco.menus = {};
					
					if(!newco.menus[templateplace])
						newco.menus[templateplace] = new Array();
					
					newco.menus[templateplace].push(dish.recipes);
				}
			}
			placeContent(content, places, placename);
		}
		if(newco.dish) {
			var dish = getDish(newco.dish);
			var content = new Array();
			var places = $('.newcodish');
			content.push(dish);
			placeContent(content, places);
		}
		if(newco.menus)
			setMenus();
		
		if(newco.special)
			newco.special();
		
}

function setMenus(){
	for (var i = 0; i < newco.templateplaces.length; i++) {
		var templateplace = newco.templateplaces[i];
		if(newco.menus[templateplace]) {
			var places = $(".newcodish" + templateplace + "recipe");
			var placename = ".newcodish" + templateplace + "recipe";
			
			if(newco.menus[templateplace].length > places.length){
				for (var p = 0; p < newco.menus[templateplace].length - places.length; p++) {
					$(places[0]).clone().insertAfter(places[places.length - 1]);
				}
				places = $(".newcodish" + templateplace + "recipe");
			}
			
			for(var x = 0; x < places.length; x++){
				var recipePlaces = $(places[x]).find(".newcodishrecipe");
				var recipeContent = new Array();
				
				for(var a = 0; a < newco.menus[templateplace][x].length; a++)
					recipeContent.push(getDish(newco.menus[templateplace][x][a]));
					
				placeContent(recipeContent, recipePlaces, placename);
			}
			
		}
	}
}

function getDish(articlecode){
	for (var i = 0; i < DISHES.length; i++)
		if(articlecode == DISHES[i].dishName)
			return DISHES[i];
	return false;
}

function getArticleFeature(article, feature){
	for(var i = 0; i < article.features.length; i++)
		if(article.features[i] == feature)
			return true;
	
	return false;
}

function checkTemplateDishes(template){
	var counter = 0;
	//newco.templatedishes[template]
	for(var i = 0; i < DISHES.length; i++){
		var dish = DISHES[i];
		//console.log(newco.templatedishes[template]);
		for(var t = 0; t < newco.templatedishes[template].length; t++){
			var templatename = newco.templatedishes[template][t];
			if(dish.dishName == templatename)
				counter++;
		}
	}
	if(counter == newco.templatedishes[template].length)
		controlContentData(template);
	
}

function placeLoader(places){
	for(var i = 0; i < places.length; i++){
		var place = places[i];
		$(place).find(".newcodishimage").attr("src", "http://culinaireversmarkt.com/contentApiLoader.gif");
		//$(place).find(".newcodishurl").attr("href", "");
		$(place).find(".newcodishdishtype").html("laden...");
		$(place).find(".newcodishwholetitle").html("laden...");
		$(place).find(".newcodishtitle").html("laden...");
		$(place).find(".newcodishshorttitle").html("laden...");
		$(place).find(".newcodishsubtitle").html("laden...");
		$(place).find(".newcodishtime").html("...");
		$(place).find(".newcodishcookingtime").html("...");
		$(place).find(".newcodishdescription").html("laden...");
		$(place).find(".newcodishper").html("...");
		$(place).find(".newcodishpreparation").html("laden...");
		$(place).find(".newcodishingredients").html("laden...");
		$(place).find(".newcodishbasicingredients").html("laden...");
		$(place).find(".newcodishinstructions").html("laden...");
		$(place).find(".newcodishdifficulty").html("-");
		$(place).find(".newcodishdifficultynumber").html("-");
		$(place).find(".newcodishprice").html("-");
		$(place).find(".newcodishshortendtitle").html("laden...");
	}
}

function pageLoader(){
	document.body.innerHTML += '<div id="pageLoader" style="background-color:black;opacity: 0.7;position:absolute;z-index:99;display:none;"><center><img style="text-align:center;opacity:1;"src="src/ajax-loader.gif"></img></center></div>';
	$("#pageLoader").prependTo(document.body);
	$("#pageLoader").show(function(){
		$(this).height($(document).height());
		$(this).width($(document).width());
		$(this).find("img").css("marginTop", $(document).scrollTop() + ($(window).height()/2));
		$(document).scroll(function(){
			$("#bestel-loader").find("img").css("marginTop", $(document).scrollTop() + ($(window).height() / 2));
		});
	});
}

function setNewcoTimer(){
	var date = newco.timerDate.split("-");
	
	var year = parseInt(date[2]);
	var month = parseInt(date[1]);
	var day = parseInt(date[0]);
	var hour = parseInt(date[3].split(":")[0]);
	var minute = parseInt(date[3].split(":")[1]);
	var second = 0;
	var end = new Date(year,month,day,hour,minute,second);
	newco.timerDate = {
		year : parseFloat(date[2]),
		month : parseFloat(date[1]) - 1,
		day : parseFloat(date[0]),
		hour : parseFloat(date[3].split(":")[0]),
		minute : parseFloat(date[3].split(":")[1]),
		second : 0
	}
	newco.timerDate.end = new Date(newco.timerDate.year,newco.timerDate.month,newco.timerDate.day,newco.timerDate.hour,newco.timerDate.minute,newco.timerDate.second);
	if(new Date() > newco.timerDate.end)
		newco.endTimer();
	else
		timeleft();
}

var eventtext = "until the next big thing"; // text that appears next to the time left
var endtext = "We reached the next big thing!!"; // text that appears when the target has been reached

function timeleft(){
	newco.endreached = false;
	var now = new Date();
	if(now.getYear() < 1900)
		yr = now.getYear() + 1900;
	var sec = newco.timerDate.second - now.getSeconds();
	var min = newco.timerDate.minute - now.getMinutes();
	var hr = newco.timerDate.hour - now.getHours();
	var dy = newco.timerDate.day - now.getDate();
	var mnth = newco.timerDate.month - now.getMonth();
	var yr = newco.timerDate.year - yr;
	var daysinmnth = 32 - new Date(now.getYear(),now.getMonth(), 32).getDate();
	if(sec < 0){
		sec = (sec+60)%60;
		min--;
	}
	if(min < 0){
		min = (min+60)%60;
		hr--;	
	}
	if(hr < 0){
		hr = (hr+24)%24;
		dy--;
	}
	if(dy < 0){
		dy = (dy+daysinmnth)%daysinmnth;
		mnth--;	
	}
	if(mnth < 0){
		mnth = (mnth+12)%12;
		yr--;
	}
	
	hr += dy*24;
	
	//console.log(dy);
	var sectext = " seconds ";
	var mintext = " minutes, and ";
	var hrtext = " hours, ";
	var dytext = " days, ";
	var mnthtext = " months, ";
	var yrtext = " years, ";
	if (yr == 1)
		yrtext = " year, ";
	if (mnth == 1)
		mnthtext = " month, ";
	if (dy == 1)
		dytext = " day, ";
	if (hr == 1)
		hrtext = " hour, ";
	if (min == 1)
		mintext = " minute, and ";
	if (sec == 1)
		sectext = " second ";
	if(now >= newco.timerDate.end){
		//console.log(endtext);
		if(newco.timerID)
			newco.endreached = true;
	}
	else{
	//console.log(yr + yrtext + mnth + mnthtext + dy + dytext + hr + hrtext + min + mintext + sec + sectext + eventtext);
	}
	//console.log([sec, min, hr, dy, mnth, yr]);
	newco.currentTime = {
		hours : hr,
		minutes : min,
		seconds : sec
	}
	
	newco.timerID = setTimeout(timeleft, 1000);
	
	
	if (newco.endreached) {
		clearTimeout(newco.timerID);
		newco.endTimer();
	}
	else 
		if (newco.timercallback) 
			newco.timercallback();
}
