
/*
 *	@Script			: agresso_corporate.js
 *	@Description	: General functions for the Agresso website. Require Mootools 1.2
 */



	
/* Contact form multi  - form element changer */
function Modify_Form_Contact_Multi(value){
	
	if (value > 0 && value < 6){
		
		for(c=1;c<6;c++){
			
			if(c==value){
				$('form_'+c).setStyle('display','');
			}else{
				$('form_'+c).setStyle('display','none');
			}
			
		}
		
	}
	
	return
	
}//func





/* ----------------------------------------- 
	
	Information download library, link-hover info script
	Shaun Clifford
	17/06/2009
	
*/
    //menu 1
	var total_information_text = new Array();
	total_information_text[0] =0;
	total_information_text[1] =0;
	
	var current_text = new Array();
	current_text[0] = 0;
	current_text[1] = 50;
	
	var last_text = new Array();
	last_text[0] = 0;
	last_text[1] = 50;
	
	var fade_timeout = new Array();
	fade_timeout[0] = 0;
	fade_timeout[1] = 0;
	
	var fade_time_ms = 6000;
	var myMorph = null;
	
	
	
	//gathers number of items being displayed
	function set_di_text(di_text_num_1,di_text_num_2){
		total_information_text[0] = di_text_num_1;
		total_information_text[1] = 50 + di_text_num_2;
	}//func
	
	
	
	//gets margin for lower slidemenu, so can work out where needs to be positioned on link-hover 
	function get_slidemenu_marginTop(text_num,total_information_text){
		
		//-50 due to count for second menu starting at 50...to avoid clashing of the two menus!
		text_num = text_num -50;
		total_information_text = total_information_text - 50;
		var itemHeight = 45; 
		var margin_top = 0;
		
		if(total_information_text > 7){
			if( text_num >= (total_information_text-4)){
				margin_top=(total_information_text-4) * itemHeight - 10;

			
			}else if(text_num > 5){
				margin_top=(text_num-1) * itemHeight - 55;
			}else{
				//The pane has relocated, if the user hovers over 1-7, it should come back up
				margin_top=0;
			}
		}
		
		return margin_top;
		
	}//func
	
	
	
	//main menu script....acts on one menu or the other, based on the menu var
	//ENHANCEMENT -> get rid of damn menu var!, base on DOM naming instead...
	function Download_InfoPane_In(text_num,menu){
			
		if(   ((menu == 1) && (total_information_text[0] > 0) && (text_num > 0))      ||     ((menu == 2) && (total_information_text[1] > 50) && (text_num > 50)) ){
			
			//set current/last vars based on menu being used
			if(menu == 1){
				
				last_text[0] = current_text[0];
				current_text[0] = text_num;
				
				var text_fade_out = new Fx.Morph($('dit_1_'+last_text[0]), {
					duration: 300, 
					transition: Fx.Transitions.Quad.easeOut,
					wait:true			
				});	
				
				var text_fade_in = new Fx.Morph($('dit_1_'+current_text[0]), {
					duration: 300, 
					transition: Fx.Transitions.Quad.easeIn,
					wait:true	
				});
				
			}else{
				
				last_text[1] = current_text[1];
				current_text[1] = text_num;
				
				var text_fade_out = new Fx.Morph($('dit_2_'+last_text[1]), {
					duration: 300, 
					transition: Fx.Transitions.Quad.easeOut,
					wait:true			
				});	
				
				var text_fade_in = new Fx.Morph($('dit_2_'+current_text[1]), {
					duration: 300, 
					transition: Fx.Transitions.Quad.easeIn,
					wait:true	
				});
				
			}//
			
			
			
			
			//if at start position
			if(   ((menu == 1) && ($('InfoPane1').className.indexOf('backimg1') > 0))      ||     ((menu == 2) && ($('InfoPane2').className.indexOf('backimg3') > 0))   ){//menu 2 sort
				
				if(menu == 1){
					$('InfoPane1').className = 'InfoPane1 backimg2';
				
					$('dit_1_'+current_text[0]).style.opacity=0;
					$('dit_1_'+current_text[0]).style.display='block';
					
				}else{//menu 2 sort
					
					//first, we may need to move the actual infopane if link list is long, and hovered link is far down the list...
					margin_top = get_slidemenu_marginTop(text_num,total_information_text[1]);
					
					myMorph.start({marginTop:margin_top});
					
					$('InfoPane2').className = 'InfoPane1 backimg4';
				
					$('dit_2_'+current_text[1]).style.opacity=0;
					$('dit_2_'+current_text[1]).style.display='block';
					
				}

				
				text_fade_in.start({
					'opacity':[0,1]
				})
				
					
				if(menu == 1){
					fade_timeout[0] = setTimeout("Download_InfoPane_Out(1)",fade_time_ms);
				}else{
					fade_timeout[1] = setTimeout("Download_InfoPane_Out(2)",fade_time_ms);
				}
				
			}else{
				//if not at start position
				
				if(menu == 1){
					
					//keep the square faded, reset the timer to keep faded, and just replace the text...
					clearTimeout(fade_timeout[0]);
					fade_timeout[0] = setTimeout("Download_InfoPane_Out(1)",fade_time_ms);
					
					if( $chk($('dit_1_'+last_text[0])) ){
						//remove current text
						text_fade_out.start({
							'opacity':[1,0],
							'display':'none'
						}).chain(function(){
							
							$('dit_1_'+current_text[0]).style.opacity=0;
							$('dit_1_'+current_text[0]).style.display='block';
							
							text_fade_in.start({
								'opacity':[0,1]
							})
						});
					}
					
				}else{
					
					//keep the square faded, reset the timer to keep faded, and just replace the text...
					clearTimeout(fade_timeout[1]);
					fade_timeout[1] = setTimeout("Download_InfoPane_Out(2)",fade_time_ms);
					
					if( $chk($('dit_2_'+last_text[1])) ){
						//remove current text
						text_fade_out.start({
							'opacity':[1,0],
							'display':'none'
						}).chain(function(){
							
							$('dit_2_'+current_text[1]).style.opacity=0
							$('dit_2_'+current_text[1]).style.display='block'
									
							text_fade_in.start({
								'opacity':[0,1]
							})
							
						});
						
						margin_top = get_slidemenu_marginTop(text_num,total_information_text[1])
						myMorph.start({marginTop:margin_top})
					}
					
				}//menu ifelse
				
			}
			
		}//end total_information_text 

		
	}//func
	
	
	
	//reset pic/text->  fade the mainpic back in, fade out the text
	function Download_InfoPane_Out(menu){
		
		if(menu == 1){
			
			var text_fade_out = new Fx.Morph($('dit_1_'+current_text[0]), {
				duration: 300, 
				transition: Fx.Transitions.Quad.easeOut,
				wait:true			
			});	
	
			text_fade_out.start({
				'opacity':[1,0]
			}).chain(function(){
				$('dit_1_'+current_text[0]).style.display='none';
				
				$('InfoPane1').className = 'InfoPane1 backimg1';
			});
			
		}else{
			
			
			
			var text_fade_out = new Fx.Morph($('dit_2_'+current_text[1]), {
				duration: 300, 
				transition: Fx.Transitions.Quad.easeOut,
				wait:true			
			});	
	
			text_fade_out.start({
				'opacity':[1,0]
			}).chain(function(){
				$('dit_2_'+current_text[1]).style.display='none';
				
				$('InfoPane2').className = 'InfoPane2 backimg3';
			});
			
			myMorph.start({marginTop:0});
			
		}

	}//func
	
	

/* ----------------------------------------- */



window.addEvent('domready', function() {
	
	
	//setup the scene for the information download library hover script
	//Shaun Clifford
	//17/06/2009
	
	if($chk($('InfoPane1'))){
		
		var di_items_1 = $$('.di_text_1');//number of di texts to use
		var di_items_2 = $$('.di_text_2');
		
		di_items_1.each(function(element, index) {
			element.setStyle('display', "none");
		});
		
		di_items_2.each(function(element, index) {
			element.setStyle('display', "none");
		});
		
		//setup other functions used, now we know how many items there are to use...
		set_di_text(di_items_1.length,di_items_2.length);
		
		myMorph = new Fx.Morph('InfoPane2', { link: 'cancel' , 'duration': 600,transition: Fx.Transitions.Quad.easeOut});
		
	}
	/* ----------------------------------------- */
	
	
	
	
	// MooTools Form Validation for all forms with id='validate'
	if ($chk($('validate'))) {
		var myFormValidation = new Validate('validate', {});
	}

	// Request the first tab latest details
	if ($chk($('latestinfocontent'))) {
		ajaxRequest('latest_info_tab', 'latestinfocontent', '&tabID=1', true);
	}

	// Request the main tab details
	/*if ($chk($('mainTab'))) {
		ajaxRequest('latest_info_tab', 'mainTab', '&tabID=0', true);
	}*/

	// Add change event to our referral dropdown if it exists on the page
	if ($chk($('referral')) && $chk($('showHide_ReferralType_Id'))) {

		// Values taken from the database
		var moreInfoRequiredArray = ['1', '9', '3', '5', '11'];
		var referralList = $('referral');

		referralList.addEvent ('change', function() {
			$('showHide_ReferralType_Id').style.display = (moreInfoRequiredArray.contains(this[this.selectedIndex].value)) ? 'block' : 'none';
		});
	}

	new SmoothScroll({ duration: 200 }, window);

	/* ----- SCROLLING NAV BUTTONS ----- */
	if ($chk($('scrollingNavScroll'))) {
		/* ----------Config Vars----------- */
			
		var slideTimer = 7000;  //time between slides (1 second = 1000), a.k.a. the interval duration
		var transitionTime = 1250; //transition time (1 second = 1000)
		var items = $$('.slide_item');  //Get array of elements for sliding
		var slideItemWidth = $('scrollWrapper').offsetWidth;
		
		/* --------end config vars-------- */
		
		//Setup positions
		items.each(function(element, index) {
			
			//since the viewer obviously has javascript on, we can remove the 'first_item' class
			if(index == 0){
				element.removeClass('first_item');
				element.setStyle('left', "0");
			}
			else{
				element.setStyle('left', slideItemWidth);
				element.setStyle('opacity', "0");
			}
		
		});
		//end setup
		
		//Slider Stuff
		var slideFunction = new function() {
			
			var numItems = items.length;  //get number of slider items
			var itemNum = 0;  //initialize a variable to hold the current slide index
			
			if (numItems > 1) {
				var slideIt = function(){ 
				
					//get item to slide out
					var curItem = items[itemNum];  
					
					//change index
					if(itemNum < (numItems - 1)){
						itemNum++; 
					}
					else{
						itemNum = 0;
					}
					
					//now get item to slide in using new index
					var newItem = items[itemNum];
					
					//set up our animation stylings for out and in motions (note:  Fx.Styles does NOT exist in moo 1.2, so we must use Fx.Morph or Fx.Tween)
					var item_in = new Fx.Morph(newItem, {
						     duration: transitionTime, 
						     transition: Fx.Transitions.Quad.easeInOut, 
						     wait:false
					});
					
					var item_out = new Fx.Morph(curItem, {
						     duration: transitionTime, 
						     transition: Fx.Transitions.Quad.easeInOut, 
						     wait:false
					});
					
					//we will set a beginning value here
					//this is so that it gives the illusion of continuous motion from one direction, even after the first cycle of items
					item_in.start({
					'left': [slideItemWidth, 0],
					'opacity':[0,1]
					});
					
					//no beginning values needed, since we always want to push the old item out to the left
					item_out.start({
					'left': '-' + slideItemWidth,
					'opacity':[0]
					});
					
				};
				
				//call the function, periodically  (note: the interval period is defined at the top of this file)
				slideIt.periodical(slideTimer, this); 
			}
		}
	}
	/* ----- END SCROLLING NAV BUTTONS ----- */
	
	
	

	
	
	

	/* ----- 	SCROLLING QUOTES	 ----- */
	if ($chk($('scrolling_quotes_box'))) {
		
			
		var swapTimer = 8000;  //time between quote changes (6 secs)
		var transitionTime = 600; //transition time
		var nextQuote = 3;//first three are showing at start (0,1,2)
		var nextBox = 0;//out of three boxes, which box should next quote be added to..
		var swapitems = $$('.quote_text');//list of elements to use/get quote data from
		var itemHTML = MultiDimensionalArray(swapitems.length,2);//actual quotes html stored for manipulation
		var boxes = MultiDimensionalArray(swapitems.length,2);//quotebox dom elements
		
		//gather html from elements and store
		for(c=0;c<swapitems.length;c++){
			itemHTML[c][0] = $('CQ_'+c+'_quote').get('html');
			itemHTML[c][1] = $('CQ_'+c+'_footer').get('html');
			
			if(c>2){
				$('CQ_'+c).set('html','');
			}else{
				boxes[c][0] = $('CQ_'+c+'_quote');
				boxes[c][1] = $('CQ_'+c+'_footer');
			}
		}
		
		
		//main quote swap function
		var swapFunction = new function() {

			
			if (itemHTML.length > 3) {//if at least 4 quotes on the page to use (3 always displayed)
				
				var swapIt = function(){ 
					
					
					var currentQuoteBox = boxes[nextBox][0];
					var currentFootBox = boxes[nextBox][1];
					
					//set up our animation stylings for fadeout
					var quote_out = new Fx.Morph(currentQuoteBox, {
						     duration: transitionTime, 
						     transition: Fx.Transitions.Quad.easeOut,
						     wait:false
					});
					var footer_out = new Fx.Morph(currentFootBox, {
						     duration: transitionTime, 
						     transition: Fx.Transitions.Quad.easeOut,
						     wait:false
					});
					
					
					//set up our animation stylings for fadein
					var quote_in = new Fx.Morph(currentQuoteBox, {
						     duration: transitionTime, 
						     transition: Fx.Transitions.Quad.easeIn 
					});
					var footer_in = new Fx.Morph(currentFootBox, {
						     duration: transitionTime, 
						     transition: Fx.Transitions.Quad.easeIn,
						     wait:false 
					})
					
					
					
					quote_out.start({
						'opacity':[1,0]
					}).chain(function(){
						
						currentQuoteBox.set('html',itemHTML[nextQuote][0]);
						
						footer_out.start({
							'opacity':[1,0]
						}).chain(function(){
							currentFootBox.set('html',itemHTML[nextQuote][1]);
							
							quote_in.start({	
								'opacity':[0,1]
							}).chain(function(){
								footer_in.start({
									'opacity':[0,1]
								}).chain(function(){
									
									//setup quote/box var for next run thru
									if(nextQuote < (swapitems.length-1)){ nextQuote++; }else{ nextQuote = 0; }
									if(nextBox < 2){ nextBox++; }else{ nextBox = 0; }
									
								});
							});
							
	
						});	
							
					});
					
				
					
					
				};
				
				
				//call the swap function, periodically
				swapIt.periodical(swapTimer, this); 
				
			}
		}
	
	}//func
	/* ----- END SCROLLING QUOTES ----- */
	
	
	

	
	
	
	/* ----- START SORT TABLES ----- */
	var sortTables = $$('table.sort');  //Get array of sort tables
	
	sortTables.each(function(element, index) {

		var rowsToDisplay = 1000000;
		var classArray = element.className.split(" ");

		for (var i = 0; i < classArray.length; i++) {
			if (classArray[i].substring(0,5) == "rows-") {
				rowsToDisplay = parseInt(classArray[i].substring(5));
			}
		}

		// set the number of rows to display on the table
		element.rowsToDisplay = rowsToDisplay;
			
		// get all header cells in this table
		var headCells = element.getElements("thead tr td, thead tr th");
		
		// add the sort class to the head cells
		for (var i = 0; i < headCells.length; i++) {
			if (!cssHandler("check",headCells[i],"no-sort")) {
				headCells[i].addClass("sort");
				headCells[i].addClass("down");
				headCells[i].addEvent('click', sortTable);
				// set the container table, this makes it easier to refer back to
				headCells[i].containerTable = element;
				headCells[i].columnIndex = i;
			}
		}
		
		// add the 'on' class to every second row (skip the first one)
		var bodyRows = element.getElements("tbody tr");
		for (var i = 1; i < bodyRows.length; i+=2) {
			cssHandler("add",bodyRows[i],"on");
		}
		// hide any extra rows
		for (var i = rowsToDisplay; i < bodyRows.length; i++) {
			cssHandler("add",bodyRows[i],"hide");
		}
		
		// add the hide class to any rows beyond the number we're displaying
		hideTableRows(element, rowsToDisplay);
		
		// add the search functonality to the table
		if (cssHandler("check",element,"search")) {
			addSearchHeader(element);
		}
		
		// add the record number select box
		if (!cssHandler("check",element,"no-record-number")) {
			addRecordNumberDropdown(element);
		}
		
	});
	/* ----- END SORT TABLES ----- */
	
	
});

function sortTable(tableElement) {
	
	// the index of the column we're sorting by
	var columnIndex = this.columnIndex;

	if (columnIndex && parseInt(columnIndex) > -1) {	
		// find out which direction we're sorting and add the class
		if (cssHandler("check",this,"down")) {
			// the new direction is UP
			var direction = "up";
			cssHandler("swp",this,"down","up");
		} else {
			// the new direction is DOWN
			var direction = "down";
			
			if (cssHandler("check",this,"up")) {
				cssHandler("swp",this,"up","down");
			} else {
				cssHandler("add",this,"down");
			}
		}

		// get the table cell matrix
		var arr_bodyRows = getTableCellsMatrix(this.containerTable);
		// sort the table
		var sortedElements = sortTableByColumn(arr_bodyRows, columnIndex, direction);
		var containerTable = this.containerTable;
	} else {
		var sortedElements = getTableCellsMatrix(tableElement);
		var containerTable = tableElement;
	}
	
	// get the body rows
	var bodyRows = containerTable.getElements("tbody tr");
	// remove all of the body row elements from the table
	for (var i = 0; i < bodyRows.length; i++) {
		bodyRows[i].parentNode.removeChild(bodyRows[i]);
	}
	
	var searchRowCells = containerTable.getElements("thead tr.searchRow td, thead tr.searchRow th");
	
	// add the rows back to the body
	containerTable.getElements("tbody").each(function(bodyElement) {

		var rowOn = false;
		
		// then re-add them in order
		for (var i = 0; i < sortedElements.length; i++) {
		
			// recreate a row
			var newRow = new Element('tr', {});
			var searchHide = false;
			
			// run the searches too
			for (var j = 0; j < searchRowCells.length; j++) {		
				searchRowCells[j].getElements("input").each(function(inputElement) {
					var value = inputElement.get('value');
					if (sortedElements[i][j].innerHTML.toLowerCase().indexOf(value.toLowerCase()) == -1) {
						newRow.className = 'search-hide';
						searchHide = true;
					}
				});
			}
			
			if (!searchHide) {
				if (rowOn) {
					newRow.className = 'on';
				}
				
				// toggle row on
				rowOn = !rowOn;
			}
						
			for (var j = 0; j < sortedElements[i].length; j++) {
				sortedElements[i][j].inject(newRow, 'bottom');
			}
			
			newRow.inject(bodyElement, 'bottom');
		}
		
		// add the hide class to any rows beyond the number we're displaying
		if (bodyElement.parentNode.rowsToDisplay) {
			hideTableRows(bodyElement.parentNode, bodyElement.parentNode.rowsToDisplay);
		}
	});
}

function sortTableByColumn(param_array, columnIndex, direction) {
		
	if (!direction) {
		direction = 'down';
	}

	if (param_array.length == 1) {
		return param_array;
	}
	
	var sorted = false;
	var madeAChange = true;
	
	while (madeAChange) {
		var madeAChange = false;
		for (var i = 1; i < param_array.length; i++) {
			if ((direction == "down" && param_array[i - 1][columnIndex].innerHTML > param_array[i][columnIndex].innerHTML)
			|| (direction == "up" && param_array[i - 1][columnIndex].innerHTML < param_array[i][columnIndex].innerHTML)) {
				// swap them around
				madeAChange = true;
				var tmpRow = param_array[i];
				param_array[i] = param_array[i - 1];
				param_array[i - 1] = tmpRow;
			}
		}
	}
	
	return param_array;
}

function hideTableRows(table, rowsToDisplay) {
	
	var rows = table.getElements("tbody tr");
	var displayCount = 0;
	
	for (var i = 0; i < rows.length; i++) {
		if (displayCount >= rowsToDisplay && !cssHandler("check",rows[i],"hide")) {
			cssHandler("add",rows[i],"hide");
		} else if (!cssHandler("check",rows[i],"search-hide")) {
			displayCount++;
		}
	}
}

function addSearchHeader(table) {
	
	// get the table thead element
	var thead = table.getElement("thead");
	var theadRows = thead.getElements("tr");
	var theadCells = theadRows[0].getElements("td, th");
	
	// create the search row
	var newRow = new Element('tr', { 'class' : 'searchRow' });
	
	for (var i = 0; i < theadCells.length; i++) {
		
		// create a new cell
		var newCell = new Element(theadCells[i].tagName, {});
		
		if (!cssHandler("check",theadCells[i],"no-sort")) {
			// add an input field
			var newInput = new Element("input", { 'type' : 'text' });
			
			newInput.inject(newCell, 'bottom');
		}
		
		// add the new cell to the new row
		newCell.inject(newRow, 'bottom');
	}

	// add it to the bottom of the header
	newRow.inject(thead, 'bottom');
	
	// add the search function to the inputs
	thead.getElements('tr.searchRow td input, tr.searchRow th input').each(function(tableInput) {
		tableInput.addEvent('keyup', searchTable);
		// clear all other search fields on focus
		tableInput.addEvent('focus', function() {
			thead.getElements('tr.searchRow td input, tr.searchRow th input').each(function(subTableInput) {
				if (subTableInput != tableInput) {
					subTableInput.set('value','');
				}
				sortTable(table);
			});
		});
	});
}

function addRecordNumberDropdown(table) {
	
	var options = [[5,'5'],[10,'10'],[15,'15'],[20,'20'],[25,'25'],[30,'30'],[50,'50'],[1000000,'all']];
	
	// get the table row count class
	var classArray = table.className.split(" ");
	
	var rowsToDisplay = 1000000;
	
	for (var i = 0; i < classArray.length; i++) {
		if (classArray[i].substring(0,5) == "rows-") {
			rowsToDisplay = parseInt(classArray[i].substring(5));
		}
	}

	// set the number of rows to display on the table
	table.rowsToDisplay = rowsToDisplay;
	
	// create the search row
	var newSelect = new Element('select', {});

	for (var i = 0; i < options.length; i++) {
		
		// create a new cell
		var newOption = new Element('option', { 'value' : options[i][0], 'html' : options[i][1] });
		
		if (options[i][0] == rowsToDisplay) {
			newOption.selected = 'selected';
		}
		
		// add the new cell to the new row
		newOption.inject(newSelect, 'bottom');
	}
	
	// add a div
	var newDiv = new Element('div', {});
	var displaySpan = new Element('span', { 'html' : 'Display ' });
	var recordsSpan = new Element('span', { 'html' : ' records' });
	// add the 'display' span
	displaySpan.inject(newDiv, 'bottom');
	// add the select to the div
	newSelect.inject(newDiv, 'bottom');
	// add the 'records' span
	recordsSpan.inject(newDiv, 'bottom');
	// add it after the table
	newDiv.inject(table, 'after');
	
	// update the values on change
	newSelect.addEvent('change', function() {
		table.rowsToDisplay = this.get('value');
		sortTable(table);
	});
}

function searchTable() {
	// lots of parent nodes to get the table - input > th > tr > thead > table
	var th			= this.parentNode;
	var tr			= th.parentNode;
	var thead		= tr.parentNode;
	var table		= thead.parentNode;
	var columnIndex	= 0;
	
	var rowCells = tr.getElements('td, th');

	for (var i = 0; i < rowCells.length; i++) {
		if (rowCells[i] == th) {
			columnIndex = i;
			break;
		}
	}
	
	var tableMatrix = getTableCellsMatrix(table);
	
	// get the body rows
	var bodyRows = table.getElements("tbody tr");
	// remove all of the body row elements from the table
	for (var i = 0; i < bodyRows.length; i++) {
		bodyRows[i].parentNode.removeChild(bodyRows[i]);
	}

	var rowsToDisplay = table.rowsToDisplay;	
	var value = this.get('value');

	var displayedRows = 0;
	var rowOn = false;
	
	// filter the rows
	table.getElements("tbody").each(function(bodyElement) {

		// then re-add them in order
		for (var i = 0; i < tableMatrix.length; i++) {
		
			// recreate a row
			var newRow = new Element('tr', {});
			
			if (displayedRows >= rowsToDisplay || tableMatrix[i][columnIndex].innerHTML.toLowerCase().indexOf(value.toLowerCase()) == -1) {
				newRow.className = 'search-hide';
			} else {		
				if (rowOn) {
					newRow.className = 'on';
				}
				
				displayedRows++;
				
				// toggle row on
				rowOn = !rowOn;
			}
						
			for (var j = 0; j < tableMatrix[i].length; j++) {
				tableMatrix[i][j].inject(newRow, 'bottom');
			}
			
			newRow.inject(bodyElement, 'bottom');
		}
	});
}

function searchTableByColumn(param_array, columnIndex, rowsToDisplay, value) {

	var sorted = false;
	var madeAChange = true;
	var displayedRows = 0;
	
	// cycle through the rows
	for (var i = 0; i < param_array.length; i++) {
		// check the relevant cell for the input value
		if (displayedRows < rowsToDisplay && param_array[i][columnIndex].innerHTML.indexOf(value) != -1) {
			// found it, remove the hidden class
			if (cssHandler("check",param_array[i],"hide")) {
				cssHandler("rem",param_array[i],"hide");
			}
			displayedRows ++;
		} else if (!cssHandler("check",param_array[i],"hide")) {
			// add the hide class if it's not already there
			cssHandler("add",param_array[i],"hide");
		}
	}
	
	return param_array;
}

function getTableCellsMatrix(table) {

	var bodyRows = table.getElements("tbody tr");
	
	var arr_bodyRows = [];
	
	for (var i = 0; i < bodyRows.length; i++) {
		var arr_rowCells = [];
		
		var rowCells = bodyRows[i].getElements("td");
		
		for (var j = 0; j < rowCells.length; j++) {
			arr_rowCells.push(rowCells[j]);
		}
		
		arr_bodyRows.push(arr_rowCells);
	}
	
	return arr_bodyRows;
}










function changeText(elem_1,elem_2,data_1,data_2){
	
	elem_1.set('html',data_1);
	elem_2.set('html',data_2);
	
}


function MultiDimensionalArray(iRows,iCols){
	
	var i;
	var j;
	   var a = new Array(iRows);
	   for (i=0; i < iRows; i++)
	   {
	       a[i] = new Array(iCols);
	       for (j=0; j < iCols; j++)
	       {
	           a[i][j] = "";
	       }
	   }
	   return(a);
} 





/* Suckerfish cross-browser timer that doesn't cause overlap - http://blog.peter-ryan.co.uk/2007/12/08/suckerfish-menus-with-hide-delay/ */

sfHover = function() {
	
	if(document.getElementById("navigation_main")){
		
		var timeout = 600;
		var cssClass = "sfhover";
	
		var queue = [];
		var reCSS = new RegExp("\\b" + cssClass + "\\b");
		var sfEls = document.getElementById("navigation_main").getElementsByTagName("li");
		for (var i=0; i<sfEls.length; i++) {
	
			// mouseover and mouseout handlers for regular mouse based interface.
			sfEls[i].onmouseover = function() {
				queueFlush();
				this.className += " " + cssClass;
			}
			sfEls[i].onmouseout = function() {
				queue.push([setTimeout(queueTimeout, timeout), this]);
			}
	
			// focus and blur handlers for keyboard based navigation.
			sfEls[i].onfocus = function() {
				queueFlush();
				this.className += " " + cssClass;
			}
			sfEls[i].onblur = function() {
				queue.push([setTimeout(queueTimeout, timeout), this]);
			}
	
			// click event handler needed for tablet type interfaces (e.g. Apple iPhone).
			sfEls[i].onclick = function(e) {
				if (this.className.search(reCSS) == -1) {
					// CSS not set, so clear all sibling (and decendants) menus, and then set CSS on this menu...
					var elems = this.parentNode.getElementsByTagName("li");
					for (var i=0; i<elems.length; i++) {
						elems[i].className = elems[i].className.replace(reCSS, "");
					}
					this.className += " " + cssClass;
				} else {
					// CSS already set, so clear all decendant menus and then this menu...
					var elems = this.getElementsByTagName("li");
					for (var i=0; i<elems.length; i++) {
						elems[i].className = elems[i].className.replace(reCSS, "");
					}
					this.className = this.className.replace(reCSS, "");
				}
				if (e && e.stopPropagation)
					e.stopPropagation();
				else
					window.event.cancelBubble = true;
			}
		}
	
		queueFlush = function () {
			while (queue.length) {
				clearTimeout(queue[0][0]);
				queueTimeout();
			}
		}
	
		queueTimeout = function() {
			if (queue.length) {
				var el = queue.shift()[1];
				el.className = el.className.replace(reCSS, "");
			}
		}
		
	}//end if nav_main
		
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
};
addLoadEvent(sfHover);

/* End Suckerfish code */


// Header search functions
var headersearch_initialtext=""

function setinitialtexts() {
	if (document.getElementById("headersearch"))	{headersearch_initialtext = document.getElementById("headersearch").value}
}

if(window.addEventListener) {
		window.addEventListener('load', setinitialtexts, false);
}

if (window.attachEvent) 	{
		window.attachEvent('onload', setinitialtexts);
}

function clearinput(el) {
	var objectname = document.getElementById(el).name;
	var initialvalue = objectname + '_initialtext';

	if (document.getElementById(el)) {
		if (document.getElementById(el).value == eval(initialvalue))
		{
			document.getElementById(el).value=""
		}
	}
}

function unclearinput(el)
{
	var objectname = document.getElementById(el).name;
	var initialvalue = objectname + '_initialtext';

	if (document.getElementById(el)) {
		if (document.getElementById(el).value=="")
		{
			document.getElementById(el).value = eval(initialvalue);
		}
	}
}

// Site selector function
function changesiteaction(oSelect) {

		var iSel = oSelect.selectedIndex;
		var oOptions = oSelect.options;
		var slocation = "http://" + oOptions[iSel].value
		window.location=slocation;

}

// Handles swap/add/removal of classes from the specified element,
// can also check whether the element contains the specified class
function cssHandler(action,element,class1,class2) {

	if (typeof element == "string") {
		// have they passed in an ID
		element = document.getElementById(element);
	}

	switch (action){
		case 'swp':
			// swap classes
			element.className =
				!cssHandler('check',element,class1) ? element.className.replace(class2,class1) : element.className.replace(class1,class2);
		break;
		case 'add':
			// add class1
			if (!cssHandler('check',element,class1)) {
				element.className += element.className ? ' '+class1 : class1;
			}
		break;
		case 'rem':
			// remove class1
			var rep = element.className.match(' ' + class1) ? ' ' + class1 : class1;
			element.className = element.className.replace(rep, '');
		break;
		case 'check':
			// check if element contains a class
			return new RegExp('\\b'+class1+'\\b').test(element.className);
		break;
	}
}




// Moves a class between the elements with the tag within the container.
function toggleClass(newSelectedId, containerId, tagName, newClassName) {

	var elementsArray = document.getElementById(containerId).getElementsByTagName(tagName);

	for (i=0; i< elementsArray.length; i++) {
		if (elementsArray[i].id == newSelectedId) {
			// this is the selected one, add the class to it.
			cssHandlerFunc = 'add';
		} else {
			// not the selected one, remove the class from it
			cssHandlerFunc = 'rem';
		}

		cssHandler(cssHandlerFunc, elementsArray[i].id, newClassName);
	}
}


// Show or hide specified element
function showHide(elementId, forceShow, forceHide) {

	var elem = document.getElementById(elementId);

	if (!forceShow && !forceHide) {
		// show/hide not specified, toggle it
		if (elem.style.display == 'none') {
			forceShow = true;
		} else {
			forceHide = true;
		}
	}

	if (forceShow) {
		// show it
		elem.style.display = 'block';
	} else if (forceHide) {
		// hide it
		elem.style.display = 'none';
	}
}

// calls the showHide function on multiple elements
function showHideMulti(containerId, tagName, forceShow, forceHide) {
	var elementsArray = document.getElementById(containerId).getElementsByTagName(tagName);

	for (i=0; i< elementsArray.length; i++) {
		showHide(elementsArray[i].id, false, false);
	}
}

// applies (and removes) classes for button/target groups
function linkedList(buttonContainer, buttonTag, selectedButtonId, buttonClassOn, buttonClassOff,
					targetContainer, targetTag, selectedTargetId, targetClassOn, targetClassOff) {
	var buttons = document.getElementById(buttonContainer).getElementsByTagName(buttonTag);
	var targets = document.getElementById(targetContainer).getElementsByTagName(targetTag);

	// apply the button classes
	for (i = 0; i < buttons.length; i++) {
		if (buttons[i].id == selectedButtonId) {
			// add the 'on' class
			if (buttonClassOn.length > 0) {
				cssHandler('add', buttons[i], buttonClassOn);
			}
			// remove the 'off' class
			if (buttonClassOff.length > 0) {
				cssHandler('rem', buttons[i], buttonClassOff);
			}
		} else {
			// add the 'off' class
			if (buttonClassOff.length > 0) {
				cssHandler('add', buttons[i], buttonClassOff);
			}
			// remove the 'on' class
			if (buttonClassOn.length > 0) {
				cssHandler('rem', buttons[i], buttonClassOn);
			}
		}
	}

	// apply the target classes
	for (i = 0; i < targets.length; i++) {
		if (targets[i].id == selectedTargetId) {
			if (targetClassOn.length > 0) {
				cssHandler('add', targets[i], targetClassOn);
			}
			// remove the 'off' class
			if (targetClassOff.length > 0) {
				cssHandler('rem', targets[i], targetClassOff);
			}
		} else {
			// add the 'off' class
			if (targetClassOff.length > 0) {
				cssHandler('add', targets[i], targetClassOff);
			}
			// remove the 'on' class
			if (targetClassOn.length > 0) {
				cssHandler('rem', targets[i], targetClassOn);
			}
		}
	}
}


// wrapper for linkedList function on checkout page
function jumpToCheckoutStep(stepNo) {

	if (stepNo > 1) {
		if (document.getElementById('deliveryMethod')) // 16:40 05/02/2009 - JH - Some forms don't have this on
		{
			deliveryMethod = document.getElementById('deliveryMethod');

			// kick them back to step 1 if no delivery method is specified
			if (deliveryMethod.value == '') {
				stepNo = 1;
				document.getElementById('deliveryMethodError').style.display = 'block';
			} else {
				document.getElementById('deliveryMethodError').style.display = 'none';
			}
		}
	} else {
		document.getElementById('deliveryMethodError').style.display = 'none';
	}

	if (stepNo == 3) {
		// Change the button text back to 'Submit'
		document.getElementById('submit').innerHTML = 'Submit';
	}

	// Set the selected button and target (fieldset) classes and reset all others.
	linkedList(	'formSteps'	, 'a'		, 'formStep' + stepNo		, 'selected'	, ''	,
				'validate'	, 'fieldset', 'checkoutStep' + stepNo	, ''			, 'hide');
}

// Selects a delivery method for the document checkout
function checkoutSelectDeliveryMethod(newSelectedId, newValue) {
	// Add the selected class to the newly selected element
	toggleClass(newSelectedId, 'deliveryMethods', 'a', 'selected');

	// set the field value to the new value
	var deliveryMethod = document.getElementById('deliveryMethod');
	deliveryMethod.value = newValue;

	var postDetails = document.getElementById('postDetails');
	var postDetailsInputs = postDetails.getElementsByTagName('input');

	// hide the post-only fields if post is not selected
	switch (deliveryMethod.value)
	{
		case 'Post':
			postDetails.style.display = 'block';
			for (i = 0; i < postDetailsInputs.length; i++) {
				cssHandler('add', postDetailsInputs[i], 'required');
			}
		break;
		case 'Website Download':
		case 'Email':
			for (i = 0; i < postDetailsInputs.length; i++) {
				cssHandler('rem', postDetailsInputs[i], 'required');
				cssHandler('rem', postDetailsInputs[i], 'error');
			}

			postDetails.style.display = 'none';
		break;
	}

	// reinitialise the mootools form validation
	if ($chk($('validate'))) {
		myFormValidation = null;
		var myFormValidation = new Validate('validate', {});
	}

	// move on to step 2
	jumpToCheckoutStep(2);
}





/*
 * 
 * @param: valueType = select list value (*.value), or just an int
 * 
 */
function AJAX_getCourses_BySolutionId(solutionId,selectedCourse,valueType){
	
	var tmpId = null;
	if(valueType){
		tmpId = solutionId;
	}else{
		tmpId = solutionId.value;
	}
	
	if( (tmpId) && ($chk($('course_select_box'))) ){
		ajaxRequest('getEventsByGroup', 'course_select_box', '&solutionid='+tmpId+'&selectedCourse='+selectedCourse, false);
	}else{
		$('course_select_box').empty().set('html', '<select name="course" id="course"><option>Please select...</option></select>');
	}
	
}//func





// sends an ajax request
function ajaxRequest(webpartToRun,ouputContainerElement, URLparams, blurOut) {

	if (blurOut && $chk($(ouputContainerElement))) {
		blurDiv(ouputContainerElement,null,true);
	}
	
	var requestURL = '/resources_global/scripts/ajax_handler.php?webpart=' + webpartToRun;

	if (URLparams) {
		requestURL = requestURL + URLparams;
	}
	
	var req = new Request.HTML({url: requestURL,
		urlEncoded: true,
		encoding: 'iso-8859-1',
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			
			if (blurOut) {
				blurDiv(ouputContainerElement,null,null,true);
			}
				
			var contentText = decodeURIComponent(responseHTML);
						
			//Clear the text currently inside the results div.
			$(ouputContainerElement).set('text', '');
			//Inject the new DOM elements into the results div.
			$(ouputContainerElement).empty().set('html', contentText);
			//$(ouputContainerElement).empty().adopt(responseTree);
			
			// If there's a screen blocker present then make sure it's resized to fit the ajax results in.
			if ($chk('div.screenBlocker')) {
				$each($$('div.screenBlocker'), function (el){
					el.style.height = ((el.getParent().offsetHeight)*4) + 'px';
				});
			}
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
			if (blurOut) {
				blurDiv(ouputContainerElement,null,null,true);
			}
			$(ouputContainerElement).set('text', 'The request failed.');
		}
	});

	req.send();
}

// (un)blurs the specified div
function blurDiv(divToBlurId,exceptions,addImg,forceRemove) {

	var divToBlur = $(divToBlurId);

	if (forceRemove || $$('#' + divToBlurId + ' .screenBlocker').length > 0) {
		
/*
		for (var j = 0; j < $$('#' + divToBlurId + ' .screenBlocker').length; j++) {
			// unblur
			divToBlur.removeChild($$('#' + divToBlurId + ' .screenBlocker')[j]);

			// make all selects visible (IE6 bug)
			var selectElements = $$('#' + divToBlurId + ' select');
			for (var i in selectElements) {
				cssHandler('rem',selectElements[i],'hide');
			}

			// Remove the onTop class
			if ($$('.onTop')) {
				for (var i = 0; i < $$('.onTop').length; i++) {
					cssHandler('rem',$$('.onTop')[i],'onTop');
				}
			}

			// Hide the screen block return elements
			if ($$('.screenBlockReturn')) {
				for (var i = 0; i < $$('.screenBlockReturn').length; i++) {
					$$('.screenBlockReturn')[i].style.display = 'none';
				}
			}
		}
		*/

		
		$each($$('#' + divToBlurId + ' .screenBlocker'), function(el_ScreenBlock, index){
		
		        // select all <select> within el_ScreenBlock
		        $$('select', el_ScreenBlock).each(function(el_Select, index) {
		               el_Select.removeClass('hide');
		        });
		
		        // remove all onTop classes
		        $$('.onTop').removeClass('onTop');
		
		        // hide screenblock return elements
		        $$('.screenBlockReturn').setStyle('display', 'none');
		
		        // remove the screen block element
		        el_ScreenBlock.dispose();
		});


	} else {
		// blur
		var newdiv = document.createElement('div');

		// set the class and height of the div
		cssHandler('add',newdiv,'screenBlocker');
		newdiv.style.height = divToBlur.offsetHeight + 'px';

		// Add the ajax swirly icon if addImg is true
		if (addImg) {
			var img = document.createElement('img');
			img.src = '/resources_global/images/lookfeel/ajax-loader.gif';
			img.alt = 'loading';

			newdiv.appendChild(img);
		}

		// make all selects invisible (IE6 bug)
		var selectElements = $$('#' + divToBlurId + ' select');
		for (var i in selectElements) {
			cssHandler('add',selectElements[i],'hide');
		}

		// the exceptions array contains the ID's of the elements which will sit above the screen block
		if (exceptions) {
			for (var i = 0; i < exceptions.length; i++) {
				var exceptionElement = document.getElementById(exceptions[i]);
				cssHandler('add',exceptionElement,'onTop');

				if ($$('.screenBlockReturn')) {
					for (var i = 0; i < $$('.screenBlockReturn').length; i++) {
						$$('.screenBlockReturn')[i].style.display = 'inline';
					}
				}
			}
		}

		// add the new div
		divToBlur.appendChild(newdiv);
	}
}




function getElementsByClassName(oElm, strTagName, strClassName) {
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}


SelectQA = function(myid)
	{
	var Elements = getElementsByClassName(document, "div", "hiddendiv");
	for (i=0; i < Elements.length; i++)
	{
		if (Elements[i].id == myid) {
			Elements[i].style.display = "block";
		}
		else {
			Elements[i].style.display = "none";
		}
	}
}

AnchorLinks = function() {
	if (document.getElementById("AnchorList"))
	{
		var currentURL = document.location;
		var thisURL = currentURL.toString();
		var the_char=thisURL.charAt(thisURL.length -2);
		if (the_char!="#")
		{
			AnchorID="1"
		}
		else
		{
			AnchorID=thisURL.charAt(thisURL.length -1);
		}

//		SelectQA('QA'+AnchorID);

		ListElements = document.getElementById("AnchorList").getElementsByTagName("A");
		for (i=0; i<ListElements.length; i++) {
			node = ListElements[i];
			if (node.nodeName=="A") {
				node.onclick = function(i) {
					SelectQA("QA" + this.href.charAt(this.href.length -1));
					return false;
				}
			}
		}
	}
}

AnchorLinksOpen = function()
{
	var currentURL = document.location;
	var thisURL = currentURL.toString();
	var the_char=thisURL.charAt(thisURL.length -2);

	ListElements = document.getElementById("AnchorList").getElementsByTagName("A");
	for (i=0; i<ListElements.length; i++)
	{
		document.getElementById("QA"+ (i+1)).style.display = "block";
	}
}

if(window.addEventListener)
{
	window.addEventListener('load', AnchorLinks, false); // gecko, safari, konqueror and standard
} else if(document.addEventListener) {
	document.addEventListener('load', AnchorLinks, false);  // opera 7
} else if(window.attachEvent) { // win/ie
	window.attachEvent('onload', AnchorLinks);
} else { // mac/ie5
	if(typeof window.onload == 'function')
	{
		var existing = onload;
		window.onload = function()
		{
			AnchorLinks();
		}
	} else {
		window.onload = function()
		{
			AnchorLinks();
		}
	}
}

// Returns true if the given value exists
function isset(value) {
	var undefined;
	return !(undefined === value);
}

// removes all child nodes of the element
function removeChildNodes(element) {
	while (element.hasChildNodes()) {
		element.removeChild(element.firstChild);
	}
}

// changes the displayed page
function changePage(pageId, containerId) {
	var pages = $(containerId).getElements('.page');

	for (var i = 0; i < pages.length; i++) {
		if (pages[i].id == pageId) {
			cssHandler("rem", pages[i], 'hiddendiv');
		} else {
			if (!cssHandler("check", pages[i], 'hiddendiv')) {
				cssHandler("add", pages[i], 'hiddendiv');
			}
		}
	}

	var scroll = new Fx.Scroll(window, { wait: false, duration: 200, transition: Fx.Transitions.Quad.easeInOut });
	scroll.toElement(containerId);
}

// handle tab switching
function switchTabs(selectedTab, functionToFire) {
	// get the tab container element
	var tabList = selectedTab.parentNode;

	// get the list items (tabs)
	var listItems = tabList.getElementsByTagName(selectedTab.tagName);

	// cycle through the tabs
	for (var i in listItems) {
		if (listItems[i] == selectedTab) {
			// apply the class 'selected' to the selectedTab
			cssHandler("add", selectedTab, 'selected');

			// if the user passed in a function then fire it
			if (functionToFire && functionToFire.isFunction()) {
				functionToFire();
			}
		} else {
			// remove the class 'selected' from any other tabs
			if (cssHandler("check", listItems[i], 'selected')) {
				cssHandler("rem", listItems[i], 'selected');
			}
		}
	}

	return false;
}

