// -----------------------------------------------------------------------------------
//
// This page has been modified from code written by Scott Upton
// http://www.uptonic.com | http://www.couloir.org
//
// This work is licensed under a Creative Commons License
// Attribution-ShareAlike 2.0
// http://creativecommons.org/licenses/by-sa/2.0/
// 
// modifications were made for specific design and implementation by MDSC staff
// http://mdsc.com
//
// Associated APIs copyright their respective owners
//
// -----------------------------------------------------------------------------------
// --- version date: 11/28/05 --------------------------------------------------------


/*--------------------------------------------------------------------------*/
//Extend Element to change content
Object.extend(Element, {
	getWidth: function(element) {
   		element = $(element);
   		return element.offsetWidth;
	},
	getHeight: function(element) {
   		element = $(element);
   		return element.offsetHeight;
	},
	setWidth: function(element,w) {
		element = $(element);
		element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
		element.style.height = h +"px";
	},
	setSrc: function(element,src) {
		element = $(element);
		element.src = src;
	},
	setHref: function(element,href) {
		element = $(element);
		element.href = href;
	},
	setTitle: function(element,href) {
		element = $(element);
		element.title = href;
	},
	setAlt: function(element,href) {
		element = $(element);
		element.alt = href;
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

/*--------------------------------------------------------------------------*/
//Slideshow has three parameters:
//1 - the Photos array = the array containing information about the photos to show
//2 - the starting array counter or starting photo to show
//3 - the duration in milliseconds of the slide show pause
//
//The Photos array needs to be defined like:
//var photoArray = new Array(
//		// Source, Width, Height, Caption, Link
//		new Array("full/photo/directory.gif", 
//				  photo size new Array(width, height)
//                "Byway Name", 
//				  "Copyright etc", 
//				  "link for image",
//				  "image to show as pin",
//				  "pin x/y size as an array(x,y)",
//				  "pin center offset left top size as an array(left,top)",
//				  "array of coordinates for the pins"
//				 );
// Add window.onload event to initialize the slideshow in the HTML page code
//Behaviour.addLoadEvent(init);
//Behaviour.apply();
//function init() {
//	mySlideShow = new Slideshow(Array,0,10000);
//	mySlideShow.initSwap();
// 
// future revisions could include a call back function for moving the pin around
//  in stead of had coding all of that here
//}
var Slideshow = Class.create();

Slideshow.prototype = {
	initialize: function(photos, id, slideTime) {
		this.photoArray = photos;
		this.photoCount = this.photoArray.length;  // Number of photos in this gallery
		this.photoNum = (!id || id<0 || id>this.photoCount) ? 0 : id; //array counter for the current photo
		this.slideTime = (!slideTime) ? 10000 : slideTime;
		this.slideTimer = null;
		this.paused = false;
		this.photoBox = 'SlideContainer';
		this.photo = 'Photo';
		this.photoContainer = 'PhotoContainer'; //have to have the photo in a div so that ie6 does the opacity correctly
		this.photoLink = 'PhotoLink';
		this.captionBox = 'CaptionContainer';
		this.caption = 'Caption';
		this.counter = 'Counter';
		this.prevLink = 'PrevLink';
		this.nextLink = 'NextLink';
		this.pauseLink = 'PauseLink';
		this.loader = 'Loading';
		this.contextMap = 'pins';
		this.imageMaxWidth = Element.getWidth(this.photoBox)-2;
		this.imageMaxHeight = Element.getHeight(this.photoBox)-2;
		Element.setOpacity(this.pauseLink,'.5');
		//Turn off the hide class on the pause and loader
		$(this.pauseLink).style.display = "inline";
		$(this.loader).style.display = "inline";
		
		//assume the foto has already loaded etc - don't fade it out then back in, just set the timer
		new Effect.Fade(this.loader, {duration: 0.5});
		clearTimeout(this.slideTimer);
		this.slideTimer = setTimeout("mySlideShow.nextPhoto()",this.slideTime);
		//set up the pin
		this.setContextPin();
	},
	setNewPhotoParams: function() {
		// Set source of new image
		this.setPhotoSize();
		Element.setSrc(this.photo,this.photoArray[this.photoNum][0]);
		Element.setHref(this.photoLink,this.photoArray[this.photoNum][4]);
		Element.setTitle(this.photoLink,this.photoArray[this.photoNum][2]);
		Element.setAlt(this.photo,this.photoArray[this.photoNum][2]);
		
		// Set prev and next links.  really these don't do aything but it sets the text for where the link goes
		var prev = (this.photoNum <= 0) ? this.photoCount : (this.photoNum);
		var next = (this.photoNum+1 >= this.photoCount) ? 1 : (this.photoNum+2);
		Element.setHref(this.prevLink, "/?i=" + prev);
		Element.setHref(this.nextLink, "/?i=" + next);
	},
	setPhotoCaption: function() {
		// Add caption from gallery array
		var bywayname = this.photoArray[this.photoNum][2];
		var copyright = this.photoArray[this.photoNum][3];
		var bywaylink = this.photoArray[this.photoNum][4];
		var caption = '<p><a href="' + bywaylink + '">' + bywayname + '</a><br /><span id="CopyRight">' + copyright + '</span></p>';
		Element.setInnerHTML(this.caption,caption);
		Element.setInnerHTML(this.counter,((this.photoNum+1)+'/'+this.photoCount));
	},
	setPhotoSize: function() {
		var width = this.photoArray[this.photoNum][1][0];
		var height = this.photoArray[this.photoNum][1][1];
		if(!width || !height) { return; }
		var scaleRatio = 1;
		if(width <= this.imageMaxWidth && height <= this.imageMaxHeight)//don't make image bigger
		{
			//center the photo
		}
		else if (width / height > this.imageMaxWidth / this.imageMaxHeight)
		{
			//true if ratio is wider than the containing box
			//resize so that width is imageMaxWidth
			scaleRatio = this.imageMaxWidth/width;
		}
		else
		{
			//resize so that height is imageMaxHeight
			scaleRatio = this.imageMaxHeight/height;
		}
		scaleRatio = (scaleRatio > 1 || scaleRatio <= 0) ? 1 : scaleRatio;//never enlarge the image
		width = Math.round(width * scaleRatio - 0.5);
		height = Math.round(height * scaleRatio - 0.5);
		Element.setWidth(this.photo, width);
		Element.setHeight(this.photo, height);

		var newPadding = '0px'; 
		if(height < this.imageMaxHeight)
		{	
			var whiteSpace = (this.imageMaxHeight - height);
			if(whiteSpace > 30)
			{
				whiteSpace /= 2;
			}
			newPadding = whiteSpace + 'px';
		}
		//used to be: var newPadding = (height < this.imageMaxHeight)?((this.imageMaxHeight - height)/2) + 'px':'0px'; 
		//center the photo vertically by adding padding
		Element.setStyle(this.photo,{paddingTop:newPadding});
	},
	showPhoto: function(){
		//clean out the timer before we set it again
		clearTimeout(this.slideTimer);
		if(!this.paused){
			this.slideTimer = setTimeout("mySlideShow.nextPhoto()",mySlideShow.slideTime);
		}
		new Effect.Fade(this.loader, {duration: 0.5});
		new Effect.Appear(this.photoContainer, {duration: 1, from: 0.2, to:1, afterFinish: function(){mySlideShow.setContextPin();}});
		new Effect.Appear(this.captionBox, {duration: 2, from: 0.0, to:0.8});
		this.preloadNextPhoto();
	},
	nextPhoto: function(){
		// stop the timer that will call nextPhoto
		clearTimeout(this.slideTimer);
		// Figure out which photo is next
		(this.photoNum >= (this.photoCount - 1)) ? this.photoNum = 0 : this.photoNum++;
		this.initSwap();
	},
	prevPhoto: function() {
		// stop the timer that will call nextPhoto
		clearTimeout(this.slideTimer);
		// Figure out which photo is previous
		(this.photoNum <= 0) ? this.photoNum = this.photoCount - 1 : this.photoNum--;
		this.initSwap();
	},
	preloadNextPhoto: function() {
		//if we can, get the next photo cached before we actually show it.  This will help avoid waiting for it to download when it changes photo
		if (document.images)
		{
			var i = (this.photoNum >= (this.photoCount - 1)) ? 0 : this.photoNum+1;
			pic1= new Image(this.photoArray[i][1][0],this.photoArray[i][1][1]); 
			pic1.src=this.photoArray[i][0]; 
		}
	},
	pause: function() {
		//toggle flag
		this.paused = (this.paused) ? false : true;
		//stop/start the timer
		if (this.paused){
			clearTimeout(this.slideTimer);
			Element.setOpacity(this.pauseLink,'1');
		}
		else{
			clearTimeout(this.slideTimer);
			this.slideTimer = setTimeout("mySlideShow.nextPhoto()",this.slideTime);
			Element.setOpacity(this.pauseLink,'.5');
		}
	},
	jumpToPhoto: function(id) {
		id--;//put id into zero based array
		//if photo is out of bounds, show the next photo
		if(!id || id < 0 || id > this.photoCount) {
			this.nextPhoto();
		}
		else {
			clearTimeout(this.slideTimer);
			this.photoNum = id;
			this.initSwap();
		}
	},
	initSwap: function() {
		//un-pause if it is currently paused
		if(this.paused){this.pause();}
		//show the loader, and fade out the photo, when it's done, set the new photo's parameters
		new Effect.Appear(this.loader, {duration: 0.5});
		new Effect.Fade(this.captionBox, {duration: 0.5, afterFinish: function(){$(mySlideShow.contextMap).hide();}});
		new Effect.Fade(this.photoContainer, {duration: 0.5, afterFinish: function(){mySlideShow.newPhoto();}});
	},
	newPhoto: function() {
		//the showPhoto() function gets called when the photo actually loads which resets the timer.  
		//This happens so that if the browser takes too long to load the image it doesn't just hang, 
		//but essentially skips the image.  We give it twice as much time for slower connections.
		clearTimeout(this.slideTimer);
		this.slideTimer = setTimeout("mySlideShow.nextPhoto()",(mySlideShow.slideTime*2));
		this.setNewPhotoParams();
		this.setPhotoCaption();
	},
	setContextPin: function() {
		
		var coordinates = this.photoArray[this.photoNum][8];
		var pinSize = this.photoArray[this.photoNum][6];
		var ImageOffset = this.photoArray[this.photoNum][7];
		var pinSizeWidth = pinSize[0];
		var pinSizeHeight = pinSize[1];
		var ImageOffsetleft = ImageOffset[0];
		var ImageOffsettop = ImageOffset[1];
		var bywayname = this.photoArray[this.photoNum][2];

		var allPins = $$('.pin');
		allPins.each(function(pin){Element.remove(pin);});
		//build the pin html
		for(keyVar=0;keyVar<(coordinates.length-1);keyVar++) {
			if(coordinates[keyVar])
			{
				var pinID = 'pin'+keyVar;
				
				var pinHTML = '<a href="'+this.photoArray[this.photoNum][4]+'" title="'+bywayname+'"><img id="'+pinID+'" class="pin alpha" src="'+this.photoArray[this.photoNum][5]+'" alt="" title="'+bywayname+'" width="'+pinSizeWidth+'" height="'+pinSizeHeight+'" /></a>';
				var contextRegion = $('pins');
				new Insertion.Bottom(contextRegion, pinHTML);
		
				var x = coordinates[keyVar][0];
				var y = coordinates[keyVar][1];
				var leftOffset = x-ImageOffsetleft;
				var topOffset = y-ImageOffsettop;
				
				$(pinID).style.position = "absolute";
				$(pinID).style.top = topOffset+'px';
				$(pinID).style.left = leftOffset+'px';
			}
		}
		
		$(this.contextMap).show();
	}
}

/*--------------------------------------------------------------------------*/

// Establish CSS-driven events via Behaviour script
var myrules = {
	'#Photo' : function(element){
		element.onload = function(){
			mySlideShow.showPhoto();
		}
	},
	'#PrevLink' : function(element){
		element.onclick = function(){
			mySlideShow.prevPhoto();
			return false;
		}
	},
	'#NextLink' : function(element){
		element.onclick = function(){
			mySlideShow.nextPhoto();
			return false;
		}
	},
	'#PauseLink' : function(element){
		element.onclick = function(){
			mySlideShow.pause();
			return false;
		}
	}
};
