/*  jQuery functions for ARTIST pages  */

$(document).ready(function(){
	var numberItems = $('#thumbList li').size(); // count how many prints (navigation only shown if more than one)

	if ( numberItems>1 ) {
		// remove outer margins of thumbnails
		// check width of #thumbList image navigation (#pageNav is more flexible outside of #thumbList)
		var centralWidth = $('#central').width();
		var thumListWidth = $('ul#thumbList').width(); // this may be already set, or implied from contents
		$('#thumbList li:first').css({marginLeft:0});
		$('#thumbList li:last').css({marginRight:0});
		// then reduce width of thumblist as per CSS margins just removed
		thumListWidth -= 8; // only do this on page load
		$('#thumbList').css({width:thumListWidth}); // now is definitely set
	} else {
		// only one item, reposition facebook icon 
		$('#facebook_link').css({margin:0, padding:0});
	};
	
	
	$('body').append( // scrolling arrows - absolute positioned (exact positioning in optiScreen function below) 
		 '<span id="ar1_l" class="arr scroll_l" title="previous item"></span>'
		+'<span id="ar1_r" class="arr scroll_r" title="next item"></span>'
		+'<span id="ar2_l" class="arr scroll_l" title="previous item"></span>'
		+'<span id="ar2_r" class="arr scroll_r" title="next item"></span>');
	// positioning variables
	var arrowHeight = 30;	// corresponds to CSS setting / span size
							// never mind height... I want to make them same height as images - easier to place anyway
	var arrowWidth = 5 	;	// (these are half size for adjustments)
	var arrowMargin = 8;
		
	// preload image so that dimensions will be available and many calculations can be 
	// done BEFORE attempting to show the image
	$('#thumbList li').mouseover(function() {
		getImgAttr($(this).attr('id').replace('item_',''));
	});
	
	function getImgAttr(thisItem){
		// performed on mouseover OR when loading image
		var theURL = $('#thumbList li#item_'+thisItem+' a').attr('href');
		// the URL is a real page link so that it will work without jQuery
		// we must calculate URL of image instead
		var imgID = theURL.replace(/.*\/(\d+)$/,'$1');
		 // cache image
		if ( $('#img_'+imgID).length<1 ) { //  IF NOT ALREADY DONE
			var imgURL = rootUrl + 'stockimages/' + imgID + '.jpg';
			// PRELOAD
			$('body').append('<img src="'+imgURL+'" id="img_'+imgID+'" style="display:none" />').show(function(){
				// image now available to get dimensions ...I HOPE
				// no, it's not good enough, BUT easy to get PHP to include that info as JSON
				// And now we just add the URL while we're at it
			// var thisItem = aObject.parent().attr('id'); // php numbers each item (though could use index())
				items[thisItem]['u'] = imgURL;	// store dimensions in object so it is always available 
											// using Array notation can accept unknown variable [thisItem]
			}); 
		};
	};


	/* GALLERY thumbnail click */
	$('#thumbList li a').click(function(evt) {
		putImage( $(this).parent().attr('id').replace('item_','') ); 
		evt.preventDefault(); // don't open link 
	});

	// on page load, put first image and text in position
	// Now PHP loads the right one anyway, but this should resize it nicely 
	// putImage includes resizing (optiscreen) but replaces everything
	if ( $('#central').text().length<3 ) { // not to run if showing biog or exhib page directly
		putImage( $('#pageNav li.showing').attr('id').replace('item_','') ); // initially use image chosen by PHP
	} else {
		$('#print_detail').css({height: $('#central').height()+10 });
		$('#facebook_link').css({margin:'-70px 0 0 5px'});
	}

	$(window).resize(function() { // THINGS TO RUN ON RESIZE
		var currentPrint = $('#thumbList li.currentItem').attr('id').replace('item_','');
		optiScreen(currentPrint);
	});
	


	function putImage (thItem) {	/* Put in position the image (& text) referenced by thObject */
		// reset #central in case previous content was set by biography etc. width as per CSS
		$('#central').html('').css({height:'auto', width:'68%', overflow:'auto'});
		getImgAttr(thItem); 
		$('#thumbList li').each(function() {  // reset currentItem & reset thumbnail borders
			$(this).removeClass('currentItem');
			$(this).find('img').css({borderColor: '#CCC'});
		});
		// then highlight THIS thumbnail
		$('#thumbList li#item_'+thItem+' img').css({borderColor: '#666'});
		$('#thumbList li#item_'+thItem).addClass('currentItem');


		// get relevant TEXT for this item 
		var printBlurb = '';
		if ( $('#thumbList li#item_'+thItem+' .prText').length>0 ) {
			printBlurb = $('#thumbList li#item_'+thItem+' .prText').html();	// get content of prText
			printBlurb = 										// and tidy it a bit 
				printBlurb.replace(/\n/g, "").replace(/<br \/><br \/>/gi, "<br />").replace(/<br \/>$/gi, "");	
		};

		//  replace content  (empty first so that box resets properly)
		$('#image_info').html('').show(function() {
			$('#image_info').html(printBlurb).show(function() {
				// then put image in place
				// ...it has already been preloaded on mouseover
				var imgURL = items[thItem].u;

				// put image in Box
				$('#central').html('<img src="'+imgURL+'" id="imgDisplay" style="display:none" />').show(function() {
					// show() not needed but can add callback to ensure calculations happen after image load
					optiScreen(thItem);
					// show the image
					$('#imgDisplay').fadeIn('slow');
				});


				// set url location
				// ... probably not possible except using the #hash part = a major rework
				//  ... or check out jQuery history plugin??
				
			});
		});
	};

		

	function optiScreen (thItem) {
		/* Every time the window is resized (& on load & click thumbnail)
		   This function checks various sizes/positions to keep all visible */
		
		// first set height of #print_detail to allow #pageNav and margin underneath. 
		var pdMargin = 10; // top and bottom margin for print_detail
		var navHite = ( numberItems>1  ?  $('#pageNav').height()  :  40 ); // still some empty space when pageNav hid
		var pdHeight = winHite-contTop-navHite-bottomMargin-pdMargin;
		$('#print_detail').css({height: pdHeight, margin: pdMargin+'px 0'});		

		if ( $('#imgDisplay').length>0 ) { // IF there is an image showing...
			// Make sure image_info doesn't get out of print_detail box.
			// Get height of artist name and #listPages
			var infoTopHite = $('#info>h2').height() + $('#info>h3').height()
			 				+ $('#info>h4').height() + $('#info>h5 ').height()
			 				+ $('#listPages').height();
			// set space before image_info
			var infoSpace = 20;
			// remaining space is max for image_info (and a bit of margin)
			var infoHite = pdHeight-infoTopHite-infoSpace-10;
			var infoWide = $('#info').width();// - centralWidth - 20;
			// alert('contentwidth:'+$('#content').width()+' - centralWidth:'+centralWidth+' = infoWide:'+infoWide);
			$('#image_info').css( {marginTop:infoSpace, height:infoHite, width:infoWide, overflow:'auto'} )
			.show(function() {
					// add scrollbars *after* everything else
					$('#image_info').jScrollPane({showArrows:true});
					// this needs to be in optiScreen() so it is redrawn on resizing window etc.
					//  as well as when loading new image.
					// Runs OK on page load and on resize. But it seems to disappear when loading new image.
					// whereas the horizontal one on #pageNav seems to be OK all the time ...WTF?
				});
		
		
			// KEEP IMAGES IN PROPORTION and in their allotted space
		
			var imgShape = items[thItem].w / items[thItem].h; // greater than 1 means landscape, less means portrait
			// alert(thItem+' - '+imgShape);
			// this gets it wrong on Resize, but not otherwise 
			// Gets thItem whatever was loaded first!!

			var imgDispHite = pdHeight-(pdMargin*2); 
			var imgDispWide = $('#central').width()-(pdMargin*2);

			var boxHite = $('#print_detail').height();
			var	boxWide = $('#central').width();
			var boxShape =  boxWide / boxHite;
		
			if ( imgShape <1 ) { // portrait image (square is considered landscape)
				if ( boxShape >1 ) { // in wide space, use full height
					$('#imgDisplay').attr({height: boxHite}).removeAttr('width');
					var newWidth = imgShape * boxHite; // nav arrows need to know this
				} else { 				// in tall space, use available width plus extra height
					var newHite = boxWide * Math.sqrt(imgShape);
					if ( newHite >boxHite ) { newHite = boxHite; };
					$('#imgDisplay').attr({height: newHite}).removeAttr('width');
					var newWidth = imgShape * newHite; // nav arrows need to know this
				};
			} else { 			// landscape image
				if ( boxShape <1 ) { // in tall space
					$('#imgDisplay').attr({width: boxWide}).removeAttr('height');
					var newWidth = boxWide; // nav arrows need to know this
				} else { 				// in wide space, room to grow
					// need to ensure this doesn't make height too big eg. for nearly-square image
					// all of which means we really 
					// need to use MATHS to use SHAPE to determine expansion possibilities
					// Don't want to add something, need a multiplier which is ONE when image is square
					// rather like imgShape   ... square root?    pow() is more adjustable
					// Very wide images may still get too wide - this is fairly rare though so a bodge will do!
					var inc = Math.pow(imgShape, 0.5);
					var newWidth = boxHite*inc;
					if ( newWidth >boxWide ) { 	// TOO wide happens occasionally
						newWidth = boxWide; 	// so artificially restrict it ... still room for improvement
					};
					$('#imgDisplay').attr({width: newWidth}).removeAttr('height');
			// alert('boxWide:'+boxWide+',  boxHite:'+boxHite+',  boxShape:'+boxShape+',  imgShape:'+imgShape+', img width:'+boxHite+', inc:'+inc+', new width:'+(boxHite*inc));
				};			
			};
		};

		if ( numberItems>1 ) {
			// check available space for #thumbList (image navigation)
			// and position scroll-arrows
			// if less than #central it must float right (else scrolls within #pageNav)
			if ( thumListWidth<centralWidth ) { 
				$('#thumbList').css({float:'right'}); 
				var pn_left = $('#thumbList').offset().left;
				var pn_wide = $('#thumbList').width();
			} else {
				$('#thumbList').css({float:'left'});
				var pn_left = $('#pageNav').offset().left;
				var pn_wide = $('#pageNav').width();
			};
			
			// scroll-arrow positioning, _after_ loaded image
			// first arrows on navigation
			var ar1_left = Math.floor(pn_left - (arrowMargin*2) - arrowWidth);
			var ar1_right = Math.floor(pn_left + pn_wide + arrowMargin + arrowWidth); // some xtra arrowWidth??!!
			// var ar1_top = $('#pageNav').offset().top + ($('#thumbList img:first').height() / 2) - arrowHeight;
			var ar1_top = $('#pageNav').offset().top;
			// arrows same height as thumbnails 
			var thumHite = $('#thumbList li:first').height();
			$('#ar1_l').css({height:thumHite, top:ar1_top, left:ar1_left, display:'block'})
				.unbind('click').click(function() {
				// need to unbind first else it will eventually have loads of click events firing
				goPrev(thItem);
			});
			$('#ar1_r').css({height:thumHite, top:ar1_top, left:ar1_right, display:'block'})
				.unbind('click').click(function() {
				goNext(thItem);
			});
			if ( $('#imgDisplay').length>0 ) { // arrows on image IF there is one (not for biog etc.)
				var imageRight = $('#print_detail').offset().left + $('#print_detail').width();
				var ar2_left = imageRight - newWidth - arrowMargin - arrowWidth -10; // 10px padding
				// alert(imageRight+' - '+items[thItem].w+' - '+arrowMargin+' - '+arrowWidth);
				// alert(items[thItem].w); // original width!! needs adjustment
				var ar2_right = ar1_right; // these at least are the same :-)
				// var ar2_top = $('#print_detail').offset().top + ($('#print_detail').height() / 2) - arrowHeight - arrowMargin; // old-style short arrows
				// arrows are same height as image (plus bit for margins etc.)
				var ar2_top = $('#print_detail').offset().top + arrowMargin;
				$('#ar2_l').css({height:boxHite+arrowMargin, top:ar2_top, left:ar2_left, display:'block'})
					.unbind('click').click(function() {
					goPrev(thItem);				
				});
				$('#ar2_r').css({height:boxHite+arrowMargin, top:ar2_top, left:ar2_right, display:'block'})
					.unbind('click').click(function() {
					goNext(thItem);
				});
			} else {
				// no image = biog or exhib = reset #central 
				resetCentral ();
			};
			

			// add fancy scrollbars for thumbnail list
			$('#pageNav').jScrollPane({showArrows:true, animateTo:true, animateInterval:400, animateStep:5});
			var api = $('#pageNav').data('jsp'); // allows use of some hidden methods in jScrollPane
										// such as scrollToElement
										// TEST scrollTo plugin
			function goPrev (thisItem) { // choose previous item number, with wrapping to last from start
				var prevItem = (thisItem>0 ? (thisItem-1) : (numberItems-1));
				putImage(prevItem);
				// also need to scroll #thumbList
				var target = $('#thumbList').find('li#item_'+prevItem);
				// $('#pageNav div.jspContainer').scrollTo(target, 500, {axis:'x'});
				api.scrollToElement(target);

				 // <a> link or form fields can be focused BUT it sorely messes up jScrollPane.
				// scrollTo plugin works on jspContainer but also scrolls jspHozizontalBar :-(
				// doesn't work on jspPane for some reason
				//  scrollTo plugin is a pain - there is some function of jScrollPane with same name, maybe confusing
				// and only scrolls by set amounts of pixel ... which I guess could be calculated 
				// but also need to check if item is visible or not.............
			};
			function goNext (thisItem) { // choose next item number, with wrapping to start from last
				// thisItem = thisItem-0; // type as number
				var nextItem = (thisItem<(numberItems-1) ? (thisItem-0+1) : 0);
				putImage(nextItem);
				// also need to scroll #thumbList
				var target = $('#thumbList').find('li#item_'+nextItem);
				// $('#pageNav div.jspContainer').scrollTo(target, 500, {axis:'x'});
				api.scrollToElement(target);
			};
		};
	
		
	}; // END optiScreen
	





/************* click page links ********************************************/	

	// on proper artist page, links are hijacked to prevent reloading the page...
	// But if showing standalone exhibition or biography pages, then use real link.

	function resetCentral () { // when showing biog or exhib (also called from optiScreen)
		$('#image_info, #ar2_l, #ar2_r').hide();
		var centralHite = $('#print_detail').height();
		$('#central').css({height:centralHite, overflow:'auto'}).jScrollPane({showArrows:true});
	};
	
	$('#exib_show a').click(function(e) { // replace #central content with (hidden) exhibition text
		var exib_text = $('#exib_hide').html();
		if ( exib_text.length ) {
			$('#central').html(exib_text);
			resetCentral ();
			e.preventDefault();
		}; // if there was no hidden text, follow link instead
	});
		
	$('#biog_show a').click(function(e) { // replace #central content with (hidden) biography text
		var biog_text = $('#biog_hide').html();
		if ( biog_text.length ) {
			$('#central').html(biog_text);
			resetCentral ();
			e.preventDefault();
		}; // if there was no hidden text, follow link instead
	});
		
	$('#work_show a').click(function(e) {
		if ( $('#image_info').length ) {
			// replace #central content with first image
			$('#image_info').show();
			if ( numberItems>1 ) { $('#ar2_l, #ar2_r').show() };
			// put back first image (it's still possible to click any thumbnail instead of this)
			putImage( $('#pageNav li.currentItem').attr('id').replace('item_','') );
			// putImage breaks here (though not obviously) so link is followed
			e.preventDefault();
		}; // if there was no image info, follow link instead
	});
	
	

});

