// WebShow V2.1 Dec09:  Now runs the show in a fixed div in the main browser window.
// V2.1: Changed so each picture goes in own cell. Minor style tweaks. Caption function added.

function Caption(n) {  // Return caption of Picture n without initial number
	return p[n].n.substr((p[n].n.indexOf(' ')+1)); 
}

// GenThumbs 20/12/09. Create <a> tags for thumbnails.
// cols=0: original style (no table). cols=1+ columns, centred, with caption underneath.
// Dec09 - each picture now goes in its own table cell
function GenThumbs(cols) {   
 if (cols==0) {
  for (var i=0; i<p.length; i++) {
   document.write('<a href="javascript:ShowPhoto('+i+');"><img src="thumbs/'+p[i].n+'.jpg" width="'
      +p[i].tw+'" height="'+p[i].th+'" title="'+p[i].n+'"></a>&nbsp;');
  }
 } else {
  w = (MaxTW+10)*cols;  // Table width
  n = Math.ceil(p.length/cols);  // No rows (images in each column)
  document.write('<table width="'+w+'" border="0" align="center"><tr><td class=ta>'); // start table + col 1
	var i;   // Variable for image number. First image is 0.
	for (var r=0; r<n; r++) {  // For n rows
	  document.write('<tr>');
		for (var c=0; c<cols; c++) { // and cols columns
			document.write('<td class=ta>');  // Start the cell
			i = r*cols+c;  // Image no for this cell
			if (i<p.length) {
				document.write('<a href="javascript:ShowPhoto('+i+');"><img src="thumbs/'+p[i].n+'.jpg" width="'
				+p[i].tw+'" height="'+p[i].th+'" title="'+p[i].n+'"></a><br>'+Caption(i)+'<br>');
				} else {document.write('&nbsp;');}   // No more pictures - filee cell
			document.write('</td>');  // end of cell
		}	
		document.write('</tr>'); // end of row
	}	
	document.write('</table><br />'); // Finished
 }  
} //--end GenThumbs--//

// Function to set opacity - browser independent.  Pass opacity as percentage. 0 - clear. 
function SetOpacity(object,opacityPct) {
	object.style.opacity = opacityPct/100;  // CSS3 compliant - most modern browsers
	object.style.filter = 'alpha(opacity='+opacityPct+')'; // IE.
	object.style.MozOpacity = opacityPct/100;  // Old mozilla and firefox
}

// Change opacity of an element (defined by id) over time. Uses SetOpacity.
// msStart - time we start the fade (in mS)
// msDuration - duration of the fade in ms.
// fromO: Initial Opacity  toO: Final opacity.
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
  // alert("Reach ChangeOpacity. FromO="+fromO+"  ToO="+toO ); 
	var element=document.getElementById(id);
	var msNow = (new Date()).getTime();
	var opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
	if (((fromO<toO) && (opacity>=toO)) || ((fromO>toO) && (opacity<=toO)))  // Reached target opacity?
	   { SetOpacity(element,toO); element.timer = undefined; }
	else {SetOpacity(element,opacity);
	  element.timer=window.setTimeout("ChangeOpacity('"+id+"',"+msDuration+","+msStart+","+fromO+","+toO+")",10);	}
}


// Next two functions allow me to find the scroll bar position when we hide the wrapper div.
// See documentation. 
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
	
	
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


// Function to cross fade between two image divs
// id1 - current imagediv (opacity 100).  id2 - new image div (opacity 0)  
// msStart - time fade commenced (mS)
// msDuration - duration of fade
function Crossfade(id1,id2,msStart,msDuration)
{ var el1 = document.getElementById(id1);
	var el2 = document.getElementById(id2);
	var msNow = (new Date()).getTime();
	var opacity1 = 100*(1-(msNow-msStart)/msDuration);  // Opacity of el1 - reducing
	var opacity2 = 100*(msNow-msStart)/msDuration;      // Opacity of el2 - increasing
	if (opacity2>=100)  // New imagediv fully isible? 
	{	SetOpacity(el1,0);  // Final opacity
	  SetOpacity(el2,100);
		// Finally change old image to "null" (1 pixel black) - stop it showing on slow links
		if (CurImg==1) {var OldImgEl = document.getElementById('img2');  }
		else { var OldImgEl = document.getElementById('img1'); }
	  OldImgEl.src = 'images/null.gif'; // Clear old image
		el1.timer = undefined;
	}
	else 
	{	SetOpacity(el1,opacity1);
		SetOpacity(el2,opacity2);
		// Reset timer to display next frame
		el1.timer = window.setTimeout("Crossfade('"+id1+"','"+id2+"',"+msStart+","+msDuration+")",15);
	}
}


// Function to get viewport size.  Browser independent. Sets global vars.
function GetViewPort() {
	vpH = window.innerHeight;
	if (!vpH)
	{
		if (document.documentElement && document.documentElement.clientWidth) 
		{ vpH = document.documentElement.clientHeight; } 
		else if (document.body.clientWidth) {vpH = document.body.clientHeight; }
	}
	vpW = window.innerWidth;
	if (!vpW)
	{
		if (document.documentElement && document.documentElement.clientHeight) 
		{ vpW = document.documentElement.clientWidth; } 
		else if (document.body.clientHeight) {vpW = document.body.clientWidth; }
	}
}


// Set show interval Invoked if value changed
function SetDelay() {   
 Delay = 1000*document.setdelay.delay.value;  // Set new delay time
} 

// Alter crossfade duration - user can chooose the effect they like best
function ChangeFade() { 
 Fade = document.setdelay.changefade.value;  // Set fade time in mS (0=no crossfade)
} 
 
// ShowPhoto (5/12/09) Display selected picture in Picture Window (occupies entire viewport)
// This function can only run by clicking one of the thumbnails.
function ShowPhoto(j) {
 scrollhor = f_scrollLeft(); // Remember horiz + vert. scroll bar positions
 scrollver = f_scrollTop(); 
 var imgdiv2 = document.getElementById('imgdiv2');  // Hide second image
 SetOpacity(imgdiv2,0);
 var wrapdiv = document.getElementById('wrapper');  // Hide wrapper (+ all child divs) 
 wrapdiv.style.display="none";
 N = j;       // Save cur. photo in global var
 CurImg = 1;  // Always use the first image when we open
 if (N<0)   // If parameter is negative, start slideshow 
 { N=0;     // .. so set timer to change to image 2
   timerID = setTimeout("RunShow()",Delay); 
 }
 
 GetViewPort();    // Browser independent; set vpW and vpH 
 var picwin = document.getElementById('picdiv');   // Picture Div
 picwin.style.display="block";     // Display the picture division and all child divs.
 picwin.style.width = vpW+'px';    // PicDiv occupies entire window
 picwin.style.height = vpH+'px';   
 // Now work out the image parameters to centre the image
 var left = (vpW-p[N].w-10)/2; // Centre picture div
 var top = (vpH-p[N].h)/2;
 if (left<0) { left=0;}
 if (top<0) { top=0;}  

 var imgdiv = document.getElementById('imgdiv1');  // Image div - always the first
 imgdiv.style.width = p[N].w+'px';
 imgdiv.style.height = (p[N].h+20)+'px';   // Img div height (+20 for caption)
 imgdiv.style.top = top+'px';  
 imgdiv.style.left = left+'px'; 
 imgEl=document.getElementById('img1');
 imgEl.src = 'images/'+p[N].n+'.jpg';       // Changle img source file
 // Now create caption - this method works in IE
 var x=document.getElementById('cap1').createCaption(); // Get table element in first image div
 x.innerHTML=Caption(N);          // set caption   
 imgEl.style.width = p[N].w+'px'; // This reserves space for picture while downloading
 imgEl.style.height = p[N].h+'px';
 SetOpacity(imgdiv,100);        // In case it was left at 0.    

 if (FirstTime==0) // Show instructions (in msgdiv) if first time through
 {
	 FirstTime=1;
	 var msgbox = document.getElementById('msgdiv');  // Message Box
   msgbox.style.left = ((vpW-340)/2)+'px'; 
	 msgbox.style.top = ((vpH-34)/2)+'px'; 
   var StartFadeIn = (new Date()).getTime();    // Time to start fade-in
   ChangeOpacity('msgdiv',300,StartFadeIn,0,70);  // Fade the message in
   timer2 = window.setTimeout("FadeMessage()",1500); // Set timer to fade out.
 }
 CachePhoto(N+1);   // Cache next photo.
} // end ShowPhoto

// FadeMessage 11/12/09. Fade out the Message Box
function FadeMessage() {  
  var StartFade = (new Date()).getTime();    // Time we start the cross-fade
  ChangeOpacity('msgdiv',2000,StartFade,70,0);  // Fade out
}


// ShowPic. 7/12/09. Update the Picwin DIV with new picture N.
function SwapPics() {  // Swap pictures
	if (CurImg==1)  // Get divs contining images, and new image element
	{	var oldimgdiv = document.getElementById('imgdiv1');
	  var newimgdiv = document.getElementById('imgdiv2');
	  var imgEl = document.getElementById('img2');  // imgEl - new image
    var capEl=document.getElementById('cap2'); // Table containing new caption
    CurImg=2;		
	} else 
	{ var oldimgdiv = document.getElementById('imgdiv2');
		var newimgdiv = document.getElementById('imgdiv1');
		var imgEl = document.getElementById('img1');
		var capEl=document.getElementById('cap1'); // Table containing new caption
		CurImg=1;
	}
	imgEl.src = 'images/'+p[N].n+'.jpg'; // Set new image source
  imgEl.style.width = p[N].w+'px';     // Reserve space for picture
  imgEl.style.height = p[N].h+'px';
	// Work out parameters to centre image
  var left = (vpW-p[N].w-12)/2; 
	var top = (vpH-p[N].h)/2;
	if (left<1) { left=0;}
	if (top<1) { top=0;}  
	newimgdiv.style.width = p[N].w+'px';
  newimgdiv.style.height = (p[N].h+20)+'px'; // Set div width + height (height+20 for caption)
  newimgdiv.style.top = top+'px';  
  newimgdiv.style.left = left+'px'; 
  capEl.caption.innerHTML = Caption(N);  // Set caption 
	if (Fade<=0) { // No cross fade
		SetOpacity(oldimgdiv,0);    // Darken old image
		SetOpacity(newimgdiv,100);  // .. and show new image
	 }
	 else {
		var startMS = (new Date()).getTime();    // start time for cross-fade
		Crossfade(oldimgdiv.id,newimgdiv.id,startMS,Fade);  // Initial fade duration=300mS	
	}
}


// Resize (7/12/09) Resize the Picwin div, and re-centre picture (if visible) 
function ResizePicWin() {
 var picwin=document.getElementById('picdiv'); // Get the picture division
 if (picwin.style.display == "block")  // Only proceed if picture window is visible
 {
		GetViewPort();
		picwin.style.width = vpW+'px';
		picwin.style.height = vpH+'px';        // Set width to available width 
		var left = (vpW-p[N].w-10)/2; // Centre picture div
		var top = (vpH-p[N].h)/2;
		if (left<1) { left=0;}
		if (top<1) { top=0;}  
		if (CurImg==1)  // Which div is currently displayed? 
		     { var imgdiv = document.getElementById('imgdiv1'); } 
		else { var imgdiv = document.getElementById('imgdiv2'); }
		imgdiv.style.top = top+'px';  
		imgdiv.style.left = left+'px'; 
	}
}


// BB NxtPhoto Function. 7/12/09. Show next photo (first picture is 0).
function NxtPhoto() {  
 N++;                // Increment picture number
 if (N==p.length) {N=0;} // Reached max? If so reset to 0
 SwapPics();         // Show current picture
 CachePhoto(N+1);   // cache next photo if necessary
} // end function


// BB PrvPhoto Function. 7/12/09. Show previous photo.
function PrvPhoto() {  
 N--;
 if (N<0) N=p.length-1;  	
 SwapPics();    
} // end function 


// RunShow Function. 7/12/09. Run slideshow.
function RunShow() {  
  N++;                     // Increment picture number
  if (N==p.length) {N=0;}  // Reached max? If so reset to 0.
  SwapPics();              // Swap pictures over
  timerID = setTimeout('RunShow()',Delay);  // Invoke function after specified delay
  CachePhoto(N+1);   // Load next photo into cache if necessary
}


// Pause show (user clicked button)
function StopShow() { 
 clearTimeout(timerID); 
}

// Close Picture Window (and stop show if necessary)
function ClosePic() { 
 var picwin=document.getElementById('picdiv'); // Get the picture division
 picwin.style.display="none"; 
 var wrapdiv = document.getElementById('wrapper');  // Display wrapper again  
 wrapdiv.style.display="block"; 
 clearTimeout(timerID);
 window.scrollTo(scrollhor,scrollver);  
}


// We can also close the picture window by hitting Escape.
function keycheck(event) 
{ 
		if (event.keyCode==27) ClosePic();
		if (event.keyCode==39) NxtPhoto();  // --> (Right)
		if (event.keyCode==37) PrvPhoto();  // <-- (Left)	
}


// Load jpg into cache.
function CachePhoto(i) {  // Load specified photo into the cache.
  if (i<p.length) {  // only if within array bounds
    if (!pCache[i]) {  // Only if not done already ie if undefined.
      pCache[i] = new Image(p[i].w,p[i].h);
      pCache[i].src = 'images/'+p[i].n+'.jpg';
    }
  }
}


// ShowVer 2.0 7/12/09  Print Ver & date last modified.
function ShowVer() {
   tdate = new Date(document.lastModified);
   document.write('Last updated '+tdate.toLocaleDateString()+'. &nbsp;Webshow '+Ver+' &copy; Erw Wen Software');
}