	//SHOPPING CART//
	$(function(){
		var overlay = $('<div class="overlay"></div>').prependTo("body");		
		overlay.wrap('<div class="overlaycontainer"></div>');

		$('.bestelform').insertAfter(overlay);
		$('.overlay').click(function(){
			closeBestelForm();						 
		})


		//If the User resizes the window, adjust center the form
		windowResize();
		$(window).bind("resize", windowResize);
		
		
		//show bestel form//
		$('.gegevens').click(function(){
			var formright = $('.rightform');
			
			
			var formHeight = formright.height();
			var bestelFormTop = ($(window).height() - formHeight) / 2;
			var bestelFormLeft = ($(window).width() - 890) / 2;
			
			
			$(".form.bestel").animate({width:"820px", height:formHeight + "px"}, {duration:600});
			$(".bestelform").animate({left:bestelFormLeft+"px", top: bestelFormTop+ "px"}, {duration:600 });
			setTimeout(function(){
				 $('.rightform').fadeIn();
			}, 500);
			$(this).fadeOut();
			
		});
		
		
		//add item to shopping cart
		$(".bestelblock .button").click(function(){
			var bestelBlock = $(this).closest(".bestelblock");
			var id = bestelBlock.attr('id');
			var price = bestelBlock.find(".prijs span").html();
			var name = bestelBlock.find('h2').html();
			
			addItemToShoppingCart(name, price, id);
			update();
			openBestelForm();	

		});
		$(".update").click(function(){
			update();									
		});
		
		
		$(".continueshopping a").click(function(){
			closeBestelForm()								
		});
		
	});
	

	
	function windowResize(){
		$('.overlay').height($(document).height());
		$('.overlay').width($(window).width());
		var bestelform = $(".bestelform");
		var bestelFormTop = ($(window).height() - bestelform.height()) / 2;
		var bestelFormLeft = ($(window).width() - bestelform.width()) / 2;
		bestelform.css("top", bestelFormTop+ "px");
		bestelform.css("left", bestelFormLeft+ "px");
	}
	
	function addItemToShoppingCart(name, price, id){
		//add shopping item//
		var excistingItem = $(".orderitem .name:contains('"+name+"')");

		if(!excistingItem.attr("class")){
			var orderItem = $(".orderitem.sample").clone().prependTo(".ordereditems").removeClass("sample");			
			orderItem.attr('id', id);
			orderItem.find(".price").html(price);
			orderItem.find(".name").html(name);
			orderItem.find(".delete").click(function(){				
				removeFromCart($(this).closest('.orderitem'));			
			});
		}else{
			var currentAmount = excistingItem.closest(".orderitem").find("#aantal").val();
			excistingItem.closest(".orderitem").find("#aantal").val(parseInt(currentAmount)+1);
		}

		$('.emptycart').hide();
		$(".gegevens").show();
	}
	
	function openBestelForm(){
		$('.gegevens').show();
		
		$(".form.bestel").css("height", "auto");
		$(".form.bestel").width("400px");	

		windowResize();
		
		$('.overlay').show();
		$('.overlay').css("opacity", 0);	
		$('.overlay').animate({opacity:.8}, {duration:500});
		$('.bestelform').fadeIn();
	}
	
	function closeBestelForm(){
		$('.rightform').fadeOut();
		$('.overlay').fadeOut();
		$('.bestelform').fadeOut();
	}
	function removeFromCart(item){
		item.slideUp();
		setTimeout(function(){
			item.remove();	
			update();
			//alert($('.orderitem').size())
			if($('.orderitem').size() <= 2){
				$('.emptycart').slideDown();
				$(".gegevens").slideUp();
			}
			
			
		},800)
	}
				   
	function update(){
		var totaal = 0;
		$.each($('.orderitem'), function(index, value){
			var orderItem = $(value);
			
			if(!orderItem.hasClass("totaal") && !orderItem.hasClass("sample")){
				var productPrice = parseFloat(orderItem.find(".price").html().replace(/€/gi, "").replace(/,/gi, "."));	
				var amount = orderItem.find("#aantal").val();
				var totalPrice = productPrice * amount;
				totaal += totalPrice;
			}
		});
		
		var totaalPriceAsString = totaal.toFixed(2) + "";		
		totaalPriceAsString = totaalPriceAsString.replace(/\./gi, ",")		
		$('.orderitem.totaal').find(".price").html("&euro;" + totaalPriceAsString);
	}
	
	//SEND FORM CART//
	$(function(){
		$(".verstuur").click(function(){
			validateForm();						  
		});	
		$(".sluiten").click(function(){
			closeBestelForm();						  
		});
	});
	
	function validateForm(){
		
		var fieldsToCheck = new Array();

		fieldsToCheck.push({field:$("input[name='bedrijfsnaam']"), validation:"isEmpty"});	
		fieldsToCheck.push({field:$("input[name='terattentievan']"), validation:"isEmpty"});
		fieldsToCheck.push({field:$("input[name='postcode']"), validation:"isEmpty"});
		fieldsToCheck.push({field:$("input[name='adres']"), validation:"isEmpty"});
		fieldsToCheck.push({field:$("input[name='plaats']"), validation:"isEmpty"});
		fieldsToCheck.push({field:$("input[name='telefoon']"), validation:"isPhone"});
		fieldsToCheck.push({field:$("input[name='email']"), validation:"isEmail"});
		
		if(!validate(fieldsToCheck)){
			checkCaptcha();				
		}

	};
	
	function checkCaptcha(){
		var code = $("input[name='verificatiecode']").val();
		$.ajax({
		   type: "POST",
		   url: BASE_URL+"captcha/checkcaptcha.php",
		   data: "norobot="+code,
		   success: function(msg){
			 
			 if(msg == "false"){
				// alert("wrong.");
				$(".verificatie").html('<img width="200" height="50" src="'+BASE_URL+'captcha/captcha.php?r='+Math.random() * 5000+'">');
			
				$("input[name='verificatiecode']").closest(".field").addClass("error");
				$("input[name='verificatiecode']").val("");
			 }else{
				sendMail(); 
			 }
		   }
		});		
	}
	
	function sendMail(){

		$('.placingorder').fadeIn();
		$('.placingorder .background').animate({opacity:.8}, {duration:300});
		var targetTop = ($(".bestelform").height() / 2) - 50;
		$('.placingorder .text').css('top', targetTop+ 'px');
		$('.placingorder .background, .placingorder .text').width($(".bestelform").width());
		$('.placingorder .background, .placingorder .text').height($(".bestelform").height());
		
		var products = getProducts();
		var productids = products.ids;
		var productamounts = products.amounts;
		/*var bedrijfsnaam = $("input[name='bedrijfsnaam']").val();
		var terattentievan = $("input[name='terattentievan']").val();
		var postcode = $("input[name='postcode']").val();
		var telefoon = $("input[name='telefoon']").val();
		var email = $("input[name='email']").val();
		var opmerkingen = $("textarea[name='opmerkingen']").val();*/
		$("input[name='productamounts']").val(productamounts);
		$("input[name='productids']").val(productids);
		$('form#bestelform').submit();
		
		
		/*$.ajax({
		  type: "POST",
		  url: BASE_URL+'bestellen/placeorder',
		  data: ({
			productids:productids,
			productamounts:productamounts,
			bedrijfsnaam:bedrijfsnaam,
			terattentievan:terattentievan,
			bedrijfsnaam:bedrijfsnaam,
			terattentievan:terattentievan,
			postcode:postcode,
			telefoon:telefoon,
			email:email,
			opmerkingen:opmerkingen			
		   }),

		  success: function(data) {			
				setTimeout(openThanksScreen, 2000);
		  }
		});*/
		
	}
	
	
	function getProducts(){
		var ids = ''
		var amounts ='';
		for(var i=0; i<$('.orderitem').size(); i++){
			var orderItem = $('.orderitem:eq('+i+')');
			
			if(!orderItem.hasClass('totaal') && !orderItem.hasClass('sample')){
				var amount = orderItem.find('#aantal').val();
				var id  = orderItem.attr('id');
				ids += id;				
				amounts += amount;
				
				if(i  <= $('.orderitem').size()-4){
					ids += ",";		
					amounts += ",";
				}
			}
		}
		
		return {ids:ids, amounts:amounts};
	}
	
	function openThanksScreen(){
		$('.placingorder').hide();		
		$('.leftform').fadeOut();
		$('.rightform').fadeOut();
		
		setTimeout(function(){
			var thanksWidth = 450;
			var thanksHeight = 120;
			var bestelFormTop = ($(window).height() - thanksHeight) / 2;
			var bestelFormLeft = ($(window).width() - thanksWidth) / 2;
			$(".form.bestel").animate({width:thanksWidth+"px", height:thanksHeight + "px"}, {duration:600});
			$(".bestelform").animate({left:bestelFormLeft+"px", top: bestelFormTop+ "px"}, {duration:600 });
			setTimeout(function(){
				$('.thankscreen').fadeIn();
			},500);
		}, 500);
	}
	

	
