
/*
 *	@Script			: agresso_corporate.js
 *	@Description	: General functions for the Agresso website. Require Mootools 1.2. And jQuery.
 */

//////////////////////////////////////////////////////////////////////////////////////
// JQUERY 																			//
//////////////////////////////////////////////////////////////////////////////////////

var tmpTextHolder = '';
var bBasketPopup = false;

// Turn on compatibility mode for jQuery 
jQuery.noConflict(); 

jQuery(document).ready(function() {
	(function($) {	
		// Please put comments here!!
		jQuery_SetupQAList();
		
		// Set up customers by product list form
		jQuery_DynamicJumplist();
		
		// Add half class to leftcol/rightcol contents
		jQuery_SetupContentColumns();
		
		// Resize home page columns to a uniform height
		jQuery_HomeColHeight();
		
		// Resize half size content columns to a uniform height
		jQuery_HalfColHeights();

		// Add the hoverover affect for all link boxes (homepage, related links etc)
		//jQuery_SetupHoverLinks(); 
		
		// Add hover over effect for descriptions on an event calendar
		//jQuery_SetupHoverEventsCalendar();
		
		// Make the social networks tab hover
		jQuery_SocialNetworksHover();
		
		// Add padding to the home page banner if the menu exists
		jQuery_HomepageMenuPadding();
				
		// Setup rotating static banners on the homepage
		jQuery_SetupBannerRotate();

		// Set up training filter side ajax functions
		jQuery_PrepTrainingFilters();

		// Set up the country pickers to forward when changed
		jQuery_PrepCountryPickers();

		// Set up the events by month controls
		jQuery_PrepEventByMonthControls();

		// Set up customers by product list form
		jQuery_PrepCustomersByProductList();

		// Set up the header tabbed menu
		jQuery_PrepHeaderTabs();

		// Set up geolocation
		jQuery_PrepGeolocation();

		// Activate any countdowns on the page
		jQuery_ActivateCountdowns();

		// CODE FOR NEW CUSTOM FORM FEATURES
		jQuery_PrepareCustomFormActions();

		// CODE FOR THE TRAINING EVENT DETAILS PAGE
		jQuery_PrepareEventDetailsActions();

		// Password strength meter
		jQuery_PrepPasswordStrengthMeter();

		//Add a click event to all documents that should use the basket
		jQuery_PrepBasketLinks();

		// Document library
		jQuery_PrepDocumentLibrary();

		// SET UP CATCH FOR IFRS FORM SUBMIT

		// CHECK FOR IFRS FORM SUBMISSION
		jQuery('#frm_ifrs_checklist').submit(function() {
			valid_form = true;
		
			// CHECK WE HAVE ALL THE ANSWERS WE NEED
			if($('input[type=radio]:checked').length!=18) {
				valid_form = false;
			}

			// HIGHLIGHT ANY QUESTIONS THAT HAVENT BEEN ANSWERED
			$('tr.answers').each(function() {
				$('input', this).each(function() {
					$('#'+ this.id +'a').addClass('error');
					$('#'+ this.id +'b').addClass('error');
				});
				$('input:checked', this).each(function() {
					$('#'+ this.id +'a').removeClass('error');
					$('#'+ this.id +'b').removeClass('error');
				});
			});

			// CHECK WE HAVE ALL THE CONTACT DETAILS FILLED IN
			$('.is_req').each(function() {
				if($(this).val()=='') {
					valid_form = false;
					$(this).addClass('error');
				} else {
					$(this).removeClass('error');
				}
			});

			if(!valid_form) {
				$('#form_entry_error').slideDown('slow');
			} else {
				// HIDE ANY ERROR WARNINGS
				$('#form_entry_error').hide();
			}
			

			return valid_form;
		});
		
		
	})(jQuery);
	
	// Home menu
	if (jQuery('#navigation_home').length > 0) {
		jQuery('#navigation_main').remove();
	}
	
	jQuery('ul.menu_nav li.divide').each(function () {
		jQuery(this).height(jQuery(this.parentNode).height());
	});
	
	jQuery('#news_archive').accordion({
		autoHeight: false,
		navigation: true,
		header: '.acc_link'
	});
	
	var browser = navigator.userAgent;
		
	if (browser.match('MSIE 6.0')) {
		// implement min-height for IE6
		jQuery('*').each(function() {
			if (jQuery(this).height() < parseInt(jQuery(this).css('min-height'))) {
				jQuery(this).height(jQuery(this).css('min-height'));
			}
		});
	}
	
	// add home menu hover effects
	jQuery('ul.menu_nav > li').hover(
		function () { jQuery(this).addClass('hovering'); },
		function () { jQuery(this).removeClass('hovering'); }
	);
	
	// Add validation to all forms
	jQuery("form").each( function() {			  
		jQuery(this).validate();
	});
	
	// SUBMIT A CUSTOM FORM
	jQuery("form #button, form #submit").click(function() {

		/**
		 * Before we validate, check to see if we are dealing with an event registration form,
		 * if so, perform some data cleaning on the fields first if required
		 */
		if(jQuery('form.eventreg').length > 0) {	// CHECKS FOR AN EVENT REGISTRATION FORM
			if(jQuery('form.eventreg .multiple').length > 0) {	// CHECK IF WE HAVE ANY FIELDS ON THIS CUSTOM FORM THAT ARE FLAGGED AS MULTIPLE AND ADD THESE AS A LIST TO THE DOM
				if(jQuery('ul#additional_registrants').length > 0) {	// CHECKS TO SEE IF ANY ADDITIONAL REGISTRANTS HAVE BEEN ADDED
					// CHECK TO SEE IF THE PRIMARY FIELDS ARE BLANK
					var field_count = 0;
					var arrFields = new Array();
					var req_fields_blank = true;
					jQuery('form.eventreg .multiple').each(function () {
						arrFields[field_count] = jQuery(this).attr('name');
						field_count++;
						if(jQuery(this).val()!='') {
							req_fields_blank = false;
						}
					});
					
					// IF ALL REQUIRED FIELDS ARE BLANK, THEN DO THE SWAP
					if(req_fields_blank) {
						// FIRST, ID ALL THE ADDITIONAL REGISTRANTS
						var registrant_number = 1;
						jQuery('ul#additional_registrants li').each(function () {
							jQuery(this).attr('id', 'reg'+registrant_number);
							registrant_number++;
						});
						
						// REPLACE THE PRIMARY FIELD VALUES WITH THE FIRST ADDITIONAL
						var this_element, the_value;
						for(x in arrFields) {
							this_element = 'form.eventreg input.multiple:eq('+x+')';
							the_value = jQuery('ul#additional_registrants li#reg1 input:eq('+x+')').val();
							jQuery(this_element).val(the_value);
						}
						
						// CLEAR THE FIRST ADDITIONAL
						jQuery('ul#additional_registrants li#reg1').remove();

						// CHECK IF WE CAN REMOVE THE ADDITIONAL BOX ALTOGETHER
						if(jQuery('#multiple-registrations-container ul#additional_registrants li').length == 0) {
							jQuery('#multiple-registrations-container').remove();
						}
		}	}	}	}
			
		// VALIDATE THE FORM
		if(jQuery(this).closest("form").valid()) {
			if (!jQuery(this).hasClass("hiddebutton")) {
				jQuery(this).addClass("hiddebutton");
				loadingScreen(jQuery(this).closest("div"));

				var field_id='', field_name='', element='';
				jQuery('.multiple').each(function () {
					field_name += jQuery(this).attr('name') +',';
				});

				// REMOVE TRAILING COMMA
				field_name = field_name.substring(0, field_name.length - 1);
				element = '<input type="hidden" id="form_multiple_fields" name="form_multiple_fields" value="'+ field_name +'" />';
				jQuery(this).closest("form").append(element);
			}
		}
	});
	
	// impliment ajax submission of forms
	jQuery("form.ajaxform #button").click(function() {
        var str = jQuery(this).closest("form.ajaxform").serialize();
		var formid = jQuery(this).closest("form.ajaxform").attr('id');

		jQuery(this).closest("form.ajaxform").validate();

		if(jQuery(this).closest("form.ajaxform").valid()){
	
			jQuery.ajax({
			   type: "POST",
			   url: "/resources_app/library/ajax/ajax_formsubmission.php",
			   data: str,
			   beforeSend: function(){ 
				  //jQuery('form.ajaxform button').after('<div id="loadingScreen"><img src="images/site/portfolio-loader.gif" /></div>');
			   },
			   dataType: "html",
			   success: function(response){
					jQuery('#' + formid).html(response);
				   //jQuery('#loadingScreen').remove();
				   animateResults();
			   }
			}); 
		}
		
		return false;
		
   	});
	
	animateResults();
	
	
//VACANCY INIT CALLS----------------------
//TODO : CHANGE HTML ELEMENT IDS, FOR BETTER, MORE SPECIFIC NAMING!! S.C
//		 CHANGE TO USE LISTENERS INSTEAD??
	
	//u4a vacancy detail call
	if(jQuery('#v_id').val()){
		var vacancy_id = jQuery('#v_id').val();
		if(vacancy_id > 0){

			var Data = new Array();
			
			Data['vacancy_id']=vacancy_id;
			Data['action']='detailVacancy';
			
			//make call
			PeopleXS_Handler(Data);
			
		}
		
	}//
	
	
	//u4a vacancy listings call
	if(jQuery('#hidden_page').val()){
		var page = jQuery('#hidden_page').val();
		var vtype = jQuery('#hidden_vtype').val();
		if(page > 0 || vtype > 0){
					
			//calls PXS handler
			var Data = new Array();
			Data['vacancy_type']=vtype;
			Data['action']='listVacancies';
			Data['page'] = page;
							
			PeopleXS_Handler(Data);

		}
	}//
	
	
	//u4a vacancy latest listings call
	if(jQuery('#hidden_vacancy_type').val()){

		var Data = new Array();
// S.G
//find the current page and select the right vacancy type for this page -this has been set up for NL site
//by default it will pick up the 3 job without considering the type
//for any specific site need to be extended
		   var vars = [], hash;
		   var hashes = window.location.href.slice(window.location.href.indexOf('') + 1).split('/');
		   for(var i = 0; i < hashes.length; i++)
		   {         
			   hash = hashes[i];
		       vars.push(hash[0]);
		       vars[hash[0]] = hash[1]; 			   
		   }

		   if (hash == 'starter')
		   {
			   Data['vacancy_type']=1;
		   }else if(hash == 'midcareer')
		   {
			   Data['vacancy_type']=2;
		   }else if(hash == 'professional')
		   {
			   Data['vacancy_type']=3;
		   }else{
			   //default
			   Data['vacancy_type']=jQuery('#hidden_vacancy_type').val();
		   }
		   
		Data['limit'] = 3;
		Data['action']='listVacancies';
		Data['listType']='summary'; 

		//make call
		PeopleXS_Handler(Data);
	
	}//
	
	
	
//END VACANCY INIT CALLS----------------------
	

	
	/* ----- START SORT TABLES ----- */
	 
	//VACANCIES SECTION
	if(jQuery("#VacancyTableSort").length > 0){
		jQuery("#VacancyTableSort").tablesorter({
			dateFormat: 'dd/mm/yyyy',
			sortList: [[3,1]],
			textExtraction: "complex"
		}); 
	}
	
	/* ----- END TABLE SORTER ----- */


	// CHECK FOR INSTANCE OF REDIRECT BUTTON AND ASSOCIATE ACTION TO IT
	if(jQuery('#url_redirect').length > 0) {
		jQuery('#url_redirect').click(function() {
			var url = jQuery(this).attr('alt');
			window.location.replace(url);
		});
	}
	
	// SEARCH RESULT OPTIONS PANEL
	var oSearchResultsForm = jQuery( '.search_results_form' ).eq(0);
	if( oSearchResultsForm.length > 0 ) {
		var iLeft = jQuery( 'label#searchBox' ).width();
		var oAdvancedContainer = jQuery( '.search_options_container' );
		var oAdvancedLink = jQuery( '.search_options_toggle' );
		var oTrack = jQuery( '.search_results_form input#search_options_advanced' );

		oSearchResultsForm.append( oAdvancedLink );
		
		oAdvancedLink.css({
			'display': 'block',
			'padding-left': iLeft
		});
		
		if( oTrack.val() == 0 ) {
			oAdvancedContainer.hide();
		}
		
		oAdvancedLink.click(function( oEvent ) {
			oEvent.preventDefault();
			oAdvancedContainer.slideToggle();

			oTrack.val( ( oTrack.val() == 0 ) ? 1 : 0 );
		});
	}

	// CHECK FOR ACTIONS TO BE PERFORMED FOR THE PROCUREMENT QUESTIONNAIRE
	if(jQuery('#questionnaire-360').length!=0) {
		questionnaire_360();
	}
	/* =SCROLL-FUNCTIONS for Twitter Feed
	=== === === === === === === === === === */
	
	jQuery( function() {
		var oContainer = jQuery('.TwitterFeedContainer' );

		// If a list of revisions exists, we need to make them scroll
		if( oContainer.length > 0 )
		{
			bugOverview_ScrollRevisions();
		}

		// Hovering over the list of reivisons will stop them from scrolling
		oContainer.hover( function()
		{
			oContainer.find( 'li' ).eq(0).stop();
		}, function() {
			bugOverview_ScrollRevisions();
		});
	});
	
});



/* on window load for script that can only execute when the page has finished loading */
jQuery( window ).load(function() {
	
	// SET THE HOMEPAGE COLUMNS BASED ON CLASS NAME
	jQuery_HomeColHeightByClass();
	
	/* ----- START FLOATING SHOWCASE LINKS ----- */
	if(jQuery( 'div.showcase_outer.floating' ).length > 0){
		// Grab the top and height of the container element
		var oContainer = jQuery( 'div.showcase_outer.floating' );
		var fContainerY = oContainer.offset().top;
		var fContainerHeight = oContainer.height();
		
		// Make the container position relative
		oContainer.css( "position", "relative" );
		
		// On window scroll
		jQuery( window ).scroll( function( oEvent ) {
			// Grab the scroll position of the window
			var fWindowScrollY = jQuery( window ).scrollTop();
			
			// Element top should be 20px above the window scroll once the window has scrolled past it
			var fTop = Math.max( fWindowScrollY - fContainerY + 20, 0 );
			
			// Grab the position of the footer and the new bottom position of the element
			var fFooterY = jQuery( '#footer' ).offset().top;
			var fBottom = fContainerY + fTop + fContainerHeight;
			
			// Make sure the bottom of the element doesn't overlap the footer
			var fPosition = ( fBottom > fFooterY ) ? fTop - ( fBottom - fFooterY ) : fTop;
			
			// Animate the element into place
			oContainer.animate({top:fPosition},{duration:500,queue:false});
		})
		
		// Fake a scroll event incase the user soft reloads the page
		jQuery( window ).trigger( 'scroll' );
	}
	
	/* ----- END FLOATING SHOWCASE LINKS ----- */
		
	/* ----- START SCROLLING CUSTOMER QUOTES ----- */
	startScrollingQuotes();
		
	/* ----- END SCROLLING CUSTOMER QUOTES ----- */
		
	/* ----- START DOCUMENT CHECKOUT TRACKING ----- */
	attachBasketEvents();
	/* ----- End DOCUMENT CHECKOUT TRACKING ----- */
		
	// SET THE HOMEPAGE COLUMNS BASED ON CLASS NAME
	jQuery_HomeColHeightByClass();
	
	// Set up BC showcased popups
	jQuery_AttachShowcaseLinkLightboxes();	

	// SET UP MAX WIDTH OF THE IMAGE GAP FOR content-tab-vertical
	jQuery_SetMaxWidthFor_content_tab_vertical();
});

/* =SCROLL-FUNCTIONS for Twitter Feed
=== === === === === === === === === === */

	/*
	 *	Scroll the list of twitter Feeds
	 */
	function bugOverview_ScrollRevisions() {
		jQuery('.TwitterFeedContainer' ).each( function( i, e ) {
			var oContainer = jQuery(e );
			var oFirst = oContainer.find( 'li' ).eq(0);
			var iHeight = oFirst.outerHeight();
			var iTopMargin = parseFloat( oFirst.css( 'margin-top' ) );
		
			// when the animation is complete, remove the first element and append it back onto the list
			fnCallback = function() {
				var oTemp = oFirst.remove();
				oTemp.css({
					'margin-top': '0'
				}).appendTo( oContainer );
			
				setTimeout( bugOverview_ScrollRevisions, 8000);
			}
		
			var iPercentageRemaining = 100 - ( ( -(iTopMargin) / iHeight ) * 100 );
			var iEffectSpeed = parseInt( ( 3000 / 100 ) * iPercentageRemaining );
		
			// Animate the top element so that it scrolls out of view
			oFirst.animate({
				'margin-top': '-' + iHeight + 'px'
			}, iEffectSpeed, 'easeInOutCubic', fnCallback );
		});
	}

/*
 * 	New custom form features
 */
function jQuery_PrepareCustomFormActions() {
	if(jQuery('#add-another-registrant').length > 0) {
		// WE HAVE AN ADD ANOTHER REGISTRANT BUTTON ON THE FORM
		jQuery('#add-another-registrant').live('click', function () {
			var req_field_error = false;
			// FIRST CHECK THE MULTIPLE REG FIELDS HAVE DATA IN THEM
			jQuery('.multiple').each(function () {
				// CHECK IF FIELD IS REQUIRED
				if(jQuery(this).hasClass('required') && jQuery(this).val()=='') {
					// IS REQUIRED AND IS EMPTY
					jQuery(this).addClass('error');
					req_field_error = true;
				} else {
					jQuery(this).removeClass('error');
				}
			});
			
			// CHECK THAT WE ARE OK TO PROCEED
			if(!req_field_error) {
				// CHECK IF WE HAVE NOT GOT OUR MULTIPLE REGS CONTAINER ON DOM, IF NOT, ADD IT
				if(jQuery('#multiple-registrations-container').length == 0) {
					// GET LOCALISED CONSTANT VALUE FOR TITLE
					var title = '';
					jQuery.ajax({
						type:	"POST",
						url:	"/resources_global/scripts/ajax_getconstant.php",
						data:	'cn=CONST_LOC_ADD_NEW_EVENT_REGISTRANT_TITLE',
						async:	false,
						success: function(response) {
							title = (response);
						}
					});
					jQuery('ul.form').after('<div id="multiple-registrations-container"><h2>'+title+'</h2><ul id="additional_registrants"></ul><div>');
				}
	
				// CHECK WE ARE OK TO ADD THIS NEW REGISTRATION DETAILS
				if(jQuery('#eventPlacesAvailable').length > 0) {
					var currentPlaces = 1;
					var placesAvailable = jQuery('#eventPlacesAvailable').val();
					if(jQuery('#multiple-registrations-container').length != 0) {
						jQuery('#additional_registrants li').each(function () { currentPlaces++; } );
						if(currentPlaces == placesAvailable) {
							// GET LOCALISED CONSTANT VALUE FOR TITLE
							if(jQuery('p.event-full').length == 0) {
								var limit_reached = '';
								jQuery.ajax({
									type:	"POST",
									url:	"/resources_global/scripts/ajax_getconstant.php",
									data:	'cn=CONST_LOC_EVENT_ONLINE_BOOKING_REACHED_MAX',
									async:	false,
									success: function(response) {
										limit_reached = (response);
									}
								});
								jQuery('#additional_registrants').after('<p class="event-full">'+limit_reached+'</p>');
							}
							return;
						}
					}
				}
	
				// GET THE DETAILS OF THE FIELDS FLAGGED AS MULTIPLE REGISTRATIONS AND ADD TO DOM
				var name_to_add='';
				var this_name='', html='', ok_to_add=true;
				jQuery('.multiple').each(function () {
					// CHECK IF FIELD IS REQUIRED
					if(jQuery(this).hasClass('required') && jQuery(this).val()=='') {
						// IS REQUIRED AND IS EMPTY
						jQuery(this).addClass('error');
						ok_to_add = false;
					} else {
						jQuery(this).removeClass('error');
						
						// ONLY ADD FIRST NAME, LAST NAME OR EMAIL ADDRESS TO ADDITIONAL REGISTRANTS LIST
						this_name = jQuery(this).attr('name');
						if(this_name=='first_name[]' || this_name=='last_name[]' || this_name=='email[]') {
							name_to_add += jQuery(this).val() + ', ';
						}
						
						// DUPLICATE THE FIELDS THAT NEED ADDING TO THE DATABASE
						// html += '<input type="hidden" name="'+ jQuery(this).attr('id') +'[]" value="'+ jQuery(this).val() + '" />';
						html += '<input type="hidden" name="'+ this_name +'" value="'+ jQuery(this).val() + '" />';
					}
				});
	
				// ADD DETAILS TO DOM
				if(ok_to_add) {
					name_to_add = name_to_add.substring(0, name_to_add.length - 2);
					if(name_to_add.length > 48)
						name_to_add = name_to_add.substring(0, 45) + '...';
					
					// CHECK THIS NAME HAS NOT ALREADY BEEN ADDED
					var registrants = '';
					jQuery('#additional_registrants li').each(function () {
						registrants = jQuery(this).html();
						registrants = registrants.substring(0, name_to_add.length);
						if(name_to_add == registrants) {
							ok_to_add = false;
							jQuery(this).effect('highlight');
						}
					});
	
					// FINAL CHECK IF OK TO ADD TO DOM
					if(ok_to_add) {
						var remove = '';
						jQuery.ajax({
							type:	"POST",
							url:	"/resources_global/scripts/ajax_getconstant.php",
							data:	'cn=CONST_LOC_ADD_NEW_EVENT_REGISTRANT_REMOVE',
							async:	false,
							success: function(response) {
								remove = (response);
							}
						});
						name_to_add = '<li>'+ name_to_add +'<span class="remove-registrant">['+remove+']'+ html +'</span></li>';
						jQuery('#additional_registrants').append(name_to_add);
						jQuery('.multiple').val('');
						
						// PUT FOCUS BACK ON FIRST MULTIPLE FIELD
						jQuery('.multiple:first').focus();
					}
				}
			}
		});
	}
	
	// REMOVE ANY SELECTED ADDITIONAL REGISTRANTS
	jQuery('.remove-registrant').live('click', function () {
		var registrants = 0;
		jQuery('#additional_registrants li').each(function () { registrants++ });

		// IF WE ONLY HAVE ONE LEFT, REMOVE ENTIRE CONTAINER FROM THE DOM
		if(registrants == 1) {
			jQuery('#multiple-registrations-container').remove();
		} else {
			// JUST REMOVE SELECTED ENTRY
			jQuery(this).parent('li').remove();
			jQuery('.event-full').remove();
		}
	});
}


/*
 * 	Prepares functionality for the event training schedules
 */
function jQuery_PrepareEventDetailsActions() {
	
	// CHECK IF THE view-schedule-details LINK IS AVAILABLE ON THIS PAGE
	if(jQuery('.view-schedule-details').length > 0) {
		jQuery('.view-schedule-details').click(function () {
			var eid = jQuery(this).attr('id').substring(5);
			var esid = 'es_'+ eid;
			
			// HIDE OPEN SCHEDULES
			jQuery('.event-schedule-detail').each(function () {
				if(jQuery(this).attr('id')!=esid) {
					jQuery(this).slideUp();
					jQuery('.event-schedule-list li').removeClass('selected');
				}
			});
			
			// OPEN THE SELECTED SCHEDULE
			jQuery('#'+ esid).slideDown();
			jQuery(this).closest('li').addClass('selected');
		});
	}

	// CHECKS IF THE register-for-event LINK IS AVAILABLE ON THIS PAGE
	if(jQuery('.register-for-event').length > 0) {
		jQuery('.register-for-event').click(function () {
			// GET THE EVENT ID THAT THE USER IS REGISTERING ON
			var Event_Id = jQuery(this).attr('id');
			
			// GET AND CHECK THAT THERE ARE T&CS SET FOR THIS EVENT
			var EventTerms = '#event-terms-tickbox-'+ Event_Id;
			if(jQuery(EventTerms).length > 0) {
				if(!jQuery(EventTerms).attr('checked')) {
					jQuery('#agree-terms-flag-'+ Event_Id).fadeIn('slow');
					var cssObj = { 'font-weight' : 'bold' };
					jQuery('#agree-terms-'+ Event_Id).css(cssObj);
					return false;
				} else {
					// TICKED
					jQuery('#agree-terms-flag-'+ Event_Id).hide();
				}
			}
		});
	}
}


/*
 *	This function returns a constant value (or localized if available) for the current site given a constant_name 
 */
function get_constant_value(str_constantname) {
	// CALL SCRIPT TO FIND CONSTANT VALUE
	jQuery.ajax({
		type:	"POST",
		url:	"/resources_global/scripts/ajax_getconstant.php",
		data:	'cn='+str_constantname,
		async:	false,
		success: function(response) {
			return(response);
		}
	}); 
}


/*
 *		Decode encoded HTML characters
 */
function html_entity_decode(str) {
	str = str.replace( /&lt;/g, '<' );
	str = str.replace( /&gt;/g, '>' );
	return str;
}

/*
 *		Call all of the functions to attach tracking to the document checkout
 */
function attachBasketEvents() {
	attachBasketAddEvents();
	attachBasketRemoveEvents();
	attachBasketCheckoutEvents();
	attachBasketWhiteBoxEvents();
	attachBasketDownloadEvents();
}

/*
 *		Track when a user adds a document to the basket
 */
function attachBasketAddEvents() {
	jQuery( '#infodownloads_data .track_basket a' ).live( 'click', function( oEvent ) {
		var sHref = jQuery( this ).attr( 'href' );
		var oPattern = /javascript:/gi;
		var bUseBasket = ( sHref.match(oPattern) != null );
		
		// Only track if this is a checkout, ignore direct downloads
		if( bUseBasket ) {
			trackAnalyticsEvent( 'Information Checkout', 'document added to basket', jQuery( 'strong', this ).text() );
		}
	});
}

/*
 *		Track when a user dismisses the white item added message
 */
function attachBasketWhiteBoxEvents() {
	jQuery( '#firstBasketItem a' ).live( 'click', function( oEvent ) {
		trackAnalyticsEvent( 'Information Checkout', 'item added message', 'click on message' );
	});
}

/*
 *		Track when a user confirms adding the document to the basket
 */
function attachBasketPopupEvents() {
	jQuery( '#basket_overlay_message a' ).live( 'click', function( oEvent ) {
		trackAnalyticsEvent( 'Information Checkout', 'document checkout message', 'click on message' );
	});
}

/*
 *		Track when a user removes a document from the basket
 */
function attachBasketRemoveEvents() {
	jQuery( '#basketWrapper ul li a.track_basket_remove' ).live( 'click', function( oEvent ) {
		trackAnalyticsEvent( 'Information Checkout', 'document removed from basket', jQuery( this ).text() );
	});
}

/*
 *		Track when the user goes through to the checkout process
 */
function attachBasketCheckoutEvents() {
	jQuery( '#basketWrapper a.track_basket_checkout' ).click( function( oEvent ) {
		trackAnalyticsEvent( 'Information Checkout', 'collect information clicked', 'collect information' );
	});
}

/*
 *		Track when the user downloads a document
 */
function attachBasketDownloadEvents() {
	jQuery( '.fileIconList li a.track_basket_download' ).click( function( oEvent ) {
		trackAnalyticsEvent( 'Information Checkout', 'document download page', jQuery( this ).text() );
	});
}

/*
 *		Track a custom analytics event
 */
function trackAnalyticsEvent( sAction, sLabel, sValue ) {
	// If analytics isn't available then don't do anything
	if( typeof( _gaq ) != 'object' ) {
		return false;
	}
	
	var sEventCategory = '_trackEvent';
	var oData = [sEventCategory, sAction, sLabel, sValue];
	
	_gaq.push( oData );
}



jQuery.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return jQuery.getUrlVars()[name];
  }
});

jQuery(".acc_link").click(function(event){
	window.location.hash=this.hash;
});

function jQuery_SetupQAList()
{
	jQuery("div.qa_list").each(function(int_Index, obj_List) {

		// Hide all BUT the first item
		jQuery("ul.list_data li").each(function(i) {
			if (i > 0) {
				jQuery(this).hide();
			}
		});

		// Bold the first link
		jQuery("ul.list_links li:first-child a").addClass("menu_selected");

		// Add onclick event for the related hrefs
		jQuery("ul.list_links li a").click(function() {
			jQuery_SwitchQAList(this, obj_List);
		});

	});
}


function jQuery_SetupContentColumns() {
	var leftCol = jQuery("div.content div.content-left-col > div").length;
	var rightCol = jQuery("div.content div.content-right-col > div").length;
	
	if (leftCol > 0 && rightCol > 0) {
		// add the half class to all child divs of the left and right columns
		jQuery("div.content div.content-left-col > div").addClass("half");
		jQuery("div.content div.content-right-col > div").addClass("half");
	}
}
	

function jQuery_HomepageMenuPadding()
{
	// if we have the menu container, which should only be on the homepage
	if (jQuery("div.menucontainer").length > 0)
	{
		jQuery("div.bannercontainer").addClass("bannercontainer_padding");
	}
}

function jQuery_SwitchQAList(obj_ItemPicked, obj_List)
{
	// Find current index
	int_IndexPicked = jQuery("ul.list_links li a", obj_List).index(obj_ItemPicked);
	
	// Clear all styling and highlight current.
	jQuery("ul.list_links li a", obj_List).removeClass("menu_selected");
	jQuery(obj_ItemPicked).addClass("menu_selected");

	// Hide all elements
	jQuery("ul.list_data li", obj_List).hide();
	
	// Show chosen element based on index
	jQuery("ul.list_data li:nth-child("+ (int_IndexPicked + 1) +")", obj_List).show();
}

function jQuery_HomeColHeight()
{
	// make sure we're on the home page
	if (jQuery("#navigation_home").length > 0) {
		// will store the max column height (in px)
		var max_height = 0;
		
		var height = 0;
		
		/* Home sectors section */
		var sector_height = jQuery("div.homesectors").height()
			+ parseInt(jQuery("div.homesectors").css("padding-top"), 10)
			+ parseInt(jQuery("div.homesectors").css("padding-bottom"), 10);
		
		if (sector_height > max_height) {
			max_height = sector_height;
		}
		
		/* Home products section */
		var products_height = jQuery("div.homeproducts").height()
			+ parseInt(jQuery("div.homeproducts").css("padding-top"), 10)
			+ parseInt(jQuery("div.homeproducts").css("padding-bottom"), 10);
		
		if (products_height > max_height) {
			max_height = products_height;
		}
		
		/* Home news section */
		var news_height = jQuery("div.homenews").height()
			+ parseInt(jQuery("div.homenews").css("padding-top"), 10)
			+ parseInt(jQuery("div.homenews").css("padding-bottom"), 10);
		
		if (news_height > max_height) {
			max_height = news_height;
		}
		
		/* Home About/Address section */
		var about_height = jQuery("div.homeabout").height()
			+ parseInt(jQuery("div.homeabout").css("margin-bottom"), 10)
			+ parseInt(jQuery("div.homeabout").css("padding-top"), 10)
			+ parseInt(jQuery("div.homeabout").css("padding-bottom"), 10)
			+ jQuery("div.homeaddress").height()
			+ parseInt(jQuery("div.homeaddress").css("margin-top"), 10)
			+ parseInt(jQuery("div.homeaddress").css("padding-top"), 10)
			+ parseInt(jQuery("div.homeaddress").css("padding-bottom"), 10)
			+ jQuery("div.contentside").height()
			+ parseInt(jQuery("div.contentside").css("margin-top"), 10)
			+ parseInt(jQuery("div.contentside").css("padding-top"), 10)
			+ parseInt(jQuery("div.contentside").css("padding-bottom"), 10);
			
		if (about_height > max_height) {
			max_height = about_height;
		}
		
		// we have the max height, now lets apply it
		var height_diff = 0;
		var new_height = 0;
		
		/* Home About/Address section */
		if (about_height < max_height) {
			height_diff = max_height - about_height;
			
			new_height = jQuery("div.homeabout").height() + (height_diff/3);
			jQuery("div.homeabout").height(new_height);
			
			new_height = jQuery("div.homeaddress").height() + (height_diff/3);
			jQuery("div.homeaddress").height(new_height);
			
			new_height = jQuery("div.contentside").height() + (height_diff/3);
			jQuery("div.contentside").height(new_height);
			
		} else {
			// about is the biggest, add 2px for the borders
			max_height = max_height + 2;
		}
		
		/* Home sectors section */
		if (sector_height < max_height) {
			height_diff = max_height - sector_height;
			new_height = jQuery("div.homesectors").height() + height_diff;
			
			jQuery("div.homesectors").height(new_height);
		}
		
		/* Home products section */
		if (products_height < max_height) {
			height_diff = max_height - products_height;
			new_height = jQuery("div.homeproducts").height() + height_diff;
			
			jQuery("div.homeproducts").height(new_height);
		}
		
		/* Home news section */
		if (news_height < max_height) {
			height_diff = max_height - news_height;
			new_height = jQuery("div.homenews").height() + height_diff;
			
			jQuery("div.homenews").height(new_height);
		}
	}
}

function jQuery_HomeColHeightByClass()
{
	// SETS ANY DIVS WITH THE CSS CLASS OF fixed_height TO ALL HAVE THE SAME HEIGHT AS THE HIGHEST FOUND DIV
	
	// MAKE SURE WE'RE ON THE HOME PAGE
	if (jQuery("#navigation_home").length > 0) {
		// WILL STORE THE MAX COLUMN HEIGHT (IN PX)
		var max_height = 0;
		var height = 0;
		var this_height = 0;

		var arr_divs = new Array();
		var arr_div_heights = new Array();
		var this_Id = '';

		// WORK OUT THE MAX HEIGHT OF ANY DIVS THAT HAVE A CLASS OF fixed_height IN THEM
		jQuery('.fixed_height').each(function (elementIndex) {
			// CHECK IF AN ID IS SET FOR THIS DIV
			if(jQuery(this).attr('id').length > 0) {
				// FOUND THE ID, USE THIS ONE
				this_Id = jQuery(this).attr('id');
			} else {
				// DOES NOT HAVE AN ID, SO ADD A TEMPORARY ONE TO IT
				this_Id = 'fixed_div_'+elementIndex;
				arr_divs[elementIndex] = this_Id;
				jQuery(this).attr("id", this_Id);
			}

			// PLACE THIS ID INTO AN ARRAY
			arr_divs[elementIndex] = this_Id;
			
			// GET THE HEIGHT OF THE CURRENT DIV
			arr_div_heights[elementIndex] = jQuery(this).height()
																				+ parseInt(jQuery(this).css("padding-top"), 10)
																				+ parseInt(jQuery(this).css("padding-bottom"), 10);

			// DETERMINE IF THIS DIV HAS THE HIGHEST HEIGHT VALUE
			if (arr_div_heights[elementIndex] > max_height) {
				max_height = arr_div_heights[elementIndex];
			}
		});

		// WE HAVE THE MAX HEIGHT, NOW LETS APPLY IT
		var height_diff = 0;
		var new_height = 0;
		max_height += 50;
		
		// LOOP THROUGH OUR ARRAY OF DIV IDS AND WORK OUT WHICH ONES TO ASSIGN A NEW HEIGHT VALUE TO MAKE THEM ALL THE SAME HEIGHT
		for(this_div in arr_divs) {
			if(arr_div_heights[this_div] < max_height) {
				// CURRENT DIV IN LOOP HAS A HEIGHT LESS THAN THE MAX, SO ALTER THIS DIVS HEIGHT
				height_diff = max_height - arr_div_heights[this_div];
				new_height = jQuery('#'+arr_divs[this_div]).height() + height_diff;
				jQuery('#'+arr_divs[this_div]).height(new_height);
			}
		}
	}
}



function jQuery_SetupBannerRotate()
{
	if (jQuery("div#banner_scroll").length > 0) {
		jQuery("div#banner_scroll").scrollable({size: 1, clickable: false}).autoscroll({autoplay: true, interval: 8000}).circular().navigator
		({
			navi: "#banner_tabs"
		,	naviItem: 'a'
		,	activeClass: 'current'
		});
	}
}

function jQuery_PrepGeolocation() {
	jQuery('#geolocation-country-pick').each(function() {
		// add a loading screen to the body
		loadingScreen('body');
		jQuery('div.floatingcontainer').insertAfter(jQuery('div.loadingScreen'));
	});
}

function jQuery_PrepTrainingFilters() {
	jQuery('ul#training-filter-side .event-filter').live('change', function () {
		jQuery_RefreshTrainingFilters();
		jQuery('#reset-filters').show().removeClass('hidden');
	});
	
	jQuery('button#reset-filters').live('click', function () {
		jQuery('ul#training-filter-side li select option').removeAttr('selected');
		jQuery('ul#training-filter-side li select').each(function () {
			jQuery(this).children().first().attr('selected', 'selected');
		});
		
		jQuery_RefreshTrainingFilters();
	});
}

// REFRESHES THE ONSCREEN TRAINING FILTER DROPDOWNS
function jQuery_RefreshTrainingFilters() {
	var URLparams = '';
	jQuery('ul#training-filter-side .event-filter').each(function () {
		if(jQuery(this).val()!='')
			URLparams += jQuery(this).attr('id') +'='+ jQuery(this).val() +'&';
	});
	ajaxRequest('refreshTrainingFilters', 'training-filter-wrap', URLparams, true, 'refreshTrainingFilters');
}

// make the country pickers forward the user when they select an option
function jQuery_PrepCountryPickers() {
	jQuery('select.form_SiteList').change(function() {
		window.location = jQuery(this).val();
	});
}

// When the user clicks a link on the controls, open the relevant div (and close all others)
function jQuery_PrepEventByMonthControls() {
	jQuery('#events_by_month_controls li a').click(function () {
		var openDiv = jQuery(this).attr("href");
		// close all divs
		jQuery('.event-month').hide();
		// open the one they clicked the control for
		jQuery(openDiv).show();
		
		// return false so it doesn't jump to the div we just opened
		// this is off because it flickers and jumps and generally goes a bit mental
		return false;
	});
}

function jQuery_PrepCustomersByProductList() {
	jQuery("#customer-product-form button").click(function() {
		var productid = jQuery("#PID").val();
		
		if (productid) {
			var URLparams = 'PID=' + productid;
			// fire the ajax to refresh the customers list
			ajaxRequest('customer_product_list', 'customers-products-list', URLparams, true);
		}
		
		// don't let the form submit
		return false;
	});
}

// set up the header tabs for clicking
function jQuery_PrepHeaderTabs() {
	jQuery("ul#header-tabbed-tabs li a").click(function( e ) {
		e.preventDefault();
		
		// for IE7 or less, don't slide, just show and hide
		var slide = true;
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) <= 7) {
			slide = false;
		}
		
		// get the href from this link, it tells us which tab to open
		//var theHref = jQuery(this).attr("href");
		var theHref = jQuery(this).attr( 'href' ).replace( /(.*)(#.*)/, '$2' );
		
		// we close if this has the selected class
		var closeThis = jQuery(this.parentNode).hasClass('selected');
		
		if (closeThis) {
			jQuery(this.parentNode).removeClass("selected");
			jQuery('ul#header-tabbed-content').removeClass("open");
			if (slide) {
				jQuery(theHref).slideUp();
			} else {
				jQuery(theHref).hide();
			}
			return;
		}
		
		// add the open class to the tab content list
		jQuery('ul#header-tabbed-content').addClass("open");
		
		// check if anything is open already
		var openTabs = jQuery("ul#header-tabbed-tabs li.selected a").length;

		// remove the selected class from all other tabs
		jQuery("ul#header-tabbed-tabs > li").removeClass("selected");
		
		// add the selected class to this tab (link)
		jQuery(this.parentNode).addClass("selected");
		
		// open the LI
		if (openTabs == 0) {
			// slide the LI open
			if (slide) {
				jQuery("li" + theHref).slideDown().addClass("selected");
			} else {
				jQuery("li" + theHref).show().addClass("selected");
			}
		} else {
			// hide the open tab (content)
			jQuery("ul#header-tabbed-content li.selected").removeClass("selected").css("display", "none");

			// display this tab (content)
			jQuery("li" + theHref).addClass("selected").css("display", "block");
		}
	});

	// Need to hide the header tabs when the window scrolls
	jQuery( window ).scroll( function() {
		jQuery( 'ul#header-tabbed-tabs li.selected a' ).trigger( 'click' );
	});
}





// resize all content half width columns to the same height
function jQuery_HalfColHeights()
{
	var max_height = 0;
	
	// find the max height of the divs
	jQuery("div.content div.half").each(function () {
		var this_height = jQuery(this).height()
			+ parseInt(jQuery(this).css("padding-top"), 10)
			+ parseInt(jQuery(this).css("padding-bottom"), 10);
			
		if (this_height > max_height) {
			max_height = this_height;
		}
	});
	
	// we have the max height, now lets apply it
	var height_diff = 0;
	var new_height = 0;
	
	jQuery("div.content div.half").each(function () {
		var this_height = jQuery(this).height()
			+ parseInt(jQuery(this).css("padding-top"), 10)
			+ parseInt(jQuery(this).css("padding-bottom"), 10);
			
		if (this_height < max_height) {
			height_diff = max_height - this_height;
			new_height = jQuery(this).height() + height_diff;
			// set the new height
			jQuery(this).height(new_height);
		}
	});
}

function animateResults(){
  jQuery(".graph div").each(function(){
      var percentage = jQuery(this).next().text();
      jQuery(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });
}


function jQuery_SetupHoverLinks()
{
  jQuery(".list_links_hover li a").hover(function(){
  	var jQuery_Span = jQuery(this).siblings('span.background');
  	jQuery(jQuery_Span).stop();
    jQuery(jQuery_Span).animate({"opacity":1});
  }, function(){
  	var jQuery_Span = jQuery(this).siblings('span.background');
    jQuery(jQuery_Span).stop();
    jQuery(jQuery_Span).animate({"opacity":0}, "slow");   
  });
}


// RETAIN VALUES FOR GIVEN FIELD FOR BEFORE AND AFTER FOCUS
function clearinput(obj) {
	obj = '#'+obj;
	tmpTextHolder = jQuery(obj).val();
	jQuery(obj).val('');
}

function unclearinput(obj) {
	obj = '#'+obj;
	if(jQuery(obj).val()=='') { jQuery(obj).val(tmpTextHolder) }
}




// Moves a class between the elements with the tag within the container.
function toggleClass(newSelectedId, containerId, tagName, newClassName) {

	var elementsArray = jQuery(tagName, '#' + containerId);

	for (i = 0; i < elementsArray.length; i++) {
		if (elementsArray[i].id == newSelectedId) {
			// this is the selected one, add the class to it.
			jQuery(elementsArray[i]).addClass(newClassName);
		} else {
			// not the selected one, remove the class from it
			jQuery(elementsArray[i]).removeClass(newClassName);
		}
	}
}




// applies (and removes) classes for button/target groups
function linkedList(buttonContainer, buttonTag, selectedButtonId, buttonClassOn, buttonClassOff,
					targetContainer, targetTag, selectedTargetId, targetClassOn, targetClassOff) {
	var buttons = jQuery(buttonTag, '#' + buttonContainer);
	var targets = jQuery(targetTag, '#' + targetContainer);

	// apply the button classes
	for (i = 0; i < buttons.length; i++) {
		if (buttons[i].id == selectedButtonId) {
			// add the 'on' class
			if (buttonClassOn.length > 0) {
				jQuery(buttons[i]).addClass(buttonClassOn);
			}
			// remove the 'off' class
			if (buttonClassOff.length > 0) {
				jQuery(buttons[i]).removeClass(buttonClassOff);
			}
		} else {
			// add the 'off' class
			if (buttonClassOff.length > 0) {
				jQuery(buttons[i]).addClass(buttonClassOff);
			}
			// remove the 'on' class
			if (buttonClassOn.length > 0) {
				jQuery(buttons[i]).removeClass(buttonClassOn);
			}
		}
	}
	
	// apply the target classes
	for (i = 0; i < targets.length; i++) {
		if (targets[i].id == selectedTargetId) {
			if (targetClassOn.length > 0) {
				jQuery(targets[i]).addClass(targetClassOn);
			}
			// remove the 'off' class
			if (targetClassOff.length > 0) {
				jQuery(targets[i]).removeClass(targetClassOff);
			}
		} else {
			// add the 'off' class
			if (targetClassOff.length > 0) {
				jQuery(targets[i]).addClass(targetClassOff);
			}
			// remove the 'on' class
			if (targetClassOn.length > 0) {
				jQuery(targets[i]).removeClass(targetClassOn);
			}
		}
	}
}



// 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
	jQuery('#deliveryMethod').val(newValue);

	var postDetailsInputs = jQuery('input', '#postDetails');

	// hide the post-only fields if post is not selected
	switch (newValue)
	{
		case 'Post':
			/* Show post details */
			jQuery('#postDetails').show();
			
			for (i = 0; i < postDetailsInputs.length; i++) {
				jQuery(postDetailsInputs[i]).addClass('required');
			}
		break;
		case 'Website Download':
		case 'Email':
			/* Hide post details */
			for (i = 0; i < postDetailsInputs.length; i++) {
				jQuery(postDetailsInputs[i]).removeClass('required');
				jQuery(postDetailsInputs[i]).removeClass('error');
			}

			jQuery('#postDetails').hide();
		break;
	}

	// move on to step 2
	jumpToCheckoutStep(2);
}

// add a loading screen
function loadingScreen(element) {
	var div = jQuery("<div>").addClass('loadingScreen').text('');	
	// append it
	div.appendTo(element);
}

// remove the loading screen(s)
function removeLoadingScreen(element){
	if (element) {
		jQuery(".loadingScreen", element).remove();
	} else {
		// remove all loading screens
		jQuery(".loadingScreen").remove();
	}
}


/*
	@Action : main handler for peopleXS. Handles all soap requests
	@Params : Data can either be a string, or an array of values
	
	@Param string: 	when using the search functionality, this func called with a string keyword, as cant add multid arrays to onclick func calls in the form, makes it easier...
	@Param array : 	action - string, relating to the required soap action...listing, or viewing details
					
*/
function PeopleXS_Handler(Data){

	//Unless search taking place (search data gathered via jquery straight from the form using func), 
	//action is provided to specify the soap action to perform (summary listings/ listings/ vacancy details) 
	if(Data == 'search' || Data['action'].length > 0){
		
		//clear any current vacancy results off the page
		vacancy_results('clear');
		
		//clear the vacancy pagination data, using pagin handler func
		vacancy_pagination('clear');
		
		//show loading gif, if not already shown...
		Loading_Handler(1);//show
		
		//gather search data, also append the action parameter
		if(Data == 'search'){
			Data = SearchFormValues('get',null);
		}

		//concat any passed data for ajax call
		var str_params = concatParameters(Data);

		//now run ajax handler, passing string-based data
		PeopleXS_Request(str_params);

	}
	
}//func



/*
	@Action : 	Gets/sets search form data. 
				Also sets up the selectbox lists for the form, using data gathered from the service.
	@Param  :   type - subaction for this function, get,reset,set,setlists
	@Param  :   data - search data passed in, for some subactions to work with
*/
function SearchFormValues(type,data){
	
	//gets the search data from the form via jQuery
	if(type=='get'){
		
		formData = new Array();
		formData['action'] 			= 'listVacancies';
		formData['Functiegebied'] 	= jQuery("select[name=Functiegebied]").val();
		formData['Locatie'] 		= jQuery("select[name=Locatie]").val();
		formData['Opleiding'] 		= jQuery("select[name=Opleiding]").val();
		formData['searchText'] 		= jQuery("input[name=searchText]").val();
		
		//saves the search data into hidden fields on the form. 
		//Enables us to remember search details for search result pagination etc
		savedsearchHandler('clear');
		
		return formData;
	
	//used to reset the search form, removing any selected options
	}else if(type == 'reset'){
		
		//clear selections
		jQuery("select[name=Functiegebied]").val('');
		jQuery("select[name=Locatie]").val('');
		jQuery("select[name=Opleiding]").val('');
		jQuery("input[name=searchText]").val('');
	
	//sets the search form options for the current search results pages...
	//If browsing search results, and user changes form elements without clicking search bttn
	//then this will reset them, letting them know which search parameters retrieved the current results...
	}else if(type=='set'){
			
		//set the user chosen data within the select lists
		try{
			if(data['Functiegebied']){
				jQuery('#Functiegebied').val(data['Functiegebied']);
			}
		}catch(e){}
		try{
			if(data['Locatie']){
				jQuery('#Locatie').val(data['Locatie']);
			} 
		}catch(e){}
		try{
			if(data['Opleiding']){
				jQuery('#Opleiding').val(data['Opleiding']);
			}
		}catch(e){}
		try{
			if(data['searchText']){
				jQuery('#searchText').val(data['searchText']);
			}
		}catch(e){}
	
		
	//setups the selectbox lists/keyword field, based on information retrieved from the API service
	//Sets the values as well, if user search param data provided	
	}else if(type=='setlists'){
		
		if(getObjSize(data['search_list_data']) > 0){
		
			var Functiegebied = '';
			var Locatie = '';
			var Opleiding = '';
			
			//set the user chosen data within the lists, if data provided
			try{
				if(data['Functiegebied']){Functiegebied=data['Functiegebied'];}
			}catch(e){}
			try{
				if(data['Locatie']){Locatie=data['Locatie'];} 
			}catch(e){}
			try{
				if(data['Opleiding']){Opleiding=data['Opleiding'];}
			}catch(e){}
			
			//if list data provided...
			if(getObjSize(data['search_list_data']['Functiegebied'])>0){
				//create options string for the list
				strOptions = createSearchOptionStr(data['search_list_data']['Functiegebied']);
				
				jQuery('#Functiegebied')
    				.find('option')
    				.remove()
    				.end()
    				.append(strOptions)
    				.val(Functiegebied);
			}
			//if list data provided...
			if(getObjSize(data['search_list_data']['Locatie'])>0){
    			//create options string for the list
				strOptions = createSearchOptionStr(data['search_list_data']['Locatie']);
				
				jQuery('#Locatie')
    				.find('option')
    				.remove()
    				.end()
    				.append(strOptions)
    				.val(Locatie);
			}
			//if list data provided...
			if(getObjSize(data['search_list_data']['Opleiding'])>0){	
    			//create options string for the list
				strOptions = createSearchOptionStr(data['search_list_data']['Opleiding']);
				
				jQuery('#Opleiding')
    				.find('option')
    				.remove()
    				.end()
    				.append(strOptions)
    				.val(Opleiding);
			}
			
			try{
				//if text input data provided...
				if(data['searchText']){jQuery("input[name=searchText]").val(data['searchText']); }
			}catch(e){}
				
		}

	}
	
}//func




/*
	@Action : Performs the ajax call to PXS service
	@Param  : str_params - concatenated parameter data to pass with the call
*/
function PeopleXS_Request(str_params){

	try{
	
		//ajax request
		jQuery.ajax({
				type: "POST",
				url: "/resources_global/scripts/PeopleXS_soap_client.php",
				data: str_params,
				dataType: "json",
				success: PeopleXS_Response
		}); 

	}catch(e){
		//An error has occurred. Try again later.
		alert('Er is een fout opgetreden. Probeer agqain later.');
	}
	
}//func



/*
	Action : Handles vacancy ajax response
	@Param : response - array data returned from PHP vacancy backend
*/
function PeopleXS_Response(response){

	//check for required action param, so we know how to handle the data returned
	try{
		if(!response['action'] ){ response['action'] = 'error'; }
	}catch(e){ response['action'] = 'error'; }
	
	//process the response based upon the specified action
	switch(response['action']){
		//Used to list both summary vacancy data on main vacancy page,
		//and list full paginated vacancy results on the listings page
		case 'listVacancies':
		
			//hide loader gif
			Loading_Handler(2);
			
			//process summary list for main vacancy page
			if(response['listType'] == 'summary'){
				
				//if any summary results data to display, then show it...
				if(response['data'].length){
					vacancy_results('set',response['data']);
				}else{
					//If no results, add a no results message to the vacancy results box
					//'No jobs available. Please try again later.'
					vacancy_results('setMessage',"Geen vacatures beschikbaar. Probeer het later opnieuw.");
				}
				
			//process full results listings, for listings page
			}else{
				
				if(response['data'].length < 4){
					
					//remove any pahination data
					vacancy_pagination('clear');
					
					//no data to display, show user message
			   		vacancy_results('setMessage',"Geen vacatures beschikbaar. Probeer het later opnieuw.");
					//clear out any saved search values
			   		savedsearchHandler('clear');
			   		//reset the search form
					SearchFormValues('reset');
					
				}else{
					
					//setup search data & params, if provided
					if(!response['search']){
						SearchFormValues('setlists',response);
					}else{
						//setup any user selected search parameters, if provided
						savedsearchHandler('set',response);
					}
				
					//add the vacancy results to the page	
					vacancy_results('set',response['data']);

					//include pagination data for the results
					vacancy_pagination(response);
					
					//setup vacancy type buttons and title
					if(response['vacancy_type']){ vt=response['vacancy_type']; }
					else						{ vt=0; 					   }
					vacancy_type_handler('set',vt);
					
				}//if
				
			}
		break;
		case 'detailVacancy':
			//hide loader gif
			Loading_Handler(2);
			//add vacancy details data to the page
			vacancy_results('set',response['data']);
		break;
		default://error
			vacancy_results('setMessage','Service niet beschikbaar. Probeer het later opnieuw.');
		break;
	}//sw

}//func


//these functions for job upload Cv smarty for NL site
//----- start ---------
_CF_checkThisform = function(_CF_this)
{
    //reset on submit
    _CF_error_exists = false;
    _CF_error_messages = new Array();
    _CF_error_fields = new Object();
    _CF_FirstErrorField = null;


    //display error messages and return success
    if( _CF_error_exists )
    {
        if( _CF_error_messages.length > 0 )
        {
            // show alert() message
            _CF_onErrorAlert(_CF_error_messages);
            // set focus to first form error, if the field supports js focus().
            if( _CF_this[_CF_FirstErrorField].type == "text" )
            { _CF_this[_CF_FirstErrorField].focus(); }

        }
        return false;
    }else {
        // run userdefined onSubmit javascript. 
    	ajaxRequest('setupNLCVSessionTemp', 'thisdoesntexistEVER', '', false);
        return true;
    }

}
//------ end -----------------



/*  VACANCY HELPER FUNCTIONS 
-----------------------------*/

/*
	@Action : creates the option strings to add to search form selectboxes. Used by SearchFormValues handler func
	@Param  : Array of option values and labels
*/
function createSearchOptionStr(optionData){

	var optionStr = '<option value="">Selecteren</option>';
	
	if(optionData){
		for(c=0;c<getObjSize(optionData);c++){
			optionStr+='<option value="'+optionData[c][0]+'">'+optionData[c][1]+'</option>';
		}
	}
	
	return optionStr;
	
}//func

/*
	@Action : Helper func for getting size of objects, as .length doesnt work for objects
	@Param  : Object to get size of
*/
function getObjSize(obj){
	
	var size = 0, key;
		for(key in obj){
			if(obj.hasOwnProperty(key)) size++;
		}
	return size;
	
}//func

/*
	@Action : Adds and removes result data from the results container onpage
	@Param  : action - subaction, 'clear','set','setMessage'
	@Param  : resultsData - provided with 'set' action, contains html data to display in the container
*/
function vacancy_results(action,resultsData){
	
	if(action == 'clear'){
		jQuery('.vacancy_results').attr("innerHTML","");
	}else if(action == 'set' && resultsData){
		jQuery('.vacancy_results').html(resultsData);
	}else if(action == 'setMessage' && resultsData){
		jQuery('.vacancy_results').html("<div class='vacancy_results_message'>"+resultsData+"</div>");
	}
	
}//func


/*
	@Action : Handler function for the search vacancy type buttons
	@Param  : action - subaction, get = makes call with specific vt id, set sets up the vacancy type buttons styling, based on selected vt
	@Param  : vt - chosen vacancy type, used for some subactions
*/
function vacancy_type_handler(action,vt){

	//vacancy button onclick call, sets up for vacancy type API call
	if(action == 'get'){

		//required params for a vt API call
		var params = new Array();
		params['action']='listVacancies';
		params['vacancy_type'] = vt;
		params['search'] = 1;
		
		//clear saved search data
		savedsearchHandler('clear');
		
		//make API call, with specified params
		PeopleXS_Handler(params);
	
	//sets up the vacancy type search titles, modifies vacancy type bttns based on selected vt
	}else if(action == 'set'){
		
		//available vacancy type search titles
		var titles = new Array('','Student\Starter','Midcareer','Professional');
		//set the title based on selected vt
		jQuery('#vacancy_type_title').html(titles[vt]);
		
		//setup the vt buttons, based on selected vt
		for(c=0;c<=3;c++){

			if(c == vt){
				jQuery("#vt_"+c+"_1").css('display', 'inline-block');
				jQuery("#vt_"+c+"_2").hide();
			}else{
				jQuery("#vt_"+c+"_1").hide();
				jQuery("#vt_"+c+"_2").css('display', 'inline-block');
			}
		}//for
		
	}//if type

}//func




/*
	@Action : Handles getting and setting the saved search data using hidden fields on form
	@Param  : action - subaction for this function, 'clear','set','get'
	@Param  : ssdata - search data required for some subactions
*/
function savedsearchHandler(action,ssdata){
	
	//clear the saved search data from the form
	if(action == 'clear'){
		
		jQuery('#savedsearch_VacancyType').val('');
		jQuery('#savedsearch_Functiegebied').val('');
		jQuery('#savedsearch_Locatie').val('');
		jQuery('#savedsearch_Opleiding').val('');
		jQuery('#savedsearch_SearchText').val('');

	//get the saved search data from form hidden fields
	}else if(action == 'get'){
		
		ssdata['vacancy_type']=jQuery('#savedsearch_VacancyType').val();
		ssdata['Functiegebied']=jQuery('#savedsearch_Functiegebied').val();
		ssdata['Locatie']=jQuery('#savedsearch_Locatie').val();
		ssdata['Opleiding']=jQuery('#savedsearch_Opleiding').val();
		ssdata['searchText']=jQuery('#savedsearch_SearchText').val();
		
		//if form values changed, whilst search results being browsed, but submit bttn not pressed,
		//reset the form values to match the search results currently being used, so user knows
		//what search data used to retrieve current search results
		var searchdata = new Array();
		searchdata = new Array();
		searchdata['vacancy_type']=ssdata['vacancy_type'];
		searchdata['Functiegebied']=ssdata['Functiegebied'];
		searchdata['Locatie']=ssdata['Locatie'];
		searchdata['Opleiding']=ssdata['Opleiding'];
		searchdata['searchText']=ssdata['searchText'];
		SearchFormValues('set',searchdata);
		
		return ssdata;
	
	//add search data to the form, used for search results pagination
	}else if(action == 'set'){
		
		if(getObjSize(ssdata)){
			if(ssdata['vacancy_type']) { document.getElementById('savedsearch_VacancyType').value=ssdata['vacancy_type'];    }
			if(ssdata['Functiegebied']){ document.getElementById('savedsearch_Functiegebied').value=ssdata['Functiegebied']; }
			if(ssdata['Locatie'])      { document.getElementById('savedsearch_Locatie').value=ssdata['Locatie'];             }
			if(ssdata['Opleiding'])    { document.getElementById('savedsearch_Opleiding').value=ssdata['Opleiding'];         }
			if(ssdata['searchText'])   { document.getElementById('savedsearch_SearchText').value=ssdata['searchText'];       }
		}

	}
	
}//func




/*
	@Action : Handles vacancy listings pagination
	@Param  : params - Pagination params used to setup onpage pagination data
	@Param  : p - current page required, used by 'get' subaction to set up paginated API call
*/
function vacancy_pagination(params,p){

	//'get' used to gather full list pagination data, 'search' keyword used to specify search results paginated data
	if(params == 'get'|| params == 'search'){
		var VacancyType=jQuery('#savedsearch_VacancyType').val();

		//setup parameters for paginated API call
		var vparams = new Array();
		vparams['action']='listVacancies';
		vparams['page'] = p;
		vparams['vacancy_type'] = VacancyType;
		
		//if search results to be used for pagination, get the saved search form data to use
		if(params == 'search'){ 
			vparams['search']=1;
			vparams = savedsearchHandler('get',vparams);
		}
		
		//make call
		PeopleXS_Handler(vparams);
	
	//clears the pagination data off the listings page
	}else if(params == 'clear'){
		jQuery('#page').attr("innerHTML","");
		jQuery('#total_pages').attr("innerHTML","");
		jQuery('#page_slash').attr("innerHTML","");
		jQuery('#prev_bttn').attr("innerHTML","");
		jQuery('#next_bttn').attr("innerHTML","");
	
	//if pagination elements on screen, setup the onscreen pagination data
	}else if(jQuery('#page') && jQuery('#total_pages')){
		
		var prevb = '';
		var nextb = '';
		var action= 'get';
		if(params['search']==1){ action = 'search'; }
		
		document.getElementById('savedsearch_VacancyType').value= params['vacancy_type'];
		jQuery('#page').html(params['page']);
		jQuery('#total_pages').html(params['total_pages']);
		jQuery('#page_slash').html('/');
		
		if(params['page'] < params['total_pages'] && params['total_pages'] > 1){
			var tmp = 0;
			tmp = parseInt(params['page'])+1;
			nextb = '<a href="#" onclick="vacancy_pagination(\''+action+'\','+(tmp)+')">Volgende</a>';
		}
		if(params['total_pages'] > 1 && params['page'] > 1){
			var tmp = 0;
			tmp = parseInt(params['page'])-1;
			prevb = '<a href="#" onclick="vacancy_pagination(\''+action+'\','+(tmp)+')">Vorige</a>';
		}

		
		if(prevb || nextb){
			jQuery('#prev_bttn').html(prevb);
			jQuery('#next_bttn').html(nextb);
		}
	}
	
}//func


/*
	@Action : concatenates parameter data together for soap ajax call.
*/
function concatParameters(data){
	
	if(data['action'].length){
		
		var str_params = '';
 
		for(var prop in data){
			str_params+=prop+'='+data[prop]+'&'; 
		} 
		str_params = str_params.substr(0,str_params.length-1);
		
		return str_params;

	}//if
	
	
}//func


/*
	@Action : handles the gif loading 
	@Param  : id - show/hide loading box
*/
function Loading_Handler(id){
	
	switch(id){
		case 1://show
		   	jQuery('#vacancy_loader_box').show();
		break;
		default://hide
			jQuery('#vacancy_loader_box').hide();
		break;
	}//sw
	
}//func



//--------------------------------------------------------------------



// sends an ajax request
/*
 * @Action	Send an ajax request, then replace container content and fire callback functions
 * @Param	webpartToRun				The name of the webpart to run (see ajax_handler.php)
 * @Param	ouputContainerElementId		The ID of the element whose content we will replace with the result
 * @Param	URLparams					The GET parameter string
 * @Param	blurOut						true/false - Do we add a loading screen to the output container while we wait for the result
 * @Param	callback					A comma separated string of callback functions (see ajaxCallback())
 */
function ajaxRequest(webpartToRun, ouputContainerElementId, URLparams, blurOut, callback ) {
	// Make sure to define SOMETHING for these vars so we dont get JS errors
	blurOut = ( typeof blurOur != 'boolean' || blurOut == false ) ? true : false;
	callback = ( typeof callback != 'string' ) ? '' : callback;
	
	// Blur the element if needed
	if( blurOut == true ) {
		loadingScreen(jQuery('#' + ouputContainerElementId));
	}
	
	// we have no basket but we're trying to add something to it, we must be using the pop up checkout form
	if (jQuery("#basketWrapper").length == 0 && webpartToRun == 'basket_add') {
		// remove the output container id
		ouputContainerElementId = null;
		// switch the webpart we're running
		webpartToRun = 'checkout_popup';
	}
	
	// URL to request
	var requestURL = '/resources_global/scripts/ajax_handler.php?webpart=' + webpartToRun;
	
	// add the URL to the start of the query string
	URLparams = "current_url=" + window.location.pathname + "&" + URLparams;
	
	// Function to run on success
	var fnSuccess = function(response){
		try {
			jQuery.parseJSON( response );
			isJson = 1;
		} catch( err ) {
			isJson = 0;
		}

		if (ouputContainerElementId == 'basketWrapper' && isJson) {
			if ( response ) {
				response = jQuery.parseJSON( response );
			}
			
			//check for a redirect
			if (response['downloadslink']) {
				window.location = response['downloadslink'];
			} else {
			
				//show tooltip message
				if (response['title'] && response['message']) {
					jQuery('#' + ouputContainerElementId).html( response['html'] );
					
					if ( !bBasketPopup || response['status'] != 200 ) {
						bBasketPopup = true;
						InformationToolTip( response['title'], response['message'],response['arguments']);
					}
				} else if (response['html']) {
					jQuery('#' + ouputContainerElementId).html(response['html']);
				}
			}
		} else if (ouputContainerElementId) {
			jQuery('#' + ouputContainerElementId).html(response);
		} else {
			// no container, so open a modal
			createModal(response, requestURL);
		}
		
		// For other ajax functions this might not always be the case, but for straight replaces
		// such as this it's safe to assume we'll always get something usable back.
		if ( callback.length > 0 ) {
			var arr_callBacks = callback.split(',');
			while ( arr_callBacks.length ) {
				var callback_func = arr_callBacks.shift();
				ajaxCallback(callback_func, response, requestURL, URLparams);
			}
		}
	}
	
	// Request the page from the server
//	alert(requestURL);
//	alert(URLparams);
	jQuery.ajax({
		type: "GET",
		url: requestURL,
		data: URLparams,
		success: fnSuccess
	});
}

//add tooltip message next to info link for document checkout purposes
function InformationToolTip(title,message,arguments){
	arguments = ( typeof( arguments ) != "object" ) ? {} : arguments;
	
	if(title && message){
		
		var overlay_title = title;
		var overlay_message = message;
		
		//ajax call to gather
		
		//overlay the page
		loadingScreen(jQuery('body'));

		//add basket information message
		var div = jQuery("<div id='basket_overlay_message'>").addClass('basket_overlay').html('<a href="javascript:removeLoadingScreen(\'body\');javascript:InformationToolTip();" class="whiteHover"><h2>'+overlay_title+'</h2><p>'+overlay_message+'</p></a>');	
		var body_height = jQuery('body').css('height');
		
		// Track the popup closure with Google Analytics
		if( arguments.track_basket == 1 ) {
			attachBasketPopupEvents();	
		}
		
		jQuery('body').append(div);
		//jQuery('.loadingScreen').height(body_height);

		//center vetically the div, based on user viewable screen area
		jQuery('#basket_overlay_message').css("top", ( jQuery(window).height() - jQuery('#basket_overlay_message').height() ) / 2+jQuery(window).scrollTop() +50+"px");
		jQuery('.loading').css("background","");
		
		// Make the popup scroll with the window
		jQuery( window ).scroll( function() {
			div.stop().animate({
				'top': jQuery( window ).scrollTop() + 300
			}, 1000 );
		});
		
		// Close the popup by pressing ESC
		jQuery( document ).keyup( function( e ) {
			if( e.which == 27 ) {
				removeInformationTooltip();
			}
		});
		
		// Close the popup by clicking the white overlay
		jQuery( 'div.loadingScreen' ).click( function() {
			removeInformationTooltip();
		});
		
		jQuery( window ).trigger( 'scroll' );
	}else{
		jQuery("#basket_overlay_message").remove();
		removeInformationTooltip();
	}
	
}//func


function removeInformationTooltip() {
	removeLoadingScreen('body');
	jQuery("#basket_overlay_message").remove();
}


// run a callback function from an ajax form
function ajaxCallback(param_callback_func, response, requestURL, URLparams) {
	switch (param_callback_func) {
//		case "refreshTrainingFilters" :
//			jQuery_PrepTrainingFilters();
//			break;
		case 'jQuery_RefreshBasketCount':
			jQuery_RefreshBasketCount();
			break;
		case 'jQuery_UpdateBasketContents':
			jQuery_UpdateBasketContents();
			break;
		case 'jQuery_RefreshHighlightedDownloads':
			jQuery_RefreshHighlightedDownloads();
			break;
		case 'jQuery_RemoveBasketLoadingScreen':
			jQuery_RemoveBasketLoadingScreen(URLparams);
			break;
		default:
			break;
	}
}

// draws a modal popup with the specified contents
function createModal(contents, formSubmitURL, titleTag) {
	
	// first find out whether we've received a JSON string
	try {
		jQuery.parseJSON( contents );
		isJson = true;
	} catch( err ) {
		isJson = false;
	}
	
	// remove any open modals
	jQuery("div.modal-wrap").remove();

	// if it's json then evaluate it, otherwise draw a modal
	if (isJson) {
		contents = jQuery.parseJSON( contents );
		
		// process the contents of the response json object
		if (contents) {
			// run any callback functions
			if (contents.parameters.callback) {
				switch(contents.parameters.callback) {
					case "turnOffBasket":
						jQuery_turnOffBasket(contents.parameters.downloadurl);
						break;
				}
			}
			
			// then redirect the user
			if (contents.redirect) {
				window.location = contents.redirect;
			}
		}
	} else {		
		// create a new one
		var modal			= jQuery("<div>").addClass("modal-wrap").html(contents);
		
		// we will get the title for the modal from the 'contents' HTML.
		// we use the H2 tag if nothing else was specified
		if (!titleTag) {
			titleTag = "H2";
		}
		var modaltitle = jQuery(titleTag, modal).html();
		// remove the 'title' tag from the content
		jQuery(titleTag, modal).remove();
			
		// get the button title from the 'contents' HTML
		var submitbuttontitle = jQuery("button", modal).first().text();
		var dialog_buttons = {};
		dialog_buttons[submitbuttontitle] = function(){
			// add a loading screen
			loadingScreen(modal);
			
			// get the string of data
			var dataString = jQuery("div.modal-wrap form").serialize();	
			
			// post it via ajax
			jQuery.ajax({
				type:		"POST",
				url:		formSubmitURL,
				data:		dataString,
				success:	function(response) {
								// create a new modal, containing the response
								createModal(response, formSubmitURL, titleTag);
							}
			});
			
			return false;
		};
		// now remove the original button
		jQuery("button", modal).remove();
			
		// put the modal at the end of the page
		jQuery(modal).appendTo(jQuery("div#framework"));
		
		// draw the modal
		var amodal = jQuery("div.modal-wrap").dialog({
			bgiframe: true,
			autoOpen: true,
			width: 500,
			modal: true,
			title: modaltitle,
			buttons: dialog_buttons
		});
	}
}


// wrapper for linkedList function on checkout page
function jumpToCheckoutStep(stepNo) {

	if (stepNo > 1) {

		if (jQuery('#deliveryMethod').length > 0) // 16:40 05/02/2009 - JH - Some forms don't have this on
		{
			// kick them back to step 1 if no delivery method is specified
			if (jQuery('#deliveryMethod').val() == '') {
				stepNo = 1;
				jQuery('#deliveryMethodError').show();
			} else {
				jQuery('#deliveryMethodError').hide();
			}
		}
	} else {
		jQuery('#deliveryMethodError').hide();
	}

	if (stepNo == 2) {
		// Change the button text back to 'Submit'
		jQuery('#submit').html('Submit');
	}

	// Set the selected button and target (fieldset) classes and reset all others.
	linkedList(	'formSteps'		, 'a'		, 'formStep' + stepNo		, 'selected'	, ''	,
				'checkoutForm'	, '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
	jQuery('#deliveryMethod').val(newValue);

	var postDetailsInputs = jQuery('input', '#postDetails');

	// hide the post-only fields if post is not selected
	switch (newValue)
	{
		case 'Post':
			/* Show post details */
			jQuery('#postDetails').show();
			
			for (i = 0; i < postDetailsInputs.length; i++) {
				jQuery(postDetailsInputs[i]).addClass('required');
			}
		break;
		case 'Website Download':
		case 'Email':
			/* Hide post details */
			for (i = 0; i < postDetailsInputs.length; i++) {
				jQuery(postDetailsInputs[i]).removeClass('required');
				jQuery(postDetailsInputs[i]).removeClass('error');
			}

			jQuery('#postDetails').hide();
		break;
	}

	// move on to step 2
	jumpToCheckoutStep(2);
}

// add a loading screen
function loadingScreen(element) {
	if( jQuery( element ).hasClass( 'no-throbber' ) ) {
		return;
	}
	
	var div = jQuery("<div>").addClass('loadingScreen').text('');	
	// append it
	div.appendTo(element);
	jQuery(div).height(jQuery(element).height());
}

// remove the loading screen(s)
function removeLoadingScreen(element){
	if (element) {
		jQuery(".loadingScreen", element).remove();
	} else {
		// remove all loading screens
		jQuery(".loadingScreen").remove();
	}
}

// handle ajax calls for the 
var last_itid;
function informationTypeHandler(itid){
	
	if(itid > 0 && itid != last_itid){
		ajaxRequest('webpart_page_information_downloads', 'infodownloads_data', 'itid='+itid, true);
		updateInfoTypeLink(itid);
		last_itid = itid;
	}
	
}//func

function updateInfoTypeLink(itid){
	
	//reset all link css classes
	jQuery('[id*="infoType_"]').parent().attr('class','category');
	//set li css
	jQuery('[id="infoType_'+itid+'"]').parent().addClass('category_selected');
	
}//func

/*
 * 	Add click events to links that add to or remove from the basket
 */
function jQuery_PrepBasketLinks() {	
	// if we're using the pop up checkout then we need to remove the tab.
	// we're removing it with JS so that the basket process still works
	// when javascript is turned off
	jQuery('div.popup_checkout').each(function() {
		jQuery('#head-tab-basket-link').closest('li').remove();
		jQuery(this).closest('li').remove();
	});
	
	// check there's still something in the tabbed area, remove it if not
	if (jQuery('ul#header-tabbed-content').children().length == 0) {
		jQuery('div#header-tabbed').remove();
	}
	
	var oHeaderTabs = jQuery( 'div#header-tabbed' );
	
	// Setup links to add documents to the basket
	jQuery( 'a.basket_add' ).live( 'click', function( e ) {
		e.preventDefault();
		var self = jQuery( this );
		
		// Hide the cookie optin message if it exists
		removeNotification( 'cookie-optin' );

		var iInformationId = self.attr( 'href' ).replace( /(.*)(#)([0-9]+)/, '$3' );
		loadingScreen(jQuery(this).closest("li"));
		ajaxRequest( 'basket_add', 'basketWrapper', '&fileId=' + iInformationId, true, 'jQuery_RefreshBasketCount,jQuery_RefreshHighlightedDownloads,jQuery_RemoveBasketLoadingScreen' );
	});
	
	// Setup links to remove documents from the basket
	jQuery( 'a.basket_remove' ).live( 'click', function( e ) {
		e.preventDefault();
		var self = jQuery( this );

		var iInformationId = self.attr( 'href' ).replace( /(.*)(#)([0-9]+)/, '$3' );
		ajaxRequest( 'basket_rem', 'basketWrapper', '&fileId=' + iInformationId, true, 'jQuery_RefreshBasketCount,jQuery_RefreshHighlightedDownloads' );
	});
	
	// Setup the links in the basket to remove items
	jQuery( 'div#basketItems ul li a', oHeaderTabs ).live( 'click', function( e ) {
		e.preventDefault();
		var self = jQuery( this );

		var iInformationId = self.attr( 'href' ).replace( /(.*)(#)([0-9]+)/, '$3' );
		ajaxRequest( 'basket_rem', 'basketWrapper', '&fileId=' + iInformationId, true, 'jQuery_RefreshBasketCount,jQuery_RefreshHighlightedDownloads' );
	});
	
	// Hack for hardcoded legacy links
	jQuery( 'a[href^="javascript:ajaxRequest(\'basket_add\'"]' ).each( function( i, e ) {
		var oSelf = jQuery( this );
		var sHref = oSelf.attr( 'href' );
		
		var iId = sHref.replace( /(.*)(\'&fileId=)([0-9]+)(\')(.*)/, '$3' );
		if( !isNaN( iId ) && iId > 0 ) {
			var bInBasket = jQuery( 'li#head-tab-basket div#basketItems a#info_' + iId ).length > 0;
			var sClass = ( bInBasket ) ? 'basket_remove' : 'basket_add';
			
			oSelf.attr( 'href', '#' + iId )
				.addClass( 'basket' )
				.addClass( sClass );
		}
	});
}

/*
 * 	Will update the header tab for the basket to show the number of items in the basket
 */
function jQuery_RefreshBasketCount() {
	var iDocumentCount = jQuery( 'div#basketItems ul li' ).length;
	var oBasketTab = jQuery( 'ul#header-tabbed-tabs a#head-tab-basket-link' );
	var sBasketText = oBasketTab.text();
	
	var sExpression = /(\()([0-9]?)(\))/;
	
	// If a document count doesn't exist, then add one
	if( !( new RegExp( sExpression ) ).test( sBasketText ) ) {
		sBasketText += ' (0)'
	}
	
	// Correct the document count
	sBasketText = sBasketText.replace( /(\()([0-9]+)(\))/, "$1" + iDocumentCount + "$3" );
	
	// If the document count is at 0, remove it
	sBasketText = sBasketText.replace( ' (0)', '' );
	
	oBasketTab.text( sBasketText );
}

/*
 * 	
 */
function jQuery_RefreshHighlightedDownloads() {
	var sBasketAddClass = 'basket_add';
	var sBasketRemoveClass = 'basket_remove';
	
	// Reset the class on all basket downloads
	jQuery( 'a.basket' ).removeClass( sBasketRemoveClass ).addClass( sBasketAddClass );
	
	// Get a list of items in the basket
	var aBasketItems = jQuery( 'div#basketWrapper div#basketItems li a' );
	aBasketItems.each( function( i, o ) {
		var oItem = jQuery( this );
		var iInformationId = oItem.attr( 'id' ).replace( /(info_)([0-9]+)/, "$2" );
		
		// update the class of any links on the page with the information id at the end of their href
		var oDownload = jQuery( 'a.basket[href$="#' + iInformationId + '"]' );
		oDownload.removeClass( sBasketAddClass ).addClass( sBasketRemoveClass );
	});
	
}

// removes loading screens that were added when adding items to the basket
function jQuery_RemoveBasketLoadingScreen(URLparams) {
	var iInformationId = URLparams.replace( /(.*)(fileId=)([0-9]+)(.*)/, '$3' );
	removeLoadingScreen(jQuery('a[href$="#' + iInformationId + '"]').closest("li"));
}

// switches all basket links on the site to direct downloads (and changes icons in the library)
function jQuery_turnOffBasket(DirectDownloadURL) {
	
	jQuery('a.basket, a.basket_add, a.basket_remove').each(function() {
		// remove the basket classes
		jQuery(this).removeClass('basket').removeClass('basket_add').removeClass('basket_remove');
		// replace the link with one for a direct download
		jQuery(this).attr('href'
						, jQuery(this).attr('href').replace(/(.*)(#)([0-9]+)/, DirectDownloadURL + '$3')
					);
	});
}

// Setup the document library
function jQuery_PrepDocumentLibrary() {
	// Clicking an information category should show all available downloads for that type
	jQuery( 'div#information-library div.types a.type-link' ).click( ShowInformationDownloads );
	
	// Make sure the initial list is equalised
	EqualiseInformationDownloadHeights();
}

// Show a list of document downloads when clicking a catgeory on the document library
function ShowInformationDownloads( e ) {
	var oCategory = jQuery( this );
	
	// Get the information type id
	var iInformationTypeId = oCategory.attr( 'href' ).replace( /(\?tid=)([0-9]+)/, "$2" );
	
	if( iInformationTypeId > 0 ) {
		e.preventDefault();
		
		var oContainer = oCategory.parents( 'div#information-library' ).eq(0);
		var oDownloads = jQuery( 'div.downloads ul#downloads-' + iInformationTypeId, oContainer );
		var oVisible = jQuery( 'div.downloads ul:not( .hidden )', oContainer );
		
		// If the clicked category is already visible then return
		if( !oDownloads.hasClass( 'hidden' ) ) {
			return;
		}
		
		// Highlight the correct category
		jQuery( 'div.types ul li.open', oContainer ).removeClass( 'open' );
		oCategory.parents( 'li' ).eq(0).addClass( 'open' );
		
		// Don't use a transition for IE<9
		if( jQuery.browser.msie && jQuery.browser.version.substr(0,1)<9) {
			oVisible.hide( 0, function() {
				jQuery( this ).addClass( 'hidden' );
				oDownloads.show().removeClass( 'hidden' );
				EqualiseInformationDownloadHeights();
			});
		} else {
			// Fade out the visible downloads
			oVisible.stop().animate({
				'opacity': 0
			}, function() {
				// Hide the old downloads
				jQuery( this ).addClass( 'hidden' );
				
				// Fade in the new downloads
				oDownloads.css( 'opacity', 0 ).removeClass( 'hidden' );
				EqualiseInformationDownloadHeights();
				oDownloads.stop().animate({
					'opacity': 1
				});
			});
		}
	}
}

function EqualiseInformationDownloadHeights() {
	var oDownloadContainer = jQuery( 'div#information-library div.downloads ul:not( .hidden )' ).eq(0);
	
	var aDownloads = jQuery( '> li', oDownloadContainer );
	var iDownloadCount = aDownloads.length;
	
	for( var i = 0; i < iDownloadCount; i += 2 ) {
		if( typeof aDownloads[i+1] == 'undefined' ) {
			break;
		}

		var oLeft = jQuery( 'a', aDownloads[i] );
		var oRight = jQuery( 'a', aDownloads[i+1] );
		
		var iHeight = Math.max( oLeft.height(), oRight.height() );
		oLeft.height( iHeight );
		oRight.height( iHeight );
	}
	
	// Make sure the container fills the height available
	var iContainerHeight = oDownloadContainer.parents( 'div#information-library' ).eq(0).height();
	oDownloadContainer.height( iContainerHeight );
	
}

/*  SCROLLING CUSTOMER QUOTES START
-----------------------------*/
	
	// Set up the customer quotes and begin scrolling through them
	function startScrollingQuotes() {
		jQuery.each( jQuery( 'div.quote_scroller' ), function( iIndex, oQuoteList ) {
			jQuery( this ).width( jQuery( this ).width() );
			
			var oQuoteList = jQuery( 'ul.list_quotes_basic', oQuoteList ).eq(0);
			var oQuotes = jQuery( 'li.quote', oQuoteList );
			
			var iFirstQuoteHeight = oQuotes.eq(0).height();
			var iQuoteWidth = oQuoteList.width();
			
			var iWidth = ( iQuoteWidth + 100 ) * oQuotes.length
			
			// Style the quote list so that it doesn't show overflow
			oQuoteList.css({
				'height': iFirstQuoteHeight + 40,
				'overflow': 'hidden',
				'width': iWidth
			});
			
			// Style the quotes so that they display in a horrizontal list
			oQuotes.removeClass( 'hidden' );
			oQuotes.css({
				'clear': 'none',
				'float': 'left',
				'margin-right': '50px',
				'position': 'relative',
				'width': iQuoteWidth
			});
			
			// Start an interval to scroll the quotes
			var iInterval = 10000;
			fnTimeout = function() {
				initScrollQuotes( oQuoteList, iInterval );
			}
			setInterval( fnTimeout, iInterval );
		})
	}
	
	// Sets up the quote list ready to scroll
	function initScrollQuotes( oQuoteList, iInterval ) {
		var oQuotes = jQuery( 'li.quote', oQuoteList );
		var oFirstQuote = oQuotes.eq(0);
		var oSecondQuote = oQuotes.eq(1);
		
		var iResizeDuration = iInterval / 16;
		var iScrollDelay = 0;

		var iFirstQuoteHeight = oFirstQuote.height();
		var iSecondQuoteHeight = oSecondQuote.height();
		
		// Resize the quote list ready for the next quote
		if( iFirstQuoteHeight < iSecondQuoteHeight ) {
			resizeScrollingQuotesList( oQuoteList, iSecondQuoteHeight, iResizeDuration );
			iScrollDelay = iResizeDuration;
		}
		
		// Scroll the quotes
		var fnScrollQuotes = function() {
			var oList = oQuoteList;
			var iDelay = iResizeDuration;
			scrollQuotes( oQuoteList, iResizeDuration );
		}
		setTimeout( fnScrollQuotes, iScrollDelay );
	}
	
	// Resizes the quote list
	function resizeScrollingQuotesList( oQuoteList, iTo, iResizeDuration ) {
		oQuoteList.animate({
			'height': iTo + 40
		}, iResizeDuration );
	}
	
	// Actually scroll the quote list
	function scrollQuotes( oQuoteList, iResizeDuration ) {
		var oQuotes = jQuery( 'li.quote', oQuoteList );
		var oFirstQuote = oQuotes.eq(0);
		var oSecondQuote = oQuotes.eq(1);
		
		// Get the distance the quotes need to travel to disappear out of view
		var iParentPadding = parseInt( oQuoteList.parent().css( 'padding-left' ).replace( 'px', '' ) ) + parseInt(  oQuoteList.parent().css( 'padding-right' ).replace( 'px', '' ) );
		var iLeft = '-' + ( oFirstQuote.width() + iParentPadding );
		
		fnCallback = function() {
			var oQuoteListSub = oQuoteList;
			var oQuotesSub = oQuotes;
			var iDelay = iResizeDuration;
			
			// Remove the first quote, reset left position and add it to the end of the list
			oFirstQuote.remove();
			oQuotesSub.css( 'left', 0 );
			oFirstQuote.appendTo( oQuoteListSub );
			
			// Shrink the quote list down to the size of the current quote
			resizeScrollingQuotesList( oQuoteListSub, oSecondQuote.height(), iDelay );
		}
		
		// Move the quotes to the left
		oQuotes.animate({
			'left': iLeft
		}, iResizeDuration * 2, fnCallback );
	}

/*  SCROLLING CUSTOMER QUOTES FINISHED
-----------------------------*/

//Function to remove the opacity filter applied to elements by IE
function removeMSIEFilter( oElement ) {
	if( jQuery.browser.msie ) {
		oElement.style.removeAttribute('filter');
	}
}//func

//Return the height of an element plus its top and bottom margin
function getElementHeightPlusMargins( oElement ) {
	oElement = jQuery( oElement );
	var iHeight = oElement.height();

	iHeight += parseFloat( oElement.css( 'margin-top' ).replace( 'px', '' ) );
	iHeight += parseFloat( oElement.css( 'margin-bottom' ).replace( 'px', '' ) );
	
	return iHeight;
}//func


//Function to show/hide login reveal for site header
function loginReveal(){
	
	if(jQuery('#login-slider').css('display') == 'none'){
		jQuery('#login-slider').slideDown();
		jQuery('div#login-tab a').removeClass('arrow-down').addClass('arrow-up');
	}else{
		jQuery('#login-slider').slideUp();
		jQuery('div#login-tab a').removeClass('arrow-up').addClass('arrow-down');
	}
	
}//func


// alias for ajax_process_login('login');
function ajax_login() {
	ajax_process_login('login');
}

// alias for ajax_process_login('logout');
function ajax_logout() {
	ajax_process_login('logout');
}

// process ajax based login
function ajax_process_login(type){
	
	// hide any error messages
	jQuery('form#login-form span.error').hide();
	
	
	if (type == 'logout') {
		ajaxLoginRequest('webpart_page_logout', 'head-tab-login', '', true);
	} else if(type == 'login') {
	
		// start as valid, we switch this if there are errors
		validated = true;
		
		//set loading screen
		loadingScreen(jQuery('#login-contents'));
		
		// gather params
		user = jQuery("input#login-username").val();
		pass = jQuery("input#login-password").val();
		
		// validate
		if (user.length == 0) {
			jQuery('span#login-username-error').show();
			validated = false;
		}
		
		if (pass.length == 0) {
			jQuery('span#login-password-error').show();
			validated = false;
		}
		
		if (validated) {
			URLparams = 'login-username='+user+'&login-password='+pass+'&submit=true';
			ajaxLoginRequest('webpart_site_form_login', 'head-tab-login', URLparams, true);
		} else {
			// we've already displayed the error messages, so lets remove the loading screen
			removeLoadingScreen(jQuery('#login-contents'));
		}
		
	}
	
}


// Site Notification Area
( function( $, window, undefined ) {
	
	var oNotificationArea, iNotificationAreaHeight;
	var sPosition, sCSSProperty;
	var oCookieOptinForm, oCookieOptinCheckbox, oCookieOptinLabel;
	
	$( document ).ready( function() {
		prepNotificationArea();
		prepCookieOptinForm();
	});
	
	function prepNotificationArea() {
		// Get the notification area element
		oNotificationArea = $( 'div#notification-area' );
		if( oNotificationArea.length == 0 ) {
			return;
		}

		// Work out where the area is and how height
		iNotificationAreaHeight = getNotificationAreaHeight();		
		if( oNotificationArea.hasClass( 'bottom' ) ) {
			sPosition = 'bottom';
			sCSSProperty = 'padding-bottom';
		} else {
			sPosition = 'top';
			sCSSProperty = 'padding-top';
		}
		
		// Make space for the area so it doesn't cover content
		jQuery( 'body' ).css( sCSSProperty, iNotificationAreaHeight );
		
		// Move the header tabs if the notification area is at the top of the page
		if( sPosition == 'top' ) {
			var oHeaderTabs = $( '#header-tabbed' );
			oHeaderTabs.css( 'top', parseInt( oHeaderTabs.css( 'top' ) ) + iNotificationAreaHeight );
		}
	}
	
	function removeNotification( sId ) {
		var oNotification = $( '#' + sId, oNotificationArea );
		
		if( oNotification.length == 0 ) {
			return;
		}
		
		var iNotificationHeight = oNotification.outerHeight();
		var bRemoveNotificationBar =  ( oNotification.length == $( 'div.notification-item', oNotificationArea ).length );
		
		oNotification.animate({
			'opacity': 0
		}, 1000, function() {
			var iNotificationAreaHeight = getNotificationAreaHeight() - iNotificationHeight;
			var iEffectTime = 500;
			
			// Animate the bodys padding
			var anim = {}
			anim[ '' + sCSSProperty ] = iNotificationAreaHeight;
			jQuery( 'body' ).animate( anim, iEffectTime );
			
			// Move the header tabs if the notification area is at the top of the page
			if( sPosition == 'top' ) {
				var oHeaderTabs = $( '#header-tabbed' );
				oHeaderTabs.animate({
					'top': iNotificationAreaHeight
				}, iEffectTime );
			}
			
			oNotification.slideUp( iEffectTime, function() {
				oNotification.remove();
				
				if( bRemoveNotificationBar ) {
					oNotificationArea.remove();
				}
			});
		});
	}
	window.removeNotification = removeNotification;
	
	function getNotificationAreaHeight() {
		return ( oNotificationArea.outerHeight() - 2 );
	}
	
	function prepCookieOptinForm() {
		oCookieOptinForm = $( 'form[name="cookie_option"]' );
		oCookieOptinForm.submit( validate_CookieOptinForm );
		
		oCookieOptinCheckbox = $( 'input#cookie-confirmation', oCookieOptinForm ).eq(0);
		oCookieOptinLabel = $( 'label[for="cookie-confirmation"]', oCookieOptinForm ).eq(0);
	}
	
	function validate_CookieOptinForm( e ) {
		if( oCookieOptinCheckbox.attr( 'checked' ) == false ) {
			// Flash the error'ing field
			var sColour = $( 'body' ).css( 'color' );
			oCookieOptinLabel.css( 'color', 'red' ).stop().animate({
				'color': sColour
			}, 2000 );
			
			// Don't submit the form
			e.preventDefault();
		}
	}
	
})( jQuery, window );



/*
 * 
 * This is shamelessly ripped from ajaxRequest();
 * 
 * @Action	Send an ajax login request, then replace container content and fire callback functions
 * @Param	webpartToRun				The name of the webpart to run (see ajax_handler.php)
 * @Param	ouputContainerElementId		The ID of the element whose content we will replace with the result
 * @Param	URLparams					The GET parameter string
 * @Param	blurOut						true/false - Do we add a loading screen to the output container while we wait for the result
 */
function ajaxLoginRequest(webpartToRun, ouputContainerElementId, URLparams, blurOut) {
	
	if (blurOut) {
		loadingScreen(jQuery('#' + ouputContainerElementId));
	}
	
	var requestURL = '/resources_global/scripts/ajax_handler.php?webpart=' + webpartToRun;
	
	// add the URL to the start of the query string
	URLparams = "current_url=" + window.location.pathname + "&" + URLparams;
	
	jQuery.ajax({
		type: "GET",
		url: requestURL,
		data: URLparams,
		success: function(response){
			// eval the json
			response = eval('(' +response+ ')');
		
			// replace the tab contents HTML
			jQuery('#' + ouputContainerElementId).html(response['HTML']);
			// replace the tab label
			jQuery('#' + ouputContainerElementId + '-link').html(response['TabText']);
		}
	});
}




/*  Attach a lightbox to all related links that lead to an image
-----------------------------*/
function jQuery_AttachShowcaseLinkLightboxes() {
	var aElements = jQuery( 'div.showcase_outer a[href$=.jpg],a[href$=.png],a[href$=.gif],a[href*=image_viewer.php]' );
	
	// Dont go any further if fancy box isn't available
	if( typeof aElements.fancybox == "undefined" ) {
		return;
	}
	
	aElements.fancybox({
		'transitionIn': 'fade',
		'transitionOut': 'fade',
		'centerOnScroll': true,
		'titleShow': false,
		'onStart': hideMediaPlayer,
		'onClosed': showMediaPlayer,
		'type': 'image'
	});
	
	aElements.each( function( i, oElement ) {
		oElement = jQuery( oElement );
		var oIcon = jQuery( '<img src="/resources_app/images/lookfeel/popup.png" class="popup-icon" />' );
		
		if( jQuery( oElement ).has( 'img' ) ) {
			var oImage = jQuery( 'img', oElement );
			oIcon.appendTo( oElement );
			
			oIcon.css({
				'left': oImage.position().left + 5,
				'top': oImage.position().top + 5
			});
		}
	});
}


/*  Hide all media players on the page (so they dont overlap modal content)
-----------------------------*/
function hideMediaPlayer() {
	var oPlayer = jQuery( 'object#MediaPlayer' );
	var oParent = oPlayer.parents( 'div' ).eq(0);

	var oPlaceholder = jQuery( '<div class="MediaPlayerPlaceholder"></div>' );

	oPlaceholder.height( oParent.height() );
	oPlaceholder.width( oParent.width() );
	oPlaceholder.appendTo( oParent );
	
	oPlayer.hide();
}

/*  Restore all media players on the page
-----------------------------*/
function showMediaPlayer() {
	var oPlayer = jQuery( 'object#MediaPlayer' );
	var oParent = oPlayer.parents( 'div' ).eq(0);
	
	jQuery( 'div.MediaPlayerPlaceholder', oParent ).remove();
	
	oPlayer.show();
}

// VALIDATE EMAIL ADDRESS
function validate_email_address(obj) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var address = obj.val();
	var validate_result = true;
	if(reg.test(address) == false) {
		validate_result = false;
	}
	return validate_result;
}

// jQuery ACTIONS REQUIRED FOR THE SUBMISSION OF THE 360 PROCUREMENT QUESTIONNAIRE
function questionnaire_360() {
	jQuery('.question_checkbox').click(function() {
		var selected_id = jQuery(this).attr('id').substring(1);
		var arr_id = selected_id.split("-");
		var current_id = arr_id[0];
		var check_q = jQuery('input[name=q'+current_id+']:checked').val();
		var check_t = jQuery('input[name=t'+current_id+']:checked').val();
		
		if(check_q > 0 && check_t > 0) {
			if(!jQuery(this).hasClass('last_answer')) {
				// BOTH Current AND Target VALUES SELECTED, OPEN NEXT SET
				var next_id = '#question' + (eval(current_id) + 1);
				jQuery(next_id).removeClass('hidden');
			} else {
				// SHOW THE NEXT BUTTON
				var step_id = jQuery(this).closest('div').attr('id');
				step_id = step_id.substring(10);
				var button = '#btn-step-' + step_id;
				jQuery(button).removeClass('hidden');
			}
		}
	});

	// WORK OUT THE MAVERICK SPEND ONCE THE REQUIRED FIELDS HAVE BEEN COMPLETED
	jQuery('#final_invoices, #final_purchaseorders').change(function () {
		var final_invoices = jQuery('#final_invoices').val();
		var final_purchaseorders = jQuery('#final_purchaseorders').val();

		if((final_invoices!='' && IsNumeric(final_invoices)) && (final_purchaseorders!='' && IsNumeric(final_purchaseorders))) {
			var final_maverickspend = 0;
			final_maverickspend = final_invoices - final_purchaseorders;
			if(final_maverickspend >= 0) {
				// WORK OUT THE PERCENTAGE OF THE MAVERICK SPEND
				final_maverickspend = parseInt(final_invoices / final_purchaseorders * 100);
				jQuery('#final_maverickspend, #mav_spend').val(final_maverickspend);
			}
		}
	});

	jQuery('.next-step-btn').click(function() {
		var thisStep = jQuery(this).parents('div').attr('id');
		var thisStepNum = thisStep.substring((thisStep.length)-1);
		var nextStepNum = eval(thisStepNum)+1;
		var nextStep = '#q360-step-'+nextStepNum;
		jQuery('#'+thisStep).hide();
		jQuery(nextStep).show();
		// RESET THE SOCIAL NETWORK FLOATER TO THE TOP
		if(jQuery('#social-networks').length > 0) {
			jQuery('#social-networks').css('top', '110px');
		}
		return false;
	});

	jQuery('#submit-btn').click(function() {
		// CHECK REQUIRED FIELDS ARE FILLED IN
		var valid_form = true;
		var numeric_field_error = false;
		jQuery('.is_req').each(function() {
			// CHECK REQUIRED FIELDS FOR VALUE
			if(jQuery(this).val()=='') {
				jQuery(this).addClass('error');
				valid_form = false;
			} else {
				jQuery(this).removeClass('error');
			}
			// CHECK FOR EMAIL ADDRESS
			if(jQuery(this).hasClass('is_email')) {
				if(!validate_email_address(jQuery(this))) {
					jQuery(this).addClass('error');
					valid_form = false;
				}
			}
		});
		jQuery('.numerical').each(function() {
			// CHECK NUMERICAL FIELDS HAVE NUMERICAL VALUES
			if(!IsNumeric(jQuery(this).val())) {
				jQuery(this).addClass('error');
				valid_form = false;
				numeric_field_error = true;
			}
		});
		if(valid_form) {
			// SUBMIT FORM
			jQuery('#form_entry_error').slideUp();
			jQuery('#frm_360_procurement_questionnaire').submit();
			loadingScreen('body');
		} else {
			jQuery('#form_entry_error').slideDown();
			if(numeric_field_error) {
				jQuery('#form_entry_numeric_error').slideDown();
			} else {
				jQuery('#form_entry_numeric_error').hide();
			}
			return false;
		}
		return false;
	});
}

function jQuery_SetMaxWidthFor_content_tab_vertical() {
	// CHECKS THE WIDTH OF ANY IMAGES IN THE UL jQuery_SetMaxWidthFor_content_tab_vertical AND SETS THE 
	// WIDTH OF THE LABEL THAT CONTAINS THEM TO BE EQUAL TO THE MAX SIZED WIDTH IMAGE PLUS 20 PIXELS
	if(jQuery('.content-tab-vertical').length > 0) {
		var max_width = 0;
		var img_width = 0;
		jQuery('.content-tab-vertical li label img').each(function () {
			img_width = jQuery(this).width();
			if(img_width > max_width) max_width = img_width;
		});
		max_width += 20;
		jQuery('.content-tab-vertical li label').each(function () {
			jQuery(this).width(max_width);
		});
	}
}

function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}

function jQuery_ActivateCountdowns() {
	var aCountdowns = jQuery( 'div.countdownContainer' );
	aCountdowns.each( function( i, oElement ) {
		oElement = jQuery( oElement );
		
		var fnCallback = function() {
			jQuery_UpdateCountdown( oElement );
		}
		
		setInterval( fnCallback, 1000 );
	});
}

function jQuery_UpdateCountdown( oElement ) {
	var oSecondsValue = jQuery( 'li.seconds span.value', oElement );
	var oMinutesValue = jQuery( 'li.minutes span.value', oElement );
	var oHoursValue = jQuery( 'li.hours span.value', oElement );
	var oDaysValue = jQuery( 'li.days span.value', oElement );

	var oSecondsSingular = jQuery( 'li.seconds span.singular', oElement );
	var oMinutesSingular = jQuery( 'li.minutes span.singular', oElement );
	var oHoursSingular = jQuery( 'li.hours span.singular', oElement );
	var oDaysSingular = jQuery( 'li.days span.singular', oElement );

	var oSecondsPlural = jQuery( 'li.seconds span.plural', oElement );
	var oMinutesPlural = jQuery( 'li.minutes span.plural', oElement );
	var oHoursPlural = jQuery( 'li.hours span.plural', oElement );
	var oDaysPlural = jQuery( 'li.days span.plural', oElement );

	var iSeconds = oSecondsValue.text();
	var iMinutes = oMinutesValue.text();
	var iHours = oHoursValue.text();
	var iDays = oDaysValue.text();
	
	iSeconds--;
	
	if( iSeconds < 0 && ( iMinutes > 0 || iHours > 0 || iDays > 0 ) ) {
		iSeconds = 59;
		iMinutes--;
	}
	
	if( iMinutes < 0 ) {
		iMinutes = 59;
		iHours--;
	}
	
	if( iHours < 0 ) {
		iHours = 23;
		iDays--;
	}
	
	if( iSeconds == 1 ) {
		oSecondsSingular.show();
		oSecondsPlural.hide();
	} else {
		oSecondsSingular.hide();
		oSecondsPlural.show();
	}
	
	if( iMinutes == 1 ) {
		oMinutesSingular.show();
		oMinutesPlural.hide();
	} else {
		oMinutesSingular.hide();
		oMinutesPlural.show();
	}
	
	if( iHours == 1 ) {
		oHoursSingular.show();
		oHoursPlural.hide();
	} else {
		oHoursSingular.hide();
		oHoursPlural.show();
	}
	
	if( iDays == 1 ) {
		oDaysSingular.show();
		oDaysPlural.hide();
	} else {
		oDaysSingular.hide();
		oDaysPlural.show();
	}

	oSecondsValue.text( Math.max( iSeconds, 0 ) );
	oMinutesValue.text( Math.max( iMinutes, 0 ) );
	oHoursValue.text( Math.max( iHours, 0 ) );
	oDaysValue.text( Math.max( iDays, 0 ) );
}



/*
 *	 Make the social networks tab move when the page scrolls
 */
function jQuery_SocialNetworksHover() {
	var oContainer = jQuery( 'ul#social-networks' ).eq(0);
	
	jQuery( window ).scroll( function( e ) {
		var iTop = parseInt( jQuery( document ).scrollTop() ) + 110;
		oContainer.stop().animate({
			'top': iTop
		}, 2000, 'easeInOutQuart' );
	});
}

/*
 *	Prep the password strength meter. This will update
 *	when a user types on the password change field
 */
function jQuery_PrepPasswordStrengthMeter() {	
	//key event
	jQuery("input#Password_Change").keyup(function(){
		// get the strength of the password
		var strength = getPasswordStrength(this);
		
		// change bar color and size
		jQuery('#password-strength-bar').attr('class', 'strengthlevel_' + strength);
		var bar_size = strength * 25;

		// animate the width of the bar
		jQuery('#password-strength-bar').stop().animate({'width': bar_size + '%'});

		// hide all the spans (they hold the strength text)
		jQuery('#password-strength span').hide();
		
		// show the correct strength text
		if (strength >= 0) {
			jQuery('#password-strength span:eq(' + strength + ')').show();
		} else {
			// strength = -1 indicates that the characters entered were invalid
			jQuery('#password-strength span.invalid').show();
		}
	});
}

// returns the strength of the password in the supplied input box
function getPasswordStrength(param_element_input) {
	// get the string from the input
	var str_password = jQuery(param_element_input).val();
	var strength = 0;
		
	// array containing banned characters
	var invalid_chars = ['[', '^', '\\', '|', '/', '.', ',', '~', '`', '<', '>', '¬', '¦', ']'];
	
	for (var i = 0; i < invalid_chars.length; i++) {
		if (str_password.indexOf(invalid_chars[i]) > -1) {
			// invalid characters, exit
			return -1;
		}
	}
	
	// calculate the strength of it
	if (str_password.length == 0) {
		// no password, so strength is super weak
		return strength;
	} else {
		// you get one point just for typing something, easy!
		strength++;
	}
	
	// add points based on conditions
	if (str_password.match(/[A-Z]/)) {
		// add a point if it contains capitals
		strength++;
	}
	
	if (str_password.match(/[0-9]/)) {
		// add a point if it contains numbers
		strength++;
	}
	
	if (str_password.length >= 8) {
		// add a point if it is 8 characters or more
		strength++;
	}

	
	// return the strength
	return strength;
}

/*
 * 	Extend the native string object to add a trim method
 */
	String.prototype.trim = function( s ) {
		return this.replace( /^\s+|\s+$/, '' );
	}
	

/*
 * 	Scrap the page for useful content to add to the dynamic jumplist
 */
	function jQuery_DynamicJumplist() {
		var sTitle = '';
		var aItems, sText, sHref, oClone, iTypeId;
		
		// Browsers that don't support this should abort now as should IE if not in site mode
		if( typeof window.external == 'undefined' || typeof window.external.msIsSiteMode == 'undefined' || !window.external.msIsSiteMode() ) {
			return;
		}
		
		// Wipe existing dynamic jumplists
		window.external.msSiteModeClearJumpList();
		
		// Define the order of items to search for
		var aPriorities = ( typeof DynamicJumplistPriority == 'object' ) ? DynamicJumplistPriority : new Array();
		
		// Keep searching the DOM until something is found or we run out of things to search for
		while( aPriorities.length > 0 ) {
			iTypeId = aPriorities.shift();
			
			switch( iTypeId ) {
				case 'articles':
					aItems = jQuery( 'div.content div.container > ul.list_links_basic li h3 a' );
					sTitle = jQuery( 'h1', aItems.parents( 'div.container' ).eq(0) ).eq(0).text();;
					break;
					
				case 'vacancies':
					aItems = jQuery( 'table#VacancyTableSort tr td a.VacancyListLink' );
					sTitle = jQuery( 'h3.vacancyTableHeader' ).eq(0).text();
					break;
					
				case 'customers':
					aItems = jQuery( 'ul.customerList div.customerdesc h3' );
					sTitle = jQuery( 'div#customers-products-list > h2' ).eq(0).text();
					break;
					
				case 'next-steps':
					aItems = jQuery( 'div.next-steps ul.list_links_basic li h5 a strong' );
					sTitle = jQuery( 'div.next-steps h2' ).eq(0).text();
					break;
					
				case 'child-pages':
					aItems = jQuery( 'div.submenu ul#navigation_sub li a' );
					sTitle = jQuery( 'div.submenu ul#breadcrumbs li.current a' ).eq(0).text();
					break;
					
				case 'page-anchors':
					var aAnchors = jQuery( 'div.contentcontainer a' );
	
					aAnchors.each( function() {
						var self = jQuery( this );
						if( typeof self.attr( 'name' ) == 'undefined' || self.attr( 'name' ).length == 0 ) {
							return;
						}
	
						var sUrl = '#' + self.attr( 'name' );
						var oContainer = jQuery( "<div></div>" );
						var oItem = jQuery( '<a href="' + sUrl + '">' + self.text() + '</a>' );
						
						oItem.appendTo( oContainer );
						aItems = jQuery( 'a', oContainer );
					});
	
					sTitle = jQuery( 'div.submenu ul#breadcrumbs li.current a' ).eq(0).text();
					break;
				
				//anchor
				
				default:
					// Do nothing
					break;
				
			}
			
			// Stop looking when items are found
			if( typeof aItems == 'object' && aItems.length > 0 ) {
				sTitle = sTitle.trim();
				break;
			}
		}
		
		// Construct the jumplist
		if( typeof aItems == 'object' && aItems.length > 0 ) {
			// Set the list label
			window.external.msSiteModeCreateJumplist( sTitle );
			
			// Add the items (in reverse order)
			for( var i = aItems.length - 1; i >= 0; i-- ) {
				oClone = jQuery( aItems[i] ).clone();
				oClone.children().remove();
				
				sText = oClone.text().trim();
				sHref = ( typeof oClone.attr( 'href' ) == 'undefined' ) ? jQuery( aItems[i] ).parents( 'a[href]' ).eq(0).attr( 'href' ) : oClone.attr( 'href' );
				
				window.external.msSiteModeAddJumpListItem( sText, sHref, '' );
			}
			
			// Apply the jumplist
			window.external.msSiteModeShowJumplist();
		}
	}


	

	
/**
 * jQuery MD5 hash algorithm function
 * 
 * 	<code>
 * 		Calculate the md5 hash of a String 
 * 		String $.md5 ( String str )
 * 	</code>
 * 
 * Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. 
 * MD5 (Message-Digest algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of data. The generated hash is also non-reversable. Data cannot be retrieved from the message digest, the digest uniquely identifies the data.
 * MD5 was developed by Professor Ronald L. Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster implementation than SHA-1.
 * This script is used to process a variable length message into a fixed-length output of 128 bits using the MD5 algorithm. It is fully compatible with UTF-8 encoding. It is very useful when u want to transfer encrypted passwords over the internet. If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag). 
 * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
 * 
 * Example
 * 	Code
 * 		<code>
 * 			$.md5("I'm Persian."); 
 * 		</code>
 * 	Result
 * 		<code>
 * 			"b8c901d0f02223f9761016cfff9d68df"
 * 		</code>
 * 
 * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
 * @link http://www.semnanweb.com/jquery-plugin/md5.html
 * @see http://www.webtoolkit.info/
 * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
 * @param {jQuery} {md5:function(string))
 * @return string
 */

(function($){
	
	var rotateLeft = function(lValue, iShiftBits) {
		return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
	}
	
	var addUnsigned = function(lX, lY) {
		var lX4, lY4, lX8, lY8, lResult;
		lX8 = (lX & 0x80000000);
		lY8 = (lY & 0x80000000);
		lX4 = (lX & 0x40000000);
		lY4 = (lY & 0x40000000);
		lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
		if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
		if (lX4 | lY4) {
			if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
			else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
		} else {
			return (lResult ^ lX8 ^ lY8);
		}
	}
	
	var F = function(x, y, z) {
		return (x & y) | ((~ x) & z);
	}
	
	var G = function(x, y, z) {
		return (x & z) | (y & (~ z));
	}
	
	var H = function(x, y, z) {
		return (x ^ y ^ z);
	}
	
	var I = function(x, y, z) {
		return (y ^ (x | (~ z)));
	}
	
	var FF = function(a, b, c, d, x, s, ac) {
		a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
		return addUnsigned(rotateLeft(a, s), b);
	};
	
	var GG = function(a, b, c, d, x, s, ac) {
		a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
		return addUnsigned(rotateLeft(a, s), b);
	};
	
	var HH = function(a, b, c, d, x, s, ac) {
		a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
		return addUnsigned(rotateLeft(a, s), b);
	};
	
	var II = function(a, b, c, d, x, s, ac) {
		a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
		return addUnsigned(rotateLeft(a, s), b);
	};
	
	var convertToWordArray = function(string) {
		var lWordCount;
		var lMessageLength = string.length;
		var lNumberOfWordsTempOne = lMessageLength + 8;
		var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
		var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
		var lWordArray = Array(lNumberOfWords - 1);
		var lBytePosition = 0;
		var lByteCount = 0;
		while (lByteCount < lMessageLength) {
			lWordCount = (lByteCount - (lByteCount % 4)) / 4;
			lBytePosition = (lByteCount % 4) * 8;
			lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
			lByteCount++;
		}
		lWordCount = (lByteCount - (lByteCount % 4)) / 4;
		lBytePosition = (lByteCount % 4) * 8;
		lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
		lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
		lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
		return lWordArray;
	};
	
	var wordToHex = function(lValue) {
		var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount;
		for (lCount = 0; lCount <= 3; lCount++) {
			lByte = (lValue >>> (lCount * 8)) & 255;
			WordToHexValueTemp = "0" + lByte.toString(16);
			WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
		}
		return WordToHexValue;
	};
	
	var uTF8Encode = function(string) {
		string = string.replace(/\x0d\x0a/g, "\x0a");
		var output = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				output += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				output += String.fromCharCode((c >> 6) | 192);
				output += String.fromCharCode((c & 63) | 128);
			} else {
				output += String.fromCharCode((c >> 12) | 224);
				output += String.fromCharCode(((c >> 6) & 63) | 128);
				output += String.fromCharCode((c & 63) | 128);
			}
		}
		return output;
	};
	
	$.extend({
		md5: function(string) {
			var x = Array();
			var k, AA, BB, CC, DD, a, b, c, d;
			var S11=7, S12=12, S13=17, S14=22;
			var S21=5, S22=9 , S23=14, S24=20;
			var S31=4, S32=11, S33=16, S34=23;
			var S41=6, S42=10, S43=15, S44=21;
			string = uTF8Encode(string);
			x = convertToWordArray(string);
			a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
			for (k = 0; k < x.length; k += 16) {
				AA = a; BB = b; CC = c; DD = d;
				a = FF(a, b, c, d, x[k+0],  S11, 0xD76AA478);
				d = FF(d, a, b, c, x[k+1],  S12, 0xE8C7B756);
				c = FF(c, d, a, b, x[k+2],  S13, 0x242070DB);
				b = FF(b, c, d, a, x[k+3],  S14, 0xC1BDCEEE);
				a = FF(a, b, c, d, x[k+4],  S11, 0xF57C0FAF);
				d = FF(d, a, b, c, x[k+5],  S12, 0x4787C62A);
				c = FF(c, d, a, b, x[k+6],  S13, 0xA8304613);
				b = FF(b, c, d, a, x[k+7],  S14, 0xFD469501);
				a = FF(a, b, c, d, x[k+8],  S11, 0x698098D8);
				d = FF(d, a, b, c, x[k+9],  S12, 0x8B44F7AF);
				c = FF(c, d, a, b, x[k+10], S13, 0xFFFF5BB1);
				b = FF(b, c, d, a, x[k+11], S14, 0x895CD7BE);
				a = FF(a, b, c, d, x[k+12], S11, 0x6B901122);
				d = FF(d, a, b, c, x[k+13], S12, 0xFD987193);
				c = FF(c, d, a, b, x[k+14], S13, 0xA679438E);
				b = FF(b, c, d, a, x[k+15], S14, 0x49B40821);
				a = GG(a, b, c, d, x[k+1],  S21, 0xF61E2562);
				d = GG(d, a, b, c, x[k+6],  S22, 0xC040B340);
				c = GG(c, d, a, b, x[k+11], S23, 0x265E5A51);
				b = GG(b, c, d, a, x[k+0],  S24, 0xE9B6C7AA);
				a = GG(a, b, c, d, x[k+5],  S21, 0xD62F105D);
				d = GG(d, a, b, c, x[k+10], S22, 0x2441453);
				c = GG(c, d, a, b, x[k+15], S23, 0xD8A1E681);
				b = GG(b, c, d, a, x[k+4],  S24, 0xE7D3FBC8);
				a = GG(a, b, c, d, x[k+9],  S21, 0x21E1CDE6);
				d = GG(d, a, b, c, x[k+14], S22, 0xC33707D6);
				c = GG(c, d, a, b, x[k+3],  S23, 0xF4D50D87);
				b = GG(b, c, d, a, x[k+8],  S24, 0x455A14ED);
				a = GG(a, b, c, d, x[k+13], S21, 0xA9E3E905);
				d = GG(d, a, b, c, x[k+2],  S22, 0xFCEFA3F8);
				c = GG(c, d, a, b, x[k+7],  S23, 0x676F02D9);
				b = GG(b, c, d, a, x[k+12], S24, 0x8D2A4C8A);
				a = HH(a, b, c, d, x[k+5],  S31, 0xFFFA3942);
				d = HH(d, a, b, c, x[k+8],  S32, 0x8771F681);
				c = HH(c, d, a, b, x[k+11], S33, 0x6D9D6122);
				b = HH(b, c, d, a, x[k+14], S34, 0xFDE5380C);
				a = HH(a, b, c, d, x[k+1],  S31, 0xA4BEEA44);
				d = HH(d, a, b, c, x[k+4],  S32, 0x4BDECFA9);
				c = HH(c, d, a, b, x[k+7],  S33, 0xF6BB4B60);
				b = HH(b, c, d, a, x[k+10], S34, 0xBEBFBC70);
				a = HH(a, b, c, d, x[k+13], S31, 0x289B7EC6);
				d = HH(d, a, b, c, x[k+0],  S32, 0xEAA127FA);
				c = HH(c, d, a, b, x[k+3],  S33, 0xD4EF3085);
				b = HH(b, c, d, a, x[k+6],  S34, 0x4881D05);
				a = HH(a, b, c, d, x[k+9],  S31, 0xD9D4D039);
				d = HH(d, a, b, c, x[k+12], S32, 0xE6DB99E5);
				c = HH(c, d, a, b, x[k+15], S33, 0x1FA27CF8);
				b = HH(b, c, d, a, x[k+2],  S34, 0xC4AC5665);
				a = II(a, b, c, d, x[k+0],  S41, 0xF4292244);
				d = II(d, a, b, c, x[k+7],  S42, 0x432AFF97);
				c = II(c, d, a, b, x[k+14], S43, 0xAB9423A7);
				b = II(b, c, d, a, x[k+5],  S44, 0xFC93A039);
				a = II(a, b, c, d, x[k+12], S41, 0x655B59C3);
				d = II(d, a, b, c, x[k+3],  S42, 0x8F0CCC92);
				c = II(c, d, a, b, x[k+10], S43, 0xFFEFF47D);
				b = II(b, c, d, a, x[k+1],  S44, 0x85845DD1);
				a = II(a, b, c, d, x[k+8],  S41, 0x6FA87E4F);
				d = II(d, a, b, c, x[k+15], S42, 0xFE2CE6E0);
				c = II(c, d, a, b, x[k+6],  S43, 0xA3014314);
				b = II(b, c, d, a, x[k+13], S44, 0x4E0811A1);
				a = II(a, b, c, d, x[k+4],  S41, 0xF7537E82);
				d = II(d, a, b, c, x[k+11], S42, 0xBD3AF235);
				c = II(c, d, a, b, x[k+2],  S43, 0x2AD7D2BB);
				b = II(b, c, d, a, x[k+9],  S44, 0xEB86D391);
				a = addUnsigned(a, AA);
				b = addUnsigned(b, BB);
				c = addUnsigned(c, CC);
				d = addUnsigned(d, DD);
			}
			var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
			return tempValue.toLowerCase();
		}
	});
})(jQuery);

