
var Lightbox = Class.create({
	
	initialize: function(content, options)
	{
		this.overlay = $('pageoverlay');
		this.lightbox = $('lightbox');
		this.container = $('lightboxContent');
		this.overlayContainer = $('overlays');
		
		this.content = $(content);
		
		this.options = options || {};		
		this.before = this.options.before;
		this.after = this.options.after;
		this.width = this.contentWidth = this.options.width || this.content.getWidth();
		this.height = this.contentHeight = this.options.height || this.content.getHeight();		
		this.hasScrolling = this.options.hasScrolling || false;
		this.allowClose = this.options.allowClose || true;

		this.halt = false;
	},
	
	visible: function()
	{
		return this.lightbox.visible();
	},
	
	resize: function()
	{		
		this.close = this.lightbox.select('div.close a').first();
		var topLeft = this.lightbox.select('div.topLeft').first();
		var topRight = this.lightbox.select('div.topRight').first();
				
		// FOR OPERA AND OTHER ERRANT BROWSERS THAT WILL NOT RETURN DIMENSIONS OF A HIDDEN ELEMENT
		var showHideToCalc = !parseInt(topLeft.getStyle('width'), 10); 
		if (showHideToCalc) this.lightbox.show();
		
		this.closeWidth = parseInt(this.close.getStyle('width'), 10);
		var topLeftSize = { width: parseInt(topLeft.getStyle('width'), 10), height: parseInt(topLeft.getStyle('height'), 10) };
		var topRightSize = { width: parseInt(topRight.getStyle('width'), 10), height: parseInt(topRight.getStyle('height'), 10) };

		if (showHideToCalc) this.lightbox.hide();

		this.width = this.contentWidth + topLeftSize.width + topRightSize.width;
		this.height = this.contentHeight + topLeftSize.height + topRightSize.height;

		this.close.setStyle({ marginLeft: this.width+'px' });
		
		if (Prototype.Browser.IE && !Prototype.Browser.IE8)
		{ 
			this.lightbox.select('div.close').first().setStyle({ marginTop: -this.height+'px' });			
		}
		if (Prototype.Browser.IE6)
		{
			this.lightbox.select('div.leftIE').first().setStyle({ height: this.contentHeight + 'px' });			
			this.lightbox.select('div.rightIE').first().setStyle({ height: this.contentHeight + 'px' });						
		}
		
		this.lightbox.setStyle({ width: this.width + 'px', height: this.height + 'px' });		
		this.lightbox.select('div.close').first().setStyle({ width: (this.width + this.closeWidth) + 'px' });		
		this.lightbox.select('div.top').first().setStyle({ width: this.contentWidth + 'px' });
		this.lightbox.select('div.bottom').first().setStyle({ width: this.contentWidth + 'px' });
		this.lightbox.select('div.left').first().setStyle({ width: (this.contentWidth + topLeftSize.width) + 'px', height: this.contentHeight + 'px' });
		this.lightbox.select('div.right').first().setStyle({ width: this.contentWidth + 'px', height: this.contentHeight + 'px' });
	},
	
	events: function()
	{
		this.close.onclick = function(e) {
			Event.stop(e);
			this.hide();
		}.bindAsEventListener(this);
	},
	show: function()
	{
	   show(true);
	},
	
	show: function(showclose)
	{		
		if (this.halt) return;
		this.halt = true;

		if (this.before)
			this.before();
		
		this.resize();
		this.events();
		
		if(showclose==false)
	   {
		   this.close.setStyle({ display: 'none' });
		}
		else
		   this.close.setStyle({ display: 'block' });
		
		
		var previousContent = this.container.firstDescendant();
		if (previousContent) 
		{
			previousContent.hide();
			this.overlayContainer.appendChild(previousContent);
		}
		this.container.update('');

		this.container.appendChild(this.content);
		this.content.show();
				
		// POSITION FIXED IS BROKEN IN IE6		
		if (this.overlay.getStyle('position') == 'absolute')
		{
			this.overlay.setStyle({
				width: (document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollWidth : document.body.offsetWidth) + 'px', 
				height: (document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight) + 'px'
			});			
		}

		var x = Math.round(((window.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth)) - this.width) / 2);
		var y = Math.round(((window.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight)) - this.height) / 2);

		// RESET FIXED POSITION
		this.lightbox.setStyle({ position: 'fixed' });		

		// IE6 CANNOT DO FIXED POSITIONING
		if (Prototype.Browser.IE6)
			this.lightbox.setStyle({ position: 'absolute' });		

		// SAFARI HAS PROBLEMS WITH OVERFLOW AUTO AND FIXED POSITIONING
		if (Prototype.Browser.WebKit)		
			if (this.hasScrolling)
				this.lightbox.setStyle({ position: 'absolute' });

		// POSITION FIXED IS BROKEN IN IE6
		if (this.lightbox.getStyle('position') == 'absolute')
		{
			x += (window.pageXOffset || (document.documentElement.scrollLeft || document.body.scrollLeft));
			y += (window.pageYOffset || (document.documentElement.scrollTop || document.body.scrollTop));

			this.selectHide();
		}

		var marginLeft = Math.round(-this.width/2);
		var marginTop = Math.round(-this.height/2);
		this.lightbox.setStyle({ top: '50%', marginLeft: marginLeft + 'px', marginTop: marginTop + 'px' });
		
		if (x < 0)
			this.lightbox.setStyle({ left: (-x/2) + 'px', marginLeft: 0, position: 'absolute' });					
		if (y < 0)
			this.lightbox.setStyle({ top: (-y/2) + 'px', marginTop: 0, position: 'absolute' });			

		var effects = [];
		
		effects.push(new Effect.Appear(this.lightbox, {from: 0.0, to: 0.999999, sync:true}));
		if (!this.overlay.visible()) effects.push(new Effect.Appear(this.overlay, {from: 0.0, to: 0.71, sync:true}));
		
		new Effect.Parallel(effects, { afterFinish: function() {
				this.overlay.onclick = function() { 
					if (this.allowClose) this.hide(); 
				}.bind(this);

				this.lightbox.setOpacity(''); 
				this.halt = false;				
			}.bind(this) });
	},
	
	hide: function()
	{
		if (this.halt) return;
		this.halt = true;
		
		var effects = [ new Effect.Fade(this.overlay, {from: 0.71, to: 0.0, sync:true}),	
							 new Effect.Fade(this.lightbox, {from: 0.999999, to: 0.0, sync:true}) ];
							
		new Effect.Parallel(effects, { afterFinish: function() {
				this.overlay.onclick = function() {};
				this.lightbox.setOpacity('');																		
				this.selectShow();
															
				if (this.after) {	this.after(); }
				this.halt = false;								
			}.bind(this) });		
	},
		
	top: function(y)
	{
		var cur = parseInt(this.lightbox.getStyle('top'),10);
		if (!y) return cur;
		
		this.lightbox.setStyle({top: (cur + y) + 'px'});
		return (cur + y);
	},
	
	selectHide: function()
	{
		// Z-INDEX IS BROKEN FOR SELECTS IN IE6		
		if (Prototype.Browser.IE6)
		{
			$$('select').each(function(x) { 
				x.setStyle({ visibility: 'hidden' });
			});

			$$('#lightbox select').each(function(x) { 
				x.setStyle({ visibility: 'visible' });
			});			
		}		
	},
	
	selectShow: function()
	{
		// Z-INDEX IS BROKEN FOR SELECTS IN IE6
		if (Prototype.Browser.IE6)
		{
			$$('select').each(function(x) { 
				x.setStyle({ visibility: 'visible' });
			});			
		}		
	}			
});

var Lightboxes = Class.create({
	
	initialize: function(selector)
	{
		this.overlays = {};
		if (!selector || typeof(selector) != 'string') return;

		this.lightbox = $('lightbox');
		if (!this.lightbox) return;

		var parts = [
			'.close a span', '.close a', '.top', '.topLeft', '.topRight', '.leftIE', 
			'.rightIE', '.left', '.right', '.bottom', '.bottomLeft', '.bottomRight', 
			'#lightboxContent', '.innerBottomLeft', '.innerBottomRight', '.overlay'
		];

		var elements = $$(selector);
		if (elements && elements.length)
		{
			elements.each(this.add.bind(this));
			this.preload(parts);
		}
	},
	
	preload: function(parts)
	{
		if (!parts || !parts.length) return;

		this.lightbox.select(parts).each(function(x) {			
			var backgroundImage = x.getStyle('backgroundImage');
			if (backgroundImage && backgroundImage != 'none')
			{
				var matches = backgroundImage.match(/url\(["']?(.*?)["']?\)/);
				var img = new Image();
				img.src = (matches[1].match(/^\.\.\//)) ? matches[1].substr(3) : matches[1];							
			}			
			if (Prototype.Browser.IE6)
			{
				var filter = x.getStyle('filter');
				if (filter)
				{
					var matches = filter.match(/src=["'](.*?)["']/);
					if (matches && matches[1]) {				
						var img = new Image();			
						img.src = matches[1];
					}
				}				
			}
		});
	},
	
	add: function(overlay)
	{
		if (overlay.id)
			this.overlays[overlay.id] = new Lightbox(overlay);
	},

	show: function(id,showclose)
	{
		if (this.overlays[id])
			this.overlays[id].show(showclose);
	},
		
	
	

	
		hide: function(id)
	{
		if (this.overlays[id])
			this.overlays[id].hide();
	}
	
	
});

var CheckForm = Class.create({

	initialize: function(selector)
	{
		this.form = $$(selector).first();
		if (!this.form) return;
		
		this.inputs = this.form.select('input[type=text]');
		
		this.inputs.each(function(x) {
			x.onfocus = this.clearOnFocus.bind(this, x);
		}.bind(this));
		
		this.form.onsubmit = this.submit.bindAsEventListener(this);
	},
	
	submit: function(e)
	{
		this.inputs.each(function(x) {
			if (!x.value.strip() || x.value == x.defaultValue)
			{
				Event.stop(e);
				throw $break;
			}
		});		
	},
	
	clearOnFocus: function(input)
	{
		input.value = '';
		$(input).addClassName('active');
		input.onfocus = function() {};
	}	
});

// GLOBAL SETUP

document.observe("dom:loaded", function() {			
	window.lightboxes = new Lightboxes('#overlays div.overlay');
	new CheckForm('#header .search form');	
});

// DEFAULT SETTINGS

Effect.DefaultOptions.duration = '0.3';

// IE VERSION DETECT
//alert(parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)));
if (Prototype.Browser.IE) Prototype.Browser['IE' + parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))] = true;//Prototype.Browser[window.XMLHttpRequest ? 'IE7' : 'IE6'] = true;
if (Prototype.Browser.IE6) try { document.execCommand("BackgroundImageCache", false, true); } catch (e) {}; 

function addOnLoad(fn)
{ 
   var old = window.onload;
   window.onload = function()
   {
       old();
       fn();
   };
}
