// hier komt de observer die zowel de check uitvoert voor de cart als de individuele items in de cart.
Event.observe(window, 'load', function() 
{
	// hier alvast automatisch mijn cartitems aanmaken.
	this.oldvalues = new Array();
    if($('cart') != null)
    {
    // bij deze keyup moet ik snel zien te vinden om welk input veld het gaat.
   		var shoppingcart = new Cart();
		shoppingcart.countAndCreateItems();
		
	    Event.observe('cart', 'keyup', function(event)    
	    {
	    	shoppingcart.getCartItem(shoppingcart.determineItemId(event));
	    	var currentitem = shoppingcart.currentcartitem;
	    		    		    	
	    	if (event.keyCode != Event.KEY_BACKSPACE)
	    	{
		    	if (currentitem)
		    	{
		    		//currentitem.updateQuantity(event);
		    		currentitem.calculatePriceAndQuantity();
		    		shoppingcart.totalprice = currentitem.totalprice;
		    	}
	    	}
	    }    
	    );
	   
			shoppingcart.cartitems.each(function(cartitem) 
			{  
				Event.observe('inp_'+cartitem.id, 'blur', function(event)
		    	{
		    		shoppingcart.getCartItem(shoppingcart.determineItemId(event));
	    			var currentitem = shoppingcart.currentcartitem;
		    		currentitem.updateQuantity(event);	
	    			currentitem.calculatePriceAndQuantity();
	    			shoppingcart.totalprice = currentitem.totalprice;
	    			
		    	}
		    	);
	    	});
			
			// Als couponmodule aan staat
			if ($('maxrows'))
			{	
				var counter = 1;
				
				shoppingcart.cartitems.each(function(cartitem) 
				{  
					
					parent.oldvalues = new Array();
					Event.observe('inp_'+cartitem.id, 'keyup', function(event)
			    	{
							
						shoppingcart.getCartItem(shoppingcart.determineItemId(event));
		    			var currentitem = shoppingcart.currentcartitem;
			    		currentitem.updateQuantity(event);	
	
			    		// if coupon?
			    		if (cartitem.coupon == 1)
			    		{
			    	
			    			
					    	// div extra descriptions aanmaken
	//		    			var coupon_extra_descriptions = Builder.node('div', 
	//		    			{	 
	//		    				id: 'coupon_extra_descriptions',
	//		    				className: 'coupon_extra_descriptions'
	//		   	 			});   
	//		    			$('coupondescription').appendChild(coupon_extra_descriptions);
			    			
				    		if ($('coupon_extra_descriptions_' + cartitem.objectinstanceid))
				    		{
					    		// alle descriptions en textarea's verwijderen
				    			$('coupon_extra_descriptions_' + cartitem.objectinstanceid).select('div').each(function(item)
								{
				    				item.remove(); 
								});
				    			
				    			
				    			var countertje = 2;
				    			$('coupon_extra_descriptions_' + cartitem.objectinstanceid).select('textarea').each(function(item)
								{
				    				this.oldvalues['item_'+ cartitem.objectinstanceid +'_'+countertje] = item.value;
				    				
				    				item.remove(); 
				    				countertje++;
								});
					    	
					    		if (currentitem.value > 1)
					    		{
					    			// nieuwe textvakken maken
					    			
					    			for (i= 2; i < (parseInt(currentitem.value)+1); i++)
					    			{
					    				var coupondescriptionlabel = Builder.node('div', 
									 	{	 
								 			id: 'coupondescriptionlabel_'+ currentitem.objectinstanceid +'_'+i, 			
								 			className: 'coupondescriptionlabel'
								 		},
								 		'Persoonlijk bericht op cadeaubon '+ i +' (max '+ $('maxrows').value +' regels, '+ $('maxcharacters').value +' karakters)');   
						    			
						                $('coupon_extra_descriptions_' + cartitem.objectinstanceid).appendChild(coupondescriptionlabel);
						                
						                var coupon_extra_textarea = Builder.node('textarea', 
						    			{	 
						    				id: 'coupondescription_'+currentitem.objectinstanceid+'_' + i,
						    				name: 'coupondescription_'+currentitem.objectinstanceid+'_' + i
						   	 			});   
						    			
						                if (parent.oldvalues['item_'+ cartitem.objectinstanceid +'_'+i])
						    			{
						    				coupon_extra_textarea.value	= parent.oldvalues['item_'+ cartitem.objectinstanceid +'_'+i];
						    			
						    			}
						                
						    			$('coupon_extra_descriptions_' + cartitem.objectinstanceid).appendChild(coupon_extra_textarea);
						    			
						    			
						    			//alert ('coupondescription'+counter+'' + i);
//						    			Event.observe(('coupondescription_'+currentitem.objectinstanceid+'_' + i), 'blur', function(event2) 
//				    				    {
//				    				    	//shoppingcart.checkCoupon(event2, 'coupondescription'+counter+'' + (i-1));
//						    				//alert ('coupondescription'+counter+'' + i);
//				    				    	shoppingcart.checkCoupon(event2, 'testcoupondescription_'+currentitem.objectinstanceid+'_' + i);
//				    				    }
//				    				    );
						    			
					    			}
					    			updateCouponDescription(shoppingcart, cartitem.objectinstanceid);
					    			
					    		}
				    		}
				    		
			    		}
			    		
			    	}
			    	);
					
				counter++;
					
		    	});
				
				
			}
			
	    Event.observe('checkout', 'click', function(event) 
	    {
	    	shoppingcart.checkCart(event);
	    }
	    );
	    
	    if ($('orderdescription'))
	    {
		    Event.observe('orderdescription', 'blur', function(event) 
		    {
		    	shoppingcart.checkCart(event);
		    }
		    );
	    }
	    
	    shoppingcart.cartitems.each(function(cartitem) 
		{ 
	    	updateCouponDescription(shoppingcart, cartitem.objectinstanceid);
		});
	    
    }
    
    if($('add') != null)
    {
	    Event.observe('add', 'click', function(event) 
	    {
	    	var sizeitemid = 0;
	    	var coloritemid = 0;
	    	
	    	if($('udcsizeitemid') != null)
	        {
	    		sizeitemid = $('udcsizeitemid').value;
	        }
	    	
	    	if($('udccoloritemid') != null)
	        {
	    		coloritemid = $('udccoloritemid').value;
	        }
	    	
	    	$('add').href = '/_ctrl/shop/cart/add/'+$('currentid').value+'/1/' + sizeitemid + '/' + coloritemid + '/';
	    	
	    }
	    );
    }
}
);

function updateCouponDescription(shoppingcart, objectinstanceid)
{
	if ($('coupondescription_'+ objectinstanceid))
    {
    	$('coupondescription_' + objectinstanceid).select('textarea').each(function(item)
		{
    		$(item.id).stopObserving('blur');
			Event.observe(item.id, 'blur', function(event) 
		    {
		    	shoppingcart.checkCoupon(event, item.id);
		    }
		    );
		});
    }
}

function Cart()
{
	this.id;
	this.cartitems = new Array();
	this.totalprice;
	this.currentcartitem;
	this.description = '';
	this.coupondescription1 = '';
	
	Cart.prototype.checkCart = function(event)
	{
		var errorinitem = false;
		
		this.cartitems.each(function(item)
		{
			if(item.value == '')
			{
				errorinitem = true;
				alert(item.title+' heeft geen geldige hoeveelheid');
				
			}
		}
		);
		
		if ($('orderdescription'))
		{
			if(!$('orderdescription').value.empty())
			{
				this.description = $('orderdescription').value.stripScripts();
				this.description = this.description.escapeHTML();
				
				// eventueel ajax request om je session cartcollection te vullen
				
				var self = this;  
			    var url = '/_ctrl/shop/cart/update/req/ajaxdescription';
			   
			    var AllOptions = 
			    {
			        method: 'post',
			        parameters: { description: this.description},
			        onSuccess: function()
			        {
			            
			        },
			        onFailure: function()
			        {
	//		            alert('mislukt om een ajax request uit te voeren.');
			        }
			    }   
			    var myAjax = new Ajax.Request(url, AllOptions);		    
			}
		}
		
		if(errorinitem)
		{
			event.stop();
		}
	};
	
	Cart.prototype.checkCoupon = function(event, id)
	{
		var splitted 			= id.split('_');
		
		objectinstanceid 		= splitted[1];
		nr 						= splitted[2];

		//$('coupondescription').select('textarea').each(function(item)
		//{
			//nr = parseInt((id.substring(17)));
			
			if($(id))
			{
				if(!$(id).value.empty())
				{
					this.coupondescription1 = $(id).value.stripScripts();
					this.coupondescription1 = this.coupondescription1.escapeHTML();
					
					var maxrows 			= $('maxrows').value;
					var maxcharactersline	= $('maxcharactersline').value;
					var maxcharacters 		= $('maxcharacters').value;
					
					var description1 		= $(id).value;
					var descriptionrows 	= description1.split('\n');
					
					var descriptionrowscount = descriptionrows.length;
					
					if (descriptionrows.length > maxrows)
					{
						alert ('U heeft te veel regels gebruikt. Verwijder '+ (descriptionrows.length - maxrows) +' regel(s).');
						setTimeout("$('coupondescription_' + objectinstanceid + '_'+nr).focus()", 400); 
						return false; 
					}
					
					descriptionrows.each(function(description_item)
					{
						if ((description_item.length/maxcharactersline).ceil() > 1)
						{
							descriptionrowscount = descriptionrowscount + ((description_item.length/maxcharactersline).ceil() -1);	
						}
					});
					
					
					if(descriptionrowscount > maxrows) 
					{
						alert('U heeft te veel karakters en/of regels gebruikt! Verwijder '+
								($(id).value.length - maxcharacters)+ ' karakters');
						setTimeout("$('coupondescription_' + objectinstanceid + '_'+nr).focus()", 400);
						return false; 
					}
									
					
					// eventueel ajax request om je session cartcollection te vullen
					
					var self = this;

				    var url = '/_ctrl/shop/cart/update/req/ajaxcoupondescription/key/'+id;
				   
				    var AllOptions = 
				    {
				        method: 'post',
				        parameters: 
				        { 
				    		coupondescription: this.coupondescription1,
				    		id: id
				    	},
				        onSuccess: function()
				        {
				            
				        },
				        onFailure: function()
				        {
		//		            alert('mislukt om een ajax request uit te voeren.');
				        }
				    }   
				    
				    var myAjax = new Ajax.Request(url, AllOptions);		    
				}	
			}
			
			
		//});
		
	};
	
	Cart.prototype.countAndCreateItems = function()
	{
		var self = this;
		
		var foundedelms = $('cart').getElementsByClassName('cartitem');
			
		for(var i = 0; i <foundedelms.length; i++)
		{
			var cartitem = new CartItem();
			var splittedid = foundedelms[i].id.split('_');
			
			// vullen van cartitemobject.
			cartitem.id = splittedid[1];
			
			cartitem.value = $('inp_'+cartitem.id).value;
			
			cartitem.title = 	$('title_'+cartitem.id).innerHTML.stripTags();
			if (splittedid[2])
			{
				cartitem.coupon = 1;	
			}
			else
			{
				cartitem.coupon = 0;
			}
			
			if (splittedid[3])
			{
				cartitem.objectinstanceid = splittedid[3];	
			}
			else
			{
				cartitem.objectinstanceid = 0;
			}
			
			
			self.cartitems.push(cartitem);
		}
	};
	
	Cart.prototype.determineItemId = function(event)
	{
		var elm = event.element();
		
		var splittedid = elm.id.split('_');
		return splittedid[1];
		
	}
	
	Cart.prototype.getCartItem = function(encodedid)
	{
		var self = this;
		
		this.cartitems.each(function(citem)
		{
			if(citem.id == encodedid)
			{
				self.currentcartitem = citem;
				
			}
		}
		);
	}
};

function CartItem()
{
	this.id;
	this.errorkey;
	this.errormessage;
	this.value;
	this.givenquantity;
	this.title;
	this.price;
	this.shippingcosts;
	this.subtotal;
	this.jsonobj;
	this.xhr;
	
	// need to create this attributes in this cartitem normaly i would put them in the cart object.
	this.totalprice;
	this.totalquantity;
   
    CartItem.prototype.updateQuantity = function(event)
    {
    	
    	var elm = event.element();
    	this.value = this.checkForValueX(elm.value);
    }
    
    /* return int */
    CartItem.prototype.checkForValueX = function(value)
   	{
   		var inputfield		= $('inp_'+this.id);
   		var workingvalue = value;
   		
   		if(workingvalue.endsWith('x'))
   		{
   			workingvalue = workingvalue.substring(0,workingvalue.length-1);
   			
   			if(this.isMatch("1234567890", workingvalue))
   			{
   				inputfield.value = workingvalue;
   				return workingvalue;
   			}
   		}
   		else
   		{
   			return value;
   		}
   	}
   	
   	CartItem.prototype.isMatch = function(valid, value)
   	{
		for( count = 0; count < value.length; count++ ) 
		{
			if( valid.indexOf(value.substring(count,count+1)) == -1 )
				return false;
		}
		
		return true;			
	};
    
    CartItem.prototype.calculatePriceAndQuantity = function()
    {	    
    	var self = this;  
	    var url = '/_ctrl/shop/cart/update/req/ajax';
	   
	    var AllOptions = 
	    {
	        method: 'get',
	        parameters: { 
	    	quantity: this.value, 
	    	encodedid: this.id },
	    	asynchronous: true, 
	        onSuccess: function(oXHR, oJson)
	        {
	            
	            //self.updateCart(oXHR, oJson);
	            self.jsonobj 	= oXHR.responseText.evalJSON();
	    		self.xhr		= oXHR;
	    		
	            // setten we hier de variabelen.
	            self.errorkey 			= self.jsonobj.errorkey;
	            self.errormessage 		= self.jsonobj.errormessage;
				self.price				= self.jsonobj.soloprice;
				self.subtotal			= self.jsonobj.subtotalprice;
				self.value      		= self.jsonobj.quantity; 
				self.givenquantity		= self.jsonobj.givenquantity;
						
				self.totalprice 		= self.jsonobj.totalprice;
				self.totalpricecredit	= self.jsonobj.totalpricecredit;
				self.totalquantity		= self.jsonobj.totalquantity;
				self.shippingcosts 		= self.jsonobj.shippingcosts;
				
				self.updateCartItemInDom();
	            
	        },
	        onFailure: function(oXHR, oJson)
	        {
//	            alert('mislukt om een ajax request uit te voeren.');
	        }
	    }   
	    var myAjax = new Ajax.Request(url, AllOptions);
    }
    
    CartItem.prototype.updateCartItemInDom = function ()
	{	
		var subtotalprice 		= $('subtot_'+this.id);
		var totalprice    		= $('totalprice');
		if ($('totalpricecredit'))
		{
			var totalpricecredit	= $('totalpricecredit');
		}
		var totalamount    		= $('totalamount');
		var errorfield	  		= $('errormessage');
		var inputfield			= $('inp_'+this.id);
		var totalquantity		= $('quantity');
		var shippingcosts		= $('shippingcosts');
		var shippingcoststotal	= $('totalshippingcosts');
	    
		 if(this.givenquantity == inputfield.value)
		 {  
		 	
		 	inputfield.value 				= this.value;
		 	subtotalprice.innerHTML 		= '&euro; '+this.subtotal;
	    	totalprice.innerHTML			= '&euro; '+this.totalprice;
	    	if($('totalpricecredit'))
	    	{
	    		totalpricecredit.innerHTML		= '&euro; '+this.totalpricecredit;
	    	}
	    	
    		if (shippingcoststotal)
    		{
	    		shippingcoststotal.innerHTML	= '&euro; '+ this.shippingcosts;
    		}
		 	if(totalamount != null && totalquantity != null)
	    	 {
	    	 	totalamount.innerHTML			= '&euro; '+this.totalprice;

	    	 }
		 	
	    	if(typeof updateCart == 'function') { 
				updateCart(this); 
			}
	    	
			if(this.errorkey != null)
			{
				errorfield.addClassName('error_active');
				
				errorfield.innerHTML = '';
				var message = '';
				switch(this.errorkey)
				{
					case 'notenoughstock':
						message = 'Op dit moment zijn er van het artikel "'+this.title+'" maar '+this.value+' op voorraad';
					break;
	
					case 'nonumber':
						message = this.title+' heeft geen geldige hoeveelheid';
					break;
	
					case 'min':
						message = +this.title+' heeft geen geldige hoeveelheid';
					break;
	
					case 'minquantity':
						message = 'Voor het artikel "'+this.title+'" geldt een minimale afname van '+this.value;
					break;
				}
				
				errorfield.innerHTML = '! '+message;
			}
  			else
  			{
  				errorfield.innerHTML = '';
  			}
	     }
	}
}; 
