// 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 (currentitem.id != 'donation')
    		{
		    	if (event.keyCode != Event.KEY_BACKSPACE)
		    	{
		    		
				    	currentitem.updateQuantity(event);
				    	currentitem.calculatePriceAndQuantity();
				    	shoppingcart.totalprice = currentitem.totalprice;
		    		
		    	}
    		}
	    	else
	    	{
	    		if (event.keyCode == Event.KEY_RETURN)
		    	{
	    			shoppingcart.addDonation();
		    	}
	    	}
	    }    
	    );
	   
			shoppingcart.cartitems.each(function(cartitem) 
			{  
				Event.observe('inp_'+cartitem.id, 'blur', function(event)
		    	{
					if (cartitem.id == 'donation')
		    		{
						shoppingcart.addDonation();
		    		}
					else
					{
						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 ($('orderdescription'))
	    {
		    Event.observe('orderdescription', 'blur', function(event) 
		    {
		    	shoppingcart.checkCart(event);
		    }
		    );
	    }
    }
    
    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 + '/';
	    	
	    }
	    );
    }
    
    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;
				
				case 'rembours':
					window.location = $('paymethod_rembours').value;
				break;
				
				case 'prepaid':
					window.location = $('paymethod_prepaid').value;
				break;
			}
	    }
	    );
    }
}
);

function Cart()
{
	this.id;
	this.cartitems = new Array();
	this.totalprice;
	this.currentcartitem;
	this.description = '';
	this.donation = 0;
	
	Cart.prototype.checkCart = function(event)
	{
		var errorinitem = false;
		
		this.cartitems.each(function(item)
		{
			if (item.id != 'donation')
    		{
				if(item.value == '')
				{
					errorinitem = true;
					alert(item.title+' heeft geen geldige hoeveelheid');
					
				}
    		}
			
		}
		);
		
		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.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;
				
			}
		}
		);
	}
	
	Cart.prototype.addDonation = function()
    {	
		if (this.isValidBedrag($('inp_donation').value, true)) 
		{
			value = $('inp_donation').value;
		}
		else
		{
			value = 0;
		}
		$('inp_donation').value = this.importBedrag(this.exportBedrag(value));
		
		this.donation = this.exportBedrag($('inp_donation').value);
		
    	var self = this;  
	    var url = '/_ctrl/shop/cart/donation/req/ajax';
	   
	    var AllOptions = 
	    {
	        method: 'get',
	        parameters: { donationvalue: this.donation },
	        onSuccess: function(oXHR, oJson)
	        {
	            //self.updateCart(oXHR, oJson);
	            self.jsonobj 	= oXHR.responseText.evalJSON();
	    		self.xhr		= oXHR;
	    		
	            // setten we hier de variabelen.
				self.totalprice	= self.jsonobj.totalprice;
				$('totalprice').innerHTML	= '&euro; '+self.totalprice;
	        },
	        onFailure: function(oXHR, oJson)
	        {
//	            alert('mislukt om een ajax request uit te voeren.');
	        }
	    }   
	    var myAjax = new Ajax.Request(url, AllOptions);
    }
	
	Cart.prototype.isValidBedrag = function(cBedrag, onlyPositive) 
	{
		// Wanneer 'onlyPositive' niet is meegegeven, dan worden zowel
		// positieve als negatieve waarden toegestaan.
		if (typeof(onlyPositive) == 'undefined')
			onlyPositive = false;

		cBedrag = trim(cBedrag);

		cBedrag = replace(cBedrag, ',', '');
		cBedrag = replace(cBedrag, '.', '');

		var validChars = '';

		if (onlyPositive)
			validChars = '0123456789+';
		else
			validChars = '0123456789-+';

		return(containsOnlyValidChars(cBedrag, validChars));
	}
	
	Cart.prototype.importBedrag = function(cBedrag)
	{
		var isNegative = false;

		cBedrag = trim(cBedrag);

		if (cBedrag == '')
			cBedrag = '0';

		if (cBedrag.charAt(0) == '-') {
			isNegative = true;

			cBedrag = cBedrag.substring(1, cBedrag.length);
		}

		// Splits het bedrag op in euro's en centen...
		var cCenten = (cBedrag.length < 2) ? ("0" + cBedrag) : cBedrag.substring(cBedrag.length - 2, cBedrag.length);
		var cEuros = (cBedrag.length < 3) ? "0" : cBedrag.substring(0, cBedrag.length - 2);

		// Plaats punten op de duizend tallen
		var len = cEuros.length;
		var pos = cEuros.length - 3;

		while (pos > 0) {
			cEuros = cEuros.substring(0, pos) + '.' + cEuros.substring(pos);

			pos = pos - 3;
		}

		if (isNegative)
			cEuros = '-' + cEuros;

		return(cEuros + "," + cCenten);
	}

	Cart.prototype.exportBedrag = function(cBedrag) {
		// Verwijder alle whitespaces voor en na het bedrag
		var tmpBedrag = trim(cBedrag);

		// Verwijder alle '+' en spaties
		tmpBedrag = replace(tmpBedrag, '+', '');
		tmpBedrag = replace(tmpBedrag, ' ', '');


		var nComma = tmpBedrag.lastIndexOf(',');
		var nDot = tmpBedrag.lastIndexOf('.');

		var nPos = Math.max(nComma, nDot);

		var cEuro = '';
		var cCent = '';

		if (nPos < 0) {
			cEuro = tmpBedrag;
			cCent = "00";
		} else {
			cEuro = tmpBedrag.substring(0, nPos);
			cCent = tmpBedrag.substring(nPos + 1, nPos + 3);

			while (cCent.length < 2)
				cCent += "0";

			cEuro = replace(cEuro, ',', '');
			cEuro = replace(cEuro, '.', '');
		}

		tmpBedrag = removeLeadingZeros(cEuro + cCent);

		if (tmpBedrag == '' && cBedrag != '')
			tmpBedrag = "0";

		return(tmpBedrag);
	}
};

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.shippingcosts	= self.jsonobj.shippingcosts;
				
				self.totalprice 	= self.jsonobj.totalprice;
				self.totalquantity	= self.jsonobj.totalquantity;
				
				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 totalshippingcosts	= $('totalshippingcosts');
 			
		 if(this.givenquantity == inputfield.value)
		 {  
			 
		 	inputfield.value 				= this.value;
		 	
		 	subtotalprice.innerHTML 		= '&euro; '+this.subtotal;
	    	totalprice.innerHTML			= '&euro; '+this.totalprice;
	    	
	    	shippingcosts.innerHTML			= '&euro; '+this.shippingcosts;
	    	totalshippingcosts.innerHTML	= '&euro; '+this.shippingcosts;
	    	
	    
		 	if(totalamount != null && totalquantity != null)
	    	 {
	    	 	totalamount.innerHTML	= '&euro; '+this.totalprice;
	    		totalquantity.innerHTML	= this.totalquantity;
	    	 }
		 	
	    	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 = '';
  			}
	     }
	}
}; 

var whitespace = new String(" \t\n\r");

function rTrim(str) {
	var s = new String(str);

	if (whitespace.indexOf(s.charAt(s.length - 1)) != -1) {
		// De lengte van de string
		var i = s.length - 1;

		// Itereer over de string van rechts naar links totdat
		// er geen whitespaces meer gevonden worden...
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;

		// Het resultaat wordt de overgebleven string
		s = s.substring(0, i + 1);
	}

	return s;
}
//
// Haal van gegeven string alle voorloop whitespaces af.
//
// OUT:	De string zonder voorloop whitespaces.
//
function lTrim(str) {
	var s = new String(str);

	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j = 0;
		var i = s.length;

		// Doorloop de string totdat er geen whitespace meer is
		// gelezen...
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
			j++;

		// Bepaal de string vanaf het eerste karakter dat geen
		// whitespace meer was...
		s = s.substring(j, i);
	}

	return s;
}
//
// Haal van gegeven string alle voor- en naloop whitespaces af.
//
// OUT:	De string zonder voor- en naloop whitespaces.
//
function trim(str) {
	return (lTrim(rTrim(str)));
}

function replace(string, text, by) {
	 var strLength = string.length;
	 var txtLength = text.length;

	 if ((strLength == 0) || (txtLength == 0))
	 	return string;

	 var i = string.indexOf(text);

	 if ((!i) && (text != string.substring(0,txtLength)))
	 	return string;

	 if (i == -1)
	 	return string;

	 var newstr = string.substring(0,i) + by;

	 if (i + txtLength < strLength)
		  newstr += replace(string.substring(i + txtLength, strLength), text, by);

	 return newstr;
}

function removeLeadingZeros(s) 
{ 
	return s.replace(/^0+/, ''); 
} 

function containsOnlyValidChars(string, validChars) {
	// Doorloop de hele string en kijk of de karakters
	// wel in de string met validChars zit...
	for (var i = 0; i < string.length; i++) {
		if (validChars.indexOf(string.charAt(i)) == -1)
			return false;
	}

	return true;
}
