/*
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);//Runs the initialize function when the window loads
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);


var imageArray = new Array();
var lightbox = Class.create();
var itemDisplay = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,
	imageIndex : null,
	imageTopic : null,
	managerDisplay : false,
	bDeleteLink : false,
	
	initialize: function(ctrl){
		if(ctrl.rel == 'manager'){
			this.managerDisplay = true;
			this.content = ctrl.href;
			if(ctrl.rev){
				this.bDeleteLink = true;
			}
		}
		else{
			//The rel attribite stores the imageIndex to be used.
			if(ctrl.rel && ctrl.rel != null && ctrl.rel != ''){
				this.imageIndex = ctrl.rel;
			}
			else{
				return false;
			}
			//The rev attribite stores the topic to be used.
			if(ctrl.rev && ctrl.rev != null && ctrl.rev != ''){
				this.imageTopic = ctrl.rev;
			}
			else{
				return false;
			}
			this.imageSource = ctrl.href;
			this.content = '/' + this.imageTopic + '/' + '?page=picture&i=' + this.imageIndex;
		}
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
	
		//If we are deleting something ask for a confirmation
		if(this.bDeleteLink == true){
			if(confirm('Are you sure?') == false){
				return false;
			}
		}
	
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		
		this.displayLightbox("block");
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// 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(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none'){
			Event.observe('overlay', 'click', this.deactivate.bindAsEventListener(this), false);
			Event.observe('lightbox', 'click', this.deactivate.bindAsEventListener(this), false);
			this.loadInfo();
		}
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		if(this.lightboxContent != null){
			this.processInfo(null);
			return;
		}		
				
		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
		
	},
	
	processInfo: function(response){
		//if there is something displayed in the target area displayed, close it
		if(document.getElementById('lbContent')){
			Element.remove($('lbContent'));
		}

		if(this.managerDisplay == true){		
			info  = '<div id="lbContent" style="overflow:auto;text-align:left;">';
		}
		else{	
			info  = '<div id="lbContent">';
		}
		
		if((this.imageIndex == null || this.imageTopic == null) && this.managerDisplay == false){
			info += 'Error displaying requested image.';
		}
		else{
 			info += response.responseText;
		}
		info += '</div>';		
		
		//Insert the found/generated code
		new Insertion.Before($('lbLoadMessage'), info);				
		
		//Make it display
		$('lightbox').className = "done";
	
		this.actions();
	},
		
	// Search through new links within the lightbox, and attach click event
	actions: function(){
			
		//Attach lightbox actions to any links within the lightbox
		lbox = document.getElementsByClassName('lbAction',document.getElementById('lightbox'));//Will be depricated in future version!!
		//Initialize lightBox
		for(i = 0; i < lbox.length; i++) {
			valid = new lightbox(lbox[i]);
		}

		//Attach the onload Handler to the image
		this.imageObj = new Image();
		this.imageObj.onload = this.alignAndDisplay.bind(this);
		this.imageObj.onerror = this.alignAndDisplay.bind(this);
		this.imageObj.onabort = this.alignAndDisplay.bind(this);
		this.imageObj.src = this.imageSource;//imgUrl;
	},
	
	alignAndDisplay: function(){
		
		var containerElement = document.getElementById('lbMain');
		if(containerElement == null){
			return;
		}
		var imgElement = containerElement.getElementsByTagName('img')[0];
		if(imgElement == null){
			return;
		}
		applyStyle(this.imageObj,imgElement,containerElement,6,true,0.1,30);
	},

	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(e){
		
		var target = e.target || e.srcElement;
		//Deactivate if clicked in the correct element
		if (target.id && (target.id  == 'overlay' || target.id  == 'lightbox')){
			this.closeLightBox();
		}
	},
	
	closeLightBox: function(){
		if(document.getElementById('lbContent')){
			Element.remove($('lbContent'));
		}		
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		this.displayLightbox("none");
	}
}

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

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

	function applyStyle(imageObj,imageElement,containerElement,borderCorrection,doFadeIn,fadeStep,fadeInterval){
		
		//If we do not have an image Object, show anyway
		if(imageObj == null){
			if(imageElement != null){
				imageElement.style.visibility = 'visible';
			}
			return;
		}
		
		if(imageObj.width == 0 && imageObj.height == 0){
			imageElement.src = '/pics/error404.gif';

			imageObj.width = 300;
			imageObj.height = 200;
			
			imageElement.style.borderWidth = 0;
			imageElement.style.padding = 0;
			borderCorrection = 0;
			
			//Make the background color the same as that of the parent of the container
			imageElement.style.backgroundColor = Element.getStyle(containerElement.parentNode,'background-color');			
		}
		
		if(doFadeIn == true){
			
			//Set the elements opacity to 0 if we are using explorer
			if (browser == 'Internet Explorer'){			
				containerElement.filters.alpha.opacity = 0;
			}
			fadeIn(containerElement.id,fadeStep,fadeInterval);
		}
		imageElement.style.visibility = 'visible';
		
		//Stop displaying the loading image
		containerElement.parentNode.style.backgroundImage = 'none';
	}

	function setOpacity(element,level){
		
		if (browser == 'Internet Explorer'){
			element.filters.alpha.opacity = parseInt(parseFloat(level)*100);
		}
		else{
			element.style.opacity = level;
		}		
	}
	function getOpacity(element){	
		
		var opacity = '';
		
		if (browser == 'Internet Explorer'){
			opacity = element.filters.alpha.opacity;
			opacity = parseInt(opacity)/100;
		}
		else{
			opacity = element.style.opacity;
		}	
			
		return parseFloat(opacity);
	}
	
	function fadeIn(elementId,step,interval){

		if(!step || !interval){
			return;
		}
		
		var element = document.getElementById(elementId);
		if(!element){
			return;
		}

		var currentOpacity = getOpacity(element);
		if(!currentOpacity && currentOpacity != 0){
			//Set the opacity to 0 and start the fading process
			setOpacity(element,'0');			
		}
		else{
			//We are done fading in
			if(currentOpacity == 1){
				return;
			}
			//Fade in
			setOpacity(element,currentOpacity + parseFloat(step));
		}
		setTimeout("fadeIn('" + element.id + "',"+ step +","+ interval +")",parseInt(interval));
	}
	