/*	---------------------------------------------------------------------------
	CLASS:		Element
	METHOD:		setSelected(value)
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com
	REVISED:	May 2009
	ABOUT:		Utility function designed to set the value of a select box
*/

Element.implement ({
	setSelected: function(value) {
		if (this.get('tag') == 'select') {
			var options = this.getElements('option');
			if ($defined(options) && options.length > 0) {
				options.each(function(option,index) {
					if (option.value == value) {
						this.selectedIndex = index;
					}
				}.bind(this));
			}
		} else {
			this.value = value;
		}
	}
});

/*	---------------------------------------------------------------------------
	CLASS:		Layout(el[,columns])
	AUTHOR:		Ryan J. Salva, http://www.capitolmedia.com
	REVISED:	January 2008
	EXAMPLE:	<div id="Wrapper"><div id="Left">Foo</div><div id="Right">Bar</div></div>
				var x = new Layout('Wrapper',['Left','Right']);
	ABOUT:		Utility function designed to fix any layout using aboslute positioning for each column
				Adjusts the page to make wrapper as tall as the highest column (left, right, etc.)
				Most Capitol Media websites use the column ids: Left, Right, Middle and Canvas	
*/

var Layout = new Class({
	initialize: function(el,columns){
		this.columns = columns;
		this.el = $(el);
		if (!$defined(this.el)) return false;
		
		this.el.setStyle('overflow','hidden');
		this.columns.each(function(col,index) {
			this.columns[index] = $(col);
		}.bind(this));
		this.columns = this.columns.clean();
		this.el.set('tween', {duration: 100});
		this.periodical = this.update.bind(this).periodical(200);
	},
	update: function() {
		var y = 0;
		this.columns.each(function(col,index) {
			var h = col.getCoordinates().height;
			if(h > y) y = h;
		});
		this.el.tween('height',y);
	}
});


/*	---------------------------------------------------------------------------
	CLASS:		Element
	METHOD:		fix();
	ABOUT:		Fixes alpha transparency in IE6
	REVISED:	February 27, 2008
*/

Element.implement({
	fix: function(){
		if(!Browser.Engine.trident) return this;
		var src;
		var size = this.getSize();
		if(this.get('tag')=='img'){
			src = this.get('src');
			if(src.indexOf('.png') < 0) return this;
			this.set('src', '/site/x.gif');
		} else {
			var bg = this.getStyle('background-image');
			if(bg && bg!='none')
				src = bg.match(/\(([^)]+)\)/)[1];
			if(src.indexOf('.png') < 0) return this;
		}
		if (src) {
			if(this.getStyle('display')=='inline' && !['input', 'textarea', 'button'].contains(this.get('tag'))) {
				this.setStyles({
					'display': 'block',
					'width': size.x,
					'height': size.y
				});
			}
			this.setStyles({
				'background': '',
				'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled="true", src="'+src+'", sizingMethod="crop")'
			});
		}
		return this;
	}
});
if(Browser.Engine.trident4) window.addEvent('domready', function() {
	$$('img[src$=png]').fix();
});




/*	---------------------------------------------------------------------------
	CLASS:		FormTip(selector,[className])
	AUTHOR:		Ryan J. Salva
	REVISED:	December 2008
*/

var FormTip = new Class({
	Implements: Options,
	options: {
		className: 'FormTip'
	},
	initialize: function(selector,options){
		this.setOptions(options);
		this.els = $$(selector);
		this.els.each(function(el,index){
			el.addEvent('focus',this.show.bindWithEvent(this));
			el.addEvent('blur',this.hide.bindWithEvent(this));
		}.bind(this));
	},
	show: function(e) {
		var e = new Event(e);
		var el = e.target;
		if ($type(el) != 'element') return false;
		var title = el.getAttribute('title');
		if (!$defined(title)) return false;
		var pos = el.getPosition(el.getOffsetParent());
		var width = el.getWidth();
		this.tip = new Element('div',{'class':this.options.className,'styles':{
			opacity: 0,
			position: 'absolute',
			left: pos.x + width,
			top: pos.y
		}}).setText(title);
		this.tip.inject(el.getParent(),'inside');
		this.tip.tween('opacity',1); 
	},
	hide: function() {
		this.tip.remove();
	}
});

/*	---------------------------------------------------------------------------
	CLASS:		Fader(container,[pause,duration,loop])
	AUTHOR:		Ryan J. Salva
	MODIFIED: December 22, 2007
 
	creates a single, rotating image on a page

	IMPLEMENTATION:
	<div id="Container">
		<img src="1.jpg" /><img src="2.jpg" /><img src="3.gif" />
	</div>
	<script type="text/javascript">
		window.addEvent('domready',function() { 
			var f = new Fader('Container');
			f.start();
		});
	</script>
*/

var Fader = new Class({
	Implements: Options,
	options: {
		pause: 5000,
		duration: 1000,
		loop: true
	},
	initialize: function(container,options) {
		this.setOptions(options);
		this.container = $(container);
		this.imgs = this.container.getElements('img');
		this.imgs.setStyles({
			'position':'absolute',
			'top':0,
			'left':0,
			'opacity':0
		});
		this.imgs[0].setStyle('opacity',1);
		this.el = new Element('div',{'styles': {
			'position':'relative'
	    }});
	    this.el.injectInside(this.container);
	    this.el.adopt(this.imgs);
		this.next = 0;
		this.start();
	},
	start: function() {
		this.show();
		this.periodical = this.show.bind(this).periodical(this.options.pause);
	},
	stop: function() {
		$clear(this.periodical);
	},
	show: function() {
		if (!this.options.loop && this.next==this.imgs.length-1) this.stop();
		this.next = (this.next==this.imgs.length-1)?0:this.next+1;
		var prev = (this.next==0)?this.imgs.length-1:this.next-1;
		
		this.imgs[this.next].fade('in');
		this.imgs[prev].fade('out');
	}
});


/*	---------------------------------------------------------------------------
	CLASS:		FlipDeck (el,items,[speed,delay,visibleitems]);
	OPTIONS:	speed:			the transition speed (default:500)
				delay:			the amount of time a news item stays at a position (default: 5000)
				visibleItems:	the number of items to show in a single frame (default:3)
	AUTHOR:		Ryan J. Salva
	EMAIL		ryan at capitolmedia.com
	REVISED:	Decembe 16, 2009
*/
 
var FlipDeck = new Class({
	Implements: [Events, Options],
	options: {
		speed: 1000,
		delay: 10000,
		visibleItems: 1,
		onComplete: $empty,
		onStart: $empty
	},
	initialize: function(el,items,options){
		this.setOptions(options);
		this.el = el;
		this.items = items;
		this.visibleItems = this.options.visibleItems;
		this.sets = [];
		this.anchors = [];
		
		if (this.items.length <= 0) return false;

		this.showing = 0;
 
		var i = this.visibleItems;
		var deck;
		this.items.each(function(item,index) {
			if (i >= this.visibleItems) {
				i = 0;
				deck = new Element('div',{
					'styles':{
						'position': 'absolute',
						'top':0,
						'left':0,
						'opacity':0
					},
					'tween':{
						'link':'cancel',
						'duration':this.options.speed
					}
				});
				this.sets.include(deck);
				this.el.adopt(deck);
			}
			deck.adopt(item);
			i++;
		}.bind(this));
		this.pagination = this.paginate();
		this.show(0);
		this.timer = this.next.periodical(this.options.delay,this);
	},
	
	show: function(deck) {
		this.sets[this.showing].tween('opacity',0);
		this.showing = deck;
		this.sets[this.showing].tween('opacity',1);
		this.flip();
		$clear(this.timer);
	},
	
	flip: function() {
		this.anchors.each(function(el,index) {
			el.removeClass('active');
		});
		if (this.anchors[this.showing]) this.anchors[this.showing].addClass('active');	
	},
	
	paginate: function() {
		var div = new Element('div');
		this.sets.each(function(s,index) {
			var a = new Element('a',{
				'href':'#',
				'text':index+1,
				'events':{
					'click': function() {
						this.show(index);
					}.bind(this)
				}
			});
			this.anchors.push(a);
			div.adopt(a);
		}.bind(this));
		return div;
	},
	
	next: function() {
		this.sets[this.showing].tween('opacity',0);
		this.showing = (this.showing >= this.sets.length-1)?0:this.showing+1;
		this.sets[this.showing].tween('opacity',1);
		this.flip();
	},
	
	previous: function() {
		this.sets[this.showing].tween('opacity',0);
		this.showing = (this.showing <= 0)?this.sets.length-1:this.showing-1;
		this.sets[this.showing].tween('opacity',1);
		this.flip();
	}
	
});

/*	---------------------------------------------------------------------------
	CLASS:		Pop
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com
	HISTORY:	06/21/08 - v1.0
 
	ABOUT:		Displays a pop up to the right of lists on controlpanel views
*/
 
var Pop = new Class({
	Implements: Options,
	options: {
		className: 'Pop',
		onComplete: Class.empty,
		onStart: Class.empty
	},
	initialize: function(el,pop,options){
		this.setOptions(options);
		this.el = el;
		this.pop = pop;
		$$('body')[0].adopt(this.pop);
		this.el.addEvent('mouseenter',this.show.bindWithEvent(this));
		this.el.addEvent('mouseleave',this.hide.bindWithEvent(this));
	},
	show: function(e) {
		var coord = this.el.getCoordinates();
		this.pop.setStyles({
			'display':'block',
			'opacity': 0,
			'position': 'absolute',
			'left': coord.left - 35,
			'top': coord.top - 40
		});
		this.pop.tween('opacity',1); 
	},
	hide: function() {
		this.pop.setStyle('display','none');
	}
});

/*	---------------------------------------------------------------------------
	CLASS:		Modal([options]);
	OPTIONS:	speed:				the transition speed (default:500)
				maskColor:			the background color of the mask (default: black)
				width:				default width of the dialog box (default:400px)
				height:				default height of the dialog box (default: auto)
				classPrefix:		used to define unique classes for each dialog box (default: "Modal")
	EVENTS:		onHide				fires when closing the Modal box
				onShow				fires when showing the Modal box
				onStart				fires when first initializing the Modal box
				onStep				fires when stepping next or previous in a series
				onUpdate			fires when the window resizes
	AUTHOR:		Ryan J. Salva, http:www.capitolmedia.com
	REVISED:	August 22, 2009
*/
 
Modal = new Class({
	Implements: [Events, Options],
	options: {
		'speed': 500,
		'maskColor': '#04143F',
		'maskOpacity': .3,
		'width': 460,
		'height': '100%',
		'classPrefix': 'modal',
		'onHide': $empty,
		'onShow': $empty,
		'onStart': $empty,
		'onStep': $empty,
		'onUpdate': $empty
	},
	initialize: function(options) {
		this.setOptions(options);
		this.el = null;
		this.series = null;
		
		this.iframe = new Element('iframe',{
			'src': 'javascript:void(0);',
			'frameborder': 0,
			'scrolling': 'no',
			'styles':{
				'position': 'absolute',
				'top': 0,
				'left': 0,
				'width': '100%',
				'height': '100%',
				'opacity': 0
			}
		});
 
		this.mask = new Element('div', {
			'class':this.options.classPrefix+'Mask',
			'styles':{
				'position':'absolute',
				'top': 0,
				'left': 0,
				'opacity': 0,
				'width': '100%',
				'background':this.options.maskColor,
				'z-index': 9999
			},
			'events':{
				'click':function(e) {
					this.hide();
				}.bind(this)
			},
			'tween':{
				'duration':this.options.speed
			}
		});
 
		this.container = new Element('div',{
			'class':this.options.classPrefix+'Container',
			'styles':{
				'position': 'absolute',
				'visibility': 'hidden',
				'width': '100%',
				'margin': 0,
				'z-index': 10000
			},
			'events':{
				'click':function(e) {
					this.hide();
				}.bind(this)
			},
			'tween':{
				'duration': this.options.speed
			}
		});
		
		this.box = new Element('div',{
			'class':this.options.classPrefix+'Box',
			'styles':{
				'margin':'0 auto',
				'width': this.options.width,
				'height':this.options.height
			},
			'events': {
				'click': function(e) {
					e.stopPropagation();
				}
			},
			'morph': {
				'duration':this.options.speed
			}
		});
 
		this.message = new Element('div',{
			'class':this.options.classPrefix+'Message',
			'morph':{
				'duration':this.options.speed
			}
		});
 
		this.close = new Element('a', {
			'href':'#', 
			'text':'Close',
			'class':this.options.classPrefix+'Close',
			'events': {
				'click': function(e) {
					e.stop();
					this.hide();
				}.bind(this)
			}
		});
		
		this.next = new Element('a', {
			'href':'#',
			'text':'Next',
			'class':this.options.classPrefix+'Next',
			'events': {
				'click': function(e) {
					e.stop();
					this.step(1);
				}.bind(this)
			}
		});
		
		this.previous = new Element('a', {
			'href':'#',
			'text':'Previous',
			'class':this.options.classPrefix+'Previous',
			'events': {
				'click': function(e) {
					e.stop();
					this.step(-1);
				}.bind(this)
			}
		});
		
		this.controls = Element('div',{
			'class': 'modalControls',
			'styles':{
				'width': '100%'
			}
		});
 
		// build our DOM
		this.mask.adopt(this.iframe);
		this.container.adopt(this.box)
		this.box.adopt(this.message, this.close);
		
		// close the modal on esc
		window.top.addEvent('keydown', function(e) {
			if(this.el && (e.key == 'esc')) {
				e.stop();
				this.hide();
			}
		}.bind(this));
 
		
		window.top.addEvent('resize',function(e) {
			if (this.el) this.update();
		}.bind(this));
		
		this.fireEvent('onStart');
	},
	
	show: function(obj,series) {

		this.state = (this.el)?'load':'mask';
		
		// if nothing is showing, we need to set-up the mask, et al
		if (this.el) {
			this.el.dispose();
		} else {
			// setup our styles before going visible
			this.mask.setStyles({
				'opacity':0,
				'height': $(window).getScrollSize().y
			});
	 
			this.container.setStyles({
				'opacity':0,
				'top': $(window).getScroll().y + 100,
				'visibility':'visible'
			});
			
			this.box.setStyles({
				'width':this.options.width,
				'height':this.options.height
			});
			
			this.message.setStyles({
				'opacity':0
			});
			
			// add our mask and container to the DOM
			document.body.appendChild(this.mask);
			document.body.appendChild(this.container);
		}
		
		// if we're showing a series of items, we have a few extra steps
		if (series && $type(series) == 'array') {
			
			// make sure we have one long list
			this.series = series.flatten();
 
			// display next/previous buttons
			this.box.adopt(this.controls, this.next, this.previous);
 
			// find the current element in the series
			this.index = this.series.indexOf(obj);
 
			// if the element can't be found, put it at the end
			if (this.index < 0) this.series.include(obj);
		} else {
			this.series = null;
		}
		
		// animate into view
		this.animate(obj);
		
		// fire the show event
		this.fireEvent('onShow');
	},
	
	animate: function(obj) {
		this.timer = $clear(this.timer);
		
		// mask > load > resize > show > hide > load > resize > show > (repeat)
		switch (this.state) {
			case 'mask':
				// animate the dialog box into view
				this.mask.tween('opacity',this.options.maskOpacity);
				this.container.tween('opacity',1);
				this.state = 'load';
				this.timer = this.animate.delay(this.options.speed,this,obj);
				break;
			case 'load':
				switch($type(obj)) {
					case 'array':
						this.series = obj;
						this.animate(this.series[0]); // pluck the first element in the array and attempt to load it
						return null;
					case 'element':
						this.state = 'resize';
						this.animate(obj);
						return null;
					case 'string':
						obj = new Element('div',{'html':obj,'styles':{'width':this.options.width,'height':this.options.height}});
						this.state = 'resize';
						this.animate(obj);
						return null;
					case 'object':
						try {
							obj.send();
						} catch (error) {
							this.animate('Invalid request.');
						}
						return null;
					default:
						return false;
						break;
				}
				break;
 
			case 'resize':
				if (this.el) this.el.dispose();
 
				// temporarily add obj to the DOM so we can determine size
				obj.setStyles({
					'opacity':0,
					'visibility':'hidden',
					'position':'absolute',
					'top':0,
					'left':0
				});
				document.body.appendChild(obj);
				var size = obj.getSize();
				
				// resize the box to the dimensions of the new element
				this.box.morph({'width':size.x,'height':size.y});
				this.state = 'show';
				this.timer = this.animate.delay(this.options.speed,this,obj);
				break;
 
			case 'show':
				this.el = obj;
				this.el.setStyles({
					'opacity':1,
					'position':'static',
					'visibility':'visible'
				});
				this.message.adopt(this.el);
				this.message.morph({'opacity':1});
				this.state = null;
				break;
 
			case 'hide':
				this.message.morph({'opacity':0});
				this.state = 'load';
				this.timer = this.animate.delay(this.options.speed,this,obj);
				break;
 
			default:
				break;
		}
	},
	
	step: function(steps) {
 
		// only continue if we're in a series of elements
		if (!this.series || this.series.length <= 0) return false;
		
		this.index = this.index + steps;
		if (this.index < 0) this.index = this.series.length -1;
		if (this.index >= this.series.length) this.index = 0
 
		// which element do we display next?
		var obj = this.series[this.index];
		
		// if the element doesn't exist, abort mission
		if (!obj) return false;
		
		this.state = 'hide';
		this.animate(obj);
		this.fireEvent('onStep');
	},
 
	update: function() {
		this.mask.setStyle('height',$(window).getScrollSize().y);
		this.fireEvent('onUpdate');
	},
 
	hide: function() {

		 // take elements out of the DOM so we can reuse them next time
		this.container.dispose();
		this.next.dispose();
		this.previous.dispose();
		this.el.dispose();
		this.el = null;
 
		// return everything to normal
		this.state = null;
		this.series = null;
		this.timer = $clear(this.timer);
		this.mask.fade('out');
		this.fireEvent('onHide');
	}
});



/*	---------------------------------------------------------------------------
	CLASS:		Validate(form, rules, [options]);
	OPTIONS:	validateOnBlur:		validate each input as the user proceeds through the form (default:true)
				selectors:			css selectors for the inputs to validate within the form (default: 'input[type=text], input[type=password], select, textarea')
				errorClass:			css class assigned to the input when validation fails (default: 'error')
				adviceClass:		css class assigned to the display message when validation fails (default: 'advice')
				waitingLabel:		text assigned to the submit button after the user clicks 'submit' (default: 'Please wait...')
				button:				submit button element (default: null, but finds input[type=submit] within the submit method)
	EVENTS:		onFail:				fires when an individual input fails validation
				onPass:				fires when an individual input passes validation
				onSuccess:			fires immediately before the form submits
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com
	REVISED:	December 14, 2009
	
*/

var Validate = new Class({
	
	Implements: [Options,Events],
	options: {
		validateOnBlur: true,
		selectors: 'input[type=text], input[type=password], input[type=checkbox], input[type=radio], input[type=password], select, textarea',
		errorClass: 'error',
		adviceClass: 'advice',
		titleAdvice: true,
		button: null,
		waitingLabel: 'Please wait...',
		onSuccess: $empty,
		onFail: $empty,
		onPass: $empty
	},

	initialize: function(form, rules, options) {
		this.setOptions(options);
		this.form = $(form);
		this.elements = this.form.getElements(this.options.selectors) // elements subject to validation;
		this.rules = [];	// rules for validation;
		
		// implement pre-defined rules
		this.standardRules.each(function(rule,index) {
			this.addRule(rule);
		}.bind(this));
		
		// implement any new rules
		if ($defined(rules)) {
			rules.each(function(rule,index) {
				this.addRule(rule);
			}.bind(this));
		}
		
		if (this.options.titleAdvice) {
			this.elements.each(function(el,index) {
				if (el.get('title')) {
					el.store('advice',el.get('title'));
					el.removeAttribute('title');
				}
			});
		}
		
		// if specified, validate onblur
		if(this.options.validateOnBlur) {
			this.elements.each(function(el,index){
				el.addEvent('blur', this.validate.bind(this, el));
			}.bind(this));
		}
		
		// validate the form onsubmit
		this.form.addEvent('submit', function(e) {
			return this.submit();
		}.bindWithEvent(this));
	},
	
	addRule: function(rule) {
		this.rules.push(rule);
	},

	addRules: function(rules) {
		rules.each(function(rule,index) {
			this.addRule(rule);
		}.bind(this));
	},
	
	submit: function() {
		if(this.validateAll()) {
			var button = (this.options.button)?this.options.button:this.form.getElement('input[type=submit]');
			if (button) {
				switch (button.get('tag')) {
					case 'input':
						button.value = this.options.waitingLabel;
						button.disabled = true;
					default:
						button.set('text',this.options.waitingLabel);
				}
			}
			return true;
		} else {
			this.fireEvent('onFail');
			return false;
		}
	},
	
	getAdvice: function(el) {
		var advice = [];
		this.rules.each(function(rule,index) {
			if (el.hasClass(rule.className)) {
				if (!rule.test(el)) advice.push(rule.advice);
			}
		});
		return advice;
	},

	getAllAdvice: function() {
		var advice = [];
		this.elements.each(function(el,index){
			advice.push(this.getAdvice(el))
		}.bind(this));
		return advice.flatten;
	},
	
	validate: function(el){
		var ok = true;
		this.rules.each(function(rule,index) {
			if (el.hasClass(rule.className)) {
				if (rule.test(el)) {
					this.fireEvent('onPass');
				} else {
					this.fireEvent('onFail');
					this.showAdvice(el,rule.advice);
					ok = false;
				}
			}
		}.bind(this));
		if (ok) this.clearAdvice(el);
		return ok;
	},
	
	validateAll: function() {
		var ok = true;
		this.elements.each(function(el,index){
			if(!this.validate(el)) {
				ok = (ok)?false:ok;
			}
		}.bind(this));
		return ok;
	
	},
	
	showAdvice: function(el, advice){
		advice = (el.retrieve('advice'))?el.retrieve('advice'):advice;
		
		if (el.retrieve('adviceGroup')) el = el.retrieve('adviceGroup');
		if(el.error == undefined) {
			el.error = new Element('div',{
				'class':this.options.adviceClass,
				'styles':{
					opacity: 0
				},
				'text':advice
			});
			if (el.retrieve('adviceElement')) {
				el.error.inject(el.retrieve('adviceElement'));
			} else {
				var pos = el.getPosition(el.getOffsetParent());
				var width = el.getWidth();
				el.error.setStyles({
					position: 'absolute',
					left: pos.x + width,
					top: pos.y
				});
				el.error.inject(el.getParent(),'inside');
			}
			el.error.tween('opacity',1); 
		} else {
			el.error.set('text',advice);
		}
		el.addClass(this.options.errorClass);
	},
	
	clearAdvice: function(el){
		el.removeClass(this.options.errorClass);
		if(el.error != undefined){
			el.error.destroy();
			el.error = undefined;
		}
	},
	
	standardRules: [
		// required field; supports input[type=text], textarea, checkbox, radio and select
		{
			'className':'required',
			'test':function(el) {
					switch (el.type) {
					case 'checkbox':
					case 'radio':
						var options = $$('input[name='+el.name+']');
						var ok = false;
						options.each(function(o){
							if (o.checked) ok = true;
						});
						if (!ok) return false;
						break;
					default:
						if (el.get('tag') == 'select' && el.selectedIndex <= 0) return false;
						if (el.value == '') return false;
						break;
				}
				return true;
			},
			'advice':'Required field'
		},
		
		// value (if any) must be an integer, i.e. positive whole number
		{
			'className':'integer',
			'test':function(el) {
				if (el.value != '') {
					if (isNaN(el.value)) {
						el.value = '';
						return false;
					}
				}
				return true;
			},
			'advice':'This field must be a number'
		},
		
		// value (if any) must be in the format name@domain.ext
		{
			'className':'email',
			'test':function(el) {
				if (el.value != '') {
					var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
					if (!el.value.toUpperCase().match(regEmail)) return false;
				}
				return true;
			},
			'advice':'Please enter a valid email address'
		},
		
		// checkbox must be checked regardless of other checkboxes in the same group
		{
			'className':'checked',
			'test':function(el) {
				if(!el.checked) return false;
				return true;
			},
			'advice':'You must check the box to continue'
		},
		
		// value (if any) must match the value of another element or character string
		{
			'className':'match',
			'test':function(el) {
				var target = el.retrieve('match');
				var str = ($type(target) == 'element')?target.value:target;
				if(el.value != str) return false;
				return true;
			},
			'advice':'Does not match'
		}
	]
});


// ---------------------------------------------------------------------
// Call these functions on page load throughout the site


// initialize the modal dialog box; keep the variable global
var modal = new Modal({'maskOpacity':.7,'width':460});

window.addEvent('domready',function() {
	// open modal dialog box when users click on "Email to a Friend"
	$('emailPage').addEvent('click',function(e){
		e.stop();
		_gaq.push(['_trackPageview', '/emailToAFriend/openModal']);
		// clone the form so we can use it again
		var el = $('emailModal').clone();
		var form = el.getElement('form');
		var submit = form.getElement('input[type=image]');
	
		// validate the cloned form
		var v = new Validate(form,[],{'submitButton':submit});
	
		// show the modal dialog
		modal.show(el);
		
		// submit the form via AJAX
		submit.addEvent('click',function(e) {
			e.stop();
	
			if (!v.validateAll()) return false;
			
			_gaq.push(['_trackPageview', '/emailToAFriend/formSent']);
			
			var div = new Element('div',{'style':'width:200px;'});
			var h1 = new Element('h2',{'text':'Please Wait'});
			var p = new Element('p',{'text':'Your message is being sent.'});
			var load = new Element('p',{'style':'text-align:center;'});
			var img = new Element('img',{'src':'/site/ajax-loader.gif','alt':''});
			div.adopt(h1,p,load.adopt(img));
			modal.show(div);
	
			// build our JSON data from the form inputs
			var data = {};
			var els = $A(form.elements);
			els.each(function(el,index) {
				data[el.name] = el.value;
			});
	
			// send it to the server
			var request = new Request.JSON({
				method: 'post',
				data: data,
				url: '/index.php/email/SendAJAX',
				onSuccess: function(respJSON, respText) {
						if (respJSON.status == "success") {
							var div = new Element('div');
							var h1 = new Element('h2',{'text':'Your message has been sent.'});
							var p = new Element('p');
							var a = new Element('a',{'text':'Close this window','events':{'click':function(e) {e.stop();modal.hide();}}});
							div.adopt(h1,p.adopt(a));
							modal.show(div);
						}
						else if (respJSON.status == "failure") {
							var div = new Element('div');
							var h1 = new Element('h2',{'text':'Oops!'});
							var p = new Element('p',{'text':'There was a problem sending your message. Please double-check your information. '});
							var a = new Element('a',{'text':'Try again','events':{'click':function(e) {e.stop();modal.hide();}}});
							div.adopt(h1,p.adopt(a));
							modal.show(div);
							if (respJSON.captcha_image) $('email_captcha_image').src = respJSON.captcha_image;
							if (respJSON.captcha_hmac) $('email_captcha_hmac').value = respJSON.captcha_hmac;
						}
						else {
							var div = new Element('div');
							var h1 = new Element('h2',{'text':'This is embarassing'});
							var p = new Element('p',{'text':'We are experiencing technical difficulties. Our webmaster has been notified. You may continue to browse the site, but this form is out of order. Sorry! '});
							var a = new Element('a',{'text':'Close this window','events':{'click':function(e) {e.stop();modal.hide();}}});
							div.adopt(h1,p.adopt(a));
							modal.show(div);
						}
					}
			}).send();
		});
	});
});

