// JavaScript Document
var DISTANCE = 89;		//total movement per click;
var LANG;				//current language;
var cat = "bookwork";	//current section;
var counter = 0;		//used to monitor the left and right arrow click;
var menuCount = null;	//total number of options in the menu;
var intervalID;		

/**
 * contains all the image gallery data in JSON format;
 */
var DATA =  {
	"en": {
		"bookwork": {
			"title": "Bookwork",
			"text": "Imago offers access to a full range of cased and limp binding facilities including sewn, notch and perfect binding, flexi-binding, wire-o, spiral, reinforced binding and even hand binding for special formats. We can cater for high volume and low print runs, long or short extents and offer four colour, duotone, stochastic and mono printing, sheet fed or web.",
			"opt": [ 'Cased binding', 'Limp binding', 'Bible printing', 'Flexi-binding', 'Spiral binding with blocked text', 'Wire-o binding' ],
			"disc": [ 	'Fish Cook, Aldo Zilli published by Jacqui Small LLP, an imprint of Aurum Press Limited. Cased, sewn binding, printed imitation cloth plus jacket.',
						'The Book of Rock, Philip Dodd published by Pavilion Books Ltd. Limp, sewn binding, cover with flaps. Cover has matt lamination and spot uv varnish.',
						'The Holy Bible, TNIV published by Hodder & Stoughton. Text printed on 34gsm bible paper, flexi-bound with silver gilt edges.  Quarter bound in two contrasting shades of PU covering material.',
						'Moon Metro, Rome published by Avalon Travel Publishing. Series of flexi-bound travel guides with laminated fold out maps.',
						'Bien cuisiner, published by Solar Spiral bound recipe book with wipe clean PP cover and PVC dividers with thumb tabs. Spine has been screen printed with the book title.',
						'Expresso Journals, published by World\'s Greatest Minds Wire-bound journals with litho printed PP covers with elasticated closures.' ],
			"img": [ 'DSC09917', 'BookofRockUK', 'DSC09851', 'DSC09870', 'DSC09134', 'DSC06364' ]
		},
		"children": {
			"title": "Children's Books",
			"text": "Imago offers over 25 years experience in the production of conventional and novelty children\'s books. Working together with many of the world\'s most successful publishers, authors and illustrators, we are a leading player in children\'s book manufacture.",
			"opt": [ 'Picture Books', 'Lift the Flap Books', 'Bath Books', 'Touch & Feels', 'Cloth / plush books', 'Pop ups' ],
			"disc": [ 	'How to Catch a Star, Oliver Jeffers published by HarperCollins Publishers. Cased picture book, plc with jacket.  Jacket printed on pearlised effect paper with no finishing. ',
						'Wibbly Pig\u0027s Garden, Mick Inkpen published by Hodder Children\'s Books. Limp bound, singer sewn picture book with lift up flaps',
						'S\u00e9raphin le Petit Dauphin, Xavier Deneux published by \u00c9ditions Tourbillon',
						'Mein Erstes Bilder-W\u00f6rterbuch, Marlit Peikert published by Ars Edition. Board book binding including touch & feels and diecut windows.',
						'Lustiges Stoffbilderbuch,  published by Esslinger Verlag. Series of animal shaped cloth books with plush covers and cotton interiors',
						'ABC? Animaux anim\u00e9s! Alain Crozon. Published by Seuil Jeunesse. Cased, singer sewn pop up book with a pop for each letter of the alphabet.'],
			"img": [ 'picture', 'wibbly', 'bath', 'touch', 'cloth', 'DSC09453' ]
		},
		"booksplus": {
			"title": "Books Plus",
			"text": "Imago has extensive experience in producing books with add-ons for both children's and adult markets. We recognise the value to publishers of being able to place books plus work with a single supplier and have developed the necessary skills and suppliers to cater for this.",
			"opt": [ 'Mind, Body and Spirit packs', 'Book and Toy sets', 'Book and CD sets', 'Books with Electronics ', 'Arts and Crafts ', 'Books with Accessories ' ],
			"disc": [ 'The Crystal Healing Pack, Judy Hall. Published by Godsfield Press. Sturdy box with magnetic closure containing vac formed blister tray and lid.  Pack contains a limp bound book and 12 tumbled crystals. ',
						'Duck in the Truck, Jez Alborough. Published by HarperCollins. Boxed set comprising custom made diecast toy car, a moulded duck figure and cased picture book.',
						'Winnie the Witch six book collection, Valerie Thomas and Korky Paul. Published by Oxford University Press. Slipcase set comprising six paperback picture books and 2 cds.',
						'Lettice, The Fairy Ball, Mandy Stanley. Published by HarperCollins. Cased picture book with twinkling LED lights integrated within front case.',
						'The Knitter\'s Bible, book and craft kit.  Published by David & Charles. Pack comprises paperback book and everything needed to make two knitted bags.',
						'Geek Logik, Garth Sundem. Published by Workman Publishing New York. Cased book with calculator housed within diecut window plus blister packaging.', ],
			"img": [ 'mind', 'toy', 'cd', 'electronics', 'arts', 'accessories' ]
		},
		"games": {
			"title": "Games & Toys",
			"text": "This is an area where Imago have growing expertise and where our manufacturing and sourcing capabilities combine together to enable the efficient co-ordination of different suppliers and components.",
			"opt": [ 'Board Games', 'Jigsaw Puzzles', 'Fridge Magnets', 'Plush Toys', 'Injection Moulded Toys' ],
			"disc": [	'Cranium Books of Outrageous Fun. Published by LB Kids, an imprint of Little, Brown and Co. Series of book games which combine a wire-o bound book together with a slide out game board. Each title has different game components, including dice, modelling clay, sand timer and erasable markers.',
						'From children\'s jigsaw books to 500 piece jigsaw puzzles, we have experience in producing all sorts of jigsaws.',
						'K\u00fchl Schrank Poesie. Published by Carl Hanser Verlag. One of a series of magnetic poetry sets which are packaged in a fridge shaped box. Sheets of rubberised magnets are screen printed and diecut into strips.',
						'Ed Monkton plush toys with gift bags. Published by Really Good Company. Series of plush toy characters from the Thoughts of Edward Monkton. We are able to produce all types of plush toys custom made to match your artwork.',
						'We are able to source injection moulded figurines, from farm animals to dinosaurs.' ],
			"img": [ 'board', 'jigsaw', 'fridge', 'plush', 'injection' ]
		},
		"specialist": {
			"title": "Specialist Processes",
			"text": "Imago has access to the widest range of finishing facilities and specialist suppliers and binding materials. Here is just a small selection of the secondary processes we are able to offer.",
			"opt": [ 'Flocking', 'Sprayed edges', 'Foiled edges', 'Diecutting', 'Encapsulation'],
			"disc": ['The Goddess Guide, Gis\u00e8le Scanlon.  Published by HarperCollins  Publishers. Case bound book with flocked cover.',
						'L\'Odyssee. Published by Albin Michelle Jeunesse. Cased book with real cloth binding and pigment foil blocking and sprayed book  edges.',
						'Gift stationery range published by Judith Glover. This memo block with matt laminated case has foiled edging.',
						'The Dancing Skeletons, Posada.  Published by Tunnel Vision Books. One in a series of \'tunnel\' or \'peep show\' books which comprises a diecut concertina which is viewed through a letter box.  ',
						'21st Century Cook, Angela Nilson and Jeni Wright. Published by Cassell Illustrated. Case bound cookery book with encapsulated PVC binding with embossed and screenprinted design on case. '],
			"img": [ 'flocking', 'sprayed', 'foiled', 'diecut', 'encapsulation' ]
		},
		"product": {
			"title": "Product Sourcing",
			"text": "Imago have a dedicated team based in Hong Kong that works solely on sourcing non-book components.  Our sourcing activities  range from tracking down off the shelf items or components, to finding suppliers who can make really unusual bespoke product.",
			"opt": [ 'Electrical Devices', 'Children\'s Jewellery', 'Silicon Wristbands', 'Play Items', 'Decorative Beads', 'Crafts Equipment', 'Party Items', 'Pens & Pencils' ],
			"disc": [ 	'',
						'',
						'',
						'',
						'',
						'',
						'',
						'' ],
			"img": [ 'DSC06411', 'necklaces', 'DSC09357', 'DSC09440', 'DSC09397', 'DSC09401', 'DSC09433', 'DSC09051' ]
		},
		"stationery": {
			"title": "Stationery",
			"text": "Imago work together with many leading gift publishers, galleries and museums to produce attractive and high quality ranges of personal stationery. Unlike many suppliers, who specialise in this field, we do not operate from a catalogue of set designs but instead offer a completely flexible and bespoke production service.",
			"opt": [ 'Greetings cards', 'Wedding Albums', 'Card Sets', 'Journals with elasticated closures', 'Journals with magnetic closure', 'Wedding Scrapbook'],
			"disc": [ 	'',
						'',
						'',
						'',
						'',
						'',
						'' ],
			"img": [ 'DSC09992', 'DSC00004', 'DSC06395', 'DSC09846', 'DSC09895', 'DSC09948' ]
		},
		"packaging": {
			"title": "Packaging Styles",
			"text": "Publishers are constantly seeking new and creative ways to package their products so that they stand out from the crowd. Imago has a wealth of expertise in this area - from selecting suitable materials to use, down to the very last detail we can help you give your product the maximum impact.",
			"opt": [ 'Zipper Tins', 'Gift Bags', 'PP Sleeves with foiling', 'PP Sleeves with screen printing', 'PP Carry Cases', 'Shaped Tins', 'Printed Tins', 'Paper Boxes', 'PLC & Board Boxes', 'Injection Moulded Slipcase', 'Fluorescent  Boxes'],
			"disc": ['Suitable for packaging CDs, pencils and other items, these zipper tins can be purchased off the shelf or custom made to your chosen size.  The tins can also be printed and embossed. ',
						'Gift bag range, Flametree Publishing. We are able to produce gift bags in various styles with various finishing options for the handles - for example satin and organza style ribbons, plastic tubular handles. The range shown have been matt laminated and glue glittered. ',
						'Antiques of the Future. Lisa S. Roberts. Published by Stewart, Tabori and Chang. Cased book in printed frosted PP slipcase with thumbcuts and foil stamping.',
						'101 Series, published by Duncan Baird Publishing. Series of swatch book style recipe books which have been packaged in screen printed frosted PP sleeves.',
						'PP suitcases with pop closures and plastic strap style handles',
						'B\u00e4rig liebe Knuddel w\u00fcnsche.  Published by Verlag Herder. Bear shaped printed tin containing cards and plush toy.',
						'',
						'',
						'',
						'Zaha Hadid, published by Thames & Hudson. 2 tiered ABS slipcase with several apertures to house four separate volumes.',
						''],
			"img": [ 'DSC09097', 'DSC00006', 'DSC09066', 'DSC09060', 'DSC09980', 'DSC09831', 'DSC09978', 'DSC09976', 'DSC09833', 'DSC06292', 'DSC09902' ]
		}
	}
}
addLoadEvent( init );

/**
 * initial default text, images, etc;
 */
function init()
{
	setLang();
	setCat();
	setDescription();
	createMenu();
}

/**
 * defines the current language the user is viewing in;
 */
function setLang(){
	LANG = 'en';
}

function evalProp( prop ){
	var val = eval('(DATA.'+LANG+'.'+cat+'.'+prop+')');
	return val;
}

/**
 * sets the current section loaded on page load;
 */
function setCat()
{
	var url = window.location.toString().split("=");
	cat = url[1] || 'bookwork';
}

/**
 * create the section examples menu;
 */
function createMenu()
{
	if(!$('menu')) return false;
	var menu = $('menu');
	var imgs =  evalProp( 'img' );
	var leftArrow = document.createElement( "div" );
	var rightArrow = document.createElement( "div" );
	var div = document.createElement( "div" );
	var parent = menu.parentNode;
	div.setAttribute("id", "thumbholder");
	leftArrow.setAttribute("id", "leftarrow");
	rightArrow.setAttribute("id", "rightarrow");
	addClass( leftArrow, "menuarrow" );
	addClass( rightArrow, "menuarrow" );
	menu.appendChild( div );	
	parent.insertBefore( leftArrow, menu );
	insertAfter( rightArrow, menu );
	YAHOO.util.Event.addListener( leftArrow, "click", fireLeft );
	YAHOO.util.Event.addListener( rightArrow, "click", fireRight );
	menuCount = imgs.length;
	
	for( var i = 0; i < imgs.length; i++ )
	{
		var el = new MenuElement( imgs[i] );
		div.appendChild( el );
		
	}
}

/**
 * fired on left arrow click;
 */
function fireLeft()
{
	if( counter < menuCount - 4) 
	{
		var targetPos = parseInt(getXpos( 'thumbholder' )) - DISTANCE;
		showtime(  'thumbholder',  targetPos,  0, 5 );
		counter++;
	}
}

/**
 * return the x pos of a particular element;
 * @param	 s{String}	target element;
 */
function getXpos( s )
{
	var elem = $( s );
	if ( !elem.style.left ) 
	{
			elem.style.left = "0px";
	}
	return elem.style.left;
}

/**
* fired on right arrow click;
*/
function fireRight()
{
	if( counter > 0 ) 
	{
		var targetPos = parseInt(getXpos( 'thumbholder' )) + DISTANCE;
		showtime(  'thumbholder',  targetPos,  0, 5 );
		counter--;
	}
}

/**
 * animate the section thumbnails;
 * @param	elementID{String}	element to animate;
 * @param	final_x{Number} 	final x pos of element;
 * @param	final_y{Number} 	final y pos of element;
 * @param	interval{Number} 	time interval to animate;
 */
function showtime( elementID, final_x, final_y, interval ) 
{
	var elem = $( elementID );
	if ( elem.movement ) 
	{
		clearTimeout( elem.movement );
	}
	if ( !elem.style.left ) 
	{
		elem.style.left = "0px";
	}
	if ( !elem.style.top ) 
	{
		elem.style.top = "0px";
	}
	
	var xpos = parseInt(elem.style.left);
	var ypos = parseInt(elem.style.top);
	
	if ( xpos == final_x  &&  ypos == final_y ) {
		return true;
	}
	if (xpos < final_x) 
	{
		var dist = Math.ceil((final_x - xpos)/20);
		xpos = xpos + dist;
		
	}
	if (xpos > final_x) 
	{
		var dist = Math.ceil((xpos - final_x)/20);
		xpos = xpos - dist;
	}
	if (ypos < final_y) 
	{
		var dist = Math.ceil((final_y - ypos)/20);
		ypos = ypos + dist;
	}
	if (ypos > final_y) 
	{
		var dist = Math.ceil((ypos - final_y)/20);
		ypos = ypos - dist;
	}
	elem.style.left = xpos + "px";
	elem.style.top = ypos + "px";
	
	var repeat = "showtime('" + elementID + "'," + final_x + "," + final_y + "," + interval + ")";
	elem.movement = setTimeout( repeat, interval );
}

/**
* create the section example link;
* @param	s{String}	used to id a particular link;
*/
function MenuElement( s )
{
	var str = s;
	var link = document.createElement( "a" );
	var image = document.createElement( "img" );
	link.setAttribute( "href", "#" );
	//custom attribute to identify link;
	link.setAttribute( "name", str );
	image.setAttribute( "src", "../images/gallery/" + str + "_t.jpg" );
	YAHOO.util.Event.addListener( link, "click", loadProduct );
	link.appendChild( image );	
	return link;
}

/**
 * triggers the loading of both product image and text;
 */
function loadProduct(){
	loadProductImage( this.name );
	loadProductText( this.name );
	
}

/**
 * loads the indevidual product image;
 * @param	str{String}	name used to tie the link to the image;
 */
function loadProductImage( str ){
	if(!$('product')) return false;
	var prod = $('product');
	var images = evalProp( 'img' );;
	var div = null;	//ref to image holder;
	var img = null;	//ref to image;
	var url = null;	//ref to image url;
	
	if( hasClass( prod, "showinstruction" ) ){
		replaceClass( prod, "showinstruction", "hideinstruction" );
	}
	if( prod.hasChildNodes() ){
		var nodes = prod.childNodes;
		for( var i = 0; i < nodes.length; i++ ){
			if( nodes[i].nodeType == 1 && 
				nodes[i].getAttribute("id") == "image" ){
				div = nodes[i];
				img = div.firstChild;
			}
		}
	}
	if ( !div ){
		div = document.createElement( "div" );
		div.setAttribute( "id", "image" );
		img = document.createElement( "img" );
	}
	for( i = 0; i < images.length; i++ ){
		if( images[i] == str ){
			url = "../images/gallery/" + str + ".jpg";
		}
	}
	img.setAttribute( "src", url );
	prod.appendChild( div );	
	div.appendChild( img );	
}

/**
 * loads the indevidual product text;
 * @param	str{String}	name used to tie the link to the text;
 */
function loadProductText( str ){
	if(!$('image')) return false;
	var img = $('image');
	var titles = evalProp( 'opt' );
	var images = evalProp( 'img' );
	var discs = evalProp( 'disc' );
	var text = null;	//ref to gallery text holder;
	var header = null;	//ref to product Description h tag;
	var title = null;	//ref to product Description header text;
	var para = null;	//ref to product Description p tag;
	var disc = null;	//ref to product Description para text;
	var title_txt = null;
	var disc_txt = null;
	
	for( var i = 0; i < images.length; i++ ){
		if( images[i] == str ){
			title_txt = titles[i];
			disc_txt  = discs[i];
		}
	}
	
	if( $('text') ){
		text = $('text');
		header = text.firstChild;
		para = text.lastChild;
		header.firstChild.nodeValue = title_txt;
		para.firstChild.nodeValue = disc_txt;
	} else {
		text = document.createElement( "div" );
		header = document.createElement( "h2" );
		para = document.createElement( "p" );
		text.setAttribute( "id", "text" );
		insertAfter( text, img );
		title = document.createTextNode( title_txt );
		disc = document.createTextNode( disc_txt );
		header.appendChild( title );
		para.appendChild( disc );
		text.appendChild( header );
		insertAfter( para, header );
	}
}

/**
 * set the sidebar elements;
 */
function setDescription(){
	if( !$('sidebar') ) return false;
	var sidebar = $('sidebar');
	var remove = new NodeHandler();
	var p = sidebar.getElementsByTagName( "p" );
	var h = sidebar.getElementsByTagName( "h2" );
	remove.removeNodes( h, sidebar );
	remove.removeNodes( p, sidebar );
	var title = document.createElement( "h2" );
	var title_text = document.createTextNode( evalProp( 'title' ) );
	var image = document.createElement( "img" );
	var url;
	var arr = evalProp( 'img' );
	var url = "../images/gallery/" + arr[0] + "_s.jpg";
	image.setAttribute( "src", url );
	title.appendChild( title_text );	
	sidebar.appendChild( title );	
	var para = document.createElement( "p" );
	var text = document.createTextNode( evalProp( 'text' ) );
	para.appendChild( text );	
	insertAfter( image, title );
	insertAfter( para, image );
}

/**
 * used in removing the default text from the gallery;
 */
function NodeHandler(){}

NodeHandler.prototype.removeNodes = function( nodes, parent )
{
	for( var i = 0; i < nodes.length; i++ )
	{
		parent.removeChild( nodes[i] );
	}
}