/*
* based on Facebox by Chris Wanstrath -- http://famspam.com/facebox
* 
* :: ported to the Prototype JS library by ::
* Phil Burrows
* http://blog.philburrows.com
* peburrows@gmail.com
* Date: 3 May 2008
*
*
* Usage:
*  
* This Prototype version is setup to automatically run when the window's load event is fired (see last three lines of this file),
* so usage is as easy as adding rel="facebox" to any link you want to use Facebox
*
* AGAIN, kudos to to Chris Wanstrath and the guys from ErrFree for really putting in the brunt of the effort exerted on this
* I just spent an evening taking all their work and molding it into something that would use Prototype
*/


var Facebox = Class.create({
	initialize	: function(extra_set){
		this.settings = {
			loading_image	: '/media/loading.gif',
			image_types		: new RegExp('\.' + ['png', 'jpg', 'jpeg', 'gif'].join('|') + '$', 'i'),
			popup_types     : new RegExp('\.' + ['pdf', 'zip', 'exe'].join('|') + '$', 'i'),
			inited				: true,	
			default_width   : 432,
			facebox_html	: '\
	  <div id="facebox" style="display:none;"> \
	    <div class="popup"> \
			<div class="background"> \
				<div class="top"> \
	                <button class="close"></button> \
				</div> \
				<div class="middle"></div> \
				<div class="bottom"></div> \
			</div> \
            <div class="content"> \
	              <div class="footer"> \
	              </div> \
			</div> \
	    </div> \
	  </div>',
			overlay_html   : '<div id="facebox_overlay" style="display:none;"></div>'
		};
		if (extra_set) Object.extend(this.settings, extra_set);
		$$('body').first().insert({bottom: this.settings.facebox_html});
		$$('body').first().insert({bottom: this.settings.overlay_html});

		this.preload = [ new Image() ];
		this.preload[0].src = this.settings.loading_image;
		
		f = this;
		/*
		$$('#facebox .b:first, #facebox .bl, #facebox .br, #facebox .tl, #facebox .tr').each(function(elem){
			f.preload.push(new Image());
			f.preload.slice(-1).src = elem.getStyle('background-image').replace(/url\((.+)\)/, '$1');
		});*/
		
//		his.keyPressListener = this.watchKeyPress().bindAsEventListener(this);
		
		this.watchClickEvents();
		fb = this;
		Event.observe($$('#facebox .background .close').first(), 'click', function(e){
			Event.stop(e);
			fb.close()
		});
/*		Event.observe($$('#facebox .close_image').first(), 'click', function(e){
			Event.stop(e);
			fb.close()
		}); */
	},
	
	// watchKeyPress	: function(e){
	// 	// not sure if the call to this will work here
	// 	if (e.keyCode == 27) this.close();
	// },
	
	watchClickEvents	: function(e){
		var f = this;
		$$('a[rel=facebox]').each(function(elem,i){
			Event.observe(elem, 'click', function(e){
				// console.log("here's what f is :: "+ f);
				Event.stop(e);
				f.click_handler(elem, e);
			});
		});
		
	},
	
	loading	: function() {
		if ($$('#facebox .loading').length == 1) return true;
		
		contentWrapper = $$('#facebox .content').first();
		contentWrapper.childElements().each(function(elem, i){
			elem.remove();
		});
		contentWrapper.insert({bottom: '<div class="loading"><img src="'+this.settings.loading_image+'"/></div>'});
		var pageScroll = document.viewport.getScrollOffsets();
		var dimensions = $('facebox').getDimensions();

		$('facebox').setStyle({
			'top': pageScroll.top + (document.viewport.getHeight() / 10) + 'px',
			'left': pageScroll.left + ((document.viewport.getWidth() / 2) -  (dimensions.width / 2)) + 'px'
		});
		
//		Event.observe(document, 'keypress', this.keyPressListener);
	},
	
	reveal	: function(data, klass,cw){
//		this.loading();
		box = $('facebox');
		if(!box.visible()) box.show();
		$('facebox_overlay').show();

		contentWrapper = $$('#facebox .content').first();
		if (klass) contentWrapper.addClassName(klass);
		contentWrapper.insert({bottom: data});
		//contentWrapper.innerHTML = data;		
		load = $$('#facebox .loading').first();
		if(load) load.remove();

		// Get the height of the top & bottom parts of the background
		var minHeight = box.select('.background .top').first().getHeight() + box.select('.background .bottom').first().getHeight();

		// Get the offsets of the viewport
		var pageScroll = document.viewport.getScrollOffsets();

		// Dimensions of the content
		var dimensions = contentWrapper.getDimensions();
		
		// Adjust the size of the background middle
		var middleHeight  = dimensions.height - 155;
		if(middleHeight < 0) middleHeight = 5;
		box.select('.background .middle').first().setStyle({height:middleHeight + 'px'});
		
		// Move the facebox to the current position		
		$('facebox').setStyle({
			'top': pageScroll.top + (document.viewport.getHeight() / 2 - dimensions.height / 2) + 'px',
			'left': pageScroll.left + ((document.viewport.getWidth() / 2) -  (dimensions.width / 2)) + 'px'
		});
				
//		Event.observe(document, 'keypress', this.keyPressListener);
	},
	
	close		: function(){
		$('facebox').hide();
		$('facebox_overlay').hide();

		contentWrapper = $$('#facebox .content').first();
		contentWrapper.childElements().each(function(elem, i){
			elem.remove();
		});
	},
		
	openUrlIframe: function(url, e, width, height, klass) {
		this.loading();

		if(e)
			Event.stop(e);
		
		var cw = null;
		
		// div
		$('facebox').show();
		
		var content = '<iframe scrolling="no" marginwidth="0" width="' + width + '" height="' + height + '" frameborder="0" src="' + url + '" marginheight="0"></iframe>'

		fb.reveal(content, klass, width);		
	},
	
	openUrl : function(url, e, klass) {
		this.loading();

		if(e)
			Event.stop(e);
		
		var cw = null;
		
		// div
		$('facebox').show();
		
		var fb = this;
		new Ajax.Request(url, {
			method		: 'get',
			onFailure	: function(transport){
				fb.reveal(transport.responseText, klass,cw);
			},
			onSuccess	: function(transport){
				fb.reveal(transport.responseText, klass,cw);
			}
		});			
	},
	
	click_handler	: function(elem, e){
		this.loading();
		
		Event.stop(e);
		
		// support for rel="facebox[.inline_popup]" syntax, to add a class
		var klass = elem.rel.match(/facebox\[\.(\w+)\]/);
		if (klass) klass = klass[1];
		
		var cw = null;
		elem.classNames().each(function(cn) {
			if(cn.substring(0,12) == 'customwidth-')
				cw = cn.substring(12);
		});
		
		// div
		$('facebox').show();
		$('facebox_overlay').show();
		
		if (elem.href.match(/#/)){
			var url				= window.location.href.split('#')[0];
			var target		= elem.href.replace(url+'#','');
			// var data			= $$(target).first();
			var d			= $(target);
			// create a new element so as to not delete the original on close()
			var data = new Element(d.tagName);
			data.innerHTML = d.innerHTML;
			this.reveal(data, klass);
		} else if (elem.href.match(this.settings.image_types)) {
			var image = new Image();
			fb = this;
			image.onload = function() {
				fb.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass, cw)
			}
			image.src = elem.href;
		} else if (elem.href.match(this.settings.popup_types)) {
			popup(elem.href);
			$('facebox').hide();
		} else {
			// Ajax
			var fb = this;
			url = elem.href;
			new Ajax.Request(url, {
				method		: 'get',
				onFailure	: function(transport){
					fb.reveal(transport.responseText, klass, cw);
				},
				onSuccess	: function(transport){
					fb.reveal(transport.responseText, klass, cw);
				}
			});
			
		}
	}
});

function popup(url) {
	newwindow=window.open(url,'name','');
	if (window.focus) {newwindow.focus()}
	return false;
}


var facebox;
Event.observe(window, 'load', function(e){
	facebox = new Facebox();
});

