/*
---
description: LightFace

license: MIT-style

authors:

Original (MooTools): David Walsh (http://davidwalsh.name)
Modified (jQuery): Shawn Scofield (http://shawnscofield.com)

requires:
- core/1.2.1: '*'

provides: [LightFace]

...
*/

var LightFace = function(options){
	
	this.options = {
		width: options.width || 'auto',
		height: options.height || 'auto',
		draggable: options.draggable || false,
		title: options.title || '',
		buttons: options.buttons || [],
		fadeDelay: options.fadeDelay || 400,
		fadeDuration: options.fadeDuration || 400,
		keys: { 
			esc : function() { this.close(); } 
		},
		content: options.content || '<p>Message not specified.</p>',
		zIndex: options.zIndex || 9001,
		pad: options.pad || 100,
		overlayAll: options.overlayAll || false,
		constrain: options.constrain || false,
		resetOnScroll: options.resetOnScroll || true,
		baseClass: options.baseClass || 'lightface',
		errorMessage: options.errorMessage || '<p>The requested file could not be found.</p>'/*,
		onOpen: options.onOpen || $empty,
		onClose: options.onClose || $empty,
		onFade: options.onFade || $empty,
		onUnfade: options.onUnfade || $empty,
		onComplete: options.onComplete || $empty,
		onRequest: options.onRequest || $empty,
		onSuccess: options.onSuccess || $empty,
		onFailure: options.onFailure || $empty
		*/
	};
	
	this.initialize = function(){
		this.state = false;
		this.buttons = {};
		this.resizeOnOpen = true;
		this.ie6 = typeof document.body.style.maxHeight == "undefined";
		return this.draw();
	}
	
	this.draw = function(){
		
		this.box = document.createElement('table');
		this.box.setAttribute('class', this.options.baseClass);
		this.box.setAttribute('style', 'z-index:'+this.options.zIndex+'; display: none');
		jQuery('body').append(this.box);
		

		//draw rows and cells;  use native JS to avoid IE7 and I6 offsetWidth and offsetHeight issues
		var verts = ['top','center','bottom'], hors = ['Left','Center','Right'], len = verts.length;
		for(var x = 0; x < len; x++) {
			var row = this.box.insertRow(x);
			for(var y = 0; y < len; y++) {
				var cssClass = verts[x] + hors[y], cell = row.insertCell(y);
				cell.className = cssClass;
				if (cssClass == 'centerCenter') {
					this.contentBox = document.createElement('div');
					this.contentBox.setAttribute('class', 'lightfaceContent');
					this.contentBox.setAttribute('style', 'width:'+this.options.width+'px');
					cell.appendChild(this.contentBox);
				}
				else {
					jQuery(cell).css('opacity',0.4);
				}
			}
		}
		
		//draw title
		if(this.options.title) {
			this.title = document.createElement('h2');
			this.title.setAttribute('class', 'lightfaceTitle');
			jQuery(this.title).html(this.options.title);
			jQuery(this.contentBox).append(this.title);
			
			if(this.options.draggable && window['Drag'] != null) {
				this.draggable = true;
				new Drag(this.box,{ handle: this.title });
				this.title.addClass('lightfaceDraggable');
			}
		}
		
		//draw message box
		this.messageBox = document.createElement('div');
		this.messageBox.setAttribute('class', 'lightfaceMessageBox');
		this.messageBox.setAttribute('style', 'height:'+this.options.height);
		jQuery(this.messageBox).html(this.options.content || '');
		//console.log(this.options.content);
		
		jQuery(this.contentBox).append(this.messageBox);
		
		//button container
		this.footer = document.createElement('div');
		this.footer.setAttribute('class', 'lightfaceFooter');
		this.footer.setAttribute('style', 'display: none');
		
		jQuery(this.contentBox).append(this.footer);
		
		
		//draw overlay
		this.overlay = document.createElement('div');
		this.overlay.setAttribute('class', 'lightfaceOverlay');
		this.overlay.setAttribute('style', 'display:none');
		
		jQuery(this.contentBox).append(this.overlay);
		
		if(this.options.overlayAll) {
			jQuery(this.overlay).css('top',(this.title ? jQuery(this.title).height() - 1: 0));
		}
		
		//create initial buttons
		this.buttons = [];
		if(this.options.buttons.length) {
			buttons = this.options.buttons;
			for(var b = 0; b < buttons.length; b++){
				this.addButton(buttons[b].title,buttons[b].event,buttons[b].color);
			}
		}
		
		//focus node
		this.focusNode = this.box;
		return this;
	};
	
	// Manage buttons
	this.addButton = function(title,clickEvent,color) {
		jQuery(this.footer).css('display','block');
		var focusClass = 'lightfacefocus' + color;
		
		var label = document.createElement('label');
		label.setAttribute('class', color ? 'lightface' + color : '');
		jQ(label).bind('mousedown', function(){
			if(color) {
				jQuery(label).addClass(focusClass);
				var ev = function() {
					jQuery(label).removeClass(focusClass);
					jQuery(document.body).unbind('mouseup',ev);
				};
				jQuery(document.body).bind('mouseup',ev);
			}
		});		
		
		this.buttons[title] = document.createElement('input');
		this.buttons[title].setAttribute('type', 'button');
		this.buttons[title].setAttribute('value', title);
		jQ(this.buttons[title]).bind('click', function(){
			clickEvent() || this.close();	
		});
		jQuery(label).append(this.buttons[title]);
		jQuery(this.footer).append(label);
		
		return this;
	};
	
	this.showButton = function(title) {
		if(this.buttons[title]) this.buttons[title].removeClass('hiddenButton');
		return this.buttons[title];
	};
	
	this.hideButton = function(title) {
		if(this.buttons[title]) this.buttons[title].addClass('hiddenButton');
		return this.buttons[title];
	};
	
	// Open and close box
	this.close = function(fast) {
		if(this.isOpen) {
			jQ(this.focusNode).fadeOut();
			//this.fireevent('close');
			this._detachEvents();
			this.isOpen = false;
		}
		return this;
	};
	
	this.open = function(fast) {
		//console.log(this.isOpen);
		if(!this.isOpen) {
			jQuery(this.focusNode).fadeIn();
			if(this.resizeOnOpen) this._resize();
			//this.fireevent('open');
			this._attachEvents();
			this.isOpen = true;
		}
		return this;
	};
	
	_setFocus = function() {
		this.focusNode.setAttribute('tabIndex',0);
		this.focusNode.focus();
	};
	
	// Show and hide overlay
	this.fade = function(fade,delay) {
		this._ie6Size();
		jQuery(this.overlay).fadeTo(delay || 'slow', fade || .5);
		//this.fireevent('fade');
		return this;
	};
	
	this.unfade = function(delay) {
		(function() {
			this.overlay.fade(0);
		}.bind(this)).delay(delay || this.options.fadeDelay);
		//this.fireevent('unfade');
		return this;
	};
	
	_ie6Size = function() {
		if(this.ie6) {
			var size = {
				x: jQuery(this.contentBox).height(),
				y: jQuery(this.contentBox).width()
			}
			var titleHeight = (this.options.overlayAll || !this.title) ? 0 : jQuery(this.title).width();
			jQuery(this.overlay).css({
				height: size.y - titleHeight,
				width: size.x
			});
		}
	};
	
	// Loads content
	this.load = function(content,title) {
		if(content) this.messageBox.set('html',content);
		if(title && this.title) this.title.set('html',title);
		//this.fireevent('complete');
		return this;
	};
	
	// Attaches events when opened
	_attachEvents = function() {
		this.keyEvent = function(e){
			if(this.options.keys[e.key]) this.options.keys[e.key].call(this);
		};
		jQuery(this.focusNode).bind('keyup', this.keyEvent);
		
		this.resizeEvent = this.options.constrain ? function(e) { 
			this._resize(); 
		} : function() { 
			this._position(); 
		};
		jQuery(window).bind('resize',this.resizeEvent);
		
		if(this.options.resetOnScroll) {
			this.scrollEvent = function() {
				this._position();
			};
			//jQuery(window).bind('scroll',this.scrollEvent);
		}
		
		return this;
	};
	
	// Detaches events upon close
	_detachEvents = function() {
		jQuery(this.focusNode).unbind('keyup',this.keyEvent);
		jQuery(window).unbind('resize',this.resizeEvent);
		if(this.scrollEvent) jQuery(window).unbind('scroll',this.scrollEvent);
		return this;
	};
	
	// Repositions the box
	_position = function() {
		var windowSize = {
			x: jQuery(window).height(),
			y: jQuery(window).width()
		}; 
		var scrollSize = {
			x: jQuery(window).scrollTop(),
			y: jQuery(window).scrollLeft()
		};
		var	boxSize = {
			x: jQuery(this.focusNode).height(),
			y: jQuery(this.focusNode).width(),
		};
		//console.log(boxSize);
		if(boxSize.x > windowSize.x){
			jQuery(this.focusNode).css({
				left: scrollSize.y + ((windowSize.y - boxSize.y)/2),
				top: 10
			});
		} else {
			jQuery(this.focusNode).css({
				left: scrollSize.y + ((windowSize.y - boxSize.y)/2),
				top: scrollSize.x + ((windowSize.x - boxSize.x)/2)
			});
		}
		
		this._ie6Size();
		return this;
	};
	
	// Resizes the box, then positions it
	_resize = function() {
		var height = this.options.height;
		if(height == 'auto') {
			//get the height of the content box
			var max = window.innerHeight - this.options.pad;
			if(this.contentBox.innerHeight > max) height = max;
		}
		this.messageBox.style.height = height;
		this._position();
	};
	
	// Expose message box
	this.toElement = function () {
		return this.messageBox;
	};
	
	// Expose entire modal box
	this.getBox = function() {
		return this.focusNode;
	};
	
	// Cleanup
	this.destroy = function() {
		this._detachEvents();
		jQuery(this.buttons).each(function(button) {
			jQuery(this).unbind('click');
		});
		jQuery(this.focusNode).remove();
		delete this.box;
	};
	
	return initialize();
};
