window.addEvent('domready', function() {

	var shoppingBasketPage = '/document_shopping_basket.php';
	if (window.location.href.substring(window.location.href.length - shoppingBasketPage.length) == shoppingBasketPage) return;

	// Images for adding and removing items.
	var shoppingBasketImages = {
		rightAdd : '/images/sas_international/Add_to_basket-en-AE.gif',
		rightRemove : '/images/sas_international/Remove_from_basket-en-AE.gif',
		leftAdd : '/images/sas_international/Add_to_basket-Left-en-AE.gif',
		leftRemove : '/images/sas_international/Remove_from_basket-Left-en-AE.gif'
	};
	
	// Can we turn PDF links into shopping basket buttons?
	var pageId = /([^\/]*?)\.php/.exec(window.location.href);
	var canAddPdfs = pageId && ['system-120_5', 'system-130_5', 'system-150_5', 'system-200_5', 'system-205_5', 'system-330_5', 'system-600_5'].contains(pageId[1]);
	
	// Stores the current items in the shopping basket.
	var currentItems = [];
	
	// Create the UI elements.
	var shoppingBasketListItems = null;
	var shoppingBasketList = new Element('div', {
		'class' : 'right-box',
		styles : {
			display : 'none',
			'background-color' : '#CAD9EC'
		}
	}).adopt(
		new Element('div', {
			'class' : 'right-box-top-shopping-basket',
			text : 'shopping basket',
			styles : {
				cursor : 'pointer'			},
			events : {
				click : function() {
					window.location.href = shoppingBasketPage;
				}
			}
		}),
		shoppingBasketListItems = new Element('div', {
			'class' : 'right-box-body',
			styles : {
				'padding-bottom' : '0'
			}
		}),
		new Element('div', {
			'class' : 'right-box-body-arrow'
		}).grab(new Element(
			'a', {
				text : 'Click here to download basket',
				href : shoppingBasketPage
			}
		))
	).inject('right-column', 'top');
	
	// Refresh the current shopping basket list.
	var showCurrentShoppingBasket = function(settings) {
		if (!settings) settings = { };
		new Request.JSON({
			url : '/services/sas_international/shopping_basket.php',
			method : 'post',
			secure : false,
			data : {
				action : 'get_list'
			},
			onComplete: function(e) {
				currentItems = [];
				shoppingBasketListItems.empty();
				for (var i in e) {
					currentItems.push(e[i]);
					shoppingBasketListItems.adopt(new Element('p', {
						text : /^(.*?)\./.exec(e[i])[1]
					}));
				}
				if (shoppingBasketList.getStyle('display') == 'none') {
					// Do we need to show it?
					if (currentItems.length > 0) {
						shoppingBasketList.setStyles({
							display : 'block',
							opacity : 0
						});
						shoppingBasketList.fade('in');
					}
				} else {
					// Do we need to hide it?
					if (currentItems.length == 0) {
						shoppingBasketList.setStyle('display', 'none');
					}
				}
				if (settings.onComplete) settings.onComplete();
			}
		}).send();
	}
	
	// Add the buttons to the page for adding/removing items from the shopping basket.
	var addShoppingBasketButtons = function() {
		$$('a img').each(function(shoppingBasketLinkImage) {
			var shoppingBasketLink = shoppingBasketLinkImage.getParent('a');
			if (shoppingBasketLink.getParent('.basic_content_editable')) return;
			if (shoppingBasketLink && /\.(dwg|pdf)$/.exec(shoppingBasketLink.href)) {
				var documentName = unescape(/\/([^\/]+\.(dwg|pdf))/.exec(shoppingBasketLink.href)[1]);
				// PDFs need to have special checks.
				var isPdf = !!/\.pdf$/.exec(documentName);
				if (isPdf) {
					if (!canAddPdfs) return;
					var imageId = /image=(\d+)/.exec(shoppingBasketLinkImage.src);
					if (imageId) imageId = parseInt(imageId[1]);
					if (![1640, 2707, 2708].contains(imageId)) return;
				}
				var shoppingBasketLinkAdder = new Element('img', {
					src : shoppingBasketImages[(isPdf ? 'left' : 'right') + (currentItems.contains(documentName) ? 'Remove' : 'Add')],
					styles : {
						cursor : 'pointer',
						'float' : isPdf ? 'none' : 'right'
					},
					events : {
						click : function() {
							if (shoppingBasketLinkAdder.src.substring(shoppingBasketLinkAdder.src.length - shoppingBasketImages[(isPdf ? 'left' : 'right') + 'Add'].length) == shoppingBasketImages[(isPdf ? 'left' : 'right') + 'Add']) {
								// Add an item to the basket.
								new Request({
									url : '/services/sas_international/shopping_basket.php',
									method : 'post',
									data : {
										action : 'add',
										item : documentName
									},
									onComplete: function(e) {
										if (e == 'OK') {
											shoppingBasketLinkAdder.set('src', shoppingBasketImages[(isPdf ? 'left' : 'right') + 'Remove']);
										} else {
											alert(e);
										}
										showCurrentShoppingBasket();
									}
								}).send();
							} else {
								// Remove an item from the basket.
								new Request({
									url : '/services/sas_international/shopping_basket.php',
									method : 'post',
									data : {
										action : 'remove',
										item : documentName
									},
									onComplete: function(e) {
										if (e == 'OK') {
											shoppingBasketLinkAdder.set('src', shoppingBasketImages[(isPdf ? 'left' : 'right') + 'Add']);
										} else {
											alert('Sorry, could not remove document from the basket (' + e + ').');
										}
										showCurrentShoppingBasket();
									}
								}).send();
							}
						}
					}
				}).inject(isPdf ? shoppingBasketLink.getParent('td') : shoppingBasketLink, isPdf ? 'bottom' : 'after');
			}
		});
	}
	
	showCurrentShoppingBasket({ onComplete : addShoppingBasketButtons });
});
