
// transitions: http://www.consideropen.com/blog/2008/08/30-days-of-mootools-12-tutorials-day-11-using-fxmorph-fx-options-and-fx-events/


OverlayDiv = new Class({
	Implements: Options,

	options: {
		duration:		1000,
		transition:		Fx.Transitions.Cubic.easeOut,
		color:			'#000000',
		opacity:		0.5,
		close_on_click:		true,
		onClick:		function() {}
	},

	initialize: function(options) {
		this.setOptions(options);

		this._fx = null;
		this._inTransition = false;
		this._curWay = 0;
		this.id = this.__register();

		var self = this;
		var id = this.id;

		with( this.element = $(document.createElement('div')) ) {
			setStyle('position', 'absolute');
			setStyle('background-color', this.options.color);
			setStyle('z-index', 80);
			setStyle('opacity', 0);
		}
		this.setSize();

		if(this.options.close_on_click) {
			this.element.onclick = function() {
				self.hide();
				self.options.onClick();
			}
		}

		document.body.appendChild(this.element);

		window.addEvent('resize', function() { this.__registerOverlayDivClasses[id].setSize(); });
	},

	__register: function() {
		if(!window.__registerOverlayDivClasses) window.__registerOverlayDivClasses = new Array();
		window.__registerOverlayDivClasses.push(this);
		return window.__registerOverlayDivClasses.length - 1;
	},


	setSize: function() {
		var h = ($(document.body).scrollHeight > $(document.body).getHeight()) ? $(document.body).scrollHeight + parseInt($(document.body).getStyle('margin-top')) + parseInt($(document.body).getStyle('margin-bottom')) : $(document.body).getHeight();
		var w = ($(document.body).scrollWidth > $(document.body).getWidth()) ? $(document.body).scrollWidth : $(document.body).getWidth();

		this.element.setStyle('top', 0);
		this.element.setStyle('left', 0);
		this.element.setStyle('width', w );
		this.element.setStyle('height', h );
	},


	show: function() {
		if(this._inTransition) this._fx.cancel;

		var self = this;
		this._fx = new Fx.Morph( this.element, {
			duration: self.options.duration,
			transition: self.options.transition,
			onStart: function() {
				self._inTransition = true;
				self._curWay = 1;
			},
			onComplete: function() {
				self._inTransition = false;
			}
		});

		this._fx.start({
			'opacity': self.options.opacity
		});

	},

	hide: function() {
		if(this._inTransition) this._fx.cancel;

		var self = this;
		this._fx = new Fx.Morph( this.element, {
			duration: self.options.duration,
			transition: self.options.transition,
			onStart: function() {
				self._inTransition = true;
				self._curWay = 0;
			},
			onComplete: function() {
				self._inTransition = false;
			}
		});

		this._fx.start({
			'opacity': 0
		});

	}

});

DisplayDiv = new Class({
	Implements: Options,

	options: {
		duration:		1000,
		transition:		Fx.Transitions.Cubic.easeOut,
		overlay:		true,
		transition_types:	['morph', 'fade'] // morph, fade
	},

	initialize: function(element, options){
		this.element = $(element);
		this.setOptions(options);
		this._inTransition = false;
		this._curWay = 0;
		this._fx = null;
		this.id = this.__register();

		var self = this;
		var id = this.id;

		this.elOpacity = (this.element.style.opacity) ? this.element.style.opacity : this.element.getStyle('opacity') ;

		this.element.setStyle('z-index', 95);
		this.element.setStyle('overflow', 'hidden');

		this.set_dimensions();

		this.element.setStyle('width', this.elWidth); // fixed width

		window.addEvent('resize', function() { this.__registerDisplayDivClasses[id].setPosition(); });
		window.addEvent('scroll', function() { this.__registerDisplayDivClasses[id].setPosition(); });

		if(this.options.overlay) {
			this.options.overlay.onClick = function() { self.hide(true); }
			this.overlay = new OverlayDiv(this.options.overlay);
			this.options.overlay = true;
		}


		this.reset();
	},


	__register: function() {
		if(!window.__registerDisplayDivClasses) window.__registerDisplayDivClasses = new Array();
		window.__registerDisplayDivClasses.push(this);
		return window.__registerDisplayDivClasses.length - 1;
	},

	set_dimensions: function() {
		if(this.element.getStyle('display') == 'none') {

			var vis = this.element.getStyle('visibility');
			var dis = this.element.getStyle('display');
			this.element.setStyle('visibility', 'hidden');
			this.element.setStyle('display', 'block');

			this.elWidth = this.element.getWidth();
			this.elHeight = this.element.scrollHeight;

			this.element.setStyle('display', dis);
			this.element.setStyle('visibility', vis);
		} else {
			this.elWidth = this.element.getWidth();
			this.elHeight = this.element.scrollHeight;
		}
	},

	reset: function() {
		this.element.setStyle('overflow', 'hidden');
		this._inTransition = false;
		this._curWay = 0;

		this.setPosition();


		for(var t=0; t<this.options.transition_types.length; ++t) {
			switch(this.options.transition_types[t]) {
				case 'morph':
					this.element.setStyle('height', '1px');
					break;
	
				case 'fade':
					this.element.setStyle('opacity', 0.0);
					break;
			}
		}

	},

	setPosition: function() {

		var style = new Object;
		style.left = ( (window.getWidth() / 2) - (this.elWidth / 2) + document.body.scrollLeft );
		style.top = ( (window.getHeight() / 2) - (this.elHeight / 2) + document.body.scrollTop );


		for(var s in style) this.element.setStyle(s, style[s]);

		this.elTop = style.top;
		this.elLeft = style.left;
	},

	toggle: function() {
		(this._curWay == 1) ? this.hide() : this.show();
	},

	show: function() {
		if(this._inTransition) this._fx.cancel();
		else this.set_dimensions();

		var self = this;

		var to = new Object;

		for(var t=0; t<this.options.transition_types.length; ++t) {
			switch(this.options.transition_types[t]) {
				case 'morph':
					to.height = this.elHeight;
					break;
	
				case 'fade':
					to.opacity = this.elOpacity;
					break;
			}
		}


		if(this.options.overlay) this.overlay.show();

		this._fx = new Fx.Morph( this.element, {
			duration: self.options.duration,
			transition: self.options.transition,
			onStart: function() {
				self._inTransition = true;
				self._curWay = 1;
				this.element.style.display = 'block';
			},
			onComplete: function() {
				self._inTransition = false;
			}
		});

		this._fx.start(to);
	},

	hide: function() {
		if(this._inTransition) this._fx.cancel();

		var self = this;

		var to = new Object;
		for(var t=0; t<this.options.transition_types.length; ++t) {
			switch(this.options.transition_types[t]) {
				case 'morph':
					to.height = 1;
					break;
	
				case 'fade':
					to.opacity = 0;
					break;
			}
		}

		if(this.options.overlay) this.overlay.hide();

		this._fx = new Fx.Morph( this.element, {
			duration: self.options.duration,
			transition: self.options.transition,
			onStart: function() {
				self._inTransition = true;
				self._curWay = 0;
			},
			onComplete: function() {
				self._inTransition = false;
				this.element.style.display = 'none';
			}
		});

		this._fx.start(to);
	}

});



function form_friend_show(div) {
	if(!Browser.loaded) return;
	div = $(div);
	if(!div) return;

	db_form_enable('friend');
	var f = db_form_get_form('friend');

	f.title.value = document.title;
	f.href.value = document.location.href;

	if(!window._friend_form_display) {
		if(!window.form_friend_options) window.form_friend_options = {};
		window._friend_form_display = new DisplayDiv(div, window.form_friend_options)
	}
	window._friend_form_display.show();
}

function form_friend_hide() {
	window._friend_form_display.hide();
}


function form_subscribe_submit(div) {
	if(!Browser.loaded) return;

	var f = document.forms['frmOptin'];
	if(!validate_email(f.email.value)) {
		alert('Please enter a valid email address.');
		f.email.focus();
		return false;
	}


	var fparams = form_make_fparams(f);
	fparams.ajax = 1;
	fparams.json_return = 1;

	var furl = f.getAttribute('action');
	if(!furl) furl = '/site/~forms/insert';

	var request = new Request({
		method: 'post',
		url: furl,
		data: fparams,
		onComplete: function(response) {

			form_subscribe_show_full_form(response, div);
		}

	});
	request.send();

	return false;
}

function form_subscribe_show_full_form(response, div) {
	div = $(div);
	if(!div) return;

	response = JSON.decode(response);

	db_form_enable(response.db);
	var f= db_form_get_form(response.db);

	f.recordid.value = response.recordid;
	//f.email.value = response.email;
	for(var k in response) {
		if(f[k] && f[k].getAttribute('type') == 'text') f[k].value = response[k];
	}

	if(!window._subscribe_form_display) {
		if(!window.form_subscribe_options) window.form_subscribe_options = {};
		window._subscribe_form_display = new DisplayDiv(div, window.form_subscribe_options)
	}
	window._subscribe_form_display.show();
}

function form_subscribe_hide() {
	window._subscribe_form_display.hide();
}






function db_form_validate(f) {

	db_form_clear_errors(f.db.value);

	var fparams = form_make_fparams(f);
	fparams.ajax = 1;

	//var msg = ''; for(var n in fparams) msg += n + ': ' + fparams[n] + '\n'; alert(msg);

	db_form_disable(f.db.value);
	db_form_show_message(f.db.value, '', 'Please wait while we process your request...');



	var furl = f.getAttribute('action');
	if(!furl) furl = '/site/~forms/insert'; 
	furl += '_ajax';

	var request = new Request({
		method: 'post',
		url: furl,
		data: fparams,
		onComplete: db_form_validate_ajax_response

	});
	request.send();

	return false;
}

function form_make_fparams(f) {
	var fparams = {};

	for(var n in f.elements) {
		if(!f.elements[n] || !f.elements[n].tagName) continue; 
		TNAME: switch(f.elements[n].tagName.toUpperCase()) {
			case 'INPUT':
				switch(f.elements[n].type) {
					case 'hidden':
					case 'text':
						fparams[f.elements[n].name] = f.elements[n].value;
						break;

					case 'radio':
					case 'checkbox':
						if(f.elements[n].checked) fparams[f.elements[n].name] = f.elements[n].value;
						break;

					case 'INPUT':

					default: break TNAME;
				}
				break;

			case 'TEXTAREA':
				fparams[f.elements[n].name] = f.elements[n].value;
				break;

			case 'SELECT':
				fparams[f.elements[n].name] = f.elements[n].value;
				break;



			default:
				break TNAME;

		}		

	}
	//var buf = ''; for(var n in fparams) { buf += n + '=' + fparams[n] + '&'; } alert(buf);
	return fparams;
}

function db_form_get_form(dbname) {
	return document.forms['db_form_'+dbname];
}

function db_form_enable(dbname) {
	db_form_disable(dbname, true);
}
function db_form_disable(dbname, enable) {
	var f = db_form_get_form(dbname);
	if(!f) return;

	for(var n in f.elements) {
		if(!f.elements[n] || !f.elements[n].tagName) continue;
		if(f.elements[n].tagName == 'INPUT' || f.elements[n].tagName == 'TEXTAREA' || f.elements[n].tagName == 'SELECT') {
			if(enable) {
				f.elements[n].disabled = 0;
			}
			else {
				f.elements[n].disabled = 1;
			}
		}
	}
}



function db_form_validate_ajax_response(response) {
	response = JSON.decode(response);

	var f = db_form_get_form(response.dbname);
	var container = $('db_form_container_'+response.dbname);


	if(response.success == true ) {
		// all ok!

		if(response.db_response_action == 1) {
			document.location = response.db_response_href;
		}
		else if(response.db_response_action == 2) {
			container.style.height = container.offsetHeight + 'px';
			f.style.display = 'none';

			var r = $('db_form_response_container_'+response.dbname);
			r.innerHTML = response.db_response_message;

			var r = $('db_form_'+response.dbname+'_intro');
			if(r) r.style.display = 'none';
		}
		else {
			db_form_show_message(response.dbname, '', 'Thank you, your submission was received.');
		}

	}
	else if(response.field_errors) {
		var foc = false;
		for(var n in response.field_errors) {
			db_form_show_error(response.dbname, n, response.field_errors[n]);

			if(!foc) {
				foc = f[n];
				if(foc) foc.select();
			}
		}


		db_form_show_error(response.dbname, '', 'Error(s) occurred, please correct the fields above and submit again.');
	}
	else {
		var d = $('div_form_error_message_'+response.dbname);
		if(d) d.innerHTML = 'Errors(s) occurred submitting form data.';
	}

	db_form_enable(response.dbname);
}

function db_form_show_error(dbname, fldname, msg) {
	db_form_show_message(dbname, fldname, msg, true);
}

function db_form_show_message(dbname, fldname, msg, error) {
	var f = db_form_get_form(dbname);

	var classname = (error) ? 'form_field_message form_field_error' : 'form_field_message';

	if(dbname) {
		var d;
		if(fldname) d = $('div_form_field_error_message_'+dbname+'_'+fldname);
		else d = $('div_form_error_message_'+dbname);

		if(d) {
			d.innerHTML = msg;
			d.className = classname;
			d.style.display = 'block';
		}
	}


	if(f.form_container.value) {
		var c = $(f.form_container.value);
		c.style.height = c.scrollHeight;
	}
}

function db_form_clear_errors(dbname) {
	var f = db_form_get_form(dbname);

	var lst = document.getElementsByTagName('div');
	for(var i=0; i<lst.length; ++i) {
		if( lst[i].id.indexOf('div_form_field_error_message_'+dbname) == 0 || lst[i].id.indexOf('div_form_error_message_'+dbname) == 0) {
			lst[i].innerHTML = '';
			lst[i].style.display = 'none';
		}
	}


	if(f.form_container.value) {
		var c = $(f.form_container.value);
		c.style.height = c.scrollHeight;
	}
}

function db_form_reset(dbname, retainfields) {
	var f = db_form_get_form(dbname);
	var container = $('db_form_container_'+dbname);
	var responsecontainer = $('db_form_response_container_'+dbname);

	responsecontainer.innerHTML = '';
	responsecontainer.style.height = '';
	f.style.display = '';
	db_form_clear_errors(dbname);
	db_form_enable(dbname);

	var r = $('db_form_'+dbname+'_intro');
	if(r) r.style.display = 'block';

	var savedata = {};
	if(retainfields instanceof Array) {
		for(var i=0; i<retainfields.length; ++i) {
			var el = f[retainfields[i]];
			if(!el) continue;

			L1: switch(el.tagName.toUpperCase()) {
				case 'INPUT':

				L2: switch(el.type) {
					case 'hidden':
					case 'text':
						savedata[el.name] = el.value;
						break;

					default: break L1;
				}

				case 'TEXTAREA':
				case 'SELECT':
					savedata[el.name] = el.value;
					break;
			}
		}
	}
	f.reset();

	for(var n in savedata) {
		f[n].value = savedata[n];
	}
}







/********************************************************************/
// validate_email()
// returns true if email appears valid
/********************************************************************/
function validate_email(email) {
	email = email.trim();
	if( email.match(/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/) || !email.match(/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/) ) return false;
	return true;
}


/********************************************************************/
// Errors class
/********************************************************************/
function Errors() {
	this.errors = new Array();

	this.add = function(msg) {
		this.errors[this.errors.length] = msg;
	}
	this.alert = function() {
		if(!this.errors.length) return false;

		var msg = 'The following error(s) have occurred:\n\n';

		for(var i=0; i<this.errors.length; ++i) {
			msg += '*  ' + this.errors[i];
			if(i < this.errors.length - 1) msg += '\n\n';
		}

		alert(msg);
		return true;
	}
}



/********************************************************************/
// getLeft(), getTop()
// these have been replaced by mootools with obj.getLeft(), obj.getTop()
/********************************************************************/
//function getLeft(obj) {
//	return (obj.offsetParent==null ? obj.offsetLeft : obj.offsetLeft + getLeft(obj.offsetParent));
//}
//function getTop(obj) {
//	return (obj.offsetParent==null ? obj.offsetTop : obj.offsetTop + getTop(obj.offsetParent));
//}



/********************************************************************/
// hasFlash()
// attempt to determine if the flash plugin is installed
/********************************************************************/
function hasFlash() {
	window.bHasFlash = false;

	var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
	if ( plugin ) window.bHasFlash = true;
	else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)) {
		document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
		document.write('on error resume next\nwindow.bHasFlash = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & 6)))\n');
		document.write('</SCR' + 'IPT\> \n');
	}

	return window.bHasFlash;
}




/********************************************************************/
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
/********************************************************************/
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		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;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		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
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = {
		'pageWidth':	pageWidth,
		'pageHeight':	pageHeight,
		'windowWidth':	windowWidth,
		'windowHeight':	windowHeight
	}
	return arrayPageSize;
}

window.getWidth = function() { return getPageSize().windowWidth; }
window.getHeight = function() { return getPageSize().windowHeight; }
document.getWidth = function() { return getPageSize().pageWidth; }
document.getHeight = function() { return getPageSize().pageHeight; }



