/*
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;
}

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

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

var lightbox = Class.create({
	yPos : 0,
	xPos : 0,

	initialize: function(ctrl, bind) {
		var bind = Object.isUndefined(bind) ? true : bind;
		this.content = ctrl.href;
		this.link = ctrl;
		if(bind){
			Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
			ctrl.onclick = function(){return false;};
		}
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (browser == 'Internet Explorer'){
			this.hideSelects('hidden');
		}
		this.prepareScroll('100%', 'hidden');
		this.displayLightbox("block");
		currentlightbox = this;
		Event.observe(window, 'keypress', this.deactivateOnEsc);
	},
	
	deactivateOnEsc: function(ev){
		if(ev.keyCode == Event.KEY_ESC){
			if(currentlightbox && !Object.isUndefined(currentlightbox))
				currentlightbox.deactivate();
		}
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareScroll: function(height, overflow){
		switch(overflow){
			case "hidden":
				this.implyScroll();
				htm = document.getElementsByTagName('html')[0];
				htm.style.height = height;
				htm.style.overflow = overflow;
				break;
			case "auto":
				htm = document.getElementsByTagName('html')[0];
				htm.style.height = height;
				htm.style.overflow = overflow;
			
				this.literalScroll();
				break;
		}
	},
	
	implyScroll: function(){
		bod = document.getElementsByTagName('body')[0];
		this.getScroll();
		this.setScroll(0,0);
		bod.setStyle({
			position: "relative",
			top: "-"+this.yPos+"px",
			left: "-"+this.xPos+"px"
		});
	},
	
	literalScroll: function(){
		var bod = document.getElementsByTagName('body')[0];
		bod.setStyle({position: "static", top: null, left: null});
		this.setScroll(this.xPos, this.yPos);
	},
	
	// 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;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		this.xPos = document.viewport.getScrollOffsets().left;
		this.yPos = document.viewport.getScrollOffsets().top;
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none'){
			this.monitorSize();
			this.loadInfo();
		}
	},
	
	monitorSize: function(){
		this.resizer = new PeriodicalExecuter(this.reposition, 0.1);
	},
	
	unmonitorSize: function(){
		this.resizer.stop();
	},
	
	reposition: function(){
		var lb = $('lightbox');
		if(!lb.visible()){
			lb.setStyle({marginTop: null, top: null});
		}else{
			var halfheight = parseInt(lb.getHeight())/2;
			var halfview = document.viewport.getHeight()/2;
			if(halfheight < halfview){
				lb.setStyle({marginTop: "-"+halfheight+"px", top: '50%'});
			}else{
				lb.setStyle({marginTop: 0, top: 0});
			}
		}
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		var el;
		var anchor = this.getLocalAnchor();
		if( anchor && anchor == "#empty"){
			this.processDOMContent(new Element('p'));
		}else if( anchor && (el = $(anchor.replace("#", ""))) ){
			this.processDOMContent(el.cloneNode(true).show());
		}else{
			var myAjax = new Ajax.Request(
	        this.content,
	        {method: 'get', parameters: "", onSuccess: this.processInfo.bindAsEventListener(this)}
			);
		}		
	},
	
	// Display Ajax response
	processInfo: function(response){
		var info = "<div id='lbContent'>" + response.responseText + "</div>";
		$('lbLoadMessage').insert({before: info});
		$('lightbox').className = "done";
		$('lightbox').select('.closer').invoke('show');
		this.actions();
	},
	
	// Display DOM content copied into LB.
	processDOMContent: function(content){
		var info = new Element('div', {'id': 'lbContent'});
		info.update(content);
		$('lbLoadMessage').insert({before: info});
		$('lightbox').className = "done";
		$('lightbox').select('.closer').invoke('show');
		this.actions();
	},
	
	getLocalAnchor: function(){
		var match;
		if( (this.content.include(window.location.host) && (match = this.content.match(/#.*/))) || (match = this.content.match(/^#.*/)) ){
			return match.last();
		}else{
			return false;
		}
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this));
			lbActions[i].onclick = function(){return false;};
		}
		Event.fire(this.link, 'lightbox:ready');
	},
	
	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
	   link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));
	 
	   var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	 
	},
	
	expand: function(){
		$('lbContent').select(".excerpt").invoke('hide');
		$('lbContent').select(".body").invoke('show');
	},
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		if($('lbContent')){
			$('lbContent').remove();
		}
		
		if (browser == "Internet Explorer"){
			this.hideSelects("visible");
		}
		this.prepareScroll("auto", "auto");
		$('lightbox').select('.closer').invoke('hide');
		this.displayLightbox("none");
		$('lightbox').writeAttribute('class', 'loading');
		Event.stopObserving(window, 'keypress', this.deactivateOnEsc);
		Event.stopObserving(this.link, 'lightbox:ready');
		currentlightbox = null;
	},
	
	deactivate_and_follow: function(e){
		this.deactivate();
		var el;
		if(el = e.findElement())
			window.open(el.href);
	}
});

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

// Onload, make all links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	var lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		var valid = new lightbox(lbox[i]);
	}
}

// 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 				= $$('body').first();
	var overlay 			= new Element('div', {id: 'overlay'});
	var lb          = new Element('div', {
		id: 'lightbox',
		'class': 'loading'
	});
	var closer      = new Element('a', {
		href: "#",
		'class': 'closer lbAction',
		rel: 'deactivate'
	});
		
	lb.insert(closer);
	lb.insert(new Element('p', {id: 'lbLoadMessage'}).insert("Loading..."));
	overlay.insert(lb);
	bod.insert(overlay);
	// bod.insert(lb);
}