
/*
 *	@Script			: agresso_corporate.js
 *	@Description	: General functions for the Agresso website. Require Mootools 1.2. And jQuery.
 */

//////////////////////////////////////////////////////////////////////////////////////
// JQUERY 																			//
//////////////////////////////////////////////////////////////////////////////////////

var tmpTextHolder = '';

// Turn on compatibility mode for jQuery 
jQuery.noConflict(); 

jQuery(document).ready(function() {
	(function($) {	
		// Please put comments here!!
		jQuery_SetupQAList();
		
		// Add half class to leftcol/rightcol contents
		jQuery_SetupContentColumns();
		
		// SET THE HOMEPAGE COLUMNS BASED ON CLASS NAME
		jQuery_HomeColHeightByClass();
		
		// 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();
		
		// 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();
	})(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();
	});
	
	// 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;
		
   	});
   	
   	// populate the product select when the solution select changes
   	jQuery('#filter_site_id').change(function () {
   		   		
   		var site_id = jQuery(this).val();
   		
   		if (site_id == '') {
   			jQuery('#product_select_row').hide();
   			// fire the product select change event
   			jQuery('#filter_product_id').change();
   		} else {
   			jQuery('#product_select_row').show();
   		}
   		
   		jQuery.ajax({
		   type: "POST",
		   url: "/resources_global/library/ajax/ajax_solutionProductSelect.php",
		   data: 'filter_site_id=' + site_id,
		   dataType: "html",
		   success: function(response){
				jQuery('#filter_product_id').html(response);
		   }
		}); 
   	});
   	
   	// refresh the events list when a different product is selected
   	jQuery('#filter_product_id').change(function () {
   		
   		var product_id = jQuery(this).val();
   		var site_id = jQuery('#filter_site_id').val();
   		
   		// if we deselected the solution then deselect the product too
   		if (site_id == "") {
   			product_id = "";
   		}
   		
   		var urlEventTypeId = jQuery.getUrlVar("etid");
   		var eventTypeParam = "";
   		
   		if (urlEventTypeId) {
   			eventTypeParam = '&etid=' + urlEventTypeId;
   		}
   		
   		// add a loading screen
   		loadingScreen(jQuery('#events_list'));
   		
   		jQuery.ajax({
		   type: "POST",
		   url: "/resources_app/library/ajax/ajax_eventsListRefresh.php",
		   data: 'filter_product_id=' + product_id + '&filter_site_id=' + site_id + eventTypeParam,
		   dataType: "html",
		   success: function(response){
				jQuery('#events_list').replaceWith(response);
				// Add hoverover affect for descriptions on an event calendar
				jQuery_SetupHoverEventsCalendar();
		   }
		});
   	});
	
	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();
		
		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----------------------
	
});


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_SetupHoverEventsCalendar()
{
  jQuery("table.calendar div.event_item").hover(function(){
  	jQuery("div.event_title", this).show();
  }, function(){
  	jQuery("div.event_title", this).hide();
  });	
}

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);
			
		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/2);
			jQuery("div.homeabout").height(new_height);
			
			new_height = jQuery("div.homeaddress").height() + (height_diff/2);
			jQuery("div.homeaddress").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;
		
		// 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()
{
	jQuery("div#banner_scroll").scrollable({size: 1, clickable: false}).autoscroll({autoplay: true, interval: 5000}).circular().navigator
	({
		navi: "#banner_tabs"
	,	naviItem: 'a'
	,	activeClass: 'current'
	});
}

function jQuery_PrepTrainingFilters() {
	jQuery("ul#training-filter-side select#filter_site_id").change(function () {
		var URLparams = 'filter_site_id=' + jQuery('#filter_site_id').val()
					+	'&SoftwareSolution_Id=' + jQuery('#SoftwareSolution_Id').val()
					+	'&SoftwareSolutionCategory_Id=' + jQuery('#SoftwareSolutionCategory_Id').val();

		// fire the ajax to refresh the filters
		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;
	});
}

// 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();
	}
}





/* ------------------------------------------------

  U4A Vacancy javascript
  
  Author : Shaun Clifford
  Date   : 12th February 2010

  ------------------------------------------------- */

/*
	@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






/*  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'){
		
		//setup parameters for paginated API call
		var vparams = new Array();
		vparams['action']='listVacancies';
		vparams['page'] = p;
		
		//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'; }
		
		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) {

	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){
			// Replace the containers content
			
			jQuery('#' + ouputContainerElementId).html(response);
			
			// 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.
			var success = true;
			
			if (callback) {
				var arr_callBacks = callback.split(',');
				var callback_func = arr_callBacks[0];
				
				ajaxCallback(callback_func, success, arr_callBacks.slice(1));
			}
		}
	});
}

// run a callback function from an ajax form
function ajaxCallback(param_callback_func, param_bool_success, param_arr_callbacks) {
	switch (param_callback_func) {
		case "refreshTrainingFilters" :
			jQuery_PrepTrainingFilters();
			break;
		default :
			break;
	}
		
	// if there are further callback functions then run them.
	if (param_arr_callbacks[0]) {
		formCallback(param_arr_callbacks[0], param_bool_success, param_arr_callbacks.slice(1));
	}
}


// 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) {
	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();
	}
}