if (typeof quantum !== "object") {quantum = {}; }
if (typeof quantum.lb !== "object") {quantum.lb = {}; }
if (typeof quantum.explorer !== "object") {quantum.explorer = {version : 8}; }
if (typeof quantum.flashshow !== "object") {quantum.flashshow = {}; }
quantum.thumbNames = (quantum.thumbNames === undefined) ? [] : quantum.thumbNames; 
quantum.baseURL = 'http://www.brianjobson.co.uk/';
quantum.maxWidth = 0;
quantum.maxHeight = 0;
quantum.totalLoaded = 0;
quantum.get = {};
quantum.set = {};
quantum.form = {};
quantum.image = {};
quantum.gally = {};
quantum.manipulate = {};
quantum.manipulate.canvas = {};
quantum.manipulate.canvas.ctx = {};
quantum.wait = {};
quantum.help = {x : 0, y : 0, opacity : 0, delay : 1500, id : 0, up : false, width : 250, height: 30, radius : 5, top : 15, left : 15};
quantum.cart = {items : [], slideShow : [], numberOfItems : 0};
quantum.checkout = {};
quantum.convert = {};
quantum.invoice = {};
quantum.flashshow.canAnimate = true;
quantum.flashshow.page = 0;
quantum.flashshow.left = 0;
quantum.flashshow.currentThumb = 1;
quantum.cookie = {"version" : 1};					// version number in use (in case we need to change!)
quantum.cookie.cartName = (quantum.cartName === undefined) ? "cart" : quantum.cartName;

/*
*
* Refer to PHP calling files for extra quantum globals.
*
*/

quantum.form.reset = function ()
{
	if (document.getElementById("colorbutton"))
	{
		document.getElementById("colorbutton").checked = true;
	}
};

quantum.form.resetPassword = function (textBox) 

{
	if ($(".userPasswrd").val() === "enter password")
	{
		$(".userPasswrd").val("");		
	}
};

quantum.manipulate.loader = function (src, effect, destination)
{
	//	Usage: quantum.manipulate.loader("http://www.brianjobson.co.uk/beta/slideshow/wedding/large/58.jpg","mono", "t1");

	var img = new Image();
	img.onload = function ()
		{
			try {
				if (effect === "mono")
				{					
					$("#"+destination).css("-ms-filter","\"progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)\"");
					$("#"+destination).css("filter","progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)");	
					document.getElementById(destination).src = quantum.manipulate.to_monochrome(img);
				}
				if (effect === "colour")
				{
					$("#"+destination).css("-ms-filter","\"progid:DXImageTransform.Microsoft.BasicImage(grayscale=0)\"");
					$("#"+destination).css("filter","progid:DXImageTransform.Microsoft.BasicImage(grayscale=0)");
					document.getElementById(destination).src = quantum.manipulate.to_colour(img);
				}
			} catch (e) {}
		};
	img.src = src;
};

quantum.explorer.to_colour = function(destination)
{
};

quantum.explorer.to_mono = function(destination)
{
};


quantum.manipulate.to_colour = function (imgObj)
{
	var x, y, i, avg, width, height, pixels;

	width = imgObj.width;
	height = imgObj.height;
	quantum.manipulate.canvas.width = width;
	quantum.manipulate.canvas.height = height;
	quantum.manipulate.canvas.ctx.drawImage(imgObj, 0, 0);
	
	pixels = quantum.manipulate.canvas.ctx.getImageData(0, 0, width, height);
	quantum.manipulate.canvas.ctx.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height);	
	return quantum.manipulate.canvas.toDataURL();
};

quantum.manipulate.to_monochrome = function (imgObj)
{
	var x, y, i, avg, width, height, pixels;
	
	width = imgObj.width;
	height = imgObj.height;
	quantum.manipulate.canvas.width = width;
	quantum.manipulate.canvas.height = height;
	quantum.manipulate.canvas.ctx.drawImage(imgObj, 0, 0);
		
	pixels = quantum.manipulate.canvas.ctx.getImageData(0, 0, width, height);
		
	for (y = 0; y < pixels.height; y++)
	{
		for (x = 0; x < pixels.width; x++)
		{
			i = (y * 4) * pixels.width + x * 4;
			avg = (pixels.data[i] + pixels.data[i + 1] + pixels.data[i + 2]) / 3;
			pixels.data[i] = avg;
			pixels.data[i + 1] = avg;
			pixels.data[i + 2] = avg;
		}
	}
	
	quantum.manipulate.canvas.ctx.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height);	
	return quantum.manipulate.canvas.toDataURL();
};


quantum.flashshow.slide = function (shift)
{
	if (!quantum.flashshow.canAnimate)
	{
		return;
	}
	
	var distance = quantum.flashshow.slide_distance, page = "";
		
	if (shift === "left" && quantum.flashshow.page > 0)
	{
		quantum.flashshow.canAnimate = false;
		quantum.flashshow.page--;
		page = "Page " + (quantum.flashshow.page + 1) + " of " + quantum.flashshow.page_count;
		quantum.flashshow.left += distance;
		$("#thumbCanvas").animate({"left" : quantum.flashshow.left}, 500, "swing", function () {quantum.flashshow.canAnimate = true; $("#page_number").html(page); });
	}

	if (shift !== "left" && quantum.flashshow.page < quantum.flashshow.page_count - 1)
	{
		quantum.flashshow.canAnimate = false;
		quantum.flashshow.page++;
		quantum.flashshow.left -= distance;
		page = "Page " + (quantum.flashshow.page + 1) + " of " + quantum.flashshow.page_count;
		$("#thumbCanvas").animate({"left" : quantum.flashshow.left}, 500, "swing", function () {quantum.flashshow.canAnimate = true; $("#page_number").html(page); });	
	}
};

quantum.flashshow.one_slide = function (shift)
{
	if (!quantum.flashshow.canAnimate)
	{
		return;
	}

	if (shift === "prev" && quantum.flashshow.currentThumb > 1)
	{
		$("#b" + (quantum.flashshow.currentThumb)).css("border-color", "#bababa");
		quantum.flashshow.currentThumb -= 1;
		quantum.flashshow.flash_current_thumb();
		$("#b" + quantum.flashshow.currentThumb).css("border-color", "#F00");
		
		if ((quantum.flashshow.currentThumb % 16) === 0)
		{
			quantum.flashshow.slide("left");
		}
		quantum.flashshow.preview_current();

	}
	
	if (shift !== "prev" && quantum.flashshow.currentThumb < quantum.flashshow.image_count)
	{
		$("#b" + quantum.flashshow.currentThumb).css("border-color", "#bababa");
		quantum.flashshow.currentThumb += 1;	
		quantum.flashshow.flash_current_thumb();
		$("#b" + (quantum.flashshow.currentThumb)).css("border-color", "#F00");
				
		if ((quantum.flashshow.currentThumb % 16) === 1 && quantum.flashshow.currentThumb > 1)
		{
			quantum.flashshow.slide("right");
		}
		quantum.flashshow.preview_current();
	}
};

quantum.flashshow.flash_current_thumb = function ()
{
	$("#t" + quantum.flashshow.currentThumb).animate({"opacity": 0.2}, 20); 
	$("#t" + quantum.flashshow.currentThumb).animate({"opacity": 1.0}, 250);
};

quantum.flashshow.preview = function (e)
{
	var large = e.target.src.replace("thumbs", "large");
	$("#b" + quantum.flashshow.currentThumb).css("border-color", "#bababa");	
	quantum.flashshow.currentThumb = parseInt((e.target.id).replace("t", ""), 10);
	$("#b" + quantum.flashshow.currentThumb).css("border-color", "#f00");	
	quantum.flashshow.preview_loader(large);
};

quantum.flashshow.preview_current = function ()
{
	var large = $("#t" + quantum.flashshow.currentThumb).attr("src").replace("thumbs", "large");
	quantum.flashshow.preview_loader(large);
};


quantum.flashshow.preload_preview = function ()
{
	var large = $(".thumbImage").first(".thumbImage").attr("src").replace("thumbs", "large");
	$("#b1").css("border-color", "#F00");
	quantum.flashshow.preview_loader(large);
};

quantum.flashshow.preview_loader = function (large) 
{
	var pre = new Image(), html, top, left, height; 
	quantum.form.reset();
	pre.onload = function () 
		{
			quantum.flashshow.canAnimate = false;
			$("#galleryPreview").animate({"opacity":0.0}, 500, function () {
				
				height = parseInt(pre.height,10);
				height = (pre.height > 365) ? 345 : height;
				left = parseInt(((500 - pre.width)/2), 10);
				top = parseInt(((365 - height)/2), 10);
				html = "<div style='position: relative; top:" + top + "px; left:" + left + "px;'>";
				html += "<img style='border:1px solid #bbb; height:" + height + "px' id='previewImageLoaded' src='" + large + "' />";
				html += "</div>";
				
				$("#galleryPreview").html(html);
				$("#galleryPreview").animate({"opacity":1.0}, 500, function () {quantum.flashshow.canAnimate = true; });
			});
		};
	pre.src = large;
};

quantum.convert.toRadians = function (d)
{
	return (Math.PI/180 * d);
};

quantum.get.refFromFilename = function (t)
{
	if (typeof (t) === "undefined") {return ""; }
	return (t.substr(t.lastIndexOf("/") + 1, t.indexOf(".jpg"))).replace(/\.jpg/,"");
};

quantum.get.image = function (c)
{
	return $("#lbx"+c).attr("src");
};

quantum.get.filecode = function (t)
{
	if (typeof (t) === "undefined") {return false; }
	if (typeof (t = quantum.get.image(t)) === "undefined") {return false; }
	return(t.substr(t.lastIndexOf("/") + 1, t.indexOf(".jpg")));
};

quantum.loader = function (loaded) 
{
	if (typeof(loaded) !== "undefined" && typeof(loaded) === "function")
	{
		loaded();
	}
};

quantum.get.viewportDimensions = function ()
{
	var body = {}, viewport = {};
	
	body.width = $("body").width();

	if (typeof window.innerWidth !== "undefined")
	{
		viewport.width = window.innerWidth;
		viewport.height = window.innerHeight;
	}
	
	else if (typeof(document.documentElement) !== "undefined" && typeof( document.documentElement.clientWidth) !== "undefined" && document.documentElement.clientWidth !== 0)
	{
		viewport.width = document.documentElement.clientWidth;
		viewport.height = document.documentElement.clientHeight;
	}

	body.height = viewport.height;
	
	if ($("#mainPageArea").height()+300 > body.height) 
	{
		body.height = $("#mainPageArea").height()+300;
	}
			
	if ($(window).height() > body.height) 
	{
		body.height = $(window).height();
	}
	
	return ({
		viewport	: viewport,
		body		: body,
		X			: $(window).scrollLeft(),
		Y			: $(window).scrollTop()
	});
};

quantum.centrify = function (o)
{
	var vp = quantum.get.viewportDimensions();
	o.left = (vp.viewport.width/2) - (o.width/2) + vp.X;
	o.top = (vp.viewport.height/2) - (o.height/2) + vp.Y; 
	return (o);
};


quantum.blackBox = function (html, obj)
{	
	var containter = {}, anim = {}, backdrop = "white", style = {background : "white"}, vp;
	container = {height : 100, width: 100, left: 0, top: 0};
	anim = {type : "tv1", speed : 500, fade : 500};
	vp = quantum.get.viewportDimensions();
	
	if (typeof(obj) === "object")
	{
		if (typeof(obj.style) === "object")
		{
			anim.type = (typeof(obj.style.animType) === "string") ? obj.style.animType : "tv1";			
			backdrop = (typeof(obj.style.background) === "string") ? obj.style.background : "white" ;
		}
		container.height = (typeof(obj.height) === "number") ? obj.height : container.height;
		container.width = (typeof(obj.width) === "number") ? obj.width : container.width;
		anim.speed = (typeof(obj.animSpeed) === "number") ? obj.animSpeed : anim.speed;
		anim.fade = (typeof(obj.fadeSpeed) === "number") ? obj.fadeSpeed : anim.fade;
	}
	
	container = quantum.centrify(container);
	
	if (! document.getElementById("backBlind"))
	{
		$("body").append("<div id='backBlind' class='backBlind' style='width:"+vp.body.width+"px; height:"+vp.body.height+"px;'></div>");	
		$("#backBlind").fadeTo(500,0.8).click(function () {$('#frontBlind, .closeBox').fadeTo(500,0.0).remove(); $(this).fadeTo(500,0.0, function () {$(this).remove(); }); });
	
		$("body").append("<div id='frontBlind' class='frontBlind' style='background-color:" + backdrop + ";top:"+(vp.viewport.height/2+ vp.Y)+"px;left:"+(vp.viewport.width/2+vp.X)+"px;'></div>");
		$('#frontBlind').html("<div id='glass' class='transDiv'>" + html + "</div>");
	}
	else
	{
		$('#glass').css("opacity",0.0).html(html);
	}

	animSettings = 
	{
		container	: container,
		anim		: anim,
		onFinish	: obj.onFinish
	};
	
	quantum.blackBoxAnimate(animSettings);
};

quantum.blackBoxAnimate = function (obj)
{

	if (obj.anim.type === "tv1")
	{
		$("#frontBlind").animate({
		height : obj.container.height, top: obj.container.top}, 
		obj.anim.speed,
		function () {$(this).animate({width: obj.container.width, left: obj.container.left},obj.anim.speed, // callback 1 - second expansion
		function () {
						var closeX, closeY;
						closeY = obj.container.top - 8;
						closeX = obj.container.width + obj.container.left - 8;
						$("body").append("<div class='closeBox' style='top:" + closeY + "px; left:" + closeX + "px;'></div>");
						$(".closeBox").click(function () {quantum.image.closeBox()});
						$("#glass").fadeTo(obj.anim.fade,1.0, obj.onFinish); 
					});					// callback 2 - bring up display and callback to finalise.
		});
	}
	else if (obj.anim.type === "tv2")
	{
		$("#frontBlind").animate(
		{width : obj.container.width, left: obj.container.left}, 
		obj.anim.speed, 
		function () {$(this).animate({height : obj.container.height, top: obj.container.top},obj.anim.speed,
		function () {$("#glass").fadeTo(obj.anim.fade,1.0,obj.onFinish); }); });	
	}
	else
	{
		$("#frontBlind").animate(
		{height : obj.container.height, top: obj.container.top, width : obj.container.width, left: obj.container.left}, 
		obj.anim.speed,
		function () {$("#glass").fadeTo(obj.anim.fade,1.0,obj.onFinish); });
	}
	
	return false;
};


quantum.image.click = function (context,e) {	
	
	var src, filecode, path, hyper, html, title;
	
	quantum.image.currentImage = $(context).attr('id');
	quantum.image.currentImage = parseInt(quantum.image.currentImage.substring(quantum.image.currentImage.indexOf("t")+1),10);

	src = $(context).attr('src');
	filecode = src.substring(src.lastIndexOf("/")+1, src.indexOf(".jpg"));
	path = src.substring(0,src.lastIndexOf("/"));
	path = path.substring(0,path.lastIndexOf("/"));
	hyper = path + "/large/" + filecode + ".jpg";	
	html = "<div class='center' style='width:36px; height: 36px; padding-top: 6px;'>";
	html += "<img style='border: 0px' src='" + quantum.baseURL + "images/loading.gif' /></div>";
	title = ($(context).attr("title"));

	quantum.blackBox(html, 
		{
			width: 50, 
			height: 50, 
			animSpeed: 200,
			fadeSpeed: 200, 
			style: {animType : "tv3"}, 
			onFinish: function () { quantum.image.load(hyper, filecode, quantum.image.currentImage, "Add to Cart"); }
		});
	return false;
};


quantum.image.load = function (hyper, filecode, dbref, saveText)
{
	var pre = new Image(), k, extraHeight = 104;
	extraHeight = (descriptions.length * 28) + 104;

	pre.onload = function () {
 
		var vp = quantum.get.viewportDimensions(), ratio = this.width / this.height;
		
		if (ratio < 0.5 || ratio > 2)
		{
			this.width = parseInt(this.width * 1.5,10);
			this.height = parseInt(this.height * 1.5,10);
		}
		
		if (this.height > vp.viewport.height)
		{
			var newHeight = vp.viewport.height - 100;
			this.width = parseInt((newHeight/this.height) * this.width,10);
			this.height = newHeight;
		}
	
	
		if (this.width + 50 > vp.viewport.width)
		{
			var newWidth = vp.viewport.width - 50;
			this.height = parseInt((newWidth/this.width) * this.height,10);
			this.width = newWidth;
		}
	
			html = "<div style='width:" + this.width + "px; height:10px;'>";
				html += "<img id='mainPreviewImage' src='" + hyper + "' style='margin-left: 10px; margin-top: 10px;";
				html += " float: left; height:"+this.height+"px; width:"+this.width+"px'/>";	
			html += "</div>";
					
			html += "<div class='orderingFrame'>";

			html += "<div class='priceList priceListHeader'>Description</div>";
			html += "<div class='priceListPrice priceListHeader'>&pound price</div>";
			html += "<div id='colourButton' style='height: 32px'>Preview in Colour</div>";
			html += "<div id='monoButton' style='height: 32px'>Preview in Black/White</div>";
			

			for (k = 0; k < descriptions.length; k++)
			{
				html += "<div class='priceList'>" + descriptions[k] + "</div>";
				html += "<div class='priceListPrice'>" + prices[k].toFixed(2) + "</div>";
				html += "<div id='colInv" + k + "' class='invCount'> </div>";
				html += "<div id='colInc" + k + "' class='symbol'><div class='Obut'>+</div></div>";
				html += "<div id='colDec" + k + "' class='symbol'><div class='Obut'>-</div></div>";
				html += "<div id='monInv" + k + "' class='invCount'> </div>";
				html += "<div id='monInc" + k + "' class='symbol'>";
				html += "<div class='Obut'>+</div></div>";
				html += "<div id='monDec" + k + "' class='symbol'><div class='Obut'>-</div></div>";	
			}
			
			html += "<div class='subTotalPreview'>Total:</div>";
			html += "<div id='imgTot' class='totalSum finalTotals'></div>";
			html += "<div id='saleOkButton'>" + saveText + "</div>";
			html += "<div id='saleCancelButton'>Cancel</div>";

			html += "</div>";
			
			extraHeight = (extraHeight > this.height) ? extraHeight : this.height;
			quantum.blackBox(html, 
			{
				width: this.width + 450, // X pixels extra to fit in the buying options
				height: extraHeight + 20, 
				animSpeed: 500,
				fadeSpeed: 500, 
				style: {animType : "tv1"}, 
				onFinish: function () 
				{	
						
					$(".orderingFrame").height(extraHeight);

					quantum.image.fillFields();
					
					$("div[id^='col'], div[id^='mon']").click(function (e) {quantum.image.clickItem(this,e); return false; });					
														
					$("#saleCancelButton").click(function () {quantum.image.closeBox();});
			
					$("#saleOkButton").click(function () {quantum.image.saleOK();});
					
					$("#colourButton").click(
						function () {							
						quantum.manipulate.loader(hyper,"colour", "mainPreviewImage");
					});

					$("#monoButton").click(
						function () {							
						quantum.manipulate.loader(hyper,"mono", "mainPreviewImage");
					});
						
				}
			}
		);

		pre.onload = null;
		pre = null; 
		return false;	
	};

	pre.src = hyper;
	return false;
};

quantum.image.closeBox = function () {
	
	$('#frontBlind,.closeBox').fadeTo(500,0.0).remove(); 
	$('#backBlind').fadeTo(500,0.0, function () 
	{ 
		$('#backBlind').remove();
	});
};

quantum.image.saleOK = function () {
	
	var saveText = (saveText === undefined) ? "Edit" : "Update" ;

	quantum.cookie.packCart();													 
	$('#frontBlind, .closeBox').fadeTo(500,0.0).remove(); 
	$('#backBlind').fadeTo(500,0.0, function () 
	{ 
		$('#backBlind').remove(); 
		if (saveText === "Edit")
		{
			quantum.cart.showCart();

		}

		if (saveText === "Update")
		{
			quantum.checkout.init();

		}
	}); 
};

quantum.image.fillFields = function () {

	var imageRef = quantum.image.currentImage, imageStack = [], imageData = [], image = {}, offset, count, type, j, k, n, temp = [], id, subtotal = 0;

	quantum.cookie.unpackCart(quantum.cookie.bake(quantum.cookie.cartName));
	
	if (quantum.cart.items[imageRef] === undefined)
	{
		return;
	}
	
	imageData = quantum.cart.items[imageRef].split(".");
	for (j = 0; j < imageData.length; j++)
	{
		imageStack = imageData[j].split(".");
		
		for (k = 0; k < imageStack.length; k++)
		{
			temp = imageStack[k].split("/");
			offset = parseInt(temp[0],10);
			count = parseInt(temp[1],10);
			type = parseInt(temp[2],10);
			
			if (count !== 0) 
			{
				subtotal += count * parseFloat(prices[offset],10);
				id = (type === 1) ? ("#colInv"+offset) : ("#monInv"+offset);
				$(id).html(temp[1]);		
			}
		}
	}
	quantum.image.updateCart(imageRef);

};

quantum.image.clickItem = function (obj, evt)
{

	// called when the ordering buttons (+/-) are clicked.
	var imageRef, buttonId = obj.id, type, symbol, digits, id, content;

	imageRef = quantum.image.currentImage;
	type = (buttonId.match("col")) ? "col" : "mon";
	symbol = (buttonId.match("Inc")) ? "+" : "-";
	digits = parseInt(buttonId.match(buttonId.match("[0-9]")),10);
	id = "#"+type+"Inv"+digits;
	content = parseInt(($(id).html() === " " || $(id).html() === "") ? 0 : $(id).html(),10);
	
	if (symbol === "+")
	{
		content++;
	}
	else
	{
		content = (content - 1 > 0) ? (content-1) : " " ;	
	}
	$(id).html(content);
	quantum.image.updateCart(imageRef);
};

quantum.image.updateCart = function (imageRef) {
		
	var k, id, size, count = 0, type, addDot = false, subtotal = 0, imageStack = "";	
	
	for (k = 0; k < descriptions.length; k++)		// iterate through ALL the options (lots of them!)
	{
		// colour column
		id = "#colInv"+k;
		
		if ($(id).html() !== " " && $(id).html() !== "")
		{
			count = parseInt($(id).html(),10)
			subtotal += count * parseFloat(prices[k],10);
			imageStack += (addDot === true) ? "." : "" ;
			imageStack += k + "/" + count + "/" + 1;
			addDot = true;
		}

		// mono column
		id = "#monInv"+k;

		if ($(id).html() !== " " && $(id).html() !== "")
		{
			count = parseInt($(id).html(),10)
			subtotal += count * parseFloat(prices[k],10);
			imageStack += (addDot === true) ? "." : "" ;
			imageStack += k + "/" + count + "/" + 0;
			addDot = true;
		}
	}	
	
	$("#"+"imgTot").html(subtotal.toFixed(2));


	if (subtotal === 0)
	{
		quantum.cart.items[imageRef] = undefined;
	}
	else
	{
		quantum.cart.items[imageRef] = imageStack;
	}
	
	quantum.cart.slides();

};

quantum.cart.showCart = function () 
{
	var j, logo, html = "";

	logo = quantum.baseURL + "images/minilogo.gif";
	html += "<div id='cartFace'>";
	html += "<div><img class='noBorder' src='" + logo + "'></div>";
	
	if (quantum.cart.items.length === 0)
	{
		html += "<div>Your cart is empty</div>"	
	}

	
	for (j = 0; j < quantum.cart.items.length; j++)
	{
		if (quantum.cart.items[j] !== undefined)
		{
			html += quantum.cart.summarise(j);
		}
	}
		
	html += "</div>";
	
	quantum.blackBox(html, 
	{
		width: 650, // X pixels extra to fit in the buying options
		height: 250, 
		
		
		animSpeed: 500,
		fadeSpeed: 500, 
		style: {animType : "tv1"}, 
		onFinish: function () 
			{	
					
				$(".editThisImage, .editThis").click(
					function (e) {
						$('#frontBlind, .closeBox').fadeTo(500,0.0).remove(); 
						$('#backBlind').fadeTo(500,0.0, function () { $('#backBlind').remove(); 
						quantum.cart.reEdit(e.target.id);
						}
				); });
			}
		}
	);
};

quantum.cart.summarise = function (imageRef)
{
	var colour, imageData, j, k, temp = [], offset, count, type, subtotal, name, imgTag, filename, total = 0, strItems = "", rows = 0, margin;
	
	imageData = quantum.cart.items[imageRef].split(".");
	name = quantum.thumbNames[imageRef];
	filename = quantum.galleryThumbs + "/" + name + ".jpg";
	imgTag = "<img src ='" + quantum.baseURL + filename + "'>";
	strItems += "<div class='cartRow'>";
	strItems += "<div id='i" + imageRef + "' class='cartPreview'>" + imgTag + "</div>";
	strItems += "<div class='cartDetailPanel'>"; 

	for (j = 0; j < imageData.length; j++)
	{
		imageStack = imageData[j].split(".");
		
		for (k = 0; k < imageStack.length; k++)
		{
			temp = imageStack[k].split("/");
			offset = parseInt(temp[0],10);
			count = parseInt(temp[1],10);
			type = parseInt(temp[2],10);
			
			if (count !== 0) 
			{
				rows += 1;
				subtotal = count * parseFloat(prices[offset],10);;
				total += subtotal;
				colour = (type === 1) ? (" colour ") : (" monochrome ");
				strItems += "<div class='cartDetailDesc'>" + descriptions[offset] + " in " + colour + "</div>";
				strItems += "<div class='cartDetail' >" + count + " x " + prices[offset].toFixed(2) + "</div><div class='cartDetailSub'>" + subtotal.toFixed(2) + "</div>"; 
			} 
		}
	}
	strItems += "<div class='cartDetailDesc noBorder'></div>";
	strItems += "<div class='cartDetail noBorder' >Image Total</div>";
	strItems += "<div class='cartDetailSub noBorder'>&pound;" + total.toFixed(2) + "</div>"; 
	strItems += "<div class='cartDetailDesc noBorder'></div>";
	strItems += "<div class='cartDetail noBorder' ></div>";
	strItems += "<div class='cartDetailSub noBorder'>";
	strItems += "<div id='" + imageRef + "' class='editThisImage'>[Edit]</div></div>"; 

	margin = (rows > 3) ? 40 : 0;
	
	strItems += "</div></div>";
	strItems += "<div class='cartSeparator' style='margin-top:" + margin + "px'></div>";

	return strItems;
};

quantum.cart.totalUp = function () {

	var j, total = 0, c = {subtotal : 0, items : 0}, cartData = {total : 0, items : 0}, html = "";

	for (j = 0; j < quantum.cart.items.length; j++)
	{
		if (quantum.cart.items[j] !== undefined)
		{
			c = quantum.cart.totalImage(quantum.cart.items[j]);
			cartData.total += c.subtotal;
			cartData.items += c.items;
		}
	}
	html = cartData.items + " items " + "&pound;" + cartData.total.toFixed(2);
	$("#cartTrolley").html(html);
	return cartData;
}

quantum.cart.totalImage = function (imageData) {

	var j, imageStack = [], total = 0, subtotal = 0, temp = [], offset = 0; count = 0, items = 0;
	
	if (imageData.length < 2)
	{
		return {subtotal : 0, items : 0};
	}
		
	imageStack = imageData.split(".");		
	
	for (k = 0; k < imageStack.length; k++)
	{
		temp = imageStack[k].split("/");
		offset = parseInt(temp[0],10);
		count = parseInt(temp[1],10);
		
		if (count !== 0) 
		{
			subtotal = count * parseFloat(prices[offset],10).toFixed(2);
			total += subtotal;
			items += count;
		} 
	}
	return {subtotal : total, items : items}; 
}


quantum.checkout.checkoutImage = function (imageRef)
{
	var colour, imageData, j, k, temp = [], offset, count, type, subtotal, name, imgTag, filename, total = 0, strItems = "", rows = 0, margin;
	
	imageData = quantum.cart.items[imageRef].split(".");
	name = quantum.thumbNames[imageRef];
	filename = quantum.galleryThumbs + "/" + name + ".jpg";
	imgTag = "<img src ='" + quantum.baseURL + filename + "'>";
	strItems += "<div class='cartRowWide'>";
	strItems += "<div id='i" + imageRef + "' class='checkThumb'>" + imgTag + "</div>";
	strItems += "<div class='cartDetailPanel'>"; 

	for (j = 0; j < imageData.length; j++)
	{
		imageStack = imageData[j].split(".");
		
		for (k = 0; k < imageStack.length; k++)
		{
			temp = imageStack[k].split("/");
			offset = parseInt(temp[0],10);
			count = parseInt(temp[1],10);
			type = parseInt(temp[2],10);
			
			if (count !== 0) 
			{
				rows += 1;
				subtotal = count * prices[offset];
				total += subtotal;
				colour = (type === 1) ? (" colour ") : (" monochrome ");
				strItems += "<div class='cartDetailDesc'>" + descriptions[offset] + " in " + colour + "</div>";
				strItems += "<div class='cartDetail' >" + count + " x " + prices[offset].toFixed(2) + "</div>";
				strItems += "<div class='cartDetailSub'>" + subtotal.toFixed(2) + "</div>"; 
			} 
		}
	}
	strItems += "<div class='cartDetailDesc noBorder'></div>";
	strItems += "<div class='cartDetail noBorder' >Image Total</div>";
	strItems += "<div class='cartDetailSub noBorder'>&pound;" + total.toFixed(2) + "</div>";
	strItems += "<div class='cartDetailDesc noBorder'></div>";
	strItems += "<div class='cartDetail noBorder' ></div>";
	strItems += "<div class='cartDetailSub noBorder'>";
	strItems += "<div id='" + imageRef + "' class='editThisImage'>[Edit]</div></div>"; 

	margin = (rows > 3) ? 40 : 0;
	
	strItems += "</div></div>";


	return strItems;
};

quantum.cart.reEdit = function (imageRef,saveText) {	
	
	var filecode, path, src, html, name;
	
	quantum.image.currentImage = imageRef;
	
	saveText = (saveText === undefined) ? "Edit" : "Update" ;

	name = quantum.thumbNames[imageRef];
	src = quantum.baseURL + quantum.galleryLarge + "/" + name + ".jpg";
	html = "<div class='center' style='width:36px; height: 36px; padding-top: 6px;'><img style='border: 0px' src='" + quantum.baseURL + "images/loading.gif' /></div>";

	quantum.blackBox(html, 
		{
			width: 50, 
			height: 50, 
			animSpeed: 200,
			fadeSpeed: 200, 
			style: {animType : "tv3"}, 
			onFinish: function () { quantum.image.load(src, filecode, quantum.image.currentImage, saveText); }
		});
	return false;
};

quantum.cart.slides = function () {
	
	var j, currentImage, filename;

	if (this.interval !== undefined)
	{
		clearInterval(this.interval);
	}

	if (quantum.cart.items.length == 0)
	{
		$("#cartSlides").html("");
		return;
	}

	quantum.cart.slideShow.length = 0;

	for (j = 0; j < quantum.cart.items.length; j++)
	{
		if (quantum.cart.items[j] !== undefined && quantum.cart.items[j] !== "undefined")
		{
			quantum.cart.slideShow[quantum.cart.slideShow.length] = j;
		}
	}
	
	filename = quantum.galleryThumbs + "/" + quantum.thumbNames[quantum.cart.slideShow[quantum.cart.slideShow.length-1]] + ".jpg";
	quantum.cart.loadSlide(filename, 0);
	
	this.interval = setInterval("quantum.cart.swapSlide()",3000);	
};

quantum.cart.swapSlide = function (reset)
{

	var newImage;
	
	if (quantum.cart.slideShow.length === 0)
	{
		this.image = 0;
		return;
	}
	
	if (this.image === undefined || reset === 0)
	{
		this.image = 0;
	}
	
	quantum.cart.loadSlide(quantum.galleryThumbs + "/" + quantum.thumbNames[quantum.cart.slideShow[this.image]] + ".jpg");

	this.image += 1;

	if (this.image	>= quantum.cart.slideShow.length)
	{
		this.image = 0;
	}
};

quantum.cart.loadSlide = function (filename, time) {

	time = (time === undefined) ? 1000 : time;
	
	$("#cartSlides").fadeOut(time,
	function ()
	{	
		var pad, h, w, img = new Image();
		img.src = quantum.baseURL + filename;
		img.onload = function () {
			pad = parseInt(parseInt($("#cartSlides").width()/2) - (img.width/4),10);
			h = parseInt(img.height /2,10);
			w = parseInt(img.width /2,10);
			imgTag = "<div><img style='width:" + w + "px; height:" + h + "px; margin-left:" + pad + "px;' src ='" + quantum.baseURL + filename + "'></div>";
			$("#cartSlides").html(imgTag).fadeIn(200);
		}
	});
}


quantum.flashshow.init = function ()
{
	var q = [], canvas;

	$(".userPasswrd").click(function () {quantum.form.resetPassword(""); });

	if (document.getElementById("page_number"))
	{
		$("#page_number").html("Page "+(quantum.flashshow.page+1)+" of " +quantum.flashshow.page_count);
		$("#galleryPrev").click(function () {quantum.flashshow.slide("left"); });
		$("#galleryNext").click(function () {quantum.flashshow.slide("right"); });	
		$("#previewPrev").click(function () {quantum.flashshow.one_slide("prev"); });
		$("#previewNext").click(function () {quantum.flashshow.one_slide("next"); });
		$("#bjtitle").click(function     () {window.open("http://www.brianjobson.co.uk","_self");});
		$(".thumbImage").click(function (e) {quantum.flashshow.preview(e); });
		$(".thumbImage").mouseover(function () {$(this).animate({"opacity": 0.2},20); $(this).animate({"opacity": 1.0},250); });
		$(".thumbImage").mouseout(function () {$(this).animate({"opacity": 1.0},100); });	

		$("#monobutton").click(function () { 
			quantum.manipulate.loader($("#t"+quantum.flashshow.currentThumb).attr("src").replace("thumbs","large"), "mono", "previewImageLoaded");
		});	
		
		$("#colorbutton").click(function () { 
			quantum.manipulate.loader($("#t"+quantum.flashshow.currentThumb).attr("src").replace("thumbs","large"), "colour","previewImageLoaded");
		});	
				
		quantum.flashshow.preload_preview();
	}
	
	// prepare a global context for a canvas.
	if (document.getElementById('context'))
	{
		quantum.manipulate.canvas = document.getElementById('context');
		if (quantum.manipulate.canvas.getContext)
		{
			quantum.manipulate.canvas.ctx = quantum.manipulate.canvas.getContext('2d');
		}
		else 
		{	/*
			var el = document.getElementById('context');
			G_vmlCanvasManager.initElement(el);
			quantum.manipulate.canvas.ctx = el.getContext('2d');*/
		}
	}

};


quantum.gally.init = function () {

	var cart, version;
	
	if (document.getElementById("gally"))
	{	
		$("img[id^='t']").click(function (e) {quantum.image.click(this,e); return false; });
		$("#editCartButton").click(function (e) {quantum.cart.showCart(); return false; });

		if (quantum.cookie.bake(quantum.cookie.cartName) === "undefined" || quantum.cookie.bake(quantum.cookie.cartName) === null)
		{
			quantum.cookie.bake(quantum.cookie.cartName, quantum.cookie.version + ":");		// sets the cart to accept data - version number is given in the first octet.
		}
		else
		{
			cart = quantum.cookie.bake(quantum.cookie.cartName);
			version = cart.split(":");
			version = parseInt(version[0],10);
			if (version !== parseInt(quantum.cookie.version,10))
			{
				quantum.cookie.bake(quantum.cookie.cartName, quantum.cookie.version + ":");		// resets the cart in case of version clash.
			
			}
			
			// cart cookie - Version + ":" + "Image number/image.size/image.count/image.type" + (. + Image Data) + ":" + ...
			quantum.cookie.unpackCart(cart);
		}
		$("a.aCheckout").click(function () { if (quantum.cart.items.length === 0) {return false;}});

	}
};

quantum.checkout.processOrder = function () 
{
	var option, agreed;
	option = $("input:radio[name=radio1]:checked").val();
	agreed = $("input:checkbox:checked").val();

	if (agreed !== "on")
	{
		alert("Please agree to the terms and conditions before continuing.");
		return false;
	}

	if (option === "p")
	{
		$("#payNowButton").val("Wait...").fadeTo(50,0.3);
		return true;
	}

	if (option === "c" || option === "t")
	{
		window.location = ("/invoice");
		return false;
	}
	
	return false;
};

quantum.checkout.makeForm = function ()
{
	var html, path = "", cartData = {}, postage;

	html = "<form id='ppCheckout' action='https://www.paypal.com/uk/cgi-bin/webscr' method='post''>";	

	html += "<div id='paymentMethod'>Payment method</div>";
	html += "<div id='radio1'><input type='radio' name='radio1' value='p' checked='checked'/></div>";
	html += "<div id='payPal'></div>";
	html += "<div id='radio2'><input type='radio' name='radio1' value='c' /></div>";
	html += "<div id='payCheck'></div>";
	html += "<div id='radio3'><input type='radio' name='radio1' value='t' /></div>";
	html += "<div id='payPhone'></div>";
	html += "<div id='check1'><input type='checkbox' /></div>";
	html += "<div class='agreed'>By checking this box, you certify that have have read, understood and agree to be bound by the ";
	html += "<a href='/terms'>terms and conditions</a> of sale.</div>";

	
	html += "<input type='hidden' name='cmd' value='_cart'>";
	html += "<input type='hidden' name='upload' value='1'>";
	html += "<input type='hidden' name='business' value='brian@brianjobson.co.uk'>";
	
	html += quantum.checkout.makeFormList();
	
	html += "<input type='hidden' name='return' value='http://www.brianjobson.co.uk/thankyou'>";
	html += "<input type='hidden' name='currency_code' value='GBP'>";
	html += "<input type='submit' id='payNowButton' value='Pay now'>";
	
	cartData = quantum.cart.totalUp();
	postage = quantum.cart.doPostage(cartData.total)

	html += "<input type=\"hidden\" name=\"postage\" value=\""   + postage +  "\">";
	html += "<input type=\"hidden\" name=\"subtotal\" value=\""  + cartData.total + postage +  "\">";
	
	html += "<div class='totalup'>Images:</div><div class='money'>&pound;" + cartData.total.toFixed(2) + "</div>";
	html += "<div class='totalup'>Shipping: </div><div class='money'>&pound;" + postage.toFixed(2) + "</div>";
	html += "<div class='totalup'>To Pay: </div><div class='money'>&pound;" + (cartData.total + postage).toFixed(2) + "</div>";
	
	html += "</form>";

	quantum.cookie.bake("toPay",(cartData.total + postage));

	$("#checkOutBoxFin").html(html);
};

quantum.cart.doPostage = function (total)
{
	if (total > 125) 
	{
		return 7.50;
	}
	
	if (total > 75) 
	{
		return 5.75;
	}

	if (total > 45) 
	{
		return 4.25;
	}

	if (total > 20) 
	{
		return 2.75;
	}
	return 1.5;
};


quantum.checkout.makeFormList = function ()
{
	var html = "", j,k,l, imageData = [], item = 0;
	
	for (j = 0; j < quantum.cart.items.length; j++)
	{
		if (quantum.cart.items[j] !== undefined)
		{		
			imageData = quantum.cart.items[j];								
			imageStack = imageData.split(".");		
		
			for (l = 0; l < imageStack.length; l++)
			{
				temp = imageStack[l].split("/");
				offset = parseInt(temp[0],10);
				count = parseInt(temp[1],10);
				type = parseInt(temp[2],10);
				
				if (count !== 0) 
				{
					item += 1;
					colour = (type === 1) ? (" colour ") : (" monochrome ");
					html += "<input type='hidden' name='item_name_" + item;
					html += "' value = '" + quantum.thumbNames[j] + ": " + descriptions[offset] + " in " + colour + "'>";
					html += "<input type='hidden' name='amount_" + item + "' value='" + prices[offset].toFixed(2) + "'>";
					html += "<input type='hidden' name='quantity_" + item + "' value='" + count + "'>";
					html += "<input type='hidden' name='on0_" + item + "' value=''>";
					html += "<input type='hidden' name='os0_" + item + "' value=''>";		
				} 
			}
		}
	}	
	return html
};



quantum.checkout.init = function ()
{
	var j, logo, html = "";

	quantum.cookie.unpackCart(quantum.cookie.bake(quantum.cookie.cartName));

	if (document.getElementById("checkoutGalley"))
	{
		logo = quantum.baseURL + "/" + "images/minilogo.gif";
		html += "<div>";
		
		for (j = 0; j < quantum.cart.items.length; j++)
		{
			if (quantum.cart.items[j] !== undefined)
			{
				html += quantum.checkout.checkoutImage(j);
			}
		}
		
		html += "</div>";

		quantum.checkout.makeForm();
		$("#checkoutGalley").html(html)
		$(".editThisImage").click( function (e) {quantum.cart.reEdit(e.target.id,"Update")}); 
		$("#payNowButton").click(function (e) {return(quantum.checkout.processOrder())});
	}
};

quantum.invoice.printable = function ()
{
	var html = "", j;
	
	quantum.userAddress = ["Marc Draco", "Some Street", "", "", "", "TS12 7GU", "", "brian@brainjobson.co.uk"]
	
	html += "<div class='printInvoiceAddress'>";
	html += "<p>Brian Jobson Photography</p>";
	html += "<p>23 Gore Sands</p>";
	html += "<p>Acklam</p>";
	html += "<p>Middlesbrough TS5 8UJ</p>";
	
	html += "</div>";
	html += "<div class='printInvoiceAddress'>";
	
	for (j = 0; j < quantum.userAddress.length; j++)
	{
		html += "<p>" + quantum.userAddress[j] + "</p>";		
	}
	
	html += "</div>";
	
	
};

window.onload = function ()
{
	quantum.flashshow.init();
	quantum.gally.init();
	quantum.checkout.init();
	quantum.form.reset();	
	quantum.cart.slides();	
	if (quantum.admin !== undefined && quantum.admin.init !== undefined)
	{
		quantum.admin.init();
	}
};

quantum.cookie.unpackCart = function (cart) {

	var j, k, imageRef, cartArray = [], firstSlash;

	if (cart === null)
	{
		return;
	}
	cart = cart.substring(cart.search(":")+1);					// remove the version number!
	
	cartArray = cart.split(":");								// split to individual images
	for (j = 0; j < cartArray.length; j++)	
	{
		firstSlash = cartArray[j].search("/");					// locate the image number
		imageRef = cartArray[j].substring(0,firstSlash);		// and slice it off...
		cartArray[j] = cartArray[j].substring(firstSlash+1);	// leave the image details
		quantum.cart.items[imageRef] = cartArray[j];
	}	
	quantum.cart.totalUp();
};

quantum.cookie.packCart = function () {

	var j, cart = "";
	
	cart = quantum.cookie.version + ":";
	
	for (j = 0; j < quantum.cart.items.length; j++)
	{
		if (quantum.cart.items[j] !== undefined && quantum.cart.items[j] !== "")
		{
			cart += j + "/" + quantum.cart.items[j] + ":";
		}
	}
	
	quantum.cookie.bake(quantum.cookie.cartName, cart);
	quantum.cart.totalUp();

};


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 * used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 * If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 * If set to null or omitted, the cookie will be a session cookie and will not be retained
 * when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 * require a secure protocol (like HTTPS).
 * @type "undefined"
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 * @author (Modified by) Marc Draco
 */

quantum.cookie.bake = function (name, value, options) {
	var path, domain, secure, expires, date, i, cookie, cookieValue, cookies, cookieArray, c;
	if (typeof value !== "undefined") 
	{ // name and value given, set cookie

		options = options || {};
		if (value === null) 
		{
			value = '';
			options.expires = -1;
		}
		expires = '';
		if (options.expires && (typeof options.expires === 'number' || options.expires.toUTCString)) 
		{
			if (typeof options.expires === 'number') 
			{
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} 
			else 
			{
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		path = options.path ? '; path=' + (options.path) : "; path=" + '/';
		domain = options.domain ? '; domain=' + (options.domain) : '';
		secure = options.secure ? '; secure' : '';		
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');		
	} 
	else 
	{ // only name given, get cookie
		cookieValue = undefined;
		if (document.cookie && document.cookie !== '') 
		{			
			name = name + "=";
			cookieArray = document.cookie.split(';');
			for (i = 0; i < cookieArray.length; i++) {
				cookie = cookieArray[i];
				while (cookie.charAt(0) === ' ') 
				{
					cookie = cookie.substring(1,cookie.length);
				}
				if (cookie.indexOf(name) === 0) 
				{
					return decodeURIComponent(cookie.substring(name.length, cookie.length));
				}
			}
			return null;
		}
	}
};
