// Javascript Application Dialog Box
// Based off of Facebox Code v1.1 (http://famspam.com/facebox/)
// Original jQuery Code Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
//
// All Original jQuery Code licensed under the MIT
//    http://www.opensource.org/licenses/mit-license.php
//
// All Modifications are Copyright 2008 Xspond Incorporated.  All rights reserved.

var DialogBox = Class.create();

DialogBox.prototype = {
	// DialogBox methods:
	// initialize: 	Constructs the initial HTML and DOM related items
	//				for the DialogBox
	// addHandlers: Adds the Event observers to any a tag which contains
	//				an href attribute and a rel tag which contains dialog_box in it
	// settings: 	Stores the default settings for dialog_box.  Can be overriden
	//				on initialize by passing in new settings.
	// show: 		Given data and options, will setup the chain for loading and 
	//				displaying a dialog_box instance.
	// showAnchor: 	If the data sent to show is actually and HTML Anchor loaded in the
	//				DOM, then it will apply the above mentioned behaviors.
	
	initialize: function(settings) {
		this.addHandlers();
		
		Element.extend(document.body);

		if (settings) Object.extend(this.settings, settings);
		if (this.settings.display_overlay) { document.body.insert(new Element('div', {id:'dialog_box_overlay', style:'display: none;'})); }

    document.body.insert(this.settings.dialog_box_html, {position: 'bottom'});
		
	    var preload = [ new Image(), new Image() ];
	    preload[0].src = this.settings.close_image
	    preload[1].src = this.settings.loading_image;
	
	    $('dialog_box_close').observe('click', this.close);
	    $('dialog_box_close_image').setStyle({'src': this.settings.close_image});
	},
	
	addHandlers : function() {
		$$('a').each(function(e) {
			var relValue = String(e.readAttribute('rel'))
			
			if(relValue.match('dialog_box') && e.readAttribute('href')) {				
				e.observe('click', function(event) { dialog_box.show(this); Event.stop(event); });
			}
		});
	},
	
	settings : {
		display_overlay: true,
		overlay_opacity: 0.6,
		loading_image: '/images/dialog_box/loading.gif',
		close_image: '/images/dialog_box/closelabel.gif',
		image_types: [ 'png', 'jpg', 'jpeg', 'gif' ],
	    dialog_box_html: '\
			<div id="dialog_box" style="display: none;"> \
			  <div id="dialog_box_popup"> \
				<div id="dialog_box_top"></div> \
				<div id="dialog_box_body"> \
		            <div id="dialog_box_content"></div> \
		            <div id="dialog_box_footer"> \
		              <a href="#" id="dialog_box_close"> \
		                <img src="/images/dialog_box/closelabel.gif" title="close" id="dialog_box_close_image" /> \
		              </a> \
		            </div> \
				</div> \
				<div id="dialog_box_bottom"></div> \
			  </div> \
			</div>'
	},
	
	// Given the passed in data, will setup the chain of events just like start,
	// except the data will be display as it is.
	show : function(data, options) {
		this.loading();
		
		if((data.nodeName) && (data.nodeName == 'A'))
			showAnchor(e);
		else
			this.reveal(data, options);
	},
	
	// Called when an anchor tag element is passed in via the show function
	// Handles all the magic for loading the anchor link data.
	showAnchor : function(e) {
		var image_types = new RegExp('\.' + this.settings.image_types.join('|') + '$', 'i');
		if(e.rel) var klass = e.rel.match(/dialog_box\[\.(\w+)\]/);
		if (klass) klass = klass[1];
										
		if(e.href.match(image_types)) {
			var image = new Image();
			var dialog_box = this;
			image.onload = function() { dialog_box.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass); }
			image.src = e.href;
		}
		
		// else if (e.href.match(/#/)) {
		// 	        var url = window.location.href.split('#')[0]
		// 	        var target = e.href.replace(url + '#','')
		// 	alert(Object.inspect(Object.clone($(target)).innerHTML));
		// 	// this.reveal(Object.clone($(target)), klass);
		// }
		
		else {
			var dialog_box = this;
			new Ajax.Request(e.href, {asynchronous:true, evalScripts:false, method:'get', onSuccess: function(response) {dialog_box.reveal(response.responseText, klass)}});
		}
	},
	
	loading : function() {
		if($('dialog_box_loading')) return true

	    var dialog_box_body = $('dialog_box_body');

	    $('dialog_box_content').update('');
		dialog_box_body.childElements().invoke('hide');
			dialog_box_body.insert('<div id="dialog_box_loading"><img src="'+this.settings.loading_image+'"/></div>', {position: 'bottom'});
	
		if(this.settings.display_overlay) {
				var arrayPageSize = getPageSize();
								
				$('dialog_box_overlay').setStyle({
					'width': arrayPageSize[0] + 'px',
					'height': arrayPageSize[1] + 'px'
				});
				
				Effect.Appear('dialog_box_overlay', {to: this.settings.overlay_opacity});
			}
	
	    var pageScroll = document.viewport.getScrollOffsets();
	   	$('dialog_box').setStyle({
	      top:	pageScroll[1] + (document.viewport.getHeight() / 10) + 'px',
	      left:	pageScroll[0] + 'px'
	    }).show();
	},
	
	stopLoading : function() {
		$('dialog_box_loading').remove();
		this.close();
	},
	
	reveal : function(data, options) {
		if(!options) options = {}
		
	    if (options.klass) $('dialog_box_content').addClassName(options.klass)
	    $('dialog_box_content').update(data);
	    $('dialog_box_loading').remove();
	
		if(options.hide_dialog_controls) {
			elements = $('dialog_box_body').childElements().inject([], function(acc, value) {				
				if(!(value.identify() == "dialog_box_footer")) acc.push(value);
				return acc;
			});
			
			elements.invoke('show');
		}
		else
			$('dialog_box_body').childElements().invoke('show');
	},
	
	close : function() {
		$('dialog_box').hide();
		if($('dialog_box_overlay')) Effect.Fade('dialog_box_overlay');
	    return false;
	}
}

function getPageSize(){
	
	var xScroll, yScroll, windowWidth, windowHeight;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	pageHeight = (yScroll < windowHeight) ? windowHeight : yScroll;

	// for small pages with total width less then width of the viewport
	pageWidth = (xScroll < windowWidth) ? xScroll : windowWidth;

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function initDialogBox() { dialogBox = new DialogBox(); }
Event.observe(window, 'load', initDialogBox, false);