// 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.
    
    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)
	    	{
		    	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;
		    	}
		    	);
	    	});
	    
	    Event.observe('checkout', 'click', function(event) 
	    {
	    	shoppingcart.checkCart(event);
	    }
	    );
	    
	   
    }
    
    if($('cartsubmit') != null)
    {
	     Event.observe('cartsubmit', 'click', function(event) 
	    {
	    	var paymethod = Form.getInputs('form1','radio','paymethod').find(function(radio) { return radio.checked; }).value;
			
	    	switch(paymethod)
			{
				case 'ideal':
					$('form1').submit();
				break;
				
				case 'invoice':
					window.location = $('paymethod_invoice').value;
				break;
			}
	    }
	    );
    }
}
);

function Cart()
{
	this.id;
	this.cartitems = new Array();
	this.totalprice;
	this.currentcartitem;
	
	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(errorinitem)
		{
			event.stop();
		}
	};
	
	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();
			
			
			
			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 },
	        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.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');
		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 (shippingcoststotal)
    		{
		    	shippingcosts.innerHTML			= '&euro; '+ this.shippingcosts;
	    		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.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 = '';
  			}
	     }
	}
}; 