/*	---------------------------------------------------------------------------
	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.update();

		window.addEvent('resize',function(e) {
			this.update();
		}.bind(this));
	},
	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:		Tabs(panels,[classPrefix])
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Creates tabbed property panels. Resulting HTML looks like this:
				<span class="PanelTab">First Tab</span>
				<span class="PanelTab">Second Tab</span>
				<div class="PanelContainer">
					<div class="Panel">
						Content displayed when you click on the first tab.
					</div>
					<div class="Panel">
						Content displayed when you click on the second tab.
					</div>
				</div>
*/

var Tabs = new Class({
	Implements: Options,
	options: {
		classPrefix: 'panel'
	},
	initialize: function(panels, options) {
		this.setOptions(options);
		if (panels.length <= 0) return false;
		
		this.panels = panels;
		this.panels.setStyle('display','none');
		
		this.tabs = [];
		this.panels.each(function(el,index) {
			var tab = new Element('span',{
				'class':this.options.classPrefix+'Tab',
				'text':el.get('title'),
				'events':{
					'click':function(e){
						e.stop();
						this.activate(el,e.target);
					}.bindWithEvent(this)
				}
			});
			this.tabs.include(tab);
		}.bind(this));
		
		this.container = new Element('div',{
			'class':this.options.classPrefix+'Container',
			'styles':{
				'overflow':'hidden',
				'height':0
			}
		});
		this.container.inject(this.panels[0],'before');
		this.panels.each(function(el,index) {
			this.container.adopt(el);
		}.bind(this));
		
		this.tabs.each(function(el,index){
			el.inject(this.container,'before');
		}.bind(this));
		
		this.activate(this.panels[0],this.tabs[0])

		
	},
	
	activate: function(panel,tab){
		this.panels.removeClass(this.options.classPrefix+'Active');
		panel.addClass(this.options.classPrefix+'Active');
		
		this.panels.setStyle('display','none');
		panel.setStyle('display','block');
		
		this.tabs.each(function(el,index){
			el.removeClass(this.options.classPrefix+'Active');
		}.bind(this));
		tab.addClass(this.options.classPrefix+'Active');
		
		this.container.tween('height',panel.getSize().y);
	}
});


/*	---------------------------------------------------------------------------
	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
				onSuccess:			fires when an individual input passes validation
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com
	REVISED:	September 25, 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...',
		onFail: $empty,
		onSuccess: $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;
		}
	},
	
	validate: function(el){
		var ok = true;
		this.rules.each(function(rule,index) {
			if (el.hasClass(rule.className)) {
				if (rule.test(el)) {
					this.fireEvent('onSuccess');
				} 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'
		}
	]
});



/*	---------------------------------------------------------------------------
	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,
		selector: 'div',
		loop: true
	},
	
	initialize: function(container,options) {
		this.setOptions(options);
		this.container = $(container);
		this.els = this.container.getElements(this.options.selector);
		this.els.setStyles({
			'position':'absolute',
			'top':0,
			'left':0,
			'opacity':0
		});
		if (this.els.length <= 0) return false;
		this.els[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() {
		if (this.els.length <= 0) return false;
		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.els.length-1)?0:this.next+1;
		var prev = (this.next==0)?this.els.length-1:this.next-1;
		
		this.els[this.next].fade('in');
		this.els[prev].fade('out');
	}
});

/*	---------------------------------------------------------------------------
	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': 400,
		'height': 200,
		'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)
			}
		});

		// 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, backspace, delete, space or enter
		window.top.addEvent('keydown', function(e) {
			if(this.el && (e.key == 'esc' || e.key == 'backspace' || e.key == 'delete' || e.key == 'space' || e.key == 'enter')) {
				e.stop();
				this.hide();
			}
		}.bind(this));

		// step previous on left or up arrow
		window.top.addEvent('keydown', function(e) {
			if(this.el && (e.key == 'left' || e.key == 'up')) {
				e.stop();
				this.step(-1);
			}
		}.bind(this));

		// step next on right or down arrow
		window.top.addEvent('keydown', function(e) {
			if(this.el && (e.key == 'right' || e.key == 'down')) {
				e.stop();
				this.step(1);
			}
		}.bind(this));
		
		window.top.addEvent('resize',function(e) {
			if (this.el) this.update();
		}.bind(this));
		
		this.fireEvent('onStart');
	},
	
	show: function(obj,series) {
		
		// paranoia: make sure there's nothing in this.box when we first open it
		if (this.el) this.el.dispose();
		
		// 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.previous, this.next);

			// 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.state = 'mask';
		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();

		// return everything to normal
		this.state = null;
		this.series = null;
		this.timer = $clear(this.timer);
		this.mask.fade('out');
		this.fireEvent('onHide');
	}
});


/*	---------------------------------------------------------------------------
	CLASS:		Ticker(el,[speed,delay,direction]);
	OPTIONS:	speed:		the transition speed (default:500)
				delay:		the amount of time a news item stays at a position (default: 5000)
				direction:	horizontal or vertical scrolling (default: 'vertical')
	AUTHOR:		Ryan J. Salva
	EMAIL		ryan at capitolmedia.com
	REVISED:	September 2008
*/

var Ticker = new Class({
	Implements: [Events, Options],
	options: {
		speed: 1000,
		delay: 5000,
		direction: 'vertical',
		selector: 'li',
		onComplete: $empty,
		onStart: $empty
	},
	initialize: function(el,options){
		this.setOptions(options);
		this.el = $(el);
		this.items = this.el.getElements(this.options.selector);
		this.timer = null;
		var w = 0;
		var h = 0;
		var coord = this.el.getCoordinates();
		if(this.options.direction.toLowerCase()=='vertical') {
			w = coord.width;
			this.items.each(function(li,index) {
				h += li.getCoordinates().width;
			});
		} else {
			h = coord.height;
			this.items.each(function(el,index) {
				w += el.getCoordinates().width;
			});
		}
		this.el.setStyles({
			position: 'absolute',
			top: 0,
			left: 0,
			width: w,
			height: h
		});
		this.fx = new Fx.Morph(this.el,{duration:this.options.speed,onComplete:function() {
			var i = (this.current==0)?this.items.length:this.current;
			this.items[i-1].inject(this.el,'inside');
			this.el.setStyles({
				left:0,
				top:0
			});
		}.bind(this)});
		this.current = 0;
		this.next();
	},
	
	next: function() {
		this.current++;
		if (this.current >= this.items.length) this.current = 0;
		var pos = this.items[this.current];
		this.fx.start({
			top: -pos.offsetTop,
			left: -pos.offsetLeft
		});
		this.timer = this.next.bind(this).delay(this.options.delay+this.options.speed);
	},
	stop: function() {
		this.fx.cancel();
		$clear(this.timer);
	}
});

