/*	---------------------------------------------------------------------------
	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);
	}
});
/*	---------------------------------------------------------------------------
	FUNCTION:	initialize the page
	LAST MODIFIED: 01/16/08
	AUTHOR:	Ryan J. Salva

	Used by the SUBTEXT control panel to import css/wysiwyg.css while in edit mode (e.g. ?edit=true)
*/

window.addEvent('domready',function() {
	
	// add the accordian to secondary navigation
	var accordion = new Accordion('.ToggleControl', '.Toggle', {
		opacity: false,
		alwaysHide: true,
		display: show,
		onActive: function(toggler, element){
			toggler.toggleClass('Active');
		},
		onBackground: function(toggler, element){
			toggler.toggleClass('Active');
		}
	}, $('Secondary'));
	
	// store tooltip title and text
	$$('.Tip').each(function(el) {
		var full_title	= el.getProperty('title');
		var str = full_title.split('::');
		if (str.length == 1) {
			el.store('tip:title',str[0]);
			el.store('tip:text','');
		} else {
			el.store('tip:title', str[0].trim());
			el.store('tip:text', str[1].trim());
		}
	});

	// add tips
	var tip = new Tips($$('.Tip'), {
		className:'tool-tip',
		showDelay: 400,
		hideDelay: 400,
		onShow:function(tip) {
				tip.fade('in');
		},
		onHide:function(tip) {
			tip.fade('out');
		}
	});
	
});


/*	---------------------------------------------------------------------------
	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.trident) window.addEvent('domready', function() {
	$$('img[src$=png]').fix();
});


/*	---------------------------------------------------------------------------

	CLASS:		Validate
	VERSION:	2.0
	AUTHOR:		Samuel Birch
	ABOUT:		Form validation
	LICENSE:	Open Source MIT Licence
	
	MODIFIED:	Ryan J. Salva, http://www.capitolmedia.com
				Updated to be compatible with Capitol Media code library
	EXAMPLE:	<input type="text" name="FooBar" class="required email" />
				var valid = new Validate('myForm');
*/

var Validate = new Class({
	
	Implements: [Options,Events],
	options: {
		validateOnBlur: true,
		errorClass: 'error',
		errorMsgClass: 'errorMessage',
		showErrorsInline: true,
		label: 'Please wait...',
		onFail: $empty,
		onSuccess: $empty
	},

	initialize: function(form, options) {
		this.setOptions(options);
		
		this.form = $(form);
		this.elements = this.form.getElements('.required, .email, .number, .postcode');

		this.list = [];
		
		this.elements.each(function(el,i){
			if(this.options.validateOnBlur){
				el.addEvent('blur', this.validate.bind(this, el));
			}
		}.bind(this));
		
		this.form.addEvent('submit', function(e){
			var event = new Event(e);
			var doSubmit = true;
			this.elements.each(function(el,i){
				if(! this.validate(el)){
					event.stop();
					doSubmit = false
					this.list.include(el);
				}else{
					this.list.remove(el);
				}
			}.bind(this));
			
			if(doSubmit){
				if(this.options.onSuccess){
					event.stop();
					this.fireEvent('onSuccess');
				} else {
					this.form.getElement('input[type=submit]').setProperty('value',this.options.label);
				}
			}else{
				// this.getList();
				this.fireEvent('onFail');
			}
			
		}.bindWithEvent(this));
	},
	
	getList: function(){
		var list = new Element('ul');
		this.list.each(function(el,i){
			if(el.title != ''){
				var li = new Element('li').set('text',el.title);
			}
		});
		return list;
	},
	
	validate: function(el){
		var valid = true;
		this.clearMsg(el);
		
		switch(el.type){
			case 'text':
			case 'textarea':
				if(el.hasClass('required') && el.value == ''){
					valid = false;
					this.setMsg(el, 'This field is required.');
				} else {
					valid = true;
				}
				if (el.value != '') {
	
					if(el.hasClass('email')){
						var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
						if(el.value.toUpperCase().match(regEmail)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Please enter a valid email address');
						}
					}
					
					if(el.hasClass('number')){
						var regNum = /[-+]?[0-9]*\.?[0-9]+/;
						if(el.value.match(regNum)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Please enter a valid number');
						}
					}
					
					if(el.hasClass('postcode')){
						var regPC = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/
						if(el.value.match(regPC)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Please enter a valid postcode');
						}
					}
				}
					
				break;
				
			case 'select-one':
				if(el.hasClass('required') && el.selectedIndex != 0) {
					valid = true;
				} else {
					valid = false;
					this.setMsg(el, 'This field is required.');
				}
				break
					
			case 'checkbox':
				if(!el.checked){
					valid = false;
					this.setMsg(el);
				}else{
					valid = true;
				}
				break;
				
			case 'radio':
				var rad = $A(this.form[el.name]);
				var ok = false;
				rad.each(function(e,i){
					if(e.checked){
						ok = true;
					}
				});
				if(!ok){
					valid = false;
					this.setMsg(rad.getLast(), 'Please select an option');
				}else{
					valid = true;
					this.clearMsg(rad.getLast());
				}
				break;
				
		}
		return valid;
	},
	
	setMsg: function(el, msg){
		if(msg == undefined){
			msg = el.get('title');
		}
		if(this.options.showErrorsInline){
			if(el.error == undefined){
				var pos = el.getPosition(el.getOffsetParent());
				var width = el.getWidth();
				el.error = new Element('div',{'class':this.options.errorMsgClass,'styles':{
					opacity: 0,
					position: 'absolute',
					left: pos.x + width,
					top: pos.y
				}}).set('text',msg);
				el.error.inject(el.getParent(),'inside');
				el.error.tween('opacity',1); 
			}else{
				el.error.set('text',msg);
			}
			el.addClass(this.options.errorClass);
		}
	},
	
	clearMsg: function(el){
		el.removeClass(this.options.errorClass);
		if(el.error != undefined){
			el.error.destroy();
			el.error = undefined;
		}
	}
	
});


/*	---------------------------------------------------------------------------
	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();
	}
});



/*	---------------------------------------------------------------------------
	FUNCTION:	openWindow(name,url,w,h)
	AUTHOR:		Ryan J. Salva
	REVISED:	November 2004

	Opens a bare-bones window with no browser controls

	EXAMPLE:
	openWindow('myWin','http://www.google.com',400,600)
*/

function openWindow(name,url,w,h) {
	window.open(url,name,'top=100,left=100,width='+w+',height='+h+',scrollbars=no,location=no,resizable=no,status=no,toolbar=no');
}


/*	---------------------------------------------------------------------------
	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: Options,
	options: {
		speed: 1000,
		delay: 10000,
		direction: 'vertical'
	},
	initialize: function(el,options){
		this.setOptions(options);
		this.el = $(el);
		this.items = this.el.getElements('li');
		if (this.items.length <=  0) return false;
		var w = 0;
		var h = 0;
		if(this.options.direction.toLowerCase()=='horizontal') {
			h = this.el.getCoordinates().height;
			this.items.each(function(li,index) {
				w += li.getCoordinates().width;
			});
		} else {
			w = this.el.getCoordinates().width;
			this.items.each(function(li,index) {
				h += li.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].injectInside(this.el);
			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.next.bind(this).delay(this.options.delay+this.options.speed);
	}
});


/*	---------------------------------------------------------------------------
	FUNCTION:	calculateROI()
	AUTHOR:		Ryan J. Salva
*/

function calculateROI() {
	var rate = $('CurrentRate').value.toInt();
	var hours = $('CurrentHours').value.toInt();

	if (isNaN(rate) || isNaN(hours)) {
		var msg = new Element('div',{'class':'Padding','styles':{
			'width': 400
		}}).setHTML('<h1>Gadzoinks!<\/h1><p>To calculate return on investment, you need to use numbers... you know, like cash? Try it again with numbers only.');
		dlg.show(msg);
		return false;
	}

	var futureRate = (rate * .8).round(2);
	$('FutureRate').set('text','$'+futureRate);
	$('FutureHours').set('text','$'+hours);

	var currentCost = (rate * hours).round(2);
	$('CurrentCost').set('text','$'+currentCost);

	var futureCost = (futureRate * hours).round(2);
	$('FutureCost').set('text','$'+futureCost);

	$('Savings').set('text','$'+(currentCost - futureCost).round(2));
}

// global used for the accordian created in the footer template
var show = -1;

/*	---------------------------------------------------------------------------
	CLASS:		Tabs(panels,[classPrefix])
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Creates tabbed property panels
*/

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);
	}
});

