// -----------------------------------------------------------------------------
// aefi.js v1.0b
//
// Provides the Base JavaScript Functionality for http://www.aefi.com
//
// Author: 		Nathan Kelly. nathan@infiniteeye.com.au
// Author Website: 	http://www.nathan-kelly.com
//			http://www.infiniteeye.com.au
//
// Additional Credits:
// Though it's nothing like it (now), this script was inspired by Lokesh Dhakar's
// Lightbox JS v2.0 script. // http://www.huddletogether.com/projects/lightbox2/
//
// Special Thanks:
// Sam Stephenson, for prototype - http://prototype.conio.net/
// Thomas Fuchs, for script.aculo.us - http://script.aculo.us/
//
// Copyright (c) 2006, An Eye For Ink Design Solutions.
//

// -----------------------------------------------------------------------------
// Configuration

var fileLoadingImage = "http://www.aneyeforink.com/design/images/loading2.gif";
var jsDir = "http://www.aneyeforink.com/aefi";

var SplashPage = Class.create();

SplashPage.prototype = {

	initialize: function() {

		var objEntryLink = document.getElementById('enter');

		// JS is enabled so we need to send the browser to the right location
		// So change the enter link from /home to /aefi before it gets clicked
		var hrefAttribute = String(objEntryLink.getAttribute('href'));
		var checkDir = /home/;
		var changeDir = hrefAttribute.replace(checkDir, "aefi");
		objEntryLink.setAttribute('href', changeDir);

		if (document.getElementById('preload-1')) {
			this.start()
			return false;
		}

	},

	start: function () {

		new Effect.Fade('splash', {
			delay: 2.0,
			duration: 2.0,
			afterFinish: function() {
				window.location = jsDir;
			}
		});

	}
};

var DhtmlPages = Class.create();

DhtmlPages.prototype = {

	initialize: function() {

		new Effect.Appear('container' , {
			duration: 2.0
		});

		// Get the links
		var objHomeLink1 = document.getElementById('home-link1');
		var objHomeLink2 = document.getElementById('home-link2');
		var objFolioLink = document.getElementById('folio-link');
		var objClientsLink = document.getElementById('clients-link');
		var objContactLink = document.getElementById('contact-link');

		// Appear the home page
		new Effect.Appear('home-viewport', {duration: 0.5});

		objHomeLink1.onclick = function() {

			myDhtmlPages.clearCurrent();

			// close the lightbox
			// remove this if you want the lightbox to have a memory between page views
			myLightbox.end();			

			new Effect.Parallel(
				[
					new Effect.Fade('folio-nav', {
						duration: 0.8
					}),
					new Effect.Fade('folio-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('clients-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('contact-viewport', {
						duration: 0.8
					})
				],
				{
					duration: 0.8,
					afterFinish: function() {
						new Effect.Parallel(
							[
								new Effect.Appear('home-viewport', {
									duration: 0.8
								}),
								new Effect.Appear('rota-quota', {
									duration: 0.8
								})
							],
							{
								duration: 0.8
							}
						);
					}
				}
			);
		}
		
		objHomeLink2.onclick = function() {

			myDhtmlPages.clearCurrent();

			// close the lightbox
			// remove this if you want the lightbox to have a memory between page views
			myLightbox.end();			

			new Effect.Parallel(
				[
					new Effect.Fade('folio-nav', {
						duration: 0.8
					}),
					new Effect.Fade('folio-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('clients-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('contact-viewport', {
						duration: 0.8
					})
				],
				{
					duration: 0.8,
					afterFinish: function() {
						new Effect.Parallel(
							[
								new Effect.Appear('home-viewport', {
									duration: 0.8
								}),
								new Effect.Appear('rota-quota', {
									duration: 0.8
								})
							],
							{
								duration: 0.8
							}
						);
					}
				}
			);
		}

		objFolioLink.onclick = function() {

			myDhtmlPages.clearCurrent();

			objFolioLink.className = 'current';

			new Effect.Parallel(
				[
					new Effect.Fade('rota-quota', {
						duration: 0.8
					}),
					new Effect.Fade('home-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('clients-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('contact-viewport', {
						duration: 0.8
					})
				],
				{
					duration: 0.8,
					afterFinish: function() {
						new Effect.Parallel(
							[
								new Effect.Appear('folio-viewport', {
									duration: 0.8
								}),
								new Effect.Appear('folio-nav', {
									duration: 0.8
								})
							],
							{
								duration: 0.8
							}
						);
					}
				}
			);

		}

		objClientsLink.onclick = function() {

			myDhtmlPages.clearCurrent();

			// close the lightbox
			// remove this if you want the lightbox to have a memory between page views
			myLightbox.end();

			objClientsLink.className = 'current';

			new Effect.Parallel(
				[
					new Effect.Fade('folio-nav', {
						duration: 0.8
					}),
					new Effect.Fade('folio-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('home-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('contact-viewport', {
						duration: 0.8
					})
				],
				{
					duration: 0.8,
					afterFinish: function() {
						new Effect.Parallel(
							[
								new Effect.Appear('clients-viewport', {
									duration: 0.8
								}),
								new Effect.Appear('rota-quota', {
									duration: 0.8
								})
							],
							{
								duration: 0.8
							}
						);
					}
				}
			);
		}

		objContactLink.onclick = function() {

			myDhtmlPages.clearCurrent();

			// close the lightbox
			// remove this if you want the lightbox to have a memory between page views
			myLightbox.end();

			objContactLink.className = 'current';

			new Effect.Parallel(
				[
					new Effect.Fade('folio-nav', {
						duration: 0.8
					}),
					new Effect.Fade('folio-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('home-viewport', {
						duration: 0.8
					}),
					new Effect.Fade('clients-viewport', {
						duration: 0.8
					})
				],
				{
					duration: 0.8,
					afterFinish: function() {
						new Effect.Parallel(
							[
								new Effect.Appear('contact-viewport', {
									duration: 0.8
								}),
								new Effect.Appear('rota-quota', {
									duration: 0.8
								})
							],
							{
								duration: 0.8
							}
						);
					}
				}
			);
		}

	},

	clearCurrent: function() {

		var objMainNav = document.getElementById('main-nav');
		var anchors = objMainNav.getElementsByTagName('a');

		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];

			Element.removeClassName(anchor, 'current');
		}
	}

};

var imageArray = new Array;
var activeImage;

Object.extend(Element, {
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src;
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href;
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

// -----------------------------------------------------------------------------
// Extending built-in Array object
// - array.removeDuplicates()
// - array.empty()

Array.prototype.removeDuplicates = function () {
	for(i = 1; i < this.length; i++){
		if(this[i][0] == this[i-1][0]){
			this.splice(i,1);
		}
	}
};

// -----------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
};

// -----------------------------------------------------------------------------
// Begin Rota Quota

var quoteArray = new Array;
var Q = 0;

var RotaQuota = Class.create();

RotaQuota.prototype = {

	initialize: function() {

		quoteArray = [];

		var objRotaQuota = document.getElementById('rota-quota');
		var objQuotes = objRotaQuota.getElementsByTagName('p');

		for (var i=0; i<objQuotes.length; i++){
			quote = objQuotes[i];

			quoteArray.push(new Array(quote.getAttribute('id')));


			Element.hide(objQuotes[i]);

			Element.show(objQuotes[0]);


		}

		setInterval( function() {

			myRotaQuota.rotateQuotes(quoteArray);

		}, 8000);

	},

	rotateQuotes: function(quoteArray) {

		new Effect.Fade(String(quoteArray[Q]), {
			duration:1,
			from:1.0,
			to:0.0
		});

		Q++;
		if (Q == quoteArray.length) Q = 0;

		new Effect.Appear(String(quoteArray[Q]), {
			duration:1,
			from:0.0,
			to:1.0
		});

	}

};

// -----------------------------------------------------------------------------
// Begin the lightbox class

var Lightbox = Class.create();

Lightbox.prototype = {

	initialize: function() {

		if (!document.getElementsByTagName && document.getElementById){ return; }

		var objFolioNav = document.getElementById('folio-nav');
		var anchors = objFolioNav.getElementsByTagName('a');		
		
		// Loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];

			var relAttribute = String(anchor.getAttribute('rel'));
			
			// Use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){

				// Here I need to manipulate the links, this way if javascript
				// is disabled it won't affect my PHP generated pages, they'll
				// still work without the flashy effects, so...
				// Get the href string we need to convert
				var hrefAttribute = String(anchor.getAttribute('href'));

				// first check to see if this operation has already been done
				// if not do it
				if (hrefAttribute.indexOf("design") == -1) {
					// Find the "folio/" part
					var extendDir = /folio\//;
					// Swap "folio/" with "design/images/folio/"
					// (this is my folio image dir, PHP doesn't need this due to mod_rewrite but JS does)
					var fixFileName = hrefAttribute.replace(extendDir, "design/images/folio\/");
					// Do the conversion
					// Add .jpg is temporary, I need to fix the PHP so I don't have to do it here.
					// It worked on my local machine but for some reason the current server has
					// some issues with my string manipulation in the PHP, looking into it.
					anchor.setAttribute('href', fixFileName + '.jpg');
					// All done
				} else {
					// if so do nothing
				}				
				
				if (anchor.getAttribute('title')) {					
					this.hoverState(anchor);					
				}
				
				anchor.onclick = function () {					
					myLightbox.start(this);
					return false;
				}
			}
		}
		
		var objViewPort = document.getElementById("folio-viewport");

		// Create Lightbox
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','lightbox');
		objViewPort.appendChild(objLightbox);

		// Create Image Container
		var objLightboxWrapper = document.createElement("div");
		objLightboxWrapper.setAttribute('id','lightbox-wrapper');
		objLightbox.appendChild(objLightboxWrapper);

		// Create loading Div
		var objLightboxLoading = document.createElement("div");
		objLightboxLoading.setAttribute('id','lightbox-loading');
		objLightbox.appendChild(objLightboxLoading);

		// Create Loading Abort Link
		var objLightboxAbort = document.createElement("a");
		objLightboxAbort.setAttribute('id','lightbox-abort');
		objLightboxAbort.setAttribute('href','#');
		objLightboxAbort.onclick = function() { myLightbox.end(); return false; }
		objLightboxLoading.appendChild(objLightboxAbort);

		// Create Loading Gif
		// this shows up in IE before the lightbox starts (NEED TO REVISE)
		var objLoadingImage = document.createElement("img");
		objLoadingImage.setAttribute('src', fileLoadingImage);
		objLoadingImage.setAttribute('alt', 'Image Loading. Click to Close.');
		objLightboxAbort.appendChild(objLoadingImage);

		// Create Image Container
		var objLightboxImageContainer = document.createElement("div");
		objLightboxImageContainer.setAttribute('id','lightbox-image-container');
		objLightboxWrapper.appendChild(objLightboxImageContainer);

		// Create Image
		var objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id','lightbox-image');
		objLightboxImageContainer.appendChild(objLightboxImage);

		// hide the lightbox-image right away
		// this fixes a bug in IE
		Element.hide('lightbox-image');

		// Create Navigation
		var objLightboxFooter = document.createElement("div");
		objLightboxFooter.setAttribute('id','lightbox-footer');
		objLightbox.appendChild(objLightboxFooter);

		var objLightboxDetails = document.createElement("span");
		objLightboxDetails.setAttribute('id','lightbox-details');
		objLightboxFooter.appendChild(objLightboxDetails);

		var objLightboxNav = document.createElement("div");
		objLightboxNav.setAttribute('id','lightbox-nav');
		objLightboxFooter.appendChild(objLightboxNav);

		var objRestartLink = document.createElement("a");
		objRestartLink.setAttribute('id','restart-link');
		objRestartLink.setAttribute('href','#');
		objRestartLink.setAttribute('title','First');
		objLightboxNav.appendChild(objRestartLink);
		
		Element.hide('restart-link');
		
		var objNextLink = document.createElement("a");
		objNextLink.setAttribute('id','next-link');
		objNextLink.setAttribute('href','#');
		objNextLink.setAttribute('title','Next');
		objLightboxNav.appendChild(objNextLink);

		var objPrevLink = document.createElement("a");
		objPrevLink.setAttribute('id','prev-link');
		objPrevLink.setAttribute('href','#');
		objPrevLink.setAttribute('title','Previous');
		objLightboxNav.appendChild(objPrevLink);
	},
	
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {
		
		if (!document.getElementsByTagName){ return; }		
		
		// fade the image when changing categories
		Effect.Fade('lightbox-image', {
			duration: 0.5
		});

		// remove current class
		this.clearCurrent();
		
		imageArray = [];
		imageNum = 0;

		var anchors = document.getElementsByTagName('a');

		// if image is NOT part of a set..
		if((imageLink.getAttribute('rel') == 'lightbox')){

			// add single image to imageArray
			imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title'), imageLink.className = 'current'));

		} else {
		// if image is part of a set..

			// loop through anchors, find other images in set, and add them to imageArray
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];

				if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
					imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title'), imageLink.className = 'current'));

					// Set the category title
					var category = String(imageLink.getAttribute('title'));
					
					Element.setInnerHTML( 'category-title', category );
					
				}
			}
			imageArray.removeDuplicates();
			while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
		}

		new Effect.Fade('placeholder', {
			duration: 1.0,
			afterFinish: function() {
				Element.show('lightbox');
				myLightbox.changeImage(imageNum);
			}
		});		
	},
	
	hoverState: function (anchor) {		
		// and now set up a funky little thing to do my hover title swap
		// I have to do it this way rather than setting innerHTML on the h3
		// otherwise I can't restore the current category title
		// so instead I create a span and position it over the h3 text
		// and onmouseout remove the span again
		// I know it seems like a hard way to go about it but it works
		var theTitle = document.getElementById('category-title');
		var hoverTitle = document.createElement('span');
		hoverTitle.setAttribute('id', 'hover-span');
			
		anchor.onmouseover = function () {
			theTitle.appendChild(hoverTitle);
			Element.setInnerHTML("hover-span", '&nbsp;' + anchor.title);		
		}
		anchor.onmouseout = function () {
			
			if (!document.getElementById('hover-span')) return;
			
			theTitle.removeChild(hoverTitle);
			
		}
	},	

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {

		activeImage = imageNum;	// update global var

		Element.hide('lightbox-image');
		Element.hide('lightbox-footer');
		if(activeImage == 0){
			Element.hide('prev-link');
		}
		if(eval(activeImage + 1) == imageArray.length) {
			Element.hide('next-link');
		}

		imgPreloader = new Image();

		// once image is preloaded, reveal the image

		new Effect.Parallel(
			[
				new Effect.AscDescReveal('lightbox-wrapper', {
					duration: 0.8
				}),
				new Effect.Opacity('lightbox-image-container', {
					duration: 0.8,
					from: 1.0,
					to: 0.2
				}),
				new Effect.Appear('lightbox-loading', {
					duration: 0.2,
					from: 0.0,
					to: 1.0
				})
			],
			{
				duration: 0.8,
				afterFinish: function() {

					imgPreloader.onload=function(){

						Element.setSrc('lightbox-image', imageArray[activeImage][0]);
						myLightbox.revealImage(imgPreloader);
					}
					imgPreloader.src = imageArray[activeImage][0];
				}
			}
		);



	},

	//
	//	resizeWrapper()
	//
	revealImage: function() {

		var objReveal = document.getElementById('lightbox-image-container');
		objReveal.style.background = '#fff';

		new Effect.Fade('lightbox-loading', {
			duration: 0.2,
			afterFinish: function() {
				new Effect.Parallel(
					[
						new Effect.Opacity('lightbox-image-container', {
							duration: 0.8,
							from: 0.2,
							to: 1.0
						}),
						new Effect.AscDescReveal('lightbox-wrapper', {
							duration: 0.8
						})
					],
					{
						duration: 1.0,
						afterFinish: function() {
							myLightbox.showImage();
						}
					}
				);
			}
		} );

	},

	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//

	showImage: function(){
		new Effect.Appear('lightbox-image', {
			duration: 0.5,
			queue: 'end',
			afterFinish: function() {
				myLightbox.updateDetails();
			}
		});
		this.preloadNeighborImages();
	},


	//
	//	updateDetails()
	//	Display caption and image number.
	//
	updateDetails: function() {

		// if image is part of set display 'Image x of x'
		if(imageArray.length > 1){
			Element.show('lightbox-details');
			Element.setInnerHTML( 'lightbox-details', eval(activeImage + 1) + " of " + imageArray.length);

			this.updateNav();
		}
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//	Once updated display the footer and nav
	//
	updateNav: function() {

		// if not first image in set, display prev image button
		if(activeImage != 0){
			Element.hide('restart-link');
			Element.show('prev-link');
			Element.setInnerHTML( 'prev-link', "&laquo; Previous Image");
			document.getElementById('prev-link').onclick = function() {
				new Effect.Fade('lightbox-image', {
					duration: 0.3,
					afterFinish: function() {
						myLightbox.changeImage(activeImage - 1); return false;
					}
				});
			}
		}
		// if not last image in set, display next image button
		if(activeImage != (imageArray.length - 1)){
			Element.hide('restart-link');
			Element.show('next-link');
			Element.setInnerHTML( 'next-link', "Next Image &raquo;");
			document.getElementById('next-link').onclick = function() {
				new Effect.Fade('lightbox-image', {
					duration: 0.3,
					afterFinish: function() {
						myLightbox.changeImage(activeImage + 1); return false;
					}
				});
			}
		}
		// if last image in set, display back to start image button
		if(activeImage == (imageArray.length -1)){
			Element.show('restart-link');			
			Element.setInnerHTML( 'restart-link', "First Image &raquo;");
			document.getElementById('restart-link').onclick = function() {
				new Effect.Fade('lightbox-image', {
					duration: 0.3,
					afterFinish: function() {
						myLightbox.changeImage(activeImage - imageArray.length + 1); return false;
					}
				});
			}
		}
		new Effect.Appear('lightbox-footer', {
			delay: 0.25,
			duration: 0.5,
			queue: 'end'
		});
		this.enableKeyboardNav();
	},
	//
	//	Clear Current link
	//
	clearCurrent: function(imageLink) {

		var objFolioNav = document.getElementById('folio-nav');
		var anchors = objFolioNav.getElementsByTagName('a');

		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];

			Element.removeClassName(anchor, 'current');

		}
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction;
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}

		key = String.fromCharCode(keycode).toLowerCase();

		if((key == 'x') || (key == 'o') || (key == 'c')){	// close lightbox
			myLightbox.end();
		} else if(key == 'p'){	// display previous image
			if(activeImage != 0){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage - 1);
			}
		} else if(key == 'n'){	// display next image
			if(activeImage != (imageArray.length - 1)){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage + 1);
			}
		}


	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){

		if((imageArray.length - 1) > activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = imageArray[activeImage + 1][0];
		}
		if(activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = imageArray[activeImage - 1][0];
		}

	},

	//
	//	end()
	//
	end: function() {
		this.clearCurrent();
		this.disableKeyboardNav();		
		new Effect.Fade( 'lightbox', {
			duration: 1.0,
			afterFinish: function() {
				Element.remove('lightbox');
				Element.setInnerHTML( 'category-title', 'Browse Our Folio');
				new Effect.Appear('placeholder', {
					duration: 1.0,
					afterFinish: function () {
						myLightbox.initialize();
					}
				});
			}
		});
	}

};

// -----------------------------------------------------------------------------------

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();

	if(key == 'x'){
	}
}

// -----------------------------------------------------------------------------

//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }

// -----------------------------------------------------------------------------
// initializer functions, these functions are the glue to get the ball rolling.
//

function initSplashPage() {

	if (!document.getElementById('splash')) return;

	mySplashPage = new SplashPage();

}

function initDhtmlPages() {

	if (!document.getElementById('content')) return;

	myDhtmlPages = new DhtmlPages();

}

function initRotaQuota() {

	if (!document.getElementById('rota-quota')) return;

	myRotaQuota = new RotaQuota();

}

function initLightbox() {

	if (!document.getElementById('folio-viewport')) return;

	myLightbox = new Lightbox();
}

// -----------------------------------------------------------------------------
// Event Observers, set the wheels in motion.
//

// SplashPage uses dom.js to fire, otherwise the entry link is not converted in time.
//Event.observe(window, 'load', initSplashPage, false);
// I'm thinking I need to fire the DhtmlPages the same way as SplashPage?
Event.observe(window, 'load', initDhtmlPages, false);
// These two don't bother the overall functionality, they can stay as is.
Event.observe(window, 'load', initRotaQuota, false);
Event.observe(window, 'load', initLightbox, false);
