// JavaScript functions

/*
Script: pbb-datepicker-1.0-beta.js
	A Javascript class for Mootools 1.2 that adds accessible and unobtrusive date pickers to your form elements

License:
	MIT-style license.

Copyright:
	Copyright (c) 2008 Pokemon_JOJO, <http://www.mibhouse.org/pokemon_jojo/>

Inspiration:
	Some functionality inspired by [Calendar.js](http://electricprism.com/aeron) Copyright (c) 2007 Aeron Glemann, [MIT License](http://opensource.org/licenses/mit-license.php)
*/

var PBBDatePickers = new Class({

	Implements: [Events, Options],

	options: {
		onShow: function(datepicker){
			datepicker.setStyle('visibility', 'visible');
		},
		onHide: function(datepicker){
			datepicker.setStyle('visibility', 'hidden');
		},
		showDelay: 100,
		hideDelay: 100,
		className: null,
		offsets: {x: 0, y: 20},
		
		dateformat: 'd/m/Y',
		
		days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // days of the week starting at sunday
		months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
		weekFirstDay : 1 // first day of the week: 0 = sunday, 1 = monday, etc..
	},
	
	initialize: function(){
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		this.setOptions(params.options || null);
		this.lock = false;
		
		this.datepicker = new Element('div').addEvents({
			'mouseover': function(){
				this.lock = true;
			}.bind(this),
			'mouseout': function(){
				this.lock = false;
			}.bind(this)
		}).inject(document.body);
		
		if (this.options.className) this.datepicker.addClass(this.options.className);

		var top = new Element('div', {'class': 'datepicker-top'}).inject(this.datepicker);
		this.container = new Element('div', {'class': 'datepicker'}).inject(this.datepicker);
		var bottom = new Element('div', {'class': 'datepicker-bottom'}).inject(this.datepicker);

		this.datepicker.setStyles({position: 'absolute', top: 0, left: 0, visibility: 'hidden'});
		
		if (params.elements) this.attach(params.elements);
	},

	attach: function(elements){
		$$(elements).each(function(element){
			var dateformat = element.retrieve('datepicker:dateformat', element.get('accept'));
			if(!dateformat) {
				dateformat = this.options.dateformat;
				element.store('datepicker:dateformat', dateformat);
			}
			var datevalue = element.retrieve('datepicker:datevalue', element.get('value'));
			if(!datevalue) {
				datevalue = this.format(new Date(), dateformat);
				element.store('datepicker:datevalue', datevalue);
			}
			element.store('datepicker:current', this.unformat(datevalue,dateformat));
			
			var inputFocus = element.retrieve('datepicker:focus', this.elementFocus.bindWithEvent(this, element));
			var inputBlur = element.retrieve('datepicker:blur', this.elementBlur.bindWithEvent(this, element));
			element.addEvents({focus: inputFocus, blur: inputBlur});
			
			element.store('datepicker:native', element.get('accept'));
			element.erase('dateformat');
		}, this);
		return this;
	},

	detach: function(elements){
		$$(elements).each(function(element){
			element.removeEvent('onfocus', element.retrieve('datepicker:focus') || $empty);
			element.removeEvent('onblur', element.retrieve('datepicker:blur') || $empty);
			element.eliminate('datepicker:focus').eliminate('datepicker:blur');
			var original = element.retrieve('datepicker:native');
			if (original) element.set('dateformat', original);
		});
		return this;
	},

	elementFocus: function(event, element){
		this.el = element;
		
		var current = element.retrieve('datepicker:current');
		this.curFullYear = current[0];
		this.curMonth = current[1];
		this.curDate = current[2];
		
		this.build();
		
		this.timer = $clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);

		this.position({page: element.getPosition()});
	},
	
	elementChange: function() {
		this.el.store('datepicker:current', Array(this.curFullYear,this.curMonth,this.curDate));
		this.el.set('value',this.format(new Date(this.curFullYear, this.curMonth, this.curDate),this.el.retrieve('datepicker:dateformat')));
		
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},

	elementBlur: function(event){
		if(!this.lock) {			
			$clear(this.timer);
			this.timer = this.hide.delay(this.options.hideDelay, this);
		}
	},
	
	position: function(event){
		var size = window.getSize(), scroll = window.getScroll();
		var datepicker = {x: this.datepicker.offsetWidth, y: this.datepicker.offsetHeight};
		var props = {x: 'left', y: 'top'};
		for (var z in props){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + datepicker[z] - scroll[z]) > size[z]) pos = event.page[z] - this.options.offsets[z] - datepicker[z];
			this.datepicker.setStyle(props[z], pos);
		}
	},

	show: function(){
		this.fireEvent('show', this.datepicker);
	},

	hide: function(){
		this.fireEvent('hide', this.datepicker);
	},
	
	build: function() {
		$A(this.container.childNodes).each(Element.dispose);
		
		var table = new Element('table',{ 'cellpadding':0, 'cellspacing':0, 'border':0 }).inject(this.container);
		var caption = this.caption().inject(table);
		var thead = this.thead().inject(table);
		var tbody = this.tbody().inject(table);		
	},
	
	// navigate: calendar navigation 
	// @param type (str) m or y for month or year
	// @param d (int) + or - for next or prev	
	navigate: function(type, d) {
		switch (type) {
			case 'm': // month
				var i = this.curMonth + d;
				
				if (i < 0 || i == 12) {
					this.curMonth = (i < 0) ? 11 : 0;
					this.navigate('y', d);
				}
				else		
					this.curMonth = i;
				
				break;
			case 'y': // year
				this.curFullYear += d;
				
				break;
		}
		
		this.el.store('datepicker:current', Array(this.curFullYear,this.curMonth,this.curDate));
		
		this.el.focus(); // keep focus and do automatique rebuild ;)
	},

	// caption: returns the caption element with header and navigation
	// @returns caption (element)
	caption: function() {
		// start by assuming navigation is allowed
		var navigation = {
			prev: { 'month': true, 'year': true },
			next: { 'month': true, 'year': true }
		};
		
		var caption = new Element('caption');

		var prev = new Element('a').addClass('prev').appendText('\x3c'); // <		
		var next = new Element('a').addClass('next').appendText('\x3e'); // >

		var month = new Element('span').addClass('month').inject(caption);			
		if (navigation.prev.month) { prev.clone().addEvent('click', function() { this.navigate('m', -1); }.bind(this)).inject(month); }
		new Element('span').set('text', this.options.months[this.curMonth]).addEvent('mousewheel', function(e){ e.stop();this.navigate('m', (e.wheel < 0 ? -1 : 1));this.build();}.bind(this)).inject(month);		
		if (navigation.next.month) { next.clone().addEvent('click', function() { this.navigate('m', 1); }.bind(this)).inject(month); }

		var year = new Element('span').addClass('year').inject(caption);			
		if (navigation.prev.year) { prev.clone().addEvent('click', function() { this.navigate('y', -1); }.bind(this)).inject(year); }
		new Element('span').set('text', this.curFullYear).addEvent('mousewheel', function(e){ e.stop();this.navigate('y', (e.wheel < 0 ? -1 : 1));this.build();}.bind(this)).inject(year);
		if (navigation.next.year) { next.clone().addEvent('click', function() { this.navigate('y', 1); }.bind(this)).inject(year); }
		
		return caption;		
	},
	
	// thead: returns the thead element with day names
	// @returns thead (element)
	thead: function() {
		var thead = new Element('thead');
		var tr = new Element('tr').inject(thead);
		for (i = 0; i < 7; i++)	{ 
			new Element('th').set('text', this.options.days[(this.options.weekFirstDay + i)%7].substr(0, 2)).inject(tr);
		}
		
		return thead;
	},
	
	// tbody: returns the tbody element with day numbers
	// @returns tbody (element)
	tbody: function() {
		var d = new Date(this.curFullYear, this.curMonth, 1);
		
		var offset = ((d.getDay() - this.options.weekFirstDay) + 7) % 7; // day of the week (offset)
		var last = new Date(this.curFullYear, this.curMonth + 1, 0).getDate(); // last day of this month
		var prev = new Date(this.curFullYear, this.curMonth, 0).getDate(); // last day of previous month
		
		var v = (this.el.get('value')) ? this.unformat(this.el.get('value'),this.el.retrieve('datepicker:dateformat')) : false;
		var current = new Date(v[0], v[1], v[2]).getTime();
		
		var d = new Date();
		var today = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); // today obv 
		
		var tbody = new Element('tbody');
		
		tbody.addEvent('mousewheel', function(e){
			e.stop(); // prevent the mousewheel from scrolling the page.
			this.navigate('m', (e.wheel < 0 ? -1 : 1));
			this.build();
		}.bind(this));		
		
		for (var i = 1; i < 43; i++) { // 1 to 42 (6 x 7 or 6 weeks)
			if ((i - 1) % 7 == 0) { tr = new Element('tr').inject(tbody); } // each week is it's own table row
			
			var td = new Element('td').inject(tr);
			var day = i - offset;
			var date = new Date(this.curFullYear, this.curMonth, day);

			if (day < 1) { // last days of prev month
				day = prev + day;
				td.addClass('inactive');
			}
			else if (day > last) { // first days of next month
				day = day - last;
				td.addClass('inactive');
			}
			else {				
				if(date.getTime() == current)  { td.addClass('hilite');  }
				else if (date.getTime() == today) { td.addClass('today');  } // add class for today
				
				td.addEvents({
					'click': function(day) {
						this.curDate = day;
						this.elementChange();
					}.bind(this, day),
					'mouseover': function(td) { 
						td.addClass('hilite'); 
					}.bind(this, td),
					'mouseout': function(td, date) {
						if(date.getTime() != current)
							td.removeClass('hilite'); 
					}.bind(this, [td, date])
				}).addClass('active');
			}
			
			td.set('text',day);
		}	
		return tbody;		
	},

	// unformat: takes a value from an input and parses the d, m and y elements
	// @param val (string)
	// @param f (string) any combination of punctuation / separators and d, j, D, l, S, m, n, F, M, y, Y
	// @returns array
	unformat: function(val, f) {
		f = f.escapeRegExp();
		
		var re = {
			d: '([0-9]{2})',
			j: '([0-9]{1,2})',
			D: '(' + this.options.days.map(function(day) { return day.substr(0, 3); }).join('|') + ')',					
			l: '(' + this.options.days.join('|') + ')',
			S: '(st|nd|rd|th)',
			F: '(' + this.options.months.join('|') + ')',
			m: '([0-9]{2})',
			M: '(' + this.options.months.map(function(month) { return month.substr(0, 3); }).join('|') + ')',					
			n: '([0-9]{1,2})',
			Y: '([0-9]{4})',
			y: '([0-9]{2})'
		}

		var arr = []; // array of indexes

		var g = '';

		// convert our format string to regexp
		for (var i = 0; i < f.length; i++) {
			var c = f.charAt(i);
			
			if (re[c]) {
				arr.push(c);

				g += re[c];
			}
			else {
				g += c;
			}
		}

		// match against date
		var matches = val.match('^' + g + '$');
		
		var dates = new Array(3);

		if (matches) {
			matches = matches.slice(1); // remove first match which is the date

			arr.each(function(c, i) {
				i = matches[i];
				
				switch(c) {
					// year cases
					case 'y':
						i = '19' + i; // 2 digit year assumes 19th century (same as JS)
					case 'Y':
						dates[0] = i.toInt();
						break;

					// month cases
					case 'F':
						i = i.substr(0, 3);
					case 'M':
						i = this.options.months.map(function(month) { return month.substr(0, 3); }).indexOf(i) + 1;
					case 'm':
					case 'n':
						dates[1] = i.toInt() - 1;
						break;

					// day cases
					case 'd':
					case 'j':
						dates[2] = i.toInt();
						break;
				}
			}, this);
		}
		
		dates[0] = (dates[0]) ? dates[0] : new Date().getFullYear();
		dates[1] = (dates[1]) ? dates[1] : new Date().getMonth();
		dates[2] = (dates[2]) ? dates[2] : new Date().getDate();

		return dates;
	},
	
	// format: formats a date object according to passed in instructions
	// @param date (obj)
	// @param format (string) any combination of punctuation / separators and d, j, D, l, S, m, n, F, M, y, Y
	// @returns string
	format: function(date, format) {
		var str = '';
		
		if (date) {
			var j = date.getDate(); // 1 - 31
      		var w = date.getDay(); // 0 - 6
			var l = this.options.days[w]; // Sunday - Saturday
			var n = date.getMonth() + 1; // 1 - 12
			var f = this.options.months[n - 1]; // January - December
			var y = date.getFullYear() + ''; // 19xx - 20xx
			
			for (var i = 0, len = format.length; i < len; i++) {
				var cha = format.charAt(i); // format char
				
				switch(cha) {
					// year cases
					case 'y': // xx - xx
						y = y.substr(2);
					case 'Y': // 19xx - 20xx
						str += y;
						break;
	
					// month cases
					case 'm': // 01 - 12
						if (n < 10) { n = '0' + n; }
					case 'n': // 1 - 12
						str += n;
						break;
	
					case 'M': // Jan - Dec
						f = f.substr(0, 3);
					case 'F': // January - December
						str += f;
						break;
	
					// day cases
					case 'd': // 01 - 31
						if (j < 10) { j = '0' + j; }
					case 'j': // 1 - 31
						str += j;
						break;
	
					case 'D': // Sun - Sat
						l = l.substr(0, 3);
					case 'l': // Sunday - Saturday
						str += l;
						break;
	
					case 'N': // 1 - 7
						w += 1;
					case 'w': // 0 - 6
						str += w;
						break;

					case 'S': // st, nd, rd or th (works well with j)
						if (j % 10 == 1 && j != '11') { str += 'st'; }
						else if (j % 10 == 2 && j != '12') { str += 'nd'; }
						else if (j % 10 == 3 && j != '13') { str += 'rd'; }
						else { str += 'th'; }
						break;
	
					default:
						str += cha;
				}
			}
		}

	  return str; //  return format with values replaced
	}
	
});

/* ----------------------------------------------------------------------------------------------- iFrame shim */
/*
Script: IframeShim.js
	Defines IframeShim, a class for obscuring select lists and flash objects in IE.

License:
	http://clientside.cnet.com/wiki/cnet-libraries#license
*/	
var IframeShim = new Class({
	
	Implements: [Options, Events],
	
	options: {
		name: '',
		className:'iframeShim',
		display:false,
		zindex: null,
		margin: 0,
		offset: {
			x: 0,
			y: 0
		},
		browsers: (Browser.Engine.trident4 || (Browser.Engine.gecko && !Browser.Engine.gecko19 && Browser.Platform.mac))
	},
	
	initialize: function (element, options){
		this.setOptions(options);
		//legacy
		if(this.options.offset && this.options.offset.top) this.options.offset.y = this.options.offset.top;
		if(this.options.offset && this.options.offset.left) this.options.offset.x = this.options.offset.left;
		this.element = $(element);
		this.makeShim();
		return;
	},
	
	makeShim: function(){
		this.shim = new Element('iframe');
		this.id = this.options.name || new Date().getTime() + "_shim";
		if(this.element.getStyle('z-Index').toInt()<1 || isNaN(this.element.getStyle('z-Index').toInt()))
		this.element.setStyle('z-Index',5);
		var z = this.element.getStyle('z-Index')-1;
		
		if($chk(this.options.zindex) && 
			 this.element.getStyle('z-Index').toInt() > this.options.zindex)
			 z = this.options.zindex;
			
 		this.shim.setStyles({
			'position': 'absolute',
			'zIndex': z,
			'border': 'none',
			'filter': 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
		}).setProperties({
			'src':'javascript:void(0);',
			'frameborder':'0',
			'scrolling':'no',
			'id':this.id
		}).addClass(this.options.className);
		
		this.element.store('shim', this);

		var inject = function(){
			this.shim.inject(this.element, 'after');
			if(this.options.display) this.show();
			else this.hide();
			this.fireEvent('onInject');
		};
		if(this.options.browsers){
			if(Browser.Engine.trident && !IframeShim.ready) {
				window.addEvent('load', inject.bind(this));
			} else {
				inject.run(null, this);
			}
		}
	},
	position: function(shim){
		if(!this.options.browsers || !IframeShim.ready) return this;
		var before = this.element.getStyles('display', 'visibility', 'position');
		this.element.setStyles({
			display: 'block',
			position: 'absolute',
			visibility: 'hidden'
		});
		var size = this.element.getSize();
		this.element.setStyles(before);
		if($type(this.options.margin)){
			size.x = size.x-(this.options.margin*2);
			size.y = size.y-(this.options.margin*2);
			this.options.offset.x += this.options.margin; 
			this.options.offset.y += this.options.margin;
		}
 		this.shim.setStyles({
			'width': size.x,
			'height': size.y
		}).setPosition({
			relativeTo: this.element,
			offset: this.options.offset
		});
		return this;
	},
	hide: function(){
		if(this.options.browsers) this.shim.setStyle('display','none');
		return this;
	},
	show: function(){
		if(!this.options.browsers) return this;
		this.shim.setStyle('display','block');
		return this.position();
	},
	dispose: function(){
		if(this.options.browsers) this.shim.dispose();
		return this;
	}
});
window.addEvent('load', function(){
	IframeShim.ready = true;
});



/* ----------------------------------------------------------------------------------------------- Implement dollar fomatting */
Number.implement({
    'dollar': function(){
		amount = this;
		amount = parseInt(amount * 100);
		amount = parseFloat(amount/100);
		
		if(((amount) == Math.floor(amount)) && ((amount - Math.floor (amount)) == 0)){
			amount = amount + '.00'
			return amount;
		}
		
		if(((amount * 10) - Math.floor(amount * 10)) == 0){
			amount = amount + '0';
			return amount;
		}
		
		if(((amount * 100) - Math.floor(amount * 100)) == 0){
			amount = amount;
			return amount;
		}
		
		return amount;
	}
});//End implement dollar



/* ----------------------------------------------------------------------------------------------- zebraStripeTable class */

//Add zebra striping to table
var zebraStripeTable = new Class({
	
	Implements: Options,

	options: {
		evenRowClass:   'evenRow',
		oddRowClass:    'oddRow',
		selectRowClass: 'selectRow',
		hoverRowClass:  'hoverRow'
	},
	
	initialize: function(table, options){
		this.setOptions(options);
		this.table          = table;
		this.activeClass    = this.options.oddRowClass;
		this.evenRowClass   = this.options.evenRowClass;
		this.oddRowClass    = this.options.oddRowClass;
		this.selectRowClass = this.options.selectRowClass;
		this.hoverRowClass  = this.options.hoverRowClass;
		this.tableRows      = this.table.getElements('tr');

		//Loop through table rows
		this.tableRows.each(function(el,index){
			
			//Stripe rows
			this.stripeRow(el,index);
			
			//Set hover over
			el.addEvent('mouseenter',function(){
				this.enterRow(el);
			}.bind(this));
			
			//Set hover out
			el.addEvent('mouseleave',function(){
				this.leaveRow(el);
			}.bind(this));
			
			//Set select
			el.addEvent('click',function(){
				if(el.hasClass(this.selectRowClass)){
					this.unSelectRow(el);
				}else{
					this.selectRow(el);
				}
			}.bind(this));
				
		}, this);

	},
	
	//Stripe rows with alternating classes
	stripeRow: function(el,index){
			
		//Check if even	row
		if(index % 2){
			el.addClass(this.evenRowClass);
		}else{
			el.addClass(this.oddRowClass);
		}

	},
	
	//When the row is selected
	selectRow: function(el){
		el.removeClass(this.activeClass).removeClass(this.hoverRowClass).addClass(this.selectRowClass);
	},
	
	//When the row is selected
	unSelectRow: function(el){
		el.removeClass(this.selectRowClass).addClass(this.activeClass);
	},
	
	//When the mouse enters the row
	enterRow: function(el){
		if(!el.hasClass(this.selectRowClass)){
			el.addClass(this.hoverRowClass).removeClass(this.activeClass);
		}
	},
	
	//When the mouse leaves the row
	leaveRow: function(el){
		if(!el.hasClass(this.selectRowClass)){
			el.removeClass(this.hoverRowClass).addClass(this.activeClass);
		}
	}
	
});//End zebraStripeTable


/* ----------------------------------------------------------------------------------------------- modalBox class */

//Display modal overlay box
var modalBox = new Class({
	
	Implements: Options,

	options: {
		closeOnClick:   true,
		overlayOpacity: 0.8,
		content:        $empty
	},
	
	initialize: function(options){
		this.setOptions(options);
		this.closeOnClick    = this.options.closeOnClick;
		this.overlayOpacity  = this.options.overlayOpacity;
		this.overlay         = $empty;
		this.contentBox      = $empty;
	},
	
	//Show the current modalBox
	show: function(){
		
		//Create an overlay
		this.overlay = new Element('div',{
		'id':'modalOverlay', 
		'class':'modalOverlay', 
		'styles':{
			'width':'100%',
			'height':window.getScrollSize().y,
			'position':'absolute',
			'top':0,
			'left':0,
			'z-index':1000,
			'opacity':0
			}
		});
		
		//Inject overlay into document body
		this.overlay.inject(document.body);
		
		//Create content box
		this.contentBox = new Element('div',{
		'id':'modalContentBox',
		'styles':{
			'position':'absolute',
			'z-index':1001
			}
		});
		
		if($type(this.options.content) == "string"){
			this.contentBox.set('html', this.options.content);
		}else{
			this.contentBox.adopt(this.options.content);
		}
		
		//Inject content box into document body
		this.contentBox.inject(document.body);
		
		//Get size of content box
		var contentBoxSize = this.contentBox.getSize();
		
		//Update content box position
		this.contentBox.setStyles({
			'top': (window.getScrollSize().y-window.getSize().y)+((window.getSize().y/2) - contentBoxSize.y),
			'left': (window.getSize().x/2)-(contentBoxSize.x/2)
		});
		
		//Hide things like select lists and embeded flash
		this.iframeShim(0);

		//Show the overlay
		this.overlay.set('opacity',this.overlayOpacity);
		
		//If closeOnClick is set to true
		if(this.closeOnClick){
			//Add click event to overlay
			this.overlay.addEvent('click',function(el){
				this.hide();
			}.bind(this));
		}
	
	},
	
	//Hide (destroy) modalBox
	hide: function(){
		//Destroy content and overlay
		this.contentBox.destroy();
		this.overlay.destroy();
		//Bring select lists and embeded flash back
		this.iframeShim(1);
	},
	
	//Set the opacity of iframe shim objects
	iframeShim: function(overlayOpacity){
		if(Browser.Engine.trident4 || (Browser.Engine.gecko && Browser.Platform.mac)) {
			$$('select').each(function(select){
				select.setStyle('opacity', overlayOpacity);
			});
		}
	}
	
});//End modalBox


/* ----------------------------------------------------------------------------------------------- Toggle the display of optional fields */
//Toggle the display of a group of input fields
var displayHiddenOptions = new Class({
	
	Implements: Options,

	options: {
		event: 'click',
		triggerValue: '',
		optionalFields: []
	},
	
	initialize: function(arr_handles,container, options){
		this.setOptions(options);
		this.arr_handles    = arr_handles;
		this.container      = container;
		this.event          = this.options.event;
		this.triggerValue   = this.options.triggerValue;
		this.optionalFields = this.options.optionalFields;
		
		//Chek handles and container exist
		if(this.arr_handles && this.container){
			
			//Make sure at leaset one handle is checked or meets the trigger value  
			var isSelected = this.arr_handles.some(function(item, index){
				return (item.checked || item.value == this.triggerValue);
			}.bind(this));
			
			//If selected
			if(isSelected){
				this.show(this.container);
			}else{
				this.hide(this.container);
			}
			
			//Loop handles
			arr_handles.each(function(handle,i){
				
				if(handle){
					//Add trigger event  to handle
					handle.addEvent(this.event, function(){
						if(handle.checked || handle.value == this.triggerValue){
							this.show(this.container);
						}else{
							this.hide(this.container);
						}
					}.bind(this));
					
				}
				
			}.bind(this));
			
		}
		
	},
	
	show: function(container){
		this.container.slide('in');
	},
	
	hide: function(container){
		container.slide('out');
		this.optionalFields.each(function(field, i){
			if($chk(field)){
				if(field.get('type') == 'radio' || field.get('type') == 'checkbox'){
					field.checked = false;
				}else{
					field.value = '';
				}
			}
		});
	}
	
});


/* ----------------------------------------------------------------------------------------------- Setup functions */
var functions = {//Start functions
	
	/*
	Display the please wait dialog
	
	this.zebraStripeTables();
	
	*/
	zebraStripeTables: function(tables){//Start zebraStripeTables

		if(tables){
			tables.each(function(table,index){
				var stripeTable = new zebraStripeTable(table);	
			});
		}
		
	},//End zebraStripeTables
	
	
	/*
	Display the please wait dialog
	
	this.waitDialog('.class','message to display');
	
	*/
	waitDialog: function(triggers,message){

		//Create new modal box
		var waitModal = new modalBox({'closeOnClick':false,'content':message});
		
		//For each trigger
		triggers.each(function(el){
			//Each time a trigger is clicked
			el.addEvent('click',function(e){
				waitModal.show();		   
			});					 
		});
	},
	
	
	/*
	Display other title
	
	this.displayOtherTitle();
	
	*/
	displayOtherTitle: function(select,container,field){//Start displayOtherTitle
		
		if(select && container && field){
			
			if(select.value == 'Other'){
				container.slide('in');
			}else{
				container.slide('out');
				field.value = '';
			}
			
			select.addEvent('change',function(){
				if(this.value == 'Other'){
					container.slide('in');
				}else{
					container.slide('out');
					field.value = '';
				}
			});
				
		}
		
	},//End displayOtherTitle
	
	
	/*
	Display billing options
	
	this.displayBillingOptions();
	
	*/
	displayBillingOptions: function(){//Start displayBillingOptions

		var billingSelect = $('billingmethod');
		var cheque        = $('cheque');
		var deposit       = $('deposit');
		var creditcard    = $('creditcard');

		if(billingSelect){

			displayMethod(billingSelect.value);
			
			billingSelect.addEvent('change',function(){
				displayMethod(this.value);
			});
			
		}
		
		function displayMethod(method){

			if(method == 'Cheque'){
				cheque.slide('in');
			}else{
				cheque.slide('out');
			}
			
			if(method == 'Direct Deposit'){
				deposit.slide('in');
			}else{
				deposit.slide('out');
			}
			
			if(method == 'Credit Card'){
				creditcard.slide('in');
			}else{
				creditcard.slide('out');
				/*$('cctype').value   = '';
				$('ccname').value   = '';
				$('ccnumber').value = '';
				$('ccexpiry').value = '';*/
			}
			
		}
		
	},//End displayBillingOptions
	
	
	/*
	Display Registration Total
	
	this.displayRegistrationTotal();
	
	*/
	displayRegistrationTotal: function(){//Start displayRegistrationTotal
		
		//Get place holder
		var placeHolder = $('totalPlaceHolder');
		
		if(placeHolder){
			
			//Create new container for total message
			var totalMessage = new Element('p',{'id':'totalDue','html':'Total due AUD $0.00'});
			
			//Replace place holder with total message
			totalMessage.replaces(placeHolder);
			
		}
		
	},//End displayRegistrationTotal
	
	
	/*
	Calculate the registration total
	
	this.calculateRegistrationTotal();
	
	*/
	calculateRegistrationTotal: function(){//Start calculateRegistrationTotal
		
		var registrationTotal         = 0;
		var workshopTotal             = 0;
		var accommodationTotal        = 0;
		var registrationAmt           = $('registrationamt');
		
		if(registrationAmt){
		
			//Registration Type 
			if($('registrationtype_option1').checked){ registrationTotal = 300; }
			if($('registrationtype_option2').checked){ registrationTotal = 100; }
			if($('registrationtype_option3').checked){ registrationTotal = 200; }
			if($('registrationtype_option4').checked){ registrationTotal = 200; }
			if($('registrationtype_option5').checked){ registrationTotal = 0; }
			
			//Functions
			if($('additional_ticket').checked){ registrationTotal = registrationTotal+99;}	
			
			//Update registration amount
			updatedTotal = registrationTotal.dollar();
			registrationAmt.value = updatedTotal;
			
			if($('totalDue')){
				$('totalDue').set('html','Total due AUD $'+updatedTotal);
			}
			
		}
	
	},//End calculateRegistrationTotal
	
	
/* ----------------------------------------------------------------------------------------------- Initialize functions */
	init: function(){
		
		//Zebra stripe tables
		this.zebraStripeTables($$('.stripeTable'));
		
		//Please wait dialog
		this.waitDialog($$('.waitModal'),'Please wait...');
		
		//Check for free student registration option
		if($('registrationtype_option5') && $('student_number')){//Start if student
			
			//Toggle student number
			var toggleStudentNumber = new displayHiddenOptions([$('registrationtype_option5')],$('student_number'),{'optionalFields':[$('studentnumber')]});
			
			//Check for breakfast option
			if($('breakfast') && $('userdefined1')){
				//Toggle breakfast
				var toggleBreakfast = new displayHiddenOptions([$('registrationtype_option1'),$('registrationtype_option2'),$('registrationtype_option3'),$('registrationtype_option4')],$('breakfast'),{'optionalFields':[$('userdefined1')]});
				
				//Hide breakfast
				$('registrationtype_option5').addEvent('click',function(){
					toggleBreakfast.hide($('breakfast'));
				});
			}
			
			//Array of elements that will hide the student number when clicked
			var toggleHideStudentNumberArray = [$('registrationtype_option1'),$('registrationtype_option2'),$('registrationtype_option3'),$('registrationtype_option4')];
			
			toggleHideStudentNumberArray.each(function(el,index){
				if(el){
					
					if(el.checked){
						toggleStudentNumber.hide($('student_number'));	
					}
					
					el.addEvent('click',function(){
						toggleStudentNumber.hide($('student_number'));
					}.bind(this));
				}								 
			}.bind(this));
		
		}//End if student
		
		//Toggle other title
		var toggleOtherTitle = this.displayOtherTitle($('title'),$('other_title'),$('othertitle'));
		
		//Toggle additional ticket
		var toggleAdditionalTicket = new displayHiddenOptions([$('additional_ticket')],$('additionalTicket'),{'optionalFields':[$('aptitle'),$('apfirstname'),$('apsurname'),$('apbadgename'),$('apposition'),$('aporganisation'),$('apdiet')]});
		
		//Toggle billing options
		this.displayBillingOptions();
		
		//Display the registration total
		this.displayRegistrationTotal();
		
		//Calculate rego total on page load
		this.calculateRegistrationTotal();
		
		if($('registrationOptions')){
			//Array of elements that will trigger registration calculation when clicked or changed
			var calculateRegistrationArray = [$('registrationOptions').getElements('input[type=radio]'),$('additional_ticket')];
			
			calculateRegistrationArray.each(function(el,index){
				if(el){

					el.addEvents({
						'click': function(){
							this.calculateRegistrationTotal();
						}.bind(this),
						'change': function(){
							this.calculateRegistrationTotal();
						}.bind(this)
					});

				}								 
			}.bind(this));
		
		}
		
		//Arrival and departure date pickers
		var datePickers = new PBBDatePickers('.pickdate');

	}

};//End functions

//Check DOM is loaded

window.addEvent('domready', functions.init.bind(functions));



