/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

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

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
// jwl: added from old lightbox, Prototype doesn't have anything like this
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = [pageWidth,pageHeight,windowWidth,windowHeight];
	return arrayPageSize;
}

function getPageScroll() {
	var yPos = 0;
	if (self.pageYOffset) {
		yPos = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){
		yPos = document.documentElement.scrollTop; 
	} else if (document.body) {
		yPos = document.body.scrollTop;
	}
	return yPos;
}
/*-----------------------------------------------------------------------------------------------*/

Event.observe(window, 'load', initialize, false);
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox2 = Class.create();

Object.extend(lightbox2.prototype, {

	initialize: function(links, showLoading) {
		this.links = (links.href ? new Array(links) : links);
		this.showLoading = (showLoading ? true : false);
		this.activeContent = 0;
		var index = 0;
		this.links.each(function(o) {
			Event.observe(o, 'click', this.activate.bindAsEventListener(this, index++));
		}.bind(this));
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(e, index) {
		Event.stop(e);
		if(index >= 0 && index < this.links.size()) {
			this.activeContent = index;
			if(browser == 'Internet Explorer'){
				this.hideSelects('hidden');
			}
			this.displayLightbox();
		}
	},

	next: function() {
		if(this.activeContent < this.links.length-1) {
			this.activeContent++;
			this.loadInfo();
		}
	},

	prev: function() {
		if(this.activeContent > 0) {
			this.activeContent--;
			this.loadInfo();
		}
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	displayLightbox: function() {
		if(browser == 'Internet Explorer') {
			var pageSizes = getPageSize();
			var pageScroll = getPageScroll();
			Element.setStyle('lbOverlay', {height: pageSizes[3]+'px', top: pageScroll + 'px'});
			Element.setStyle('lbContentContainer', {top: pageScroll + (pageSizes[3] / 15) + 'px'});
		}

		new Effect.Appear('lbOverlay', { duration: 0.0, from: 0.0, to: 0.8 });
		
		$('lbContentContainer').setStyle({display: 'block'});
		$('lbContent').setStyle({width: 'auto', visibility: 'hidden'});
		this.loadInfo();
	},

	hideLightbox: function() {
		new Effect.Fade('lbOverlay', { duration: 0.0, afterFinish: function() { $('lbOverlay').hide(); }});
		$('lbContentContainer').setStyle({display: 'none'});
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		if(this.showLoading) $('lbLoading').show();
		var activeObject = this.links[this.activeContent];
		if(activeObject.href) {
			if(activeObject.href.match(/jpg|gif|png/)) {
				this.processInfo('<img class="lightbox-chunk lightbox-image" src="' + activeObject.href + '" />');
			}
			else {
				var myAjax = new Ajax.Request(activeObject.href,
							      {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this), evalScripts: true});
			}
		}
	},

	// Display Ajax response
	processInfo: function(response) {
                Position.prepare();
		var content = $('lbContentDynamic');

		content.update(response.responseText ? response.responseText : response);

		var rightArrow, leftArrow;
		if((rightArrow = $('right-arrow')) && (leftArrow = $('left-arrow'))) {
			Event.observe($('left-arrow'), 'click', function() {
					this.prev();
				}.bind(this));
			Event.observe($('right-arrow'), 'click', function() {
					this.next();
				}.bind(this));
			if(this.activeContent == 0)
				$('left-arrow').hide();
			else if(this.activeContent == this.links.length-1)
				$('right-arrow').hide();
		}
		
		/*  Oi.  I really want to look into narrative javascript for some of this stuff */
		setTimeout(this.finishInfo.bind(this), 100);
	},
	
	finishInfo: function() {
		var w = 0;
		$$('.lightbox-chunk').each(function(o) {
				w += o.getWidth();
			});
		w = w || 250;
		if(w < 15) {
			/* 15 px?  It's probably not fully loaded yet */
			setTimeout(this.finishInfo.bind(this), 100);
			return;
		}
		
		$('lbLoading').hide();
		Element.setStyle($('lbContent'), {width: w + 'px', visibility: 'visible'});
	},
	
	addFooter: function(element) {
		new Insertion.Bottom(element, '<div id="lbClose"><span class="close" />close</span>' +
				              '<img src="/images/tricycle.gif" alt="Tricycle" class="logo" /><div class="kill"></div></div>');
		var closeImg = document.getElementsByClassName('close', element)[0];
		Event.observe(closeImg, 'click', function() { this.deactivate(); }.bind(this));
		Element.setStyle(closeImg, {cursor: 'pointer'});
	},
	
	deactivate: function(){
		var content = $('lbContent');
		if(content) {
			if (browser == "Internet Explorer"){
				this.hideSelects("visible");
			}
		
			this.hideLightbox();
		}
	}
});

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

// Make the links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	$$('.lightbox').each(function(o) {
		new lightbox2(o);
	});
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
	var bod = document.getElementsByTagName('body')[0];
	var lbOverlay = document.createElement('div');
	lbOverlay.id = 'lbOverlay';
	Element.hide(lbOverlay);
	var lbContentContainer = document.createElement('div');
	lbContentContainer.id = 'lbContentContainer';
	var lbContent = document.createElement('div');
	lbContent.id = 'lbContent';
	var lbContentDynamic = document.createElement('div');
	lbContentDynamic.id = 'lbContentDynamic';
	var lbLoading = document.createElement('div');
	lbLoading.id = 'lbLoading';
	Element.hide(lbLoading);
	lbLoading.update('<img src="/images/loading.gif" alt="Loading..." />');

	lbContent.appendChild(lbContentDynamic);
	lbContentContainer.appendChild(lbContent);
	bod.appendChild(lbOverlay);
	bod.appendChild(lbContentContainer);
	bod.appendChild(lbLoading);
	lightbox2.prototype.addFooter(lbContent);

	Event.observe(lbContent, 'click', function(e) { Event.stop(e); });
	Event.observe(lbContentContainer, 'click', function() { lightbox2.prototype.deactivate(); });
	Event.observe(lbOverlay, 'click', function() { lightbox2.prototype.deactivate(); });

	lbOverlay.addClassName(current_color + '-overlay');
}
