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

With changes from UNC GA

Depends on prototype and system/modules/javascript/ajax_utils.js

*/

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

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

// the currently open lightbox
// assuming only one will be open at a time.
//
// to close the open lightbox do openLightbox.deactivate()
var openLightbox = null;


// open a lightbox by name, not by attaching to anchor
var lightBoxesByName = new Object();

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

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

function lb_observe_keypress()
{
	Event.observe(document, 'keypress', lb_keypress, false);
}

function lb_keypress(e)
{


	// http://users.fmg.uva.nl/rgrasman/jscript/2005/07/capturing-escape-esc-key-in-javascript.html
	
	if($('lightbox').style.display=='block') {

		var kC  = (window.event) ?  // MSIE or Firefox?
			event.keyCode : e.keyCode;

		var Esc = (window.event) ?   
			27 : e.DOM_VK_ESCAPE // MSIE : Firefox

		if(kC==Esc) {
			openLightbox.deactivate();
		}
	}
		

   // still process the key press
   return true;
}

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

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

Event.observe(window, 'load', lb_observe_keypress, false);

function resizeLightbox() 
{
	var max_height;

	// http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
	if (window.innerHeight) 
		max_height = window.innerHeight;
	else if (document.documentElement.clientHeight)
		max_height = document.documentElement.clientHeight;
	else if (document.body.clientHeight)
		max_height = document.body.clientHeight;
	else
		max_height = 580;

	max_height -=80; // leave space


	// resize current lightbox to fit size of contents.
	if (openLightbox != null ) {

		// in IE, it only returns the correct # the second time you
		// retrieve it. may have something to do with window
		// still loading???
		lb_height = $('lightbox').scrollHeight;
		lb_height = $('lightbox').scrollHeight;

		if (lb_height > max_height) {
			lb_height = max_height;
		}


		// hack: firefox is not adding bottom margin to scrollHeight
		if (browser == 'Netscape Navigator') {
			lb_height += 10;
		}
		
		$('lightbox').style.height = lb_height+'px';
		$('lightbox').style.marginTop = -(lb_height/2)+'px';

		var lb_height = $('lightbox').scrollHeight;
	}
	
}


var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl, add_parameter, func_call_mode, new_href, on_success) {
		// in func_call_mode, lb will be shown in response to a function,
		// not because of an onClick event response automatically added to
		// an anchor by lb library. must supply new_href.
		//
		// in func_call mode, ctrl is a  lightbox name, not an actual
		// ctrl object

		if (func_call_mode)
			this.setURL(new_href, add_parameter);
		else
			this.setURL(ctrl.href, add_parameter);

		if (!func_call_mode ) {
			Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
			ctrl.onclick = function(){return false;};
		}
		else {
			lightBoxesByName[ctrl]=this;
		}
		this.on_success = on_success;
	},
	
	setURL: function( url, add_parameter){

		if (add_parameter) {
			if (url.indexOf('?') == -1 ) {
				this.content = url + '?lightbox=1';
			}
			else if (url.charAt(url.length-1)=='?') {
				this.content = url + 'lightbox=1';
			}
			else {
				this.content = url +'&lightbox=1';
			}
		}
		else {
			this.content = url;
		}
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){


		// is open already
		if ($('lightbox').style.display=='block')
			return;


		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}

		$('lightbox').style.height = '100px'; 
		$('lightbox').style.marginTop = '-50px';

		this.displayLightbox("block");

		openLightbox = this;
	},
	
	// 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') this.loadInfo();
	},
	
	// Begin Ajax request based off of the href of the clicked link
	loadInfo: function() {

		$('lightbox').className = 'loading'; 

		// must have something in it for spin_div to look right.
		$('lightbox').innerHTML	= '&nbsp;'

		try {
			ajax_spin_div('lightbox', 24, 24);
		} catch (e) {}

		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", evalScripts: true, onComplete: this.processInfo.bindAsEventListener(this)}
		);
	},
	
	// Display Ajax response
	processInfo: function(response){
		// has to have something in it for spin div to work.
		//$('lightbox').innerHTML="&nbsp;"; 
		
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		
		// insert instead of innerHTML= so that JS will run.
		Element.update($('lightbox'), info)
		//new Insertion.Top($('lightbox'), info)
		$('lightbox').className = "done";	
		this.actions();		
		
		if (this.on_success != null)
			eval(this.on_success);
			
		resizeLightbox(); // -dd
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');
		
		if (lbActions == null)
			return;

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},
	
	// 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)}

	   );

	 

	},
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){

		// destroy swfupload buttons in lightboxes
		try {
			if ( (typeof SWFUpload) == 'object' 
					|| (typeof SWFUpload) == 'function' ) {
				var object =  SWFUpload.instances;

				for (var key in object) {
					try {
  						if (object[key].customSettings.inLightbox) {
							object[key].destroy();
						}
					} catch (err) {}
				}
			}
		}
		catch (err) {}
		
		Element.remove($('lbContent'));
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displayLightbox("none");
		openLightbox = null;


	}
}

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

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

	lbox = document.getElementsByClassName('lbOnParam');
	
	if (lbox != null)
	{
		for(i = 0; i < lbox.length; i++) {
			valid = new lightbox(lbox[i], true);
		}
	}
}

// add new lightbox activate/deactivate links.
// used for a div that was just updated,
// that contains possible new lightbox links.

function addLightboxLinks(div_id) {

	lbox = $(div_id).getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i], false);
	}

	lbox = $(div_id).getElementsByClassName('lbOnParam');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i], true);
	}

	// also register actions like 'Close'
	if (openLightbox != null ) {
		lbActions = $(div_id).getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', openLightbox[lbActions[i].rel].bindAsEventListener(openLightbox), false);
			lbActions[i].onclick = function(){return false;};
		}
	}

}



// register lightbox by name
// used to create lightbox when there is no link on the page
//
// new_href, add_parameter are optional.

function registerLightBoxByName(name, new_href, add_parameter)
{
	if (add_parameter == null)
		add_parameter = false;
		
	valid = new lightbox(name, add_parameter, true, new_href);
}

// activate lightbox by name 

function activateLightBoxByName(name, new_href, add_parameter, on_success)
{
	if (lightBoxesByName[name] == null) {
		valid = new lightbox(name, add_parameter, true, new_href, on_success);
	}

	if (new_href != null)
		lightBoxesByName[name].setURL(new_href, true);
		
	lightBoxesByName[name].activate();
}

// can use this instead of registerLightBoxByName and 
// activateLightboxByName

function activateLightBox(new_href, add_parameter, on_success)
{
	activateLightBoxByName('default', new_href, add_parameter, on_success);
}


// deactivate
function deactivateLightBoxByName(name)
{
	lightBoxesByName[name].deactivate();
}



//----------------------------------
// serialize a form and submit it to url,
// then replace replace_div 
// with the results.
//
// note that prototype serializes the value of
// all buttons, not just the one clicked.
//
// @param url - url to submit to
// @param form_name - name of the form to submit
// @param replace_div - the div to replace with
// 		results.
//----------------------------------

function submitAjaxForm(url, form_name, replace_div) {
	var ajax = new Ajax.Updater(
	{success: replace_div},
	url,
	{method: 'post', parameters: Form.serialize(form_name), onFailure: reportLightboxError, evalScripts: true});
	return false;
}


function reportLightboxError(error) { 
	alert('Could not process request, please refresh page and try again');
}


// 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() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	lb.className 	= 'loading';

	//lb.innerHTML	= '<div id="lbLoadMessage"></div>';
	
	bod.appendChild(overlay);
	bod.appendChild(lb);
}
