/*!
	Slimbox v1.7 - The ultimate lightweight Lightbox clone
	Modified version by Bjorn Enki
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/

var Slimbox = (function() {

	// Global variables, accessible to Slimbox only
	var win = window, ie6 = Browser.Engine.trident4, options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,

	// Preload images
	preload = {}, preloadPrev = new Image(), preloadNext = new Image(),

	// DOM elements
	overlay, center, image, sizer, prevLink, nextLink, bottomContainer, bottom, caption, number,

	// Effects
	fxOverlay, fxResize, fxImage, fxBottom;

	/*
		Initialization
	*/

	win.addEvent("domready", function() {
		// Append the Slimbox HTML code at the bottom of the document
		$(document.body).adopt(
			$$(
				overlay = new Element("div", {id: "lbOverlay", events: {click: close}}),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			).setStyle("display", "none")
		);

		image = new Element("div", {id: "lbImage"}).injectInside(center).adopt(
			sizer = new Element("div", {styles: {position: "relative"}}).adopt(
				prevLink = new Element("a", {id: "lbPrevLink", href: "#", events: {click: previous}}),
				nextLink = new Element("a", {id: "lbNextLink", href: "#", events: {click: next}})
			)
		);

		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			new Element("a", {id: "lbCloseLink", href: "#", events: {click: close}}),
			caption = new Element("div", {id: "lbCaption"}),
			number = new Element("div", {id: "lbNumber"}),
			new Element("div", {styles: {clear: "both"}})
		);
	});


	/*
		Internal functions
	*/

	function position() {
		var scroll = win.getScroll(), size = win.getSize();
		$$(center, bottomContainer).setStyle("left", scroll.x + (size.x / 2));
		if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
	}

	function setup(open) {
		["object", ie6 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});

		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		win[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);

		$('lbPrevLink').setStyle('opacity', '0');
		$('lbNextLink').setStyle('opacity', '0');
	}

	function keyDown(event) {
		var code = event.code;
		// Prevent default keyboard action (like navigating inside the page)
		return options.closeKeys.contains(code) ? close()
			: options.nextKeys.contains(code) ? next()
			: options.previousKeys.contains(code) ? previous()
			: false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if (imageIndex >= 0) {
			activeImage = imageIndex;
			activeURL = images[imageIndex][0];
			prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
			nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);

			stop();
			center.className = "lbLoading";

			preload = new Image();
			preload.onload = animateBox;
			preload.src = activeURL;
			pageTracker._trackPageview(activeURL.substr(24));
		}

		return false;
	}

	function animateBox() {
		center.className = "";
		fxImage.set(0);
		image.setStyles({backgroundImage: "url(" + activeURL + ")", display: ""});
		sizer.setStyle("width", preload.width);
		$$(sizer).setStyle("height", preload.height);
		$$(prevLink, nextLink).setStyle("height", '63px');

		caption.set("html", '<h3>'+images[activeImage][2]+'</h3><p>'+images[activeImage][1]+'</p>' || "");
//		number.set("html", (((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));
		Cufon('h3');

		if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
		if (nextImage >= 0) preloadNext.src = images[nextImage][0];

		centerWidth = image.offsetWidth + 13;
		centerHeight = image.offsetHeight + 12;
		var top = Math.max(0, middle - (centerHeight / 2)), check = 0, fn;
		if (center.offsetHeight != centerHeight) {
			check = fxResize.start({height: centerHeight, top: top});
		}
		if (center.offsetWidth != centerWidth) {
			check = fxResize.start({width: centerWidth, marginLeft: -centerWidth/2});
		}
		fn = function() {
			bottomContainer.setStyles({width: centerWidth - 7, top: top + centerHeight - 71, marginLeft: -centerWidth/2, visibility: "hidden", display: ""});
			fxImage.start(1);
		};
		if (check) {
			fxResize.chain(fn);
		}
		else {
			fn();
		}
	}

	function animateCaption() {
		$('lbCenter').setStyle('overflow', 'visible');
		var fxlbtn = new Fx.Morph($('lbPrevLink'), { duration: '400' });
		var fxrbtn = new Fx.Morph($('lbNextLink'), { duration: '400' });
		if (prevImage >= 0) {
			prevLink.style.display = "";
			fxrbtn.start({ 'opacity': '1' });
		}
		if (nextImage >= 0) {
			nextLink.style.display = "";
			fxlbtn.start({ 'opacity': '1' });
		}
		fxBottom.set({
			'margin-top': bottom.offsetHeight
		}).start({
			'margin-top': 0
		});
		bottomContainer.style.visibility = "";
	}

	function stop() {
		preload.onload = $empty;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		fxResize.cancel();
		fxImage.cancel();
		fxBottom.cancel();
		$$(image, bottomContainer).setStyle("display", "none");
	}

	function close() {
		$('lbCenter').setStyle('overflow', 'hidden');
		if (activeImage >= 0) {
			stop();
			activeImage = prevImage = nextImage = -1;
			center.style.display = "none";
			fxOverlay.cancel().chain(setup).start(0);
		}

		return false;
	}


	/*
		API
	*/

	Element.implement({
		slimbox: function(_options, linkMapper) {
			// The processing of a single element is similar to the processing of a collection with a single element
			$$(this).slimbox(_options, linkMapper);

			return this;
		}
	});

	Elements.implement({
		/*
			options:	Optional options object, see Slimbox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 3 elements:
					the image URL, image caption and the link text (may contain HTML)
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		slimbox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				return [el.href, el.title, el.get('html')];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredLinks = links.filter(linksFilter, this);
				return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
			});

			return links;
		}
	});

	return {
		open: function(_images, startImage, _options) {
			options = $extend({
				loop: true,				// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				overlayFadeDuration: 400,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
				resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// false uses the mootools default transition
				initialWidth: 50,			// Initial width of the box (in pixels)
				initialHeight: 50,			// Initial height of the box (in pixels)
				imageFadeDuration: 400,			// Duration of the image fade-in animation (in milliseconds)
				captionAnimationDuration: 400,		// Duration of the caption animation (in milliseconds)
				counterText: "Other Clients: {x} of {y}",	// Translate or change as you wish, or set it to false to disable counter text for image groups
				closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
				previousKeys: [37, 80],			// Array of keycodes to navigate to the previous image, default: Left arrow (37), 'p' (80)
				nextKeys: [39, 78]			// Array of keycodes to navigate to the next image, default: Right arrow (39), 'n' (78)
			}, _options || {});

			// Setup effects
			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});
			fxResize = new Fx.Morph(center, $extend({duration: options.resizeDuration, link: "chain"}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			fxImage = new Fx.Tween(image, {property: "opacity", duration: options.imageFadeDuration, onComplete: animateCaption});
			fxBottom = new Fx.Morph(bottom, {duration: options.captionAnimationDuration, wait:false, transition: Fx.Transitions.Quart.easeOut});

			// The function is called for a single image, with URL and Title as first two arguments
			if (typeof _images == "string") {
				_images = [[_images, startImage]];
				startImage = 0;
			}

			middle = win.getScrollTop() + (win.getHeight() / 2);
			centerWidth = options.initialWidth;
			centerHeight = options.initialHeight;
			center.setStyles({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2, display: ""});
			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			fxOverlay.set(0).start(options.overlayOpacity);
			position();
			setup(1);

			images = _images;
			options.loop = options.loop && (images.length > 1);
			return changeImage(startImage);
		}
	};

})();


// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	$$(document.links).filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	}).slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};
window.addEvent("domready", Slimbox.scanPage);

var scrolling=false, hoverlock=false, scrolled_last = '';
// button title functionality
	function titleset(thenum) {
		thenum--;
		var voffset = thenum*-24;
		var hoffset = 65-((thenum+1)*22);
		if(thenum == 4) { hoffset-=3; }
		$('portfolio-titles').setStyles({
			'right': hoffset+'px',
			'background-position': 'center '+voffset+'px'
		});
	}
//

window.addEvent('domready', function() {

$$('.portfolio-testim').each(function(pt) {
	var pthref = pt.get('href');
	var pthrefarr = pthref.split('#');
	var newpthref = 'http://www.bjornenki.com/portfolio#'+pthrefarr[1]+'_4';
	pt.set('href', newpthref);
});

	// testimonial functionality 
		var req = new Request({ 
			url: 'testimonials?query',
			method: 'get', 
			onComplete: function(response) {
				var responsearr = response.split('##S2##');
				var testimplacehs = $$('.portfolio-testimplaceholder');
				responsearr.each(function(ra, i) {
					var rap = ra.split('##S1##');
					var rap1 = '<blockquote>'+rap[0]+'</blockquote>';
					var rap2 = '<cite>'+rap[1]+'</cite>';
					var testimonial = rap1+rap2;
					var updatediv = testimplacehs[i];
					$(updatediv).set('html', testimonial);
				});
				(function() { Cufon('cite'); }).delay('100');
			}
		}).send(); 	
	// end testimonial functionality 



document.addEvents({
	'mousewheel': function(e) {
		scrolling = false;
		hoverlock = false;
	}
});


// add an 'x' to the end of all image ids so the browser wont scroll to them due to the anchor changing	
	$$('.section-width').each(function(sw) {
		var newid = sw.get('id')+'x';
		sw.set('id', newid);
	});
//
	
// image description functionality 
	var imgdesc = $$('.portfolio-imgdesc');
	imgdesc.each(function(idesc, i){
		idesc.setStyles({ // 'clears' the testimonials for JS users initially 
			'padding-top': '330px',
			'background-position': '0 330px'
		}); 
		var idparent = idesc.getParent();
		var fadeeffect = new Fx.Morph(idesc, {duration:500, wait:false, transition: Fx.Transitions.Quart.easeOut});
		function fadedesc(px, opacity) {
			fadeeffect.start({
				'padding-top': px, 
				'background-position': '0 '+px
			});
		}

		idparent.addEvent('mouseover', function() {
			fadedesc('245px', '1');
		});
		idparent.addEvent('mouseout', function() {
			fadedesc('330px', '0');
		});
	});
// end image description functionality 


var width_scrolls = $$('.section-width');
var hrefs = $$('.width-control');

// make each list item cause title to be white 
	function feattitwhite(liel) {
		$('portfolio-controls').getChildren().each(function(e) {
			e.removeClass('highlight');
		});
		liel.addClass('highlight');
	}

	hrefs.each(function(pli) {
		pli.addEvent('mouseover', function() {
			feattitwhite(pli.getParent());
		});
	});
// 


// create previous/next buttons 
	function prevnextbtns(i) {
		var prev, next;
		if(i==0) { prev = hrefs.length-1; next = i+1; }
		else if(i == hrefs.length-1) { next = 0; prev = i-1; }
		else { prev = i-1; next = i+1; }
		$('prev_btn').set('href', hrefs[prev]);
		$('next_btn').set('href', hrefs[next]);
		var pnbtns = $$('.portfolio_prevnext');
		pnbtns.each(function(pnb) {
			pnb.addEvent('focus', function() {
				pnb.blur();
			});
		});
	}
// 


// make each button clickable 
	hrefs.each(function(section, i){
		if(i < width_scrolls.length) {		   
			section.addEvent('focus', function() {
			   	section.blur();
			});
			section.addEvent('click', function(event){
				var thisnum = section.get('href').split('_');
				titleset(thisnum[1]);
				portdotactivate(section, width_scrolls[i].id);
				prevnextbtns(i);
			});		    
			section.addEvent('mouseover', function() {
					hoverlock = true;
					titleset(section.get('href').split('_')[1]);
			});
			section.addEvent('mouseout', function() {
					hoverlock = false;
					scrolled_last = 'reset';
			});
		}
	});						
// 
// events to trigger the title changing for links out 
	$$('.portfolio-linkout').each(function(plo) {
		plo.addEvent('mouseover', function(){
			hoverlock = true;
			titleset(5);
			feattitwhite(plo.getParent());
		});
		plo.addEvent('mouseout', function(){
			hoverlock = false;
			scrolled_last = 'reset';
		});
	});

// 


// portfolio scrolling functionality 
	var pagebox = $('portfolio-scroller');
	var scroll = new Fx.Scroll(pagebox, {
		wait: false,
		duration: 700,
		offset: {'x': -0, 'y': -0},
		transition: Fx.Transitions.Cubic.easeOut,
		onComplete: function() {
			scrolling = false;
		}
	});
// 


// function to enable portfolio dot change for active items 
	function portdotactivate(btnel, imgelid) {
		scrolling = true;
		var oldon = $$('.portdot-on');
		oldon.removeClass('portdot-on');
		btnel.addClass('portdot-on');
		scroll.toElement(imgelid);
		scrolled_last = imgelid;
	}
// 


// periodically check the anchor to determine if it's changed - for direct links or for back/forward buttons 
	var anchorcheck = function() {
		if(scrolling === false && hoverlock === false) { 
			if(location.hash == '' && scrolled_last != width_scrolls['0'].id) { 
				var firstportdot = $$('.portfolio-dot');
				portdotactivate(firstportdot['0'], width_scrolls['0'].id);
				feattitwhite($(firstportdot['0'].getParent()));
				titleset(1);
				prevnextbtns(0);
			} else if(scrolled_last != location.hash.substring(1)+'x' && location.hash != '') {
				var zc=0; var arrnum;
				var fullurl = 'http://www.bjornenki.com/portfolio'+location.hash;
				for(z in hrefs) {
					if(hrefs[zc] == fullurl) {
						arrnum = zc;
						break;
					}
					zc++;
				}
				prevnextbtns(arrnum);
				var hashdiv = location.hash.substring(1)+'x';
				var hashname = hashdiv.substring(0, hashdiv.length-3)+'-controls';
				var controls = $(hashname).getChildren();
				var hashnum = hashdiv.substring(hashdiv.length-2, hashdiv.length-1); hashnum--;
				btnel = controls[hashnum];
				hashnum++;
				titleset(hashnum);
				feattitwhite($(hashname));
				portdotactivate(btnel, $(hashdiv).id);
			}
		}
	}
	anchorcheck.periodical(50);
// 


});
