var
	ccshop =
	{
		itemsTotal: 0,
		priceSubtotal: 0,
		priceShipping: 0,
		rowNum: 0,

		init: function()
		{
			var e = document.getElementById('ccshop');

			if ( e )
			{
				var
					cookieContents = ccshop.getCookieContents()
					items = '';
					;

				for ( i in cookieContents )
				{
					items +=
						'<tr>' +
						'<td>' +
							'<fieldset>' +
								'<input type="text"   name="quantity_x"  value="' + cookieContents[i].quantity + '" onfocus="this.select();" onkeyup="ccshop.updateTotals();" onblur="ccshop.updateTotals();"/>' +
								'<input type="hidden" name="amount_x"    value="' + ( parseFloat(cookieContents[i].price) + parseFloat(cookieContents[i].shipping) ) + '"/>' +
								'<input type="hidden" name="item_name_x" value="' + cookieContents[i].name + '"/>' +
								'<input type="hidden" value="' + cookieContents[i].price    + '"/>' +
								'<input type="hidden" value="' + cookieContents[i].shipping + '"/>' +
							'</fieldset>' +
						'</td>' +
						'<td><span>' + cookieContents[i].name + '</span> <a href="javascript: return void(0);" onclick="ccshop.itemRemove(this.parentNode.parentNode, \'' + cookieContents[i].name + '\', 1);" title="Remove item">X</a></td>' +
						'<td class="price">' + ccshopConfig.currencySym + cookieContents[i].price + '</td>' +
						'</tr>'
						;
				}

				e.innerHTML =
					'<p id="items_total"></p>' +
					'<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">' +
						'<fieldset>' +
							'<input type="hidden" name="cmd" value="_cart">' +
							'<input type="hidden" name="upload" value="1">' +
							'<input type="hidden" name="business" value="' + ccshopConfig.paypalId + '">' +
							'<input type="hidden" name="currency_code" value="' + ccshopConfig.currency + '">' +
						'</fieldset>' +						
						'<table id="ccshop_cart" cellspacing="0" cellpadding="0"><tbody><th>Qty.</th><th>Product name</th><th>Amount</th>' + items + '</tbody></table>' +
						'<p id="price_subtotal">Subtotal: <span>' + ccshopConfig.currencySym + '0.00</span></p>' +
						'<p id="price_shipping">Shipping: <span>' + ccshopConfig.currencySym + '0.00</span></p>' +
						'<p id="price_total"   >Total:    <span>' + ccshopConfig.currencySym + '0.00</span></p>' +
						'<fieldset>' +
							'<input class="button" type="submit" value="Buy now (PayPal)">' +
						'</fieldset>' +						
					'</form>'
					;

				ccshop.updateTotals();
			}

			return true;
		},

		itemAdd: function(name, quantity)
		{
			var uniqueItem = true;

			var
				quantity = parseInt(quantity) || 1,
				price    = ccshopItems[name]['price'],
				shipping = ccshopItems[name]['shipping']
				;
			
			if ( price )
			{			
				var e = document.getElementById('ccshop_cart').getElementsByTagName('tbody')[0];

				if ( e )
				{
					// Check if item is already in cart
					var cartContents = ccshop.getCartContents();
					
					for ( i in cartContents )
					{
						if ( name == cartContents[i].name )
						{
							cartContents[i].quantity_input.value = cartContents[i].quantity + quantity;
							
							uniqueItem = false;
						}
					}

					// Add item
					if ( uniqueItem )
					{
						var 
							tr              = document.createElement('tr'),
							td_quantity     = document.createElement('td'),
							td_product_name = document.createElement('td'),
							td_price        = document.createElement('td')
							;
							
						td_price.setAttribute('class', 'price');
						
						td_quantity.innerHTML =
							'<fieldset>' +
								'<input type="text"   name="quantity_x"  value="' + quantity + '" onfocus="this.select();" onkeyup="ccshop.updateTotals(); updateQuantity(this);" onblur="ccshop.updateTotals(); updateQuantity(this);"/>' +
								'<input type="hidden" name="amount_x"    value="' + ( parseFloat(price) + parseFloat(shipping) ) + '"/>' +
								'<input type="hidden" name="item_name_x" value="' + name + '"/>' +
								'<input type="hidden" value="' + price    + '"/>' +
								'<input type="hidden" value="' + shipping + '"/>' +
							'</fieldset>'
							;

						td_product_name.innerHTML =
							'<span>' + name + '</span> <a href="javascript: return void(0);" onclick="ccshop.itemRemove(this.parentNode.parentNode, \'' + name + '\', 1);">Remove</a><br style="clear: both;"/>'
							;

						td_price.innerHTML =
							ccshopConfig.currencySym + price.toFixed(2)
							;

						tr.appendChild(td_quantity);
						tr.appendChild(td_product_name);
						tr.appendChild(td_price);

						e.appendChild(tr);
					}

					ccshop.updateTotals();
				}
			}
			else alert('Item does not exist!');
		},

		itemRemove: function(e, name, quantity)
		{
			// Remove item
			if ( e )
			{
				e.parentNode.removeChild(e);
				
				ccshop.updateTotals();
			}

			return true;
		},

		updateTotals: function()
		{
			ccshop.itemsTotal    = 0;
			ccshop.priceSubtotal = 0;
			ccshop.priceShipping = 0;
			
			var
				cartContents = ccshop.getCartContents(),
				rows         = document.getElementById('ccshop_cart').getElementsByTagName('tbody')[0].getElementsByTagName('tr')
				;
			
			ccshop.rowNum = 0;
			
			for ( i in cartContents )
			{
				ccshop.rowNum ++;

				ccshop.itemsTotal    += cartContents[i].quantity;
				ccshop.priceSubtotal += cartContents[i].quantity * cartContents[i].price;
				ccshop.priceShipping += cartContents[i].quantity * cartContents[i].shipping;

				var input = rows[ccshop.rowNum].getElementsByTagName('input');

				input[0].setAttribute('name', 'quantity_'  + ccshop.rowNum);
				input[1].setAttribute('name', 'amount_'    + ccshop.rowNum);
				input[2].setAttribute('name', 'item_name_' + ccshop.rowNum);
			}
			
			var itemsTotal = document.getElementById('items_total');

			itemsTotal.innerHTML = ccshop.itemsTotal ? ( ccshop.itemsTotal == 1 ? '1 item in cart' : ccshop.itemsTotal + ' items in cart' ) : 'No items in cart';

			var priceSubtotal = document.getElementById('price_subtotal').getElementsByTagName('span')[0];
			var priceShipping = document.getElementById('price_shipping').getElementsByTagName('span')[0];
			var priceTotal    = document.getElementById('price_total'   ).getElementsByTagName('span')[0];

			if ( ccshop.itemsTotal && ccshop.priceShipping < ccshopConfig.minShipping ) ccshop.priceShipping = ccshopConfig.minShipping;
			
			priceSubtotal.innerHTML = ccshopConfig.currencySym + ccshop.priceSubtotal.toFixed(2);
			priceShipping.innerHTML = ccshopConfig.currencySym + ccshop.priceShipping.toFixed(2);
			priceTotal.innerHTML    = ccshopConfig.currencySym + ( ccshop.priceSubtotal + ccshop.priceShipping ).toFixed(2);

			ccshop.setCookie();
		},

		getCartContents: function()
		{
			var
				cartContents = {},
				j = 0,
				rows = document.getElementById('ccshop_cart').getElementsByTagName('tbody')[0].getElementsByTagName('tr');

			// Iterate through table rows, store data in object
			for ( i = 0; i < rows.length; i ++ )
			{
				if ( rows[i].getElementsByTagName('td').length )
				{
					var input = rows[i].getElementsByTagName('td')[0].getElementsByTagName('input');

					cartContents[j] = {
						quantity:       parseFloat(input[0].value) || 0,
						quantity_input: input[0],
						price:          parseFloat(input[3].value) || 0,
						shipping:       parseFloat(input[4].value) || 0,
						name:           input[2].value
						}

					j ++;
				}
			}

			return cartContents;
		},

		setCookie: function()
		{
			var
				cartContents = ccshop.getCartContents(),
				cookieContents = ''
				;

			for ( i in cartContents )
			{
				cookieContents += cartContents[i].quantity + '--' + cartContents[i].name + '++';
			}

			document.cookie = 'ccshop=' + cookieContents + ';path=/';
		},

		getCookieContents: function()
		{
			var
				cookieContents = {},
				match          = document.cookie.match(/ccshop=(.+)/)
				;

			if ( match )
			{
				var items = match[1].split('++');
				
				for ( i in items )
				{
					if ( typeof(items[i]) == 'string' )
					{
						var pair = items[i].split('--');
						
						if ( window.ccshopItems[pair[1]] )
						{
							cookieContents[i] = {
								quantity: pair[0],
								price:    window.ccshopItems[pair[1]]['price'],
								shipping: window.ccshopItems[pair[1]]['shipping'],
								name:     pair[1]
								};
						}
					}
				}
			}
			
			return cookieContents;
		}
	}
	;

window.onload = ccshop.init;
