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

// Removed the line below, b/c as of prototype 1.6, Event.unloadCache has been removed
//Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,
	contentType : '',
	inlineContent : '',

	initialize: function(ctrl) {				
		this.content = ctrl.href;

		if ( ctrl.hasClassName('image') ) {
			this.contentType = 'image';
		}
		if ( ctrl.hasClassName( 'inline-image' ) ) {
			this.contentType = 'inline-image';
			pieces = this.content.split(/#/);
			id = pieces[1];
			this.inlineContent = document.getElementById(id).innerHTML;
                        this.inlineContent = this.inlineContent.replace(/<a class="image" href=(.*)><\/a>/, "<img src=$1 />");
		}
		if ( ctrl.hasClassName( 'inline' ) ) {
			this.contentType = 'inline';
			pieces = this.content.split(/#/);
			id = pieces[1];
			this.inlineContent = document.getElementById(id).innerHTML;
		}
		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.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){
		var 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){
		if(display != 'none') {
			var loadResult = this.loadInfo();
			
			if ( loadResult ) {
				new Effect.Appear('overlay', {duration: 0.35});
				$('lbWrapper').style.display = display;
	
				setTimeout("Effect.SlideDown('lightbox', {duration: 0.8});", 400);
			}
		}
		
		else if ( display == 'none' ) {
			new Effect.SlideUp('lightbox', {duration: 0.8});
			

			setTimeout("$('lbWrapper').style.display = '"+display+"'; Effect.Fade('overlay', {duration: 0.35});", 900);
		}
		
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		if ( this.contentType == 'image' ) {
			$('lbContent').update('<div id="top-decoration"><span id="title">Item Closeup</span><a href="" rel="deactivate" class="lbAction"><img src="/images/topclose.gif" height="20" hspace="7" width="20" class="right-button" /></a></div><div id="lightbox-container"><div id="content-container" class="hasImage"><img src="'+this.content+'" valign="middle" align="center" /></div> <!-- div#content-container --></div> <!-- div#container -->');

			this.actions();
		}
		else if ( this.contentType == 'inline-image' ) {
			$('lbContent').update('<div id="top-decoration"><span id="title">Item Closeup</span><a href="" rel="deactivate" class="lbAction"><img src="/images/topclose.gif" height="20" hspace="7" width="20" class="right-button" /></a></div><div id="lightbox-container"><div id="content-container" class="hasText">'+this.inlineContent+'</div> <!-- div#content-container --></div> <!-- div#container -->');
			
			this.actions();
		}
		else if ( this.contentType == 'inline' ) {
			$('lbContent').update('<div id="top-decoration"><span id="title">Item Review</span><a href="" rel="deactivate" class="lbAction"><img src="/images/topclose.gif" height="20" hspace="7" width="20" class="right-button" /></a></div><div id="lightbox-container"><div id="content-container" class="hasText">'+this.inlineContent+'</div> <!-- div#content-container --></div> <!-- div#container -->');
			
			this.actions();
		}
		else {
			var request_url = prepareHref(this.content);
		
			var myAjax = new Ajax.Request(
	  				request_url,
	  				{method: 'get', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
			);
		}
		
		return 1;
	},
	
	// Display Ajax response
	processInfo: function(response){
	
		var info = response.responseText;
	
		$('lbContent').update(info);

		$('lightbox').className = "done";
	
		this.actions();
		
	},
	
	actions: function(){

		// Search through new links within the lightbox, and attach click event.

		var lbActions = document.getElementsByClassName('lbAction');

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

	        // Ajaxify form submissions within the lightbox

		var forms = $('lbContent').getElementsByTagName('form');

		for (var i=0; i<forms.length; i++) {
		    ajaxifyLightboxForm(forms[i]);
		}
	},
	
	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
		var link = Event.element(e);
		
		contentType = '';
				
		if ( link.hasClassName('image') ) {
			$('lbContent').update('<img src="'+link+'" />');
			$('lightbox').className = "done";
			this.actions();
		}
	 
		var myAjax = new Ajax.Request(
			  							prepareHref(link.href),
			  							{
			  								method: 'get',
			 							 	parameters: "",
						 					onLoading: function() {
												var lbContent = $('content-container');
												lbContent.update('<img src="/images/ajax-loader-darkgreen.gif" style="margin: 195px 0 0 152px;" />');
											},
											onComplete: this.processInfo.bindAsEventListener(this)
										}
										);	 
	},
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		
		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(){
	addLightboxMarkup();
	lightboxify($$('.lbOn'));
}

function lightboxify(elements) {

	for (var i=0; i<elements.length; i++) {
	    new lightbox(elements[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() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	overlay.style.display = 'none';
	loadingBox 			= document.createElement('div');
	loadingBox.id		= 'loading';


	lbWrapper					= document.createElement('div');
	lbWrapper.id				= 'lbWrapper';
	lbWrapper.style.display		= 'none';
	lbWrapper.innerHTML	= '<div id="lightbox" style="display: none; ">' +
						  	'<div id="lbContent"></div>' +
						  '</div>';
	bod.appendChild(overlay);
	bod.appendChild(lbWrapper);
}

/*-----------------------------------------------------------------------------------------------*/
/* Ajaxify form submissions within the lightbox - TTL specific                                   */
/*-----------------------------------------------------------------------------------------------*/

function ajaxifyLightboxForm( formelem ) {

    // Rewrite form's action to POST to ajax + lightbox url

    var action = formelem.readAttribute('action');
    action += '?ajax=1&lb=1';
    formelem.writeAttribute('action', action);

    formelem.onsubmit = function() {

		var ajaxopts = {};
		ajaxopts.method = 'POST';
		ajaxopts.parameters = this.serialize(true);
	
		ajaxopts.onSuccess = function(rsp) {
	
		    // Replace lightbox content with ajax response content.
		    // Leave lightbox header, footer, and sidenav links alone.
	
		    var ajax_content = document.createElement("div");
		    ajax_content.innerHTML = rsp.responseText;
		    ajax_content = $(ajax_content).select('div#ajaxContent')[0].innerHTML;
	
		    $$('div#ajaxContent').each(
				function (elem) {
				    elem.update(ajax_content);
				    
				    //scroll back to the top on form response
					document.getElementById('content-container').scrollTop = 0;
				}
		    );
	
	            // Ajaxify form submissions within the new lightbox content.
	
	            $('lbContent').select('form').each(
					function (elem) {
	                    ajaxifyLightboxForm(elem);
					}
	            );
	         
		};
	
		ajaxopts.onFailure = function(rsp) {
		    alert("there was an error submitting the form, please try again")
		};
	
		var req = new Ajax.Request(this.readAttribute('action'), ajaxopts);
		return false;
    };
}

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

function prepareHref(request_url) {
	var browserURL = document.location.href;
	var secureURL = 0;
		
	if ( browserURL.indexOf("https:") > -1 ) {
		secureURL = 1;
	}
	
	
	if ( secureURL && (request_url.indexOf("http:") > -1) ) { // solve same-domain problem for SSL url / non-SSL'ed link
		request_url = "https:" + request_url.slice(5,request_url.length);
	}
	else if ( !secureURL && (request_url.indexOf("https:") > -1) ) { // solve same-domain problem for nonSSL url / SSL'ed link
		request_url = "http:" + request_url.slice(6,request_url.length);
	}
	
	


	if ( request_url.indexOf('?') == -1 ) {
		request_url += '?ajax=1&lb=1';
	}
	else {
		// if ajax doesn't exist in string, append &ajax=1
		if ( request_url.indexOf('ajax=1') == -1 ) {
			request_url += '&ajax=1';
		}
		if ( request_url.indexOf('lb=1') == -1 ) {
			request_url += '&lb=1';
		}
		
	}

	return request_url;
}
