/* TILightbox: the Tierra Interactive Lightbox (inline popup)
   Display remote content in a lightbox using AJAX
   
   Two ways to initialize the lightbox:
   
   1)
   var pageWide = new TILightbox('a[rel*=lightbox]', options);
   
   2)
   var singleton = new TILightbox($('some-id'), options);
*/

var TILightbox = new Class({
	Implements: [Options, Events],
	Binds: ['close'],
	options: {
		baseHref: '/images/', // This overrides baseHref in all option objects below
		
		useWaiter: false,
		parentSelector: '', // necessary to grab the element to overlay with the waiter
		waiterOptions: { // Supports all options that Waiter supports; these are our custom defaults
			containerProps: {
				styles: {
					top: 'auto',
					left: 'auto',
					bottom: '0px',
					right: '0px'
				}
			},
			img: {
				src: 'loading.gif',
				styles: {
					width: 'auto', height: 'auto',
					position: 'absolute',
					bottom: '5px',
					right: '5px'
				}
			},
			layer: { styles: { 'background-color': '#fff', opacity: .4 } }
		},
		
		useUI: true,
		uiOptions: { // Supports all options normally supported by StickyWin.UI; these are defaults
			width: '400px',
			cssClassName: 'popup'
		},
		
		useModal: true,
		modalOptions: { // Supports all normal modal options; these are defaults
			modalStyle: {
				'background-color': '#643B25',
				'opacity': .6
			}
		}
	},
	items: [],
	active: null,
	
	initialize: function(element, options) {
		this.setOptions(options);
		
		if ($type(element) == 'string') {
			this.items = $$(element);
		} else {
			this.items = [element];
		}
		
		this.items.each(function(el) {
			el.lightbox = this;
			el.addEvent('click', this.open);
		}.bind(this));
	},
	
	open: function(e) {
		if ($chk(e)) e.stop();
		
		var opt = this.lightbox.options;
		
		// Set up the waiter
		if (opt.useWaiter) {
			var parent = this.getParent(opt.parentSelector);
			var waiterOptions = $merge({ baseHref: opt.baseHref }, opt.waiterOptions);
			parent.wait(waiterOptions);
		}
		
		// Set up the modal box
		// Never-changing values
		var winOptions = {
			url: this.get('href'),
			modalize: opt.useModal,
			wrapWithUi: opt.useUI,
			onDisplay: function() {
				if (opt.useWaiter)
					parent.release();
				if ($type(opt.onDisplay) == 'function')
					opt.onDisplay();
			}
		};
		// Add modal and UI values if necessary
		if (opt.useModal) {
			winOptions.modalOptions = opt.modalOptions;
		}
		if (opt.useUI) {
			winOptions.uiOptions = $merge({ baseHref: opt.baseHref }, opt.uiOptions);
		}
		
		// Create the actual window
		this.lightbox.active = new StickyWin.Modal.Ajax(winOptions).update();
		return this.lightbox.active;
	},
	
	close: function(e) {
		if ($chk(e)) e.stop();
		if ($type(this.active)) {
			this.active.hide();
		}
	}
});