//Public javascript functions


/*
	Slimbox v1.7 - The ultimate lightweight Lightbox clone
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
var Slimbox=(function(){var F=window,n=Browser.Engine.trident4,u,g,G=-1,o,w,E,v,y,M,s,m={},t=new Image(),K=new Image(),I,a,h,q,J,e,H,c,A,L,x,i,d,C;F.addEvent("domready",function(){document.id(document.body).adopt($$(I=new Element("div",{id:"lbOverlay",events:{click:D}}),a=new Element("div",{id:"lbCenter"}),H=new Element("div",{id:"lbBottomContainer"})).setStyle("display","none"));h=new Element("div",{id:"lbImage"}).injectInside(a).adopt(q=new Element("div",{styles:{position:"relative"}}).adopt(J=new Element("a",{id:"lbPrevLink",href:"#",events:{click:B}}),e=new Element("a",{id:"lbNextLink",href:"#",events:{click:f}})));c=new Element("div",{id:"lbBottom"}).injectInside(H).adopt(new Element("a",{id:"lbCloseLink",href:"#",events:{click:D}}),A=new Element("div",{id:"lbCaption"}),L=new Element("div",{id:"lbNumber"}),new Element("div",{styles:{clear:"both"}}))});function z(){var N=F.getScroll(),O=F.getSize();$$(a,H).setStyle("left",N.x+(O.x/2));if(v){I.setStyles({left:N.x,top:N.y,width:O.x,height:O.y})}}function l(N){["object",n?"select":"embed"].forEach(function(P){Array.forEach(document.getElementsByTagName(P),function(Q){if(N){Q._slimbox=Q.style.visibility}Q.style.visibility=N?"hidden":Q._slimbox})});I.style.display=N?"":"none";var O=N?"addEvent":"removeEvent";F[O]("scroll",z)[O]("resize",z);document[O]("keydown",p)}function p(O){var N=O.code;return u.closeKeys.contains(N)?D():u.nextKeys.contains(N)?f():u.previousKeys.contains(N)?B():false}function B(){return b(w)}function f(){return b(E)}function b(N){if(N>=0){G=N;o=g[N][0];w=(G||(u.loop?g.length:0))-1;E=((G+1)%g.length)||(u.loop?0:-1);r();a.className="lbLoading";m=new Image();m.onload=k;m.src=o}return false}function k(){a.className="";d.set(0);h.setStyles({backgroundImage:"url("+o+")",display:""});q.setStyle("width",m.width);$$(q,J,e).setStyle("height",m.height);A.set("html",g[G][1]||"");L.set("html",(((g.length>1)&&u.counterText)||"").replace(/{x}/,G+1).replace(/{y}/,g.length));if(w>=0){t.src=g[w][0]}if(E>=0){K.src=g[E][0]}M=h.offsetWidth;s=h.offsetHeight;var P=Math.max(0,y-(s/2)),N=0,O;if(a.offsetHeight!=s){N=i.start({height:s,top:P})}if(a.offsetWidth!=M){N=i.start({width:M,marginLeft:-M/2})}O=function(){H.setStyles({width:M,top:P+s,marginLeft:-M/2,visibility:"hidden",display:""});d.start(1)};if(N){i.chain(O)}else{O()}}function j(){if(w>=0){J.style.display=""}if(E>=0){e.style.display=""}C.set(-c.offsetHeight).start(0);H.style.visibility=""}function r(){m.onload=$empty;m.src=t.src=K.src=o;i.cancel();d.cancel();C.cancel();$$(J,e,h,H).setStyle("display","none")}function D(){if(G>=0){r();G=w=E=-1;a.style.display="none";x.cancel().chain(l).start(0)}return false}Element.implement({slimbox:function(N,O){$$(this).slimbox(N,O);return this}});Elements.implement({slimbox:function(N,Q,P){Q=Q||function(R){return[R.href,R.title]};P=P||function(){return true};var O=this;O.removeEvents("click").addEvent("click",function(){var R=O.filter(P,this);return Slimbox.open(R.map(Q),R.indexOf(this),N)});return O}});return{open:function(P,O,N){u=$extend({loop:false,overlayOpacity:0.8,overlayFadeDuration:400,resizeDuration:400,resizeTransition:false,initialWidth:250,initialHeight:250,imageFadeDuration:400,captionAnimationDuration:400,counterText:"Image {x} of {y}",closeKeys:[27,88,67],previousKeys:[37,80],nextKeys:[39,78]},N||{});x=new Fx.Tween(I,{property:"opacity",duration:u.overlayFadeDuration});i=new Fx.Morph(a,$extend({duration:u.resizeDuration,link:"chain"},u.resizeTransition?{transition:u.resizeTransition}:{}));d=new Fx.Tween(h,{property:"opacity",duration:u.imageFadeDuration,onComplete:j});C=new Fx.Tween(c,{property:"margin-top",duration:u.captionAnimationDuration});if(typeof P=="string"){P=[[P,O]];O=0}y=F.getScrollTop()+(F.getHeight()/2);M=u.initialWidth;s=u.initialHeight;a.setStyles({top:Math.max(0,y-(s/2)),width:M,height:s,marginLeft:-M/2,display:""});v=n||(I.currentStyle&&(I.currentStyle.position!="fixed"));if(v){I.style.position="absolute"}x.set(0).start(u.overlayOpacity);z();l(1);g=P;u.loop=u.loop&&(g.length>1);return b(O)}}})();

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	$$(document.links).filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	}).slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};
window.addEvent("domready", Slimbox.scanPage);


/* ----------------------------------------------------------------------------------------------- End third party classes */


/* ----------------------------------------------------------------------------------------------- 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


/* ----------------------------------------------------------------------------------------------- checkAll class */

//Add check all box and associate with a group of target checkboxes
var checkAll = new Class({
	
	Implements: Options,

	options: {},
		
	initialize: function(checkAllCheckBox, targetCheckBoxes, options){
		
		this.setOptions(options);
		this.checkAllCheckBox = checkAllCheckBox;
		this.targetCheckBoxes = targetCheckBoxes;
		
		//If check box and targets exist
		if(this.checkAllCheckBox && this.targetCheckBoxes){
			//Set onclick
			this.checkAllCheckBox.addEvent('click',function(){
				
				if(!this.checkAllCheckBox.checked){
					this.unCheckBoxes(this.targetCheckBoxes);
				}else{
					this.checkBoxes(this.targetCheckBoxes);
				}
				
			}.bind(this));
			
		}
		
	},
	
	//Check all boxes
	checkBoxes: function(targetCheckBoxes){
		targetCheckBoxes.each(function(checkBox,index){
			checkBox.checked = true;
		});
	},
	
	//Uncheck all boxes
	unCheckBoxes: function(targetCheckBoxes){
		targetCheckBoxes.each(function(checkBox,index){
			checkBox.checked = false;
		});
	}

});



/* ----------------------------------------------------------------------------------------------- checkAllResults class (extends checkAll class)*/

//Check all for results table
var checkAllResults = new Class({
	
	Extends: checkAll,
	
	options: {
		selectRowClass: 'selectRow'
	},
	
	initialize: function(checkAllCheckBox, targetCheckBoxes, options){
		this.parent(checkAllCheckBox, targetCheckBoxes, options);
		this.selectRowClass = this.options.selectRowClass;
	},
	
	//Check all boxes
	checkBoxes: function(targetCheckBoxes){
		targetCheckBoxes.each(function(checkBox,index){
			var parentRow = checkBox.getParent('tr');
			if(parentRow){
				parentRow.addClass(this.selectRowClass);
			}
			checkBox.checked = true;
		},this);
	},
	
	//Uncheck all boxes
	unCheckBoxes: function(targetCheckBoxes){
		targetCheckBoxes.each(function(checkBox,index){
			var parentRow = checkBox.getParent('tr');
			if(parentRow){
				parentRow.removeClass(this.selectRowClass);
			}
			checkBox.checked = false;
		},this);
	}
	
});//End checkAllResults



/* ----------------------------------------------------------------------------------------------- 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 un 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



/* ----------------------------------------------------------------------------------------------- zebraStripeResultsTable class (extends zebraStripeTable class) */

//Zebra Striping for admin results table
var zebraStripeResultsTable = new Class({
	
	Extends: zebraStripeTable,
	
	initialize: function(table,options){
		this.parent(table,options); 
	},
	
	//When the row is selected
	selectRow: function(el){
		el.removeClass(this.activeClass).removeClass(this.hoverRowClass).addClass(this.selectRowClass);
		var updateCheckBox = el.getElement('.updateCheck');
		if(updateCheckBox){
			updateCheckBox.checked = true;
		}
	},
	
	
	//When the row is un selected
	unSelectRow: function(el){
		el.removeClass(this.selectRowClass).addClass(this.activeClass);
		var updateCheckBox = el.getElement('.updateCheck');
		if(updateCheckBox){
			updateCheckBox.checked = false;
		}
	}
	
	
});//End zebraStripeResultsTable



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

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

	options: {
		closeOnClick:   true,
		showCloseButton:true,
		overlayOpacity: 0.8,
		titleText:      'Message',
		content:        $empty,
		width:          '500px'
	},
	
	
	initialize: function(options){
		this.setOptions(options);
		this.closeOnClick    = this.options.closeOnClick;
		this.showCloseButton = this.options.showCloseButton;
		this.overlayOpacity  = this.options.overlayOpacity;
		this.titleText       = this.options.titleText;
		this.width           = this.options.width;
		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 title bar
		var titleBar = new Element('div',{'id':'modalTitleBar'});
		
		//Create title
		var title = new Element('h1',{'id':'modalTitle','html':this.titleText});
		
		//Check if including close button
		if(this.showCloseButton){
		
			//Create close button
			var closeButton = new Element('a',{
				'id':'modalCloseButton',
				'href':'#',
				'html':'<span>Close</span>',
				'events':{
					'click': function(e){
						e.stop();
						this.hide();
					}.bind(this)
				}
			});
			//Inject close button into title bar
			titleBar.adopt(title, closeButton);
		}
		
		//Create content box
		this.contentBox = new Element('div',{
		'id':'modalContentBox',
		'styles':{
			'width':this.width,
			'position':'absolute',
			'z-index':1001
			}
		});
		
		//Inject title bar
		this.contentBox.adopt(titleBar);
		
		//Check if content is just a string
		if($type(this.options.content) == "string"){
			this.options.content = '<p>'+this.options.content+'</p>';
		}
		
		//Inject content into box
		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.getScroll().y+((window.getSize().y/2)-(contentBoxSize.y/2))),
			'left': (window.getSize().x/2)-((this.width).toInt()/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));
		}
	
	},//End show the current modalBox
	
	
	//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



/* ----------------------------------------------------------------------------------------------- confirmationDialog class */

//Confirmation dialog, displays a modal box with a message and Yes/No buttons
var confirmationDialog = new Class({
	
	Implements: Options,

	options: {
		onConfirm: $empty,
		onDeny:    $empty
	},
	
	initialize: function(message,options){
		this.setOptions(options);
		this.message   = message;
		this.modal     = new modalBox({'closeOnClick':false,'titleText':'Are you sure?','width':'300px'});
	},
	
	
	//Show the dialog
	show: function(){

		var dialogWrapper = new Element('div');
		
		var messageContainer = new Element('p',{'html':this.message});
		
		var yesButton = new Element('button',{
			'id':'confirmButtonYes',
			'name':'confirmButtonYes',
			'class':'dialogButton',
			'html':'<span>Yes</span>',
			'events':{
				'click':this.options.onConfirm
			}
		});
		
		var noButton = new Element('button',{
			'id':'confirmButtonNo',
			'name':'confirmButtonNo',
			'class':'dialogButton',
			'html':'<span>No</span>',
			'events':{
				'click':this.options.onDeny
			}
		});

		messageContainer.inject(dialogWrapper);
		yesButton.inject(dialogWrapper);
		noButton.inject(dialogWrapper);
		
		this.modal.setOptions({'content':dialogWrapper});
		this.modal.show();
		
	},//End show the dialog
	
	
	//Hide (destroy) dialog
	hide: function(){
		this.modal.hide();
	}
	
});//End confirmationDialog


/* ----------------------------------------------------------------------------------------------- Toggle the display of optional fields */

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

	options: {
		event: 'click',
		optionalFields: []
	},
	
	initialize: function(handle,container, options){
		this.setOptions(options);
		this.handle         = handle;
		this.container      = container;
		this.event          = this.options.event;
		this.optionalFields = this.options.optionalFields;

		if(this.handle && this.container){
			
			this.slideFx = new Fx.Slide(this.container ,{
				onComplete : function(){
					 if(this.open){
						 if(!Browser.Engine.trident4){
							 this.wrapper.setStyle('height','auto');
						 }
					 }
				}
			});
			
			if(this.handle.checked){
				this.show();
			}else{
				this.hide();
			}
			
			this.handle.addEvent(this.event, function(){
				if(this.handle.checked){
					this.show();
				}else{
					this.hide();
				}
			}.bind(this));
		
		}
	},
	
	show: function(){
		this.slideFx.slideIn();
	},
	
	hide: function(){
		this.slideFx.slideOut();
		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 cs functions
var csFunctions = {//Start csFunctions
			
/* ----------------------------------------------------------------------------------------------- zebraStripeTables function */
	
	//Add zebra striping to tables
	zebraStripeTables: function(tables){//Start create check all

		if(tables){
			tables.each(function(table,index){
				var stripeTable = new zebraStripeTable(table);	
			});
		}
		
	},//End zebraStripeTables
	
	
	
/* ----------------------------------------------------------------------------------------------- zebraStripeResultTables function */
	
	//Add zebra striping to results tables
	zebraStripeResultTables: function(tables){//Start create check all
		
		if(tables){
			tables.each(function(table,index){
				var stripeTable = new zebraStripeResultsTable(table);	
			});
		}
		
	},//End zebraStripeResultTables
	
	
	
/* ----------------------------------------------------------------------------------------------- addCheckAllResults function */
	
	//Add check all checkbox to the results options header
	addCheckAllResults: function(){
		
		var resultOptionsHeader = document.id('resultOptionsHeader');
	
		if(resultOptionsHeader){
			
			//Swap out contents of resultOptionsHeader
			resultOptionsHeader.set('html', '<ul><li>'+resultOptionsHeader.get('text')+'</li><li id="checkAllOption"></li></ul>');
			
			//Create checkAll checkbox
			var resultsTableCheckAll = new Element('input', {'type':'checkbox','id':'resultsTableCheckAll','name':'resultsTableCheckAll','title':'Check all'});
			
			//Insert into resultOptionsHeader
			document.id('checkAllOption').adopt(resultsTableCheckAll);
			
			//Create instance of checkAllResults
			var adminCheckAll = new checkAllResults(document.id('resultsTableCheckAll'), $$('.updateCheck'));

		}
		
	},//End addCheckAllResults
	
	
	
/* ----------------------------------------------------------------------------------------------- waitDialog function */
	
	//Display the please wait dialog
	waitDialog: function(triggers,message){
		
		//Stick message in paragraph
		var dialogMessage = new Element('p',{'html':message});
		
		//Create confirmation dialog
		var waitModal = new modalBox({'closeOnClick':false,'closeButton':false,'content':dialogMessage,'width':'100px'});
		
		triggers.each(function(el){
			el.addEvent('click',function(e){	
				waitModal.show();		   
			});					 
		});
	},
	
	

/* ----------------------------------------------------------------------------------------------- confirmDialog function */
	
	//Display a dialog confirming the user's choice
	confirmDialog: function(triggers,message){

		//Create confirmation dialog
		var confirmDialog = new confirmationDialog(message,{});
		
		triggers.each(function(el){
			el.addEvent('click',function(e){
				
				e.stop();
				
				confirmDialog.setOptions({
					'onConfirm':function(){ 
						//Continue to original link
						window.location = el.getProperty('href');
					},
					'onDeny':function(){ 
						confirmDialog.hide();
					}
				});
				
				confirmDialog.show();		   
			});					 
		});
		
	},//End confirmDialog

/* ----------------------------------------------------------------------------------------------- wysiwyg_file_browser function */
	
	//Custom file browser for the wysiwyg editor
	wysiwyg_file_browser: function (field_name, url, type, win){
		
		//Absolute url to file browser
		var file_browser_url = 'http://www.mtbdirt.com.au/file-browser/type/'+type;
		
		//Open popup window containing the file browser
		tinyMCE.activeEditor.windowManager.open({
			file:           file_browser_url,
			title:          'File Browser',
			width:          745,
			height:         410,
			resizable:      false,
			scrollbars:     'yes',
			inline:         'yes',
			close_previous: 'yes'
		},
		{
			window: win,
			input:  field_name
		});
		
		return false;
		
	},//End wysiwyg_file_browser()

	
/* ----------------------------------------------------------------------------------------------- initWysiwygs function */
	
	//Initialise wysiwyg editors
	initWysiwygs: function(textarea,type,toggleEditorDisplay){
		
		//Get textarea id
		var textAreaId = textarea.get('id');
		
		//Toggle editor function
		function toggleEditor(id) {
			if(!tinyMCE.get(id)){	
				tinyMCE.execCommand('mceAddControl', false, id);
				document.id(textAreaId+'_toggler').addClass('wysiwygEnabled');
				document.id(textAreaId+'_toggler').set('html','Disable editor');
				document.id(textAreaId+'_prevButton').setStyle('display', '');
			}else{
				tinyMCE.execCommand('mceRemoveControl', false, id);
				document.id(textAreaId+'_toggler').removeClass('wysiwygEnabled');
				document.id(textAreaId+'_toggler').set('html','Enable editor');
				document.id(textAreaId+'_prevButton').setStyle('display', 'none');
			}
		}
		
		
		//If toggling editor display
		if(toggleEditorDisplay == 'enabled'){
			//Create toggle button
			new Element('span',{
				'id':textAreaId+'_toggler',
				'class':'wysiwygToggle wysiwygEnabled',
				'html':'Disable editor',
				'events': {
					'click': function(){
						toggleEditor(textAreaId);
					}
				}
			}).inject(textarea,'before');
		}
		
		
		//Create preview button
		new Element('span',{
			'id':textAreaId+'_prevButton',
			'class':'wysiwygPreview',
			'html':'Preview',
			'events': {
				'click': function(){
					tinyMCE.execCommand('mcePreview', false, textAreaId);
				}
			}
		}).inject(textarea,'before');
		
		//Switch editor type
		switch(type){
			
			//Advanced editor, full functionality
			case 'advanced':
				var editor = new tinymce.Editor(textAreaId, {
					
					theme:                  'advanced',
					convert_urls:           false,
					width:                  '100%',
					accessibility_warnings : false,
					dialog_type:            'window',

					//Include plugins
					plugins: 'safari,style,table,advimage,emotions,preview,media,contextmenu,paste,fullscreen,noneditable,xhtmlxtras,codeprotect,spellchecker',
				
					//Theme options
					theme_advanced_buttons1:          'undo,redo,preview,fullscreen,cleanup,code,visualaid,spellchecker,|,pastetext,pasteword,|,removeformat',
					theme_advanced_buttons2:          'bold,italic,underline,strikethrough,sub,sup,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleprops,forecolor,backcolor,styleselect,formatselect,fontsizeselect',
					theme_advanced_buttons3:          'link,unlink,image,bullist,numlist,outdent,indent,blockquote,tablecontrols,emotions,charmap,media',
					theme_advanced_blockformats :     'p,div,h1,h2,h3,h4,h5,h6,blockquote,dt,dd,code,samp',
					theme_advanced_toolbar_location:  'top',
					theme_advanced_toolbar_align:     'left',
					theme_advanced_statusbar_location:'bottom',
				
					//Content CSS
					content_css: 'http://www.mtbdirt.com.au/_themes/public/css/wysiwyg_content.css',
					
					//Popup dialogs skin
					inlinepopups_skin: 'cs_cms',
					
					//Preview window size
					plugin_preview_width:  '600',
					plugin_preview_height: '350',
					
					//Source editor size
					theme_advanced_source_editor_width: '600',
					theme_advanced_source_editor_height: '350',

					//Custom file browser
					file_browser_callback: this.wysiwyg_file_browser
					
				});
			break;
			
			//Default basic functionality
			default:
				var editor = new tinymce.Editor(textAreaId, {
												
					theme:                  'advanced',
					convert_urls:           false,
					width:                  '100%',
					accessibility_warnings : false,
					dialog_type:            'window',
					
					//Include plugins
					plugins: 'safari,advimage,emotions,preview,media,paste,xhtmlxtras,spellchecker',
					
					//Theme options
					theme_advanced_buttons1:         'undo,redo,spellchecker,code,|,link,unlink,image,media,emotions,|,bold,italic,underline,strikethrough,bullist,numlist,|,justifyleft,justifycenter,justifyright,justifyfull,|,forecolor,removeformat',
					theme_advanced_buttons2:         'formatselect,fontsizeselect',
					theme_advanced_buttons3:         '',
					theme_advanced_blockformats :    'p,div,h1,h2,h3,h4,h5,h6,blockquote,dt,dd',
					theme_advanced_toolbar_location: 'top',
					theme_advanced_toolbar_align:    'left',

					//Content CSS
					content_css: 'http://www.mtbdirt.com.au/_themes/public/css/wysiwyg_content.css',
					
					//Popup dialogs skin
					inlinepopups_skin: 'cs_cms',
					
					//Preview window size
					plugin_preview_width:  '600',
					plugin_preview_height: '350',
					
					//Source editor size
					theme_advanced_source_editor_width: '600',
					theme_advanced_source_editor_height: '350',
					
					//Custom file browser
					file_browser_callback: this.wysiwyg_file_browser
					
				});
			break;
				
		}//End switch(type)
		
		//Display editor
		editor.render();
			
	},//End initWysiwygs
	
	
	
/* ----------------------------------------------------------------------------------------------- wysiwgPopups function */
	
	//Set wysiwg popups code
	wysiwgPopups: function(){
		
		//For each selectFileLink
		$$('.selectFileLink').addEvent('click',function(e){
			
			//Stop link click
			e.stop();
	
			//Get file url
			var fileUrl = this.get('href');
			
			//Get current popup window
			var win = tinyMCEPopup.getWindowArg("window");
	
			//Insert file url
			win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = fileUrl;
			
			//Images
			if(win.ImageDialog){
				if(win.ImageDialog.getImageData){ win.ImageDialog.getImageData(); }//Update image dimensions
				if(win.ImageDialog.showPreviewImage){ win.ImageDialog.showPreviewImage(fileUrl); }//Display image preview
			}
			
			//Media
			if($defined(win.switchType)){
				win.switchType(fileUrl);
			}
			
			//Preview
			if($defined(win.generatePreview)){
				win.generatePreview();					
			}
	
			//Close popup window
			tinyMCEPopup.close();
							   
		});//End .selectFileLink
	
	},//End wysiwgPopups
	
/* ----------------------------------------------------------------------------------------------- quoteButton function */

	//User shortcuts dropdown container
	quoteButton: function(){//Start quoteButton
		
		//Get quote buttons
		var quoteButtons  = $$('.quoteButton');
		
		//Check for quote buttons
		if(quoteButtons){//Start check quote buttons
			
			//Loop each button
			quoteButtons.each(function(button){
				
				//Get post id number by removing quote_ from id
				var idNumber = button.get('id').substring(6);
				
				//Get matching post user name
				var postUsername = document.id('postUser_'+idNumber);
				
				//Get matching post permanent link
				var postLink = document.id('postLink_'+idNumber).get('href');
				
				//Get matching post body
				var postBody = document.id('postBody_'+idNumber);
				
				//Check post items exist
				if(postUsername && postLink && postBody){//Start if exists
					
					//Create new link
					var quoteButton = new Element('a',{
					'href':'#quick_reply',
					'class':'linkQuote',
					'html':'Quote'
					});
					
					//Empty
					button.set('text','');
					
					//Inject quote button
					quoteButton.inject(button);
					
					//On click event for quote button
					quoteButton.addEvent('click',function(){
	
						//If tinymce exists
						if(tinyMCE.get('forum_post_content')){								
							//Get existing content
							var exContent = tinyMCE.activeEditor.getContent();
							//Add to post body content
							var editorContent = exContent+'<blockquote><p>Quote: <a href="'+postLink+'" target="_self" title="Jump to quoted post">'+postUsername.get('text')+'</a></p>'+postBody.get('html')+'</blockquote><p>&nbsp;</p>';
							//Send to tinymce
							tinyMCE.activeEditor.setContent(editorContent);
						}
						
					});
					
				}//End if exists
				
			});
			
		}//End check quote buttons
		
	},//End quoteButton	
	
/* ----------------------------------------------------------------------------------------------- ajaxUsernameSearch function */

	//Display a username search box
	ajaxUsernameSearch: function(input){//Start ajaxUsernameSearch
		
		//Check input exists
		if(input){//Start check exists
			
			//URL to get usernames from
			var requestUrl = 'http://www.mtbdirt.com.au/ajax-username-search';
				
			//Build search button
			new Element('span',{
				'class':'searchToggler',
				'title':'Search for usernames',
				'events': {
					'click': function(){
						toggleUserSearch();
					}
				}
			}).inject(input,'after');
			
			//AJAX Request
			var req = new Request({//Start ajax request
				
				//On successfull request
				onSuccess: function(result){//Start get result
					
					//Remove spinner
					document.id('userResultsWrapper').removeClass('ajaxSpinner');
					
					//Get names from result
					var arr_names = JSON.decode(result);
					
					//If names returned
					if(arr_names){//Start is names
						
						//Create list and inject into results wrapper
						var resultsList = new Element('ul',{
							'id':'userResultsList'
						}).inject(document.id('userResultsWrapper'),'top');
						
						//Loop through names
						$each(arr_names,function(value, key){
							
							//Create li and inject into results list
							var resultLi = new Element('li',{
								'text':value,
								'title':'Add username',
								'events': {
									'click': function(){
										
										//Get current input value
										var currentValue = input.get('value');
										
										//If value is not empty
										if(currentValue != ''){//Start if empty
											
											//If ,value
											if(currentValue.contains(','+value)){
												this.addClass('userResultRemoved');
												this.removeClass('userResultAdded');
												var newValue = currentValue.replace(','+value,'');
												input.set('value',newValue);
											}else{
												//If value
												if(currentValue.contains(value)){
													this.addClass('userResultRemoved');
													this.removeClass('userResultAdded');
													var newValue = currentValue.replace(value,'');
													input.set('value',newValue);
												}else{
													this.removeClass('userResultRemoved');
													this.addClass('userResultAdded');
													input.set('value',currentValue+','+value);
												}
											}
		
										}else{//Else if empty
											
											//Is empty
											this.addClass('userResultAdded');
											input.set('value',value);
											
										}//End if empty

									}
								}
							}).inject(document.id('userResultsList'),'top');
							
						});
						
					}else{//End is names
						
						//No names returned
						document.id('userResultsWrapper').set('html','<p>No matching usernames</p>');
						
					}//End is names
					
				}.bind(this)//End get result
				
			});//End ajax request
			
			//Search users
			function searchUsers(searchTerm){
				
				//Clean up search term
				var searchTerm = searchTerm.replace('%','').trim();
				
				//Empty results wrapper
				document.id('userResultsWrapper').empty();
				
				//Display spinner
				document.id('userResultsWrapper').addClass('ajaxSpinner');
				
				//Send AJAX request to get names
				req.send({'url':requestUrl+'/'+searchTerm});
				
			}
			
			function toggleUserSearch(){
				
				//Create search wrapper
				var searchWrapper = new Element('div',{
					'id':'userSearchWrapper'
				});
				
				//Create form wrapper
				var searchFormWrapper = new Element('div',{
					'id':'userSearchFormWrapper',
					'class':'formBlock'
				}).inject(searchWrapper,'top');
				
				//Create results wrapper
				var resultsWrapper = new Element('div',{
					'id':'userResultsWrapper'
				}).inject(searchWrapper,'bottom');
				
				//Create search input
				var searchInput = new Element('input',{
					'name':'username_search',
					'id':'username_search',
					'value':'',
					'class':'inputTextField',
					'events': {
						'keyup': function(){
							searchUsers(this.getProperty('value'));
						}
					}
				}).inject(searchFormWrapper,'top');
				
				//Create new modal for search form
				var searchModal = new modalBox({'closeOnClick':true,'titleText':'Search usernames','content':searchWrapper,'width':'200px'});
				
				//Show the search modal
				searchModal.show();
				
			}
			
		}//End check exists
		
	},//End ajaxUsernameSearch

/* ----------------------------------------------------------------------------------------------- ajaxCollapsibleCategories function */

	//Allows forum categories to collapse and sets user preference
	ajaxCollapsibleCategories: function(categories){//Start ajaxCollapsibleCategories
		
		//Check categories exists
		if(categories){//Start check exists
			
			//URL to get set category collapse
			var requestUrl = 'http://www.mtbdirt.com.au/ajax-collapse-forum-categories';
			
			//Loop categories
			categories.each(function(category){
				
				//Set forum category id
				var forumCategoryId = category.get('id').substring(9);
				
				//Get category title
				var categoryTitle = category.getElement('.categoryTitle');
				
				//Get boards container
				var forumBoards = category.getElement('.forumBoards');
				
				//Set slide FX for category drop down
				var categoryDropDown = new Fx.Slide(forumBoards,{transition:Fx.Transitions.Quart.easeOut});
				
				//Check title and boards exist
				if(categoryTitle && forumBoards){//Start check title/boards exist
					
					//Build collapse button
					var categoryHandle = new Element('span',{
						'class':'forumCategoryHide',
						'title':'Hide this category',
						'events': {
							'click': function(){
								reqChange.send({'url':requestUrl+'/change/'+forumCategoryId});
							}
						}
					}).inject(categoryTitle,'bottom');
					
					//Check status request
					var reqCheck = new Request({//Start ajax request
						
						//On successfull request
						onSuccess: function(result){//Start get result
							
							//If true
							if(result == 'true'){
								categoryDropDown.hide();
								categoryHandle.set('class','forumCategoryHide');
								categoryHandle.set('title','Show this category');
							}else{
								categoryDropDown.show();
								categoryHandle.set('class','forumCategoryShow');
								categoryHandle.set('title','Hide this category');
							}
							
						}.bind(this)//End get result
				
					});//End ajax request
					
					//Check current status
					reqCheck.send({'url':requestUrl+'/check/'+forumCategoryId});
					
					
					//Change status request
					var reqChange = new Request({//Start change request
						
						//On successfull request
						onSuccess: function(result){//Start get result
							
							//If true
							if(result == 'true'){
								categoryDropDown.slideOut();
								categoryHandle.set('class','forumCategoryHide');
								categoryHandle.set('title','Show this category');
							}else{
								categoryDropDown.slideIn();
								categoryHandle.set('class','forumCategoryShow');
								categoryHandle.set('title','Hide this category');
							}
							
						}.bind(this)//End get result
				
					});//End change request

				}//End check title/boards exist
				
			});//End loop categories
			
		}//End check exists
		
	},//End ajaxCollapsibleCategories
	
/* ----------------------------------------------------------------------------------------------- postCountDownTimer function */
	
	//Count down a number in a container to zero then remove the container
	postCountDownTimer: function(container){//Start postCountDownTimer
		
		//Check for container
		if(container){//Start is container
			
			//Set container and get initial number
			var counter = { 'container':container, 'number':container.get('text').toInt() };
			
			//Decrement function 
			var decrement = function(){
				
				//If greater than zero
				if(this.number > 1){
					//Decrement number
					this.number--;
					//Update container
					this.container.set('text',this.number);
				}else{
					//Clear function
					$clear(decrement);
					//Remove parent message
					var parent = this.container.getParent('div');
					if(parent){ parent.destroy(); }
					
				}

			};
			
			//Execute derement function every second
			var timer = decrement.periodical(1000, counter);
			
		}//End is container
		
	},//End postCountDownTimer
	
/* ----------------------------------------------------------------------------------------------- selectSearchBoards function */
	
	//Select which boards to search
	selectSearchBoards: function(){//Start selectSearchBoards
		
		//Get trigger checkbox
		var categoriesTrigger   = document.id('advanced_search_boards');
		//Get container
		var categoriesContainer = document.id('searchBoards');
		
		//Set catagory heights array
		var arrHeights = [];
		
		//If triger and container exist
		if(categoriesTrigger && categoriesContainer){//Start is trigger and container

			//Get category containers
			var categoryContainers = categoriesContainer.getElements('dl');
			
			//If containers exist
			if(categoryContainers){//Start if category containers
			
				//Loop through category containers
				categoryContainers.each(function(categoryContainer,index){//Start loop category containers
					
					//Get category checkall checkbox
					var categoryCheckAll = categoryContainer.getElement('input[type=checkbox]');
					
					//Get all child board checkboxes
					var categoryBoardChecks = categoryContainer.getElements('input[type=checkbox]');
					
					//If checkAll exists
					if(categoryCheckAll && categoryBoardChecks){//Start if checkAll exists
						
						//Create checkall instance for this group of boards
						var triggerCategoryCheckAll = new checkAll(categoryCheckAll, categoryBoardChecks);
						
					}//End if checkAll exists
					
					//Get height of this category container
					var categoryContainerHeight = categoryContainer.getSize().y;
					
					//Add to catagory heights array
					arrHeights.include(categoryContainerHeight);
					
				});//End loop category containers 
				
				//Get the height of the largest category container
				var maxHeight = arrHeights.max();

				//Loop through category containers and set stlyes
				categoryContainers.each(function(categoryContainer,index){
					categoryContainer.setStyles({'width':'220px','height':maxHeight,'float':'left'});
				});
				
			}//End if category containers
			
			//Create displayHiddenOptions instance to show/hide boards
			var searchBoards = new displayHiddenOptions(categoriesTrigger,categoriesContainer,{'optionalFields':categoriesContainer.getElements('input[type=checkbox]')});
			
		}//End is trigger and container
		
	},//End selectSearchBoards


/* ----------------------------------------------------------------------------------------------- additionalTextFields function */
	
	//Additional text fields
	additionalTextFields: function(defaultFieldBlock,name,id,defaultCount){//Start additionalTextFields 
		
		if(defaultFieldBlock){//Start is field block
		
			//Check for name
			if(name == ''){
				name = 'field';
			}
		
			//Check for name
			if(id == ''){
				id = name;
			}
			
			//Check for count
			if(defaultCount == ''){
				defaultCount = 0;
			}
			
			//Create add choice label
			var addField = new Element('dd',{'class':'input addField','html':'<label>Add</label>'});
			
			//Inject beneath last input
			addField.inject(defaultFieldBlock,'bottom');
			
			//Add on click event to add choice
			addField.addEvent('click',function(e){
				
				//Increment count
				defaultCount++;
				
				//Create a new elements
				var newInputDd     = new Element('dd',{'class':'input'});
				var newInputField  = new Element('input',{'type':'text','name':name,'id':id+'_'+defaultCount,'value':'','class':'inputTextField'});
				var newInputDelete = new Element('label',{'class':'deleteInput','text':'Delete'});
								
				//Inject inputs into dd
				newInputDd.adopt(newInputField);
				newInputDelete.inject(newInputDd,'bottom');
				
				//Inject dd after existing inputs
				newInputDd.inject(addField,'before');
				
				//Set delete onclick
				newInputDelete.addEvent('click',function(e){
					
					e.stop();
					
					//Delete dt and dd
					newInputDd.dispose();
					
				}.bind(this));
				
			}.bind(this));
		
		}//End is field block
		
	},//End additionalTextFields
	
/* ----------------------------------------------------------------------------------------------- additionalFiles function */
	
	//Additional trail file file fields
	additionalFiles: function(defaultFileBlock,name,id,defaultCount){//Start additionalFiles
		
		if(defaultFileBlock){//Start is field block

			//Check for name
			if(name == ''){
				name = 'file';
			}
		
			//Check for name
			if(id == ''){
				id = name;
			}
			
			//Check for count
			if(defaultCount == ''){
				defaultCount = 0;
			}
			
			//Create add choice label
			var addFile = new Element('dd',{'class':'input addFile','html':'<label>Add file</label>'});
			
			//Inject beneath last input
			addFile.inject(defaultFileBlock,'bottom');
			
			//Add on click event to add choice
			addFile.addEvent('click',function(e){
				
				//Increment count
				defaultCount++;
				
				//Create a new elements
				var newInputDd     = new Element('dd',{'class':'input'});
				var newInputField  = new Element('input',{'type':'file','name':name,'id':id+'_'+defaultCount,'class':'inputFileField'});
				var newInputDelete = new Element('label',{'class':'deleteInput','text':'Delete'});
								
				//Inject inputs into dd
				newInputDd.adopt(newInputField);
				newInputDelete.inject(newInputDd,'bottom');
				
				//Inject dd after existing inputs
				newInputDd.inject(addFile,'before');
				
				//Set delete onclick
				newInputDelete.addEvent('click',function(e){
					
					e.stop();
					
					//Delete dt and dd
					newInputDd.dispose();
					
				}.bind(this));
				
			}.bind(this));
		
		}//End is field block
		
	},//End additionalFiles

/* ----------------------------------------------------------------------------------------------- resizeImages function */
	
	//Resize images to max width
	resizeImages: function(arrImages,maxWidth){//Start resizeImages
		
		//Check for images and width
		if(arrImages && maxWidth){
			
			//Loop images
			arrImages.each(function(el,i){
				
				//Get width
				var width = el.getSize().x;
				
				//If greater than maxwidth
				if(width > maxWidth.toFloat()){
					//Shrink
					el.set('width',maxWidth.toFloat());
					//Remove height
					el.erase('height');
				}
				
			});
			
		}
		
	},//End resizeImages
	
/* ----------------------------------------------------------------------------------------------- init function */

	//Initialise cs functions
	init: function(){
		
		//this.ajaxChangeMood();
		this.quoteButton();
		this.ajaxCollapsibleCategories($$('.categoryCollapse_enabled'));
		this.selectSearchBoards();
		this.waitDialog($$('.waitModal'),'Please wait...');
		//this.confirmDialog($$('.linkDelete'),'Are you sure you want to delete this?');
		this.ajaxUsernameSearch(document.id('message_recipients'));
		this.ajaxUsernameSearch(document.id('advanced_search_user'));
		this.ajaxUsernameSearch(document.id('ignore_forum_posts'));
		this.ajaxUsernameSearch(document.id('ignore_private_messages'));
		this.additionalTextFields(document.id('pollChoices'),'arr_forum_poll_choices[]','forum_poll_choice',5);
		this.additionalFiles(document.id('trailMaps'),'arr_trail_maps[]','arr_trail_map',2);
		this.additionalFiles(document.id('trailFiles'),'arr_trail_files[]','arr_trail_file',2);
		this.additionalFiles(document.id('trailPhotos'),'arr_trail_photos[]','arr_trail_photo',2);
		this.additionalFiles(document.id('ridePhotos'),'arr_ride_photos[]','arr_ride_photo',2);
		this.postCountDownTimer(document.id('postTimeout'));
		this.zebraStripeResultTables($$('.resultsTable'));
		this.zebraStripeTables($$('.permissionsGrid'));
		this.addCheckAllResults();

		//Toggle poll options
		var pollOptions = new displayHiddenOptions(document.id('create_poll'),document.id('pollOptions'),{'optionalFields':[document.id('delete_poll'),document.id('reset_vote_count'),document.id('forum_poll_question'),document.id('arr_forum_poll_choices'),document.id('forum_poll_max_votes'),document.id('forum_poll_expire'),document.id('forum_poll_change_vote'),document.id('forum_poll_hide_results')]});
		
		/*//Advanced wysiwyg editors
		$$('.wysiwygAdvanced').each(function(textarea){
			this.initWysiwygs(textarea,'advanced');
		}.bind(this));*/
		
		//Basic wysiwyg editors
		$$('.wysiwygBasic').each(function(textarea){
			this.initWysiwygs(textarea,'basic','enabled');
		}.bind(this));
		
		//wysiwgPopups
		this.wysiwgPopups();
		
		//If IE6 resize forum post images
		//if(Browser.Engine.trident && Browser.Engine.version <= 4){
			this.resizeImages($$('.postContent img'),595);
		//}
		
	}
									 
};//End csFunctions


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

