
/*  jQuery functions for most pages */
$(document).ready(function(){

	$('.spacer1').remove(); // these are only to pad out pages when jQ not available
	$('.spacer2').remove();
	$('.spacer4').remove();



	function fixLayout () {
		winHite = $(window).height();
		menuHite = $('#menu_fixed').height() - $('#logo').height();
		contentTop = $('#SearchBox').offset().top;
		// alert($('#menu_fixed').height()+' - '+$('#logo').height()+' = '+menuHite);
		$('#content').css({minHeight: menuHite}); // pad out empty space before bottom triangle
		// var menutop = $('#menuVW').position().top;
		if ( (menuHite + contentTop +30) < winHite ) {
			$('#menuVW').css({position:'fixed'});
		} else {
			$('#menuVW').css({position:'absolute'});
		};
		// work out available space for Stock List (if it exists)
		var introTextHite = $('#content h2').height() + $('#content p.left').outerHeight() + 30;

		stockListHite = winHite-contentTop-introTextHite-100;  // not quite sure why this needs so much extra
		if ( stockListHite < menuHite ) {stockListHite = menuHite; };
		if ( typeof($('#stockList')=='object' ) ) {
			// alert(stockListHite);
			$('#stockList').css({ height:stockListHite })
		};
	}
	fixLayout(); // run on document.ready
	$(window).resize(function() { // and run on resize
		fixLayout();
	});


	/********* the SERIOUS stuff  - loading entire lists *******/
	if ( typeof(numRecords)=='number' && numRecords>0) {
		// various details are provided by result_list.php in html page - such as sql, startNo
		sql = sql										// some changes to the query
			.replace(/ LIMIT\s+\d+,\d+/, '')			// no LIMIT
			.replace(/SELECT\s+\*/i, "SELECT `stockID` AS `s` "); // don't need all, only stockID

		// ruthlessly get rid of all actual content and rearrange title etc.
		$('#itemListBlock').remove(); // main content listing
		$('#content br').remove(); // some spurious breaks
		var resultText = $('.navresult:first').text(); // rescue useful info before...
		$('.navform').remove(); // irrelevant page navigation
		$('#content h2').css({float:'left', margin:'0 0 6px'});
		if ( $('#pref_sort').length==0 ) {	// if there is no sorting drop-down in the form
			$('form#prefSet').remove();		// then we don't need the form at all
		} else {
			$('span#pref_perPage').remove(); // irrelevant 'items per page' form
			$('form#prefSet').css({float:'right', display:'inline'});
			// DANG! I think this must override soth_print.css which is meant to hide forms
			// so must actually remove it prior to printing :-(
		};

		// turns out that showing everything is a bit mad for some browsers when over 1000 or so items
		// Ditched this idea for now - more complex than thought and no-one has requested it
		// Show "loading" warning instead
		var itemsPerPage = 20; // set variable to invoke LIMIT and do some navigation calculations
		var navExtra = '';
		// var sqlExtra = '';
		// if ( numRecords>itemsPerPage*1.25 ) {
		//
		//
		// 	var limitStart = (startNo>=itemsPerPage ? startNo : 0); // THIS'LL SCREW UP WHEN st=STOCKid
		//
		//
		// 	var prevStart = startNo-itemsPerPage;
		// 	var nextStart = startNo+itemsPerPage;
		// 	var qs = window.location.href.match(/\?/);
		// 	var nextUrl = window.location.href.replace(/&?st=\d+/,'')+(qs ? '&' : '?')+'st='+nextStart;
		// 	navExtra = '. Showing first '+itemsPerPage+'. <a href="'+nextUrl+'">Next '+itemsPerPage+'&rarr;</a>';
		// 	// sqlLimit = ;
		// 	sql = sql+" LIMIT "+limitStart+","+itemsPerPage;
		// };

		$('<div />', { // new div created with useful info (collected above)
			'id': 'navresult',
			'class': 'navtext',
			'style': 'border-bottom:1px solid #7D9EA3',
			html: '<p style="height:16px;"><strong>'+resultText+'</strong>'+navExtra
				+' <em id="loading"> &nbsp; LOADING... please wait...<img style="vertical-align:top" src="'+domainPath+'images/loader-green.gif" width="16" height="16" alt="" /></em>'
				+'<span id="print" title="print listing"><img src="'+domainPath+'images/printer.gif" /></span>'
				+'</p>'
			})
			.appendTo('#content');

		var shCart = shopCart.split(':');
		// shCart is now array to check each item against to see if already in cart

		// first load list of stock numbers, formatted in placer-boxes ready for content
		// send sql to PHP to get full list of items as JSON
		$.getJSON(domainPath+'ajax_stock_list.php', {'q': sql}, function(json) {
			var stkItems = []; // array to store stock items
			$.each(json, function(key, item) { // each item returned as JSON is made into a div
				// var itemNo = key +1 +startNo; // important - add startNo so catalog nums are right if paging
												// but then it can't scroll to startNo... if that matters
												// Not paginating yet anyway.
				var itemNo = key +1;
				stkItems.push(
					'<div class="it'+(displayStyle=='print' ? ' itp' : '')
						+'" id="item_'+itemNo+'">'
						+(displayStyle!='print' ? '<div class="wrapr">' : '')
							+'<div class="placer empty '+displayStyle+'" id="stk_'+item.s+'">'
							+'</div>'
						+(displayStyle!='print' ? '</div>' : '')
						+(displayStyle!='print' ? '<div class="ctrl"></div>' : '')
					+'</div>'
					);
				});

			$('<div />', { // new div is created and stkItems put into it ... neat!
				'id': 'stockList',
				html: stkItems.join('')
				})
				.appendTo('#content').css({height:stockListHite, overflow:'auto'})
				.scroll(function() {
					fillView(); // fill viewport with ajax loaded data whenever it moves
				});
			// decide where to start the page view: items may be identified by either StockID OR ItemNo
			var itemStart = (
					 $('#stk_'+startNo).length ? '#stk_'+startNo
				 : ( $('#item_'+startNo).length ? '#item_'+(startNo-0+1) // item must NOT be zero
				 :   '#item_1' ) );  //  default failure goes to item 1
			// how many might fit? tricky - assume large screen and small browser
			var how_many_items_might_fit = (displayStyle=='print' ? 24 : 10);
			var itemStartNumber = itemStart.replace('#item_','')-0;
			if ( itemStartNumber<5 || stkItems.length<how_many_items_might_fit ) {
				fillView(); // trigger fillView when there may be no scrolling
			} else { // scroll to requested item, (& trigger fillView)
				$('#stockList').scrollTo(itemStart);
			};
			// $('#loading').hide();
		});




		function fillView (print_ALL, inc_Images) {
			// build a list of which StockID's needed to fill viewport, plus some either side (not yet visible)
			// only get those not already complete (by class flags)
				// Sometimes it gets triggered twice for the same number,
				// I suppose only when fast scrolling and no way around it
			var printALL = (typeof(print_ALL)!='undefined' ? print_ALL : false); // default only get in viewport
			var includeImages = (typeof(inc_Images)!='undefined' ? inc_Images : true); // default show images
			var itemNos = []; // array for item placer numbers
			// alert('printALL '+(printALL ? 'true':'false')+', includeImages '+(includeImages ? 'true':'false') );
			if ( printALL ) { // if request to load them all at once (eg. to print list)
				$('div.it').each(function() {
					itemNos.push( $(this).attr('id').replace('item_', '')-0 );
				});
			} else {		// NORMAL - only want those in viewport
				$('div.it:in-viewport').each(function() {
					itemNos.push( $(this).attr('id').replace('item_', '')-0 );
				});
			};

			var itemFirst = itemNos[0];
			var itemLast = itemNos[itemNos.length-1];
			if ( printALL ) {
				itemFirst =1;
			} else {
				itemFirst = (itemFirst>4 ? itemFirst-4 : 1); // stretch range before and after viewport
				itemLast = itemLast + itemNos.length;
			};
// alert('itemNos.length: '+itemNos.length+' - first: '+itemFirst+' - last: '+itemLast);

			// got list of items, now check each one and add stockNo to list if not loaded already
			if ( itemNos.length ) {
				var stkNos = []; // array of Stock Numbers to get
				for (i=itemFirst; i<=itemLast; i++) { // I just learned cannot use == comparator, only <
					var itemID = $('#item_'+i).find('div.empty').attr('id');
					if ( typeof(itemID)!='undefined' ) {
						var idd = itemID.replace('stk_','')-0;
						stkNos.push( idd );
					};
				};
				// alert('stkNos.length: '+stkNos.length);

				if ( stkNos.length ) {
					var stkList = stkNos.join('~');
					// request short details for LIST of stockID's - should be quicker than many small requests
					// foreach item returned, fill in details
					// them remove 'empty' class so it will not be filled again
					$('#loading').show(function() { // show "loading" until loopCount is big enough
						$.getJSON(domainPath+'ajax_stock_list.php', {'stkList': stkList}, function(jsn) {
							var loopCount = 0;
							$.each(jsn, function(key, item) { // each item returned as JSON is inserted into placer
								loopCount ++;
									// define lots of vars on one line:
								var stkID = item.s
									itemNum = $('#stk_'+stkID).parents('.it').attr('id').replace('item_', '')
									catNo = (catlog ? itemNum+'. ' : '')
									avail = item.available-0 // JSON provides string; some values MUST be number
									thePrice = (avail ? '&pound;'+item.price : '<span class="sold">[sold]</span>');
									itemImg = item.img-0;
								var enqLink = '<span style="display:inline-block;width:104px"></span>'; // default blank
								// inserted links are confusing for IE7, so forced pos:static
								var pLink = '<a class="plink" style="position:static" href="'+domainPath+'Search.php?stk='+stkID+'&amp;type%5B%5D='+item.sType+'s" title="Permanent link to this item"><img src="'+domainPath+'images/plink.png" /></a>';
								if ( avail ) {
									enqLink = '<a style="position:static" href="'+domainPath+'ContactUs.php?t='
										+item.sType.slice(0,1)+'&stk='+item.s
										+'&jq" title="Buy or Enquire&hellip;"><img src="'
										+domainPath+'images/orderEnquire.gif" alt="enquire" class="enq" /></a>';
								}
								if ( $.inArray(item.s, shCart)!=-1 ) { // ... or if already in cart
									enqLink = '<span class=cart><a href="'+domainPath
									+'ContactUs.php?list=1">in Shopping Cart<img src="'
									+domainPath+'images/cart.gif" class="enq" /></a></span>';
								};

								if ( displayStyle=='print' ) { // PRINT style
									theWords = (itemImg ? (includeImages ? '<img class="thum" src="'
										+domainPath+'stockimg/sized/'+stkID+'t.jpg" />' : '')
										: (printALL ? ''
										: '<img class="thum dummy" src="'+domainPath+'images/print_dummy.gif" />'))
									+'<p>'+catNo+(avail ? '' : '<span class="red">(SOLD) </span>')
									+(item.author!=null ? '<span class="auth">'+item.author+'</span>'+'<br />' : '')
									+item.titl+(item.pLatin ? ' <span class="latin">('
										+item.pLatin+')</span>' : '')+'</p>'
									+'<p>'+item.pForm+'</p>'
									+'<p class="price"'
									+(printALL ? '' : ' style="display:none"')+'>'+thePrice+'</p>'
									+'<p class="desc"'
									+(printALL ? '' : ' style="display:none"')+'> '+item.publish+'</p>'
									// desciption field is NOT needed for prints - duplicated info
									// +'<p class="desc" style="display:none"> '+item.descr+'</p>'
									+'<p class="inCart">'+enqLink+'</p>'; // just stored here for now

								} else { // BOOK or MIXED
									theWords = (itemImg ? (includeImages ? '<img class="thum" src="'
									+domainPath+'stockimg/sized/'+stkID+'t.jpg" />' : '') : '')
									+(item.heading!=null ? '<h3>'+item.heading+'</h3>' : '')
									+'<p>'+catNo
									+(item.author!=null ? '<span class="auth">'+item.author+'</span> ' : '')
									+item.titl+'</p>'
									+'<p> '
									+(item.publish!=null ? '<span class="publish">'+item.publish+'</span>' : '')
									+(item.pForm!=null ? ' <span class="pForm">'+item.pForm+'</span>' : '')
									+'</p>'
									+'<p class="price">'+thePrice+'</p>'
									+'<div style="display:none ; text-align:center" class="mainImg"></div>'
									+'<p class="desc"> '+item.descr+'</p>';
								};
								// I just learned about CONTEXT - more efficient to specify closer to
								// where we're aiming. Using ID is already very good of course.
								// $('#stk_'+stkID, $('#stockList'))
								// ...can this really be better than just the ID?
								// ...is it not the same as $('#stockList #stk_'+stkID) ??
								// "internally, selector context is implemented with the .find() method"
								//  So it's the same as $('#stockList').find('#stk_'+stkID)
								// In the case of a unique ID though I don't think it's worth it

								// Generally the item will now be complete
								if ( includeImages ) { // unless images omitted for printing
									$('#stk_'+stkID).removeClass('empty');
								};
								$('#stk_'+stkID).html(theWords);

								if ( displayStyle!='print' ) { // extras in .ctrl area for books (or mixed cat)
									// next line just for choosing correct image!
									var ucFirstType = item.sType.slice(0,1).toUpperCase() + item.sType.slice(1);
									$('#stk_'+stkID).parent('.wrapr').siblings('.ctrl').html(
										pLink
										+'<img class="showHide" src="'
										+domainPath+'images/detail'+ucFirstType+'.gif" /> &nbsp '
										+enqLink
										// +' &nbsp; <span class="price">'+thePrice+'</span>'
										);
								};
								if ( loopCount==stkNos.length ) {
									// after all loaded, hide feedback graphic
									$('#loading').hide();
									if ( printALL ) {
										if ( includeImages ) {
											$('.wrapr img').css({display:"inline"});
										} else {
											$('.wrapr img').css({display:"none", height:0})
										};
										$('#prefSet').css({display:"none"})
										print();
									};
								};
							}); // end each()

						}); // end getJSON()
					});



				} else {
					// no stock numbers to load, but may still want to trigger print
					// THIS IS JUST DUPLICATED FROM ABOVE   >8-(
					if ( printALL ) {
						if ( includeImages ) {
							$('.wrapr img').css({display:"inline"});
						} else {
							$('.wrapr img').css({display:"none"})
						};
						$('#prefSet').css({display:"none"})
						print();
					};
				};

			};

		};

		 $('#print').click(function() {	// click the print button
		 	// show choice to print visible or ALL
		 	//
		 	// ***** OH DEAR ... printing visible seems to scroll to top of #content on Firefox at least
		 	//
			var prWarning = '';
			if ( numRecords > 400 ) {
				prWarning = '(please be patient whilst loading)';
			};
			var clickPos = $(this).offset();
			var cpTop = clickPos.top + 8;
			var cpLeft = clickPos.left - 80;
			var textForBox = '<img id="cpClose" title="cancel" src="'+domainPath+'images/close.gif" />PRINT:<br /><em id="cp1">Short text list</em>'
			+(displayStyle=='print' ? '' : '<em id="cp2">Full text list</em>')
			+'<em id="cp3">Full list with images</em>'
			$('<span />', { // new span inserted
				id: 'printChoice',
				style: 'top:'+cpTop+'px ; left:'+cpLeft+'px ; ',
				html: textForBox
				+prWarning
			}).appendTo($('#contentHW'));

		 });

		$('#printChoice').live('click', function(e) { // what happens with the print list created above
			var targ = $(e.target);
			if ( targ.is('#cpClose') ) {
				$(this).remove();
			};
			if ( targ.is('em') ) { // to print,
				// if displaying print-style format, must reorganised into book-like list with all text
				if ( displayStyle=='print' ) {
					$('.dummy').remove();
					$('.thumb2').css({float:'right', display:'inline'});
					$('.inCart').remove();
					$('.placer p').show();
					$('.it').each(function(index) {
						if ( $(this).hasClass('itp') ) {
							 // item boxes already contain all info & thumbnail
							$(this).css({float:'none', height:'auto', width:'auto'});
							$(this).children('.placer')
								.removeClass('print')
								.addClass('book').addClass('wrapr');
						} else { // any "opened" items hidden
							$(this).hide();
						};
					});
				};

				// extend what is visible
				$('#content').css({borderWidth:"0"});
				$('.ctrl').css({display:"none"});
				$('#stockList').css({overflow:"visible", height:"auto"});
				$('.it').css({borderWidth:'0 0 1px'});
				var incImages = false
				if ( targ.is('#cp1') ) { // short list - hide images, short wrapr
					$('.wrapr').css({minHeight:"100", height:"100"});
				};
				if ( targ.is('#cp2') ) { // full list - hide images but increase space
					$('.wrapr').css({minHeight:"500", height:"auto"});
				};
				if ( targ.is('#cp3') ) { // full list - show images, increase space
					incImages = true;
					$('.wrapr').css({minHeight:"500", height:"auto"});
				};


					// load all empty items
				fillView(true, incImages); // and PRINT when all loaded
				$(this).remove();

			};
		});

		$('.it').live('click', function(e){ // decide action to perform on clicking an item
			var targ = $(e.target);
			// if click is on 'ctrl' or 'thum' but not on 'enq' (allow that to follow href)
			if (( targ.hasClass('thum') || targ.hasClass('ctrl') || targ.parents().hasClass('ctrl') )
					&& !targ.hasClass('enq') && !targ.children().hasClass('enq')) {
				if ( typeof($(this).find('.placer').attr('id'))=='undefined' ) {
					var stkNo = $(this).attr('id').replace('prt_', ''); // find print id
				} else {
					var stkNo = $(this).find('.placer').attr('id').replace('stk_', ''); // find book id
				};

				if ( $(this).find('.placer').hasClass('open') ) {
					if ( $(this).find('.placer').hasClass('print')
					 	|| $(this).find('.placer').hasClass('bok') ) {
						shrinkPrint(stkNo);
					} else {
						shrinkBook(stkNo);
					};
				} else {
					if ( $(this).find('.placer').hasClass('print') ) {
						expandPrint(stkNo);
					} else {
						expandBook(stkNo);
					};
				};
			};
		});

		function expandBook (stkNo) { // for BOOK or MIXED format pages
			var thisItem = $('#stk_'+stkNo);
			if ( !$(thisItem).hasClass('filled') ) { // get details if NOT already done
				// details to get - size of main image and catalogue list
				$.getJSON(domainPath+'ajax_stock_list.php', {'stk': stkNo}, function(item) {
					// var bigDescr = item[0].descr;
					// full description already loaded, so we already know the height
					var textHite = $(thisItem).height();

					var catList = [];
					if ( item[0].cat!=null ) {
						$.each(item[0].cat, function(key, ct) { // add each catalogue to list
							if ( ct.catName!=catlog ) { // UNLESS it's the catalogue we're viewing
								catList.push('<a href="'+domainPath+'Catalogue.php?cat='+ct.catName+'">'+ct.catTitle+'</a>');
							};
						});
					};
					var catText = '';
					var catHite = 0;
					var cats = catList.length;
					if ( cats ) { // this item features in some (other) catalogues
						catText = '<p class="catDetail">This book is '+(catlog ? 'also ' : '')+'included in catalogue'+(cats>1 ? 's' : '')+' &mdash; '
						+catList.join(', ') +'</p>';
					};
					$(thisItem).append(catText).show(function() {
						catHite = $('.catDetail', this).height();
					});

					var bigImageHite = item[0].imgHite -0; // cast as numeric
					if ( bigImageHite ) {
						$('#stk_'+stkNo+' .mainImg').html('<img src="'+domainPath+'stockimg/sized/'+stkNo+'.jpg" height="'+bigImageHite+'" />');
						var numImages = item[0].img -0;
						if (numImages >1) {
							$('#stk_'+stkNo+' .mainImg').after('<br /><span style="text-align:center;width:100%;display:inline-block">'+item[0].imgThums+'</span>');
							bigImageHite += 100; // add fixed height of thumbnails
						}
					};

					placerHite = textHite+bigImageHite+catHite+30; // some extra for margins
					$(thisItem).addClass('filled').css({height:placerHite}); // FIX HEIGHT
					$(thisItem)
						.find('.thum').hide().end()
						.find('.mainImg').show().end()
						.addClass('open').show(function() { // no resizing until everything in place
							$(thisItem).parent('.wrapr').animate({'height':placerHite}, '500');
							if ( thisItem.height()>180 ) {
								$('#stockList').scrollTo('#stk_'+stkNo, 400, {easing:'swing'});
							};
							stockImageThumbs(stkNo); // place thumbs if possible
						});
				});


			} else { // if already filled, only check the required height

				placerHite = $(thisItem).height();

				$(thisItem)
					.find('.thum').hide().end()
					.find('.mainImg').show().end()
					.addClass('open').show(function() { // no resizing until everything in place
						$(thisItem).parent('.wrapr').animate({'height':placerHite}, '500');
						if ( thisItem.height()>180 ) {
							$('#stockList').scrollTo('#stk_'+stkNo, 400, {easing:'swing'});
						};
					});
			};
				// feedback icon change
			$(thisItem).parent('.wrapr').siblings('.ctrl').find('img.showHide').attr('src',
				domainPath+'images/less.gif');
		};

		function expandPrint (stkNo) { // for PRINT format pages
			var thisPrint = $('#stk_'+stkNo);
			var thisItemNo = thisPrint.parent('.itp').attr('id').replace('item_', '');
			if ( !thisPrint.hasClass('filled') ) { // get details if NOT already done
				// details to get -  image(s) and catalogue list
				$.getJSON(domainPath+'ajax_stock_list.php', {'stk': stkNo}, function(item) {

					var imagesHtml = '';
					var bigImageHite = item[0].imgHite -0; // cast as numeric
					var numImages = item[0].img -0;
					if ( bigImageHite ) {
						imagesHtml = '<div class="mainImg"><img src="'+domainPath+'stockimg/sized/'+stkNo+'.jpg" height="'+bigImageHite+'" /></div>';
						if (numImages >1) {
							imagesHtml += '<br />'+item[0].imgThums;
						}
					};

					var catList = [];
					if ( item[0].cat!=null ) {
						$.each(item[0].cat, function(key, ct) { // add each catalogue to list
							if ( ct.catName!=catlog ) { // UNLESS it's the catalogue we're viewing
								catList.push('<a href="'+domainPath+'Catalogue.php?cat='+ct.catName+'">'+ct.catTitle+'</a>');
							};
						});
					};
					var catText = '';
					var cats = catList.length;
					if ( cats ) { // this item features in some catalogues
						catText = '<p class="catDetail">This print is '+(catlog ? 'also ' : '')+'included in catalogue'+(cats>1 ? 's' : '')+' &mdash; '
						+catList.join(', ') +'</p>';
					};

					// Try to work out height of text... this is madness to be sure!
					var textLength = thisPrint.text().length;
					var textBreaks = 0;
					if ( thisPrint.html().match(/<br/gi) ) {
						var textBreaks = thisPrint.html().match(/<br/gi).length;
					}
					var textParas = thisPrint.html().match(/<p/gi).length;
					// textHite is lines of 100 chars plus empty lines all at 16px each
					var textLines = ( (textLength/100)+textBreaks+textParas ) ;
					var lineHite = 16;
					var textHite = textLines *lineHite;
					//  TOTAL height required for detail view
					prtHite = textHite-0+bigImageHite
						+( numImages>1 ? 100 : 0 ) // extra for thumbnails (hardcoded stockImg.php)
						+( cats ? lineHite : 0 );

					thisPrint.addClass('filled');

					var enqLink = thisPrint.find('.inCart').html(); // enquire link, to go in .ctrl

					var printText = thisPrint.html();
										// .replace(/<img class="thum.*?>/, '') // ditch thumbnail
										// .replace(/display:\s?none/g, '');  // show price
							// IE has a problem with these regexp
							// now done later with jQ - more reliable


					// fix size of container div to act as placeholder for hidden content
					thisParent = thisPrint.parent('.itp');
					thisParent.width(thisParent.width()).height(thisParent.height());
					// (tried giving this less height so if a whole line goes the
					// space collapses. Nice idea but difficult to put height back correctly)

					// create stk_ block for large details on line above
						// always four items per line, so I can work out which is first on this line
						// does this calculation need to be so awkward?
					var lineStartNo = thisItemNo-(thisItemNo%4)+(thisItemNo%4==0 ? -3 : 1);
					var lineStart = $('#item_'+lineStartNo);
					// create stk_ div before current line and fill with details
					lineStart.before('<div class="it" id="prt_'+stkNo+'" style="display:none">' //
						+'<div class="wrapr bok placer open" style="height:auto">'
						+'<div class="pic">'+imagesHtml+'</div>'
							//+(bigImageHite ? '<p style="text-align:center" class="mainImg">'
							//+'<img src="'+domainPath+'stockimg/sized/'+stkNo+'.jpg" height="'
							//+bigImageHite+'" /></p>' : '')
						+printText+(cats ? catText : '')
						+'</div>'
						+'<div class="ctrl">'
						+'<a class="plink" href="'+domainPath+'Search.php?stk='+stkNo
						+'&amp;type%5B%5D=prints" title="Permanent link to this item"><img src="'
						+domainPath+'images/plink.png" /></a>'
						+'<img src="'+domainPath+'images/less.gif" /> &nbsp; '
						+enqLink+'</div>'
						+'</div>').show(function() {
							thisPrint.fadeOut('fast');
							$('#prt_'+stkNo).find('.thum').remove().end()
								.find('p.desc').show().end()
								.find('p.price').show();
							$('#prt_'+stkNo).fadeIn('500').find('.wrapr')
								.slideDown();
							$('#stockList').scrollTo('#prt_'+stkNo, 400, {easing:'swing'});
							stockImageThumbs(stkNo); // place thumbs if possible
						});
				});


			} else { // if already filled, only check the required height
				// when created (above), the wrapr grows to size and keeps it
				// the outer container ".it" is now grown to that size plus a bit for .ctrl
				thisPrint.fadeOut('fast');
				$('#prt_'+stkNo).fadeIn('fast');
				$('#stockList').scrollTo('#prt_'+stkNo, 400, {easing:'swing'});
			};
		};


		function shrinkBook (stkNo) {
			var thisItem = $('#stk_'+stkNo);
			thisItem.parent('.wrapr').animate({'height':'100px'}, '500').show(function() {
				if ( thisItem.height()>180 ) {
					$('#stockList').scrollTo('#stk_'+stkNo, 400, {easing:'swing'});
				};
				thisItem
					.find('.mainImg').hide().end()
					// .find('.price').hide().end()
					.find('.thum').show().end()
					.removeClass('open');
			});
			thisItem.parent('.wrapr').siblings('.ctrl').find('img.showHide').attr('src',
				domainPath+'images/detailBook.gif');
		};

		function shrinkPrint (stkNo) {
			var thisPrt = $('#prt_'+stkNo); // large details to be hidden
			var fullSize = ( thisPrt.height()>200 ? true : false); // so no scroll if not moving much
			var thisItem = $('#stk_'+stkNo);// thumbnail etc. to be shown
			thisPrt.fadeOut(600, function() {
				thisItem.fadeIn('fast');
				if ( fullSize ) {
					$('#stockList').scrollTo('#stk_'+stkNo, 400, {easing:'swing'});
				};
			});

		};


	};


	if (typeof(stockNumber)!='undefined') {
		// run once if stockNumber set by PHP in head i.e. for single item on page
		stockImageThumbs(stockNumber);
	}

	function stockImageThumbs (stkNo) {
		/******* handle STOCK IMAGE THUMBNAIL clickS    ****/
		// thumbnails are added by stockimage php class,
		// jQ needs to make them pretty and useful
		// look for item with this stkNo & prefix stk_ OR prt_
		// #stk_ always exists but print may also have #prt_
		var thisItem = false;
		if ( $('#prt_'+stkNo).length ) {
			thisItem = $('#prt_'+stkNo);
		} else if ( $('#stk_'+stkNo).length ) { // 'elseif' is NOT javascript
			thisItem = $('#stk_'+stkNo);
		}

		if (thisItem) {
			var thisMainImgBox = thisItem.find('.mainImg');
			var thCount = 0;
			var thumbs = [];
			thisItem.find('.thumb2').each(function(index) { // check size of each thumbnail
				thumbs[thCount] = $(this).width() / $(this).height(); // record the ratio
				$(this).parent().after('&nbsp;'); // space after the enclosing <a />
				thCount ++;
			});
			// thumbs is now array containing relative SHAPES of images
			// 1 is square;  >1 is landscape; <1 is portrait

			if ( thCount>1 ) { // there are more than one thumbnail
				var mainImgHite = thisMainImgBox.children('img').height();
				var boxHite = mainImgHite;
				if ( thumbs[0] >1 ) {	// if main image is landscape
					// sort thumbs by size
					var thSorted = thumbs.sort(function(a,b){return a-b});
					// a number representative of the range of shapes
					var thDiff = thSorted[thSorted.length-1] - thSorted[0];
					// '1' is quite large, '2' very large
					var c = 0.4; // a constant to adjust how this works :-\
					// now make the box a reasonable size to fit any available image
					boxHite = Math.floor(boxHite * (thDiff + c));
					if (boxHite > mainImgHite && $('#prt_'+stkNo).length) {
						// if growing image space, prt_ needs to grow too
						var thisWrapr = thisItem.children('.wrapr');
						var wrapH = thisWrapr.height();
						//thisWrapr.css({height:(wrapH-0+boxHite-mainImgHite)});
					}

				};
				var boxWide = thisMainImgBox.width();
				var boxTop = thisMainImgBox.position().top;
				var boxLft = thisMainImgBox.position().left;

				// position image box and overlay a second box
				thisMainImgBox.css({height:boxHite+'px'});
				var boxPad = Math.floor((boxHite-mainImgHite)/2);
				thisMainImgBox.children('img').css({paddingTop:boxPad+'px'});
				thisMainImgBox.after('<div class="mainImg2" style="text-align:center"></div>');
				thisMainImgBox.css({height:boxHite+'px', width:boxWide+'px'});
				thisMainImgBox.siblings('.mainImg2').css({marginTop:'-'+boxHite+'px', height:boxHite+'px', width:boxWide+'px'});

				var boxNow = 'mainImg';
				var boxNex = 'mainImg2';
			} else {	// if only one thumbnail, no need to show it
				thisItem.find('.thumb2').hide();
			};

			thisItem.find('.thumb2').click(function(evt) {
				var thLink = $(this).parent().attr('href');
				var thShape = $(this).width() / $(this).height();
				var dimension = ' height="'+boxHite+'" ';
				var pad = '';
				if ( thShape>1 ) {
					// deduce height of incoming landscape image and adjust padding for vertical position
					var imgHite = Math.floor(boxWide/thShape);
					while (imgHite > boxHite) { // cheap iteration ... surely there is a better maths way
						imgHite = imgHite-10;
					}
					var imgPadding = Math.floor((boxHite-(imgHite))/2);
					var pad = 'style="padding-top:'+imgPadding+'px"';
					dimension = ' height="'+imgHite+'" ';
				};
				// place this image
				thisItem.find('.'+boxNex).html('<img src="'+thLink+'"'+dimension+pad+' />');
				thisItem.find('.'+boxNow+' img').fadeOut('fast');
				// swap boxes for next time
				boxNow = (boxNow=='mainImg' ? 'mainImg2' : 'mainImg');
				boxNex = (boxNex=='mainImg' ? 'mainImg2' : 'mainImg');

				evt.preventDefault();
			});
		};




	};





	// submit form on change
	$('#prefSet select').change(function() {
		$('#prefSet').submit();
	});


});

