/* 
	The following information must not be removed:
	Awesome Box
	Written by: Paul Armstrong, Paul Armstrong Designs
	Site: http://paularmstrongdesigns.com
	Idea and some functions from the original Lightbox:
		http://huddletogether.com/projects/awesomebox2/
	Example & Documentation: http://paularmstrongdesigns.com/examples/js/awesome-box/
	Thu Jun 22 22:38:39 2006
	Updated: Tue Dec 12 19:52:44 2006

	Thanks to Jesse Mullan (http://jpmullan.com) and Zach Johnson (http://tech.no.logi.es),
	Lokesh Dhakar (http://www.huddletogether.com) - creator of the original Lightbox,
	and the YUI team for the awesome JS Library.

	This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
	http://creativecommons.org/licenses/by-sa/2.5/

	Required Yahoo! UI Libraries:
		* yahoo.js
		* dom.js
		* event.js
		* animation.js
		** suggested to use the -min.js files for better load times
*/

YAHOO.awesomebox = function() {
	var aMargin = 25; // Margin from window edges
	var aPadding = 10; // Padding around image
	var aOpacity = 0.9; // Overlay Opacity
	var aLoadImg = 'http://www.yourhomepage.com/wp-content/plugins/ws_picviewer/images/aLoading.gif'; // path to loading image
	var aClose = 'http://www.yourhomepage.com/wp-content/plugins/ws_picviewer/images/aClose.gif'; // path to close image
	var aImgTypes = new Array('jpg', 'gif', 'png');
	var lastID = 'footer'; // last ID on the page, used for initial popup image

	var $D = YAHOO.util.Dom;
	var $E = YAHOO.util.Event;
	var $A = YAHOO.util.Anim;
	var $M = YAHOO.util.Motion;
	var $Ease = YAHOO.util.Easing;
	var $ = $D.get;
	
	var aLoaded = new Array(); // we'll fill this with each loaded image
	
	/* inArray(value)
	* Returns the key of the array that value is assigned to if true, null if false.
	*/
	Array.prototype.inArray = function(value) {
		for (i=0; i < this.length; i++) { if (this[i] == value) { return i; } }
		return null;
	}
	
	/* isNumber(a)
	* Checks whether something is a number. 
	* Used with the inArray method for checking logical statements.
	*/
	function isNumber(a) {
	    return typeof a == 'number' && isFinite(a);
	}
	
	var properties = new Object();
	/* 
	* Find all links going to a file with an aImgTypes
	*/
	properties.allImgs = function() {
		var links = document.getElementsByTagName('a');
		var photos = new Array();
		for(i = 0; i < links.length; i++) {
			for(j = 0; j < aImgTypes.length; j++) {
				if(links[i].href.indexOf(aImgTypes[j]) != -1) {
					photos.push(links[i])
				}
			}
		}
		return photos;
	}
	/* properties.pageWidth() and properties.pageHeight()
	* Returns the width and height of the content in the document.
	*/
	properties.pageWidth = function() {
		var xScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
		}
		if(xScroll < $D.getViewportWidth()) {
			pageWidth = $D.getViewportWidth();
		} else {
			pageWidth = xScroll;
		}
		return pageWidth;
	};
	properties.pageHeight = function() {
		var yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			yScroll = document.body.offsetHeight;
		}
		if(yScroll <= $D.getViewportHeight()) {
			pageHeight = $D.getViewportHeight();
		} else { 
			pageHeight = yScroll;
		}
		return pageHeight;
	};
	
	/* properties.xScroll() and properties.yScroll()
	* Returns the position of the X and Y scrollbars.
	*/
	properties.xScroll = function() {
		var xScroll = window.scrollX || document.documentElement.scrollLeft;
		return xScroll;
	}	
	properties.yScroll = function() {
		var yScroll = window.scrollY || document.documentElement.scrollTop;
		return yScroll;
	}	

	/* getTitle(item)
	* If an image is contained in the <a></a> element, the alt attribute is used as the title.
	* If not, the title will be the words appearing within the <a></a> element.
	*/
	function getTitle(item) {
		var title;
		var thumb = $(item).getElementsByTagName('img')[0];
		if(thumb) { title = $(thumb).getAttribute('alt');
			if(title == null) { title = ''; }
		}
		else { title = item.innerHTML; }
		return title;
	}
	
	/* getLongdesc(item)
	* If an image is contained in the <a></a> element, the longdesc attribute is used.
	* If no thumbnail is found, the title attribute is used.
	*/
	function getLongdesc(item) {
		var longdesc;
		var thumb = $(item).getElementsByTagName('img')[0];
		if(thumb) { longdesc = thumb.getAttribute('longdesc'); }
		else { longdesc = item.getAttribute('title'); }
		if(!(longdesc == null)) { longdesc = '<p>'+longdesc+'</p>'; }
		else { longdesc = ''; }
		return longdesc;
	}
	
	/* scaleImg(aImage)
	* If necessary, returns width and height attributes, proportionally scaled to fit the window.
	* Also returns the X and Y position of the image.
	*/
	function scaleImg(aImage) {
		var sWidth, sHeight;
		if(aImage.width+aPadding+aMargin > $D.getViewportWidth()) {
			sWidth = $D.getViewportWidth() - (2*aMargin);
			sHeight = aImage.height * (sWidth / aImage.width);
			if(sHeight > ($D.getViewportHeight() - (5*aMargin))) {
				sHeight = $D.getViewportHeight() - (5*aMargin);
				sWidth = aImage.width * (sHeight / aImage.height);
			}
			var imgScale = ' width="'+sWidth+'" height="'+sHeight+'"';
		} else if(aImage.height+aPadding+(2*aMargin) > $D.getViewportHeight()) {
			sWidth = aImage.width * ($D.getViewportHeight()-aMargin / aImage.height);
			sHeight = $D.getViewportHeight()-aMargin - (5*aMargin);
			if(sWidth > ($D.getViewportHeight() - (2*aMargin))) {
				sWidth = aImage.width * (sHeight / aImage.height);
				sHeight = aImage.height * (sWidth / aImage.width);
			}
			var imgScale = ' width="'+sWidth+'" height="'+sHeight+'"';
		} else {
			sHeight = aImage.height;
			sWidth = aImage.width;
			imgScale = '';
		}
		xPos = (($D.getViewportWidth() - sWidth)/2)+properties.xScroll()-(aMargin/2);
		yPos = (($D.getViewportHeight() - sHeight)/2)+properties.yScroll()-(aMargin/2);

		var scaleAtts = new Array(sWidth, sHeight, xPos, yPos, imgScale);
		return scaleAtts;
	}
	
	/* getPhotoset(rel)
	* Returns an array of all <a> elements with the specified rel attribute.
	*/
	function getPhotoset(rel) {
		var photos = properties.allImgs();
		var photoset = new Array();
		for(i = 0; i < photos.length; i++) {
			var iRel = photos[i].getAttribute('rel');
			if(iRel == rel) { photoset.push(photos[i]); }
		}
		return photoset;
	}

	return {
		init : function() {
			if (navigator.appVersion.indexOf("MSIE") != -1){
				var temp = navigator.appVersion.split("MSIE")
				if(parseFloat(temp[1]) < 7.0) {
					return;
				}
			}
			if(window.location.href.indexOf('#') != -1) {
				var currentPhoto = window.location.href.split('#')[1];
				for(q = 0; q < properties.allImgs().length; q++) {
					var temp = properties.allImgs()[q].href.split('/');
					var name = temp[temp.length-1].split('.')[0];
					if(currentPhoto == name) {
						$E.onAvailable(lastID, this.popup, $(properties.allImgs()[q]), true);
					}
				}
			}
			
			/* create the overlay and aBox. */
			var aOverlay = document.createElement('div');
			var aBox = document.createElement('div');
			document.getElementsByTagName('body')[0].appendChild(aOverlay);
			document.getElementsByTagName('body')[0].appendChild(aBox);
			aOverlay.id = 'aOverlay';
			aBox.id = 'aBox';
			$D.setStyle('aOverlay', 'opacity', '0');
			$D.setStyle('aBox', 'opacity', '0');
			
			$E.addListener(properties.allImgs(), 'click', this.popup);
			$E.addListener('aOverlay', 'click', this.close);
			$E.addListener('aClose', 'click', this.close);
			$E.addListener('aImg', 'click', this.close); 
		},

		popup : function(e) {
			var img = $(this).getAttribute('href');
			var thumb = $(this).getElementsByTagName('img')[0];
			var rel = $(this).getAttribute('rel');
			var photoobj = this;
			
			/*
			* Check if photo belongs to a set.
			* If so, create the next/previous links.
			*/
			if(!(rel == null)) {
				var prev = '<a id="aPrev" onclick="YAHOO.awesomebox.slideshow(\''+photoobj+'\', \'previous\', \''+rel+'\')">previous</a>';
				var next = '<a id="aNext" onclick="YAHOO.awesomebox.slideshow(\''+photoobj+'\', \'next\', \''+rel+'\')">next</a>';
				var index = '<p class="aIndex">'+rel+': '+(parseInt(getPhotoset(rel).inArray(photoobj))+1)+' of '+getPhotoset(rel).length+'</p>';
			} else {
				var prev = ''; var next = ''; var index = '';
			}
			
			var fadeIn = new $A('aOverlay', { opacity: { from: 0, to: aOpacity } }, 0.1);
			var loadimage = new Image();
			loadimage.src = aLoadImg;
			
			fadeIn.onStart.subscribe(function() {
				$('aOverlay').innerHTML = '<img id="aLoadImg" src="" alt="Loading '+getTitle(photoobj)+'. Please Wait!" />';
				$('aLoadImg').src = loadimage.src;

				/* Position the loading image. */
				$E.onAvailable('aLoadImg', function() {
					var xPos = (($D.getViewportWidth() - loadimage.width)/2)+properties.xScroll();
					var yPos = (($D.getViewportHeight() - loadimage.height)/2)+properties.yScroll();
					$D.setX('aLoadImg', xPos);
					$D.setY('aLoadImg', yPos);
				});
				
				/* Set the overlay to cover everything. */
				$D.setStyle('aOverlay', 'display', 'block');
				$D.setStyle('aOverlay', 'width', properties.pageWidth()+'px');
				$D.setStyle('aOverlay', 'height', properties.pageHeight()+'px');

				var aImage = new Image();
				aImage.src = img;
				
				/* Check if image has been loaded yet. If/when it is, make it do awesome */
				if(isNumber(aLoaded.inArray(aImage.src))) {
					populate(aImage);
				} else {
					aImage.onload = function() { 
						aLoaded.push(aImage.src);
						populate(aImage);
					}
				}
				
				function populate(aImage) {
					/* Get the attributes from scaleImage() */
					var sWidth = scaleImg(aImage)[0];
					var sHeight = scaleImg(aImage)[1];
					var xPos = scaleImg(aImage)[2];
					var yPos = scaleImg(aImage)[3];
					var imgScale = scaleImg(aImage)[4];
					
					/* If this is a photoset, preload the next image */
					if(next != '') {
						var nextnum = parseInt(getPhotoset(rel).inArray(photoobj))+1;				
						if(nextnum == getPhotoset(rel).length) { nextnum = 0; }

						var nextimg = getPhotoset(rel)[nextnum].getAttribute('href');

						var nextaImg = new Image();
						nextaImg.src = nextimg;
						aLoaded.push(nextaImg.src);
					} 
					
					/* Remove the loading image. Add content to aBox. */
					/*
					<div id="aBox">
						<img id="aImg" />
						<img id="aClose" />
						<div id="aInternal">
							[<a id="aPrev">Previous</a><a id="aNext">Next</a>]
							<h1>Title</h1>
							[<p>Long Description</p>]
							[<p>Rel Tag & Photo Number</p>]
						</div>
					</div>
					*/
					$('aOverlay').innerHTML = '';
					$('aBox').innerHTML = '<img id="aImg" src="" alt="'+getTitle(photoobj)+'"'+imgScale+' />'
						+'<img id="aClose" src="'+aClose+'" onclick="YAHOO.awesomebox.close();" alt="Click to Close" />'
						+'<div id="aInternal">'
						+prev+next
						+'<h1>'+getTitle(photoobj)+'</h1>'
						+getLongdesc(photoobj)
						+index
						+'</div>';
					$('aImg').src = aImage.src;
					
					/* When aBox is available, do all the animation goodness. */
					$E.onAvailable('aBox', function() {
						$D.setStyle('aBox', 'display', 'block');

						var aGrow = new $M(
							'aBox', 
							{ 
								points: { from: [$D.getViewportWidth()/2, ($D.getViewportHeight()/2)+properties.yScroll()], to: [xPos, yPos] },
								opacity: { from: 0, to: 1.0 }, 
								height: { from: 0, to: sHeight+(50) }, 
								width: { from: 0, to: sWidth } 
							}, 0.2
						);
						aGrow.onComplete.subscribe(function() {
							var showimg = new $A(
								'aImg', { opacity: { from: 0, to: 1 } }, 0.4
							);
							showimg.onStart.subscribe(function() {
								var showclose = new $A(
									'aClose', { opacity: { from: 0, to: 1 } }, 0.4
								);
								var showinternal = new $A(
									'aInternal', { opacity: { from: 0, to: 1 } }, 0.4
								);
								showclose.animate();
								showinternal.onComplete.subscribe(function() {
									var filename = img.split('/')[img.split('/').length-1].split('.')[0];
									window.location = window.location.href.split('#')[0]+'#'+filename;
								});
								showinternal.animate();
							});
							showimg.animate();
						});
						aGrow.animate();				
					});
				}
			});
			fadeIn.animate();
			/* Stop the browser from its default link action. */
			$E.stopEvent(e);	
		},
		
		/* slideshow
		* Called from next and previous links in aBox
		*/
		slideshow : function(current, item, rel) {
			var prevnum = parseInt(getPhotoset(rel).inArray(current))-1;
			var nextnum = parseInt(getPhotoset(rel).inArray(current))+1;

			if(prevnum == -1) { prevnum = getPhotoset(rel).length-1; }
			if(nextnum == getPhotoset(rel).length) { nextnum = 0; }
			
			if(item == 'previous') { var newimg = prevnum; } else { var newimg = nextnum; }
			var img = getPhotoset(rel)[newimg];
			var thumb = getPhotoset(rel)[newimg].getElementsByTagName('img')[0];
			
			var prev = '<a id="aPrev" onclick="YAHOO.awesomebox.slideshow(\''+img+'\', \'previous\', \''+rel+'\')">previous</a>';
			var next = '<a id="aNext" onclick="YAHOO.awesomebox.slideshow(\''+img+'\', \'next\', \''+rel+'\')">next</a>';
			var index = '<p class="aIndex">'+rel+': '+(parseInt(getPhotoset(rel).inArray(img))+1)+' of '+getPhotoset(rel).length+'</p>';
			
			var hidecurrent = new $A('aImg', { opacity: { to: 0 } }, 0.2);
			$D.setStyle('aOverlay', 'width', properties.pageWidth()+'px');
			$D.setStyle('aOverlay', 'height', properties.pageHeight()+'px');
			hidecurrent.onStart.subscribe(function() {
				var hideclose = new $A('aClose', { opacity: { to: 0 } }, 0.4);
				var hideinternal = new $A('aInternal', { opacity: { to: 0 } }, 0.4);
				hideclose.animate();
				hideinternal.animate();
			});
			
			hidecurrent.onComplete.subscribe(function() {
				var loadimage = new Image();
				loadimage.src = aLoadImg;
				$('aBox').innerHTML = '<img id="aLoadImg" src="" alt="Loading '+getTitle(img)+'. Please Wait!" />';
				$('aLoadImg').src = loadimage.src;
	
				var xPos = (($D.getViewportWidth() - loadimage.width)/2);
				var yPos = (($D.getViewportHeight() - loadimage.height)/2)+properties.yScroll();
				$D.setX('aLoadImg', xPos);
				$D.setY('aLoadImg', yPos);
	
				var aImage = new Image();
				aImage.src = img;

				/* Check if image has been loaded yet. If/when it is, make it do awesome */
				if(isNumber(aLoaded.inArray(aImage.src))) {
					populate(aImage);
				} else {
					aImage.onload = function() { 
						aLoaded.push(aImage.src);
						populate(aImage);
					}
				}
				
				function populate() {
					var sWidth = scaleImg(aImage)[0];
					var sHeight = scaleImg(aImage)[1];
					var xPos = scaleImg(aImage)[2];
					var yPos = scaleImg(aImage)[3];
					var imgScale = scaleImg(aImage)[4];
					
					if(next != '') {
						var nextnum = parseInt(getPhotoset(rel).inArray(img))+1;				
						if(nextnum == getPhotoset(rel).length) { nextnum = 0; }

						var nextimg = getPhotoset(rel)[nextnum];

						/* Check/Load if next image has been loaded yet. */
						if(isNumber(aLoaded.inArray(nextimg))) { } else {
							var nextaImg = new Image();
							nextaImg.src = nextimg;
							aLoaded.push(nextaImg.src);
						}
					} 
					
					/* Fill aBox with stuff. */
					$('aBox').innerHTML = '<img id="aClose" src="'+aClose+'" onclick="YAHOO.awesomebox.close();" alt="Click to Close" />'
						+'<img id="aImg" src="" alt="'+getTitle(img)+'"'+imgScale+' />'
						+'<div id="aInternal">'
						+prev+next
						+'<h1>'+getTitle(img)+'</h1>'
						+getLongdesc(img)
						+index
						+'</div>';
					
					$('aImg').src = aImage.src;
					
					/* Do the animation stuffs */
					$E.onAvailable('aBox', function() {
						$D.setStyle('aBox', 'display', 'block');
						var aGrow = new $M(
							'aBox', 
							{ 
								points: { to: [xPos, yPos] },
								opacity: { to: 1.0 }, 
								height: { to: sHeight+(50) }, 
								width: { to: sWidth } 
							}, 0.2
						);
						aGrow.onComplete.subscribe(function() {
							var showimg = new $A(
								'aImg', { opacity: { from: 0, to: 1 } }, 0.4
							);
							showimg.onStart.subscribe(function() {
								var showclose = new $A(
									'aClose', { opacity: { from: 0, to: 1 } }, 0.4
								);
								var showinternal = new $A(
									'aInternal', { opacity: { from: 0, to: 1 } }, 0.4
								);
								showclose.animate();
								showinternal.onComplete.subscribe(function() {
									
									var filename = aImage.src.split('/')[aImage.src.split('/').length-1].split('.')[0];
									window.location = window.location.href.split('#')[0]+'#'+filename;
								});
								showinternal.animate();
							});
							showimg.animate();
							$D.setStyle('aImg', 'display', 'block');
						});
						aGrow.animate();
					});
				}
			});
			hidecurrent.animate();
		},
		
		/* close
		* Invoked via the 'X' image or clicking the darkened overlay.
		* Does animation goodness to hide everything that was created.
		*/
		close : function() {
			var hideimg = new $A('aImg', { opacity: { to: 0 } }, 0.1);
			hideimg.onStart.subscribe(function() {
				var hideclose = new $A('aClose', { opacity: { to: 0 } }, 0.1);
				var hideinternal = new $A('aInternal', { opacity: { to: 0 } }, 0.1);
				hideclose.animate();
				hideinternal.animate();
			});
			hideimg.onComplete.subscribe(function() {
				var aFade = new $M(
					'aBox', { 
						points: { 
							from: [xPos, yPos], to: [$D.getViewportWidth()/2, ($D.getViewportHeight()/2)+properties.yScroll()] 
						},
						height: { to: 0 },
						width: { to: 0 }, 
						opacity: { from: 1, to: 0 } 
					}, 0.2
				);
				aFade.onComplete.subscribe(function() {
					$D.setStyle('aBox', 'display', 'none');
					$('aBox').innerHTML = '';
					var fadeoverlay = new $A(
						'aOverlay', { opacity: { from: aOpacity, to: 0 } }, 0.1
					);
					fadeoverlay.onComplete.subscribe(function() {
						$D.setStyle('aOverlay', 'display', 'none');
					});
					fadeoverlay.animate();
				});
				aFade.animate();
			});
			hideimg.animate();
		}
	}
}();
YAHOO.util.Event.addListener(window, 'load', YAHOO.awesomebox.init, YAHOO.awesomebox, true);
