/*--------------------------------------------------------------------------------

TABLE OF CONTENTS:
------------------
 1.0 - Attacments JS
 2.0 - Updated page JS
	2.1 - Update the page container utilities
 3.0 - Search
 4.0 - Staff search JS
	4.1 - Predictive staff search
	4.2 - Advanced staff search
	4.3 - Update the 'search criteria' box

------------------------------------------------------------------------------*/


/*------------------------------------------------------------------------------
  1.0 - Attacments JS
------------------------------------------------------------------------------*/

/**
 * Sets the centre image and updates title, content and meta date for the image.
 *
 * @param required string post_id The ID of the image to be displayed
 * @param required string security The security nonce required for the AJAX request
 */
function run_attachment_update(post_id, security){
	
	/** Check that the image has an ID. If not, return to prevent the image being reloaded unnecessarily */
	post_id = post_id.split('-');
	if(post_id[1] === undefined){
		return null;
	}
	post_id = post_id[1];
	
	/**
	 * Clear the attachment title, content and centre image, and show the loading block
	 */
	document.getElementById('attachment-body').style.display = 'none';
	document.getElementById('updateable-meta').style.display = 'none';
	document.getElementById('loading-attachment').style.display = 'block';
	document.getElementById('loading-meta').style.display = 'block';
	
	/** Create the data object to parse to the AJAX request */
	var data = {
		action: 'get_image',
		security: security,
		post_id: post_id
	};
	
	/** Run the AJAX request to refresh the image being displayed and the previous/next links and store the results */
	var image_refresh_jqxhr = jQuery.post(MyAjax.ajaxurl, data, function(response){
		title = $_GET('title', response, '&&&', '===');
		permalink = $_GET('permalink', response, '&&&', '===');
		attachment = $_GET('attachment', response, '&&&', '===');
		meta = $_GET('meta', response, '&&&', '===');
		edit_post_link = $_GET('edit_post_link', response, '&&&', '===');
	});
	
	/** Once both AJAX requests are done, run the actual image update */
	image_refresh_jqxhr.done(function(){
		
		/** Update the edit post link */
		update_edit_post_link(edit_post_link);
		
		/** Display the image, title and description, and hide the loading block */
		document.getElementById('attachment-body').innerHTML = attachment;
		document.getElementById('updateable-meta').innerHTML = meta;
		document.getElementById('loading-attachment').style.display = 'none';
		document.getElementById('loading-meta').style.display = 'none';
		document.getElementById('attachment-body').style.display = 'inline';
		document.getElementById('updateable-meta').style.display = 'inline';
		
		/** Update the page title */
		document.title = title+' \u00AB Dyne Drewett';
		
		/** Add the Google +1 button */
		gapi.plusone.go('google-plusone');
		
		/** Update the page history */
		if(window.history.replaceState){ // Check for HTML5 support
			window.history.replaceState(false, title, permalink);
		} else { // Else updats the hash if not HTML5 compatible
			window.location.hash = post_id;
		}
			
	});
}


/*------------------------------------------------------------------------------
  2.0 - Updated page JS
------------------------------------------------------------------------------*/

/**
 * @param required string ajax_array All of the detial required for the AJAX page refresh
 * @param required string security The security nonce required for the AJAX request
 * @param string update_state Whether or not to update the state. If undefinded state will be updated
 */	
function run_load_updated_page(post_id, security, update_state){
	
	/** Hide the page contents */
	document.getElementById('post-content').style.display = 'none';
	
	/** Show the loading icon */
	document.getElementById('loading-page').style.display = 'block';
	
	/** Blur the active element so that the incorrect one is not highlighted after an AJAX back/forward event */
	$('a[href="'+document.activeElement+'"]').blur();
				
	/** Hides the sliding news and TLA widgets and removes the expanded calss tab */
	$('.JS_news_page_tab').find('h2').removeClass('expanded_tab');
	$('.JS_news_page_tab').find('ul').slideUp(600);
	
	/** Create the data object to parse to the AJAX request */	
	post_id = post_id.split('-');
	page = post_id[2];
	post_id = post_id[1];
	var data = {
		action: 'show_updated_page',
		security: security,
		post_id: post_id,
		page: page
	};
	
	/** Get the refreshed page content */
	var content_refresh_jqxhr = jQuery.post(MyAjax.ajaxurl, data, function(response){
		type = $_GET('type', response, '&&&', '===');
		title = $_GET('title', response, '&&&', '===');
		permalink = $_GET('permalink', response, '&&&', '===');
		page_parent_id = $_GET('page_parent_id', response, '&&&', '===');
		refreshed_content = $_GET('page_content', response, '&&&', '===');
		selected_categories = $_GET('selected_categories', response, '&&&', '===');
		edit_post_link = $_GET('edit_post_link', response, '&&&', '===');
		sidebar_testimonial = $_GET('sidebar_testimonial', response, '&&&', '===');
	});
	
	content_refresh_jqxhr.done(function(){
		
		/** Update the edit post link */
		update_edit_post_link(edit_post_link);
		
		/** Update the sidebar testimonial linked to the new service being displayed */
		update_sidebar_testimonial(sidebar_testimonial);
		
		/** Update the active sidebar */
		update_active_service_type(page_parent_id);
		
		/** Update the 'selected' class in the services and our poeple sidebars */
		$("li").removeClass("selected in_category");
		$("li#post-"+post_id).addClass("selected");
		
		/** Update the active news and TLA categories */
		if(type === 'news' || type === 'tla' || type === 'service'){
			var success = highlight_selected_categories(selected_categories);
		}
		
		/** Show the correct sliding_sidebar(news only) */
		show_correct_sliding_sidebar(type);
		
		/** Populate the page and hide the loading block */
		document.getElementById('post-content').innerHTML = refreshed_content;
		document.getElementById('loading-page').style.display = 'none';
		document.getElementById('post-content').style.display = 'block';
		
		/** Update the page title */
		document.title = title+' \u00AB Dyne Drewett';
		
		/** Add the Google +1 button */
		gapi.plusone.go('google-plusone');
		
		/** Update Google Analytics */
		_gaq.push(['_trackPageview', permalink]);
		
		/** Update the page history */
		if(window.history.replaceState){ // Check for HTML5 support
			if(update_state !== false){
				var state_object = {
					post_id: 'post-'+post_id,
					page_parent_id: page_parent_id,
					security: security
				};
				window.history.pushState(state_object, title, permalink);
			}
		} else { // Else updats the hash if not HTML5 compatible
			window.location.hash = post_id;
		}
			
	});
}

/*------------------------------------------------------------------------------
  2.1 - Update the page container utilities
------------------------------------------------------------------------------*/

/**
 * Adds the 'in_category' class to selected ID's
 *
 * @param required string response The categories to mark as 'in_category'
 */
function highlight_selected_categories(categories){
	var categories = categories.split('&');
	
	$('#news-category-list').removeClass('in_category');
	$('#tla-category-list').removeClass('in_category');
	$('#services-sidebar-widget').removeClass('in_category');
	
	for(x in categories){
		$('#'+categories[x]).addClass('in_category');
	}
}

/**
 * Shows the correct sliding sidebar (Used for news and TLA only)
 *
 * @param required string real_type The actual selected type of content, not the dummy type as needed to replace the current content
 */
function show_correct_sliding_sidebar(type){
	
	/** Check to see which sliding menu should be visible in the sidebar (News and TLA only) */
	if(type === 'news' || type === 'tla'){
		if(type === 'tla'){
			$('.JS_sliding_menu').find('#tla-category-list h2').addClass('expanded_tab');
			$('.JS_sliding_menu').find('#tla-category-list ul').slideDown(600);
		} else if(type === 'news'){
			$('.JS_sliding_menu').find('#news-category-list h2').addClass('expanded_tab');
			$('.JS_sliding_menu').find('#news-category-list ul').slideDown(600);
		}
	}
	
	/** Check to see which sliding menu should be visible in the sidebar (Services only) */
	if(type === 'service' && window.history.replaceState){ // Check for HTML5 support
		var current_class = get_service_class(page_parent_id);		
		if(page_parent_id !== ''){
			if(!$('.JS_sliding_menu').find('#'+current_class+' h2').hasClass('expanded_tab')){
				$('.JS_sliding_menu').find('h2').removeClass('expanded_tab');
				$('.JS_sliding_menu').find('ul').slideUp(800);
				$('.JS_sliding_menu').find('#'+current_class+' h2').addClass('expanded_tab');
				$('.JS_sliding_menu').find('#'+current_class+' ul').slideDown(600);
			}
		}
	}
}

/**
 * Updates the active class in the site navigation (Used for services only)
 *
 * @param required string page_parent_id The ID of the tab to mark as active
 */
function update_active_service_type(page_parent_id){
	
	var current_class = get_service_class(page_parent_id);
	$('body').removeClass('ind-services');
	$('body').removeClass('bus-services');
	$('body').removeClass('agri-services');
	$('body').addClass(current_class);
}

/**
 * Get the service class that relates to a page parent ID
 *
 * @param required string page_parent_id The ID of to get the service calss of
 */
function get_service_class(page_parent_id){
	
	if(page_parent_id !== 0){
		var service_class;
		switch(page_parent_id){
			case '69':
				service_class = 'ind-services';
				break;
			case '155':
				service_class = 'bus-services';
				break;
			case '3721':
				service_class = 'agri-services';
				break;
			default :
				service_class = '';
		}
	} else { 
		service_class = '';
	}
	
	return service_class;
}

/**
 * Updatest the 'Edit Post' link in the admin bar at the top of the page
 *
 * @param required string edit_post_link The updated link to display
 */
function update_edit_post_link(edit_post_link){
	
	$('#wp-admin-bar-edit').html(edit_post_link);
}

/**
 * Updates the testimonial in the sidebar when a user is viewing a service
 *
 * @param required string sidebar_testimonial The updated testimonial to display
 * @param required string security The security nonce required for the AJAX request
 */
function update_sidebar_testimonial(sidebar_testimonial){
	
	$('#testimonial-linked-to-service-content').html(sidebar_testimonial);
}

/*------------------------------------------------------------------------------
  3.0 - Search/Index update
------------------------------------------------------------------------------*/

/**
 * Searches for posts that match the criteria defined by the user on the search page
 *
 * @param required string term The term being searched by the user
 * @param required string security The security nonce required for the AJAX request
 * @param required string security The page number to show results for
 */
function update_index(term, security, page_num){
	
	/** Set the variables */
	var post_type = $('#post-type-filter').val();
	var results;
	
	/** Show the loading icon and hide the original search results */
	document.getElementById('loading').style.display = 'block';
	$('#post-index').html('');
	
	var data = {
		action: 'get_filtered_search_results',
		security: security,
		term: term,
		page_num: page_num,
		post_type: post_type
	};
	
	/** Get the search results */
	var search_refresh_jqxhr = jQuery.post(MyAjax.ajaxurl, data, function(response){
		results = response;
	});
	
	search_refresh_jqxhr.done(function(){
		
		/** Repopulate the search area */
		$('#post-index').html(results);
		
		/** Hide the loading icon */
		document.getElementById('loading').style.display = 'none';
		
	});
}


/*------------------------------------------------------------------------------
  4.0 - Staff search JS
------------------------------------------------------------------------------*/

/*------------------------------------------------------------------------------
  4.1 - Predictive staff search
------------------------------------------------------------------------------*/
/**
 * Searches for matching members of staff and places results under the Search Our People box
 *
 * @param required string term The term being searched by the user
 * @param required string security The security nonce required for the AJAX request
 */
function initiate_predictive_staff_search(term, security){
	
	/** Hide the 'predictive-results' and check that 'value' is not empty */
	document.getElementById('predictive-results').style.display = 'none';
	if(term === ''){
		return;
	}
	
	/** Show the loading icon */
	document.getElementById('loading-sidebar').style.display = 'block';
	
	/** Create the data object to parse to the AJAX request */
	var data = {
		action: 'get_predictive_results',
		security: security,
		term: term,		
	};

	/** Create the data object to parse to the AJAX request */	
	jQuery.post(MyAjax.ajaxurl, data, function(response){
		document.getElementById('predictive-results').innerHTML = response;
		document.getElementById('loading-sidebar').style.display = 'none';
		document.getElementById('predictive-results').style.display = 'inline';
	});
};


/*------------------------------------------------------------------------------
  4.2 - Advanced staff search
------------------------------------------------------------------------------*/
/**
 * Searches for matching members of staff and places results under the Search Our People box
 *
 * @param string letter The surname letter being search by the user ('undefined' if not currently being searched)
 * @param required string security The security nonce required for the AJAX request
 * @param string name_search_type The type of search being carried out
 */
function initiate_staff_search(letter, security, name_search_type){
	
	/** Get the dropdown contents */
	if(letter === undefined && letter !== 'clear') { letter = $_GET('staff_search'); }
	var job_role = document.getElementById('job-roles').value;
	var office = document.getElementById('offices').value;
	var ind_service = document.getElementById('ind-services').value;
	var bus_service = document.getElementById('bus-services').value;
	var agri_service = document.getElementById('agri-services').value;
	var orderby = document.getElementById('results-order').value;
	
	/** Remove the 'selected' class from any letters for the surname search */
	$('.individual-letter-box').removeClass('selected-letter');		
	
	/** Checks to see if a letter is selected and populates the removal box if it is */
	if(letter !== undefined && letter !== 'clear'){
		$('#clear-letter-search').html('<a id="clear" href="#?staff_search=clear"><p>Remove &#039;'+letter+'&#039; from search</p></a>');
		document.getElementById('clear-letter-search').style.display = 'block';
	} else {
		document.getElementById('clear-letter-search').style.display = 'none';
	}
	
	/** Hides the search critera box */
	document.getElementById('search-criteria').style.display = 'none';
	
	/** Check to see if all dropdowns are set to default, and exit if they are */
	if(job_role === '-1' && office === '-1' && ind_service === '-1' && bus_service === '-1' && agri_service === '-1' && (letter === undefined || letter === 'clear')){
		$('#staff-search-results').html('<p>Please select from one of the dropdowns or click a letter above to search Our People.</p>');
		return;
	}
			
	/** Hide the page content */
	jQuery('#post-title').slideUp(800);
	jQuery('#post-content').slideUp(800);
	jQuery('#line-seperator').slideUp(400);
	$('#search-our-people h3').replaceWith(function(){
		return '<h2>' + $(this).contents().text() + '</h2>';
	});
	$('#search-our-people div.clear').html('');
	
	/** Show the loading icons */
	document.getElementById('staff-search-results').style.display = 'none';
	document.getElementById('loading').style.display = 'block';
	document.getElementById('loading-search-criteria').style.display = 'block';
	
	/** Create the data object to parse to the AJAX request */
	var data = {
		action: 'get_staff_search_results',
		security: security,
		letter: letter,
		name_search_type: name_search_type,
		job_role: job_role,
		office: office,
		ind_service: ind_service,
		bus_service: bus_service,
		agri_service: agri_service,
		orderby: orderby
	};
	
	/** Get the search results */
	var results_refresh_jqxhr = jQuery.post(MyAjax.ajaxurl, data, function(response){
		results = response;
	});
	
	/** Get the 'Search criteria' */
	data.action = 'update_search_parameters';
	var search_criteria_refresh_jqxhr = jQuery.post(MyAjax.ajaxurl, data, function(response){
		search_criteria = response;
	});
	
	results_refresh_jqxhr.done(function(){
		search_criteria_refresh_jqxhr.done(function(){
			
			/** Display the results and hide the loading block */
			document.getElementById('staff-search-results').innerHTML = results;
			document.getElementById('loading').style.display = 'none';
			document.getElementById('staff-search-results').style.display = 'inline';
			
			/** Display the search criteria and hide the loading block */
			document.getElementById('search-criteria').innerHTML = search_criteria;
			document.getElementById('loading-search-criteria').style.display = 'none';
			document.getElementById('search-criteria').style.display = 'block';
			
			/** Add the 'active-dropdown-option' class to any dropdown that is active in the staff filter search */
			if(job_role !== '-1') $('#term-'+job_role).addClass('active-dropdown-option');
			if(office !== '-1') $('#term-'+office).addClass('active-dropdown-option');
			if(ind_service !== '-1') $('#term-'+ind_service).addClass('active-dropdown-option');
			if(bus_service !== '-1') $('#term-'+bus_service).addClass('active-dropdown-option');
			if(agri_service !== '-1') $('#term-'+agri_service).addClass('active-dropdown-option');
			
			/** Removes focus from all of the inputs */
			$('#job-roles').blur();
			$('#offices').blur();
			$('#ind-services').blur();
			$('#bus-services').blur();
			$('#agri-services').blur();
			$('#results-order').blur();
			
			/** Add the 'selected' class to the selected letter */
			$('.individual-letter-box').removeClass('selected-letter');
			$('#'+letter).addClass('selected-letter');
		
		});
	});
};


/*------------------------------------------------------------------------------
  4.3 - Update the 'search criteria' box
------------------------------------------------------------------------------*/
/**
 * Updats the 'Search criteria' box on the Our People page when a user makes a search
 *
 * @param required object data The current search critera
 */
function update_search_parameters(data){
	data.action = 'update_search_parameters';
	
	jQuery.post(MyAjax.ajaxurl, data, function(response){
		document.getElementById('search-criteria').innerHTML = response;
		document.getElementById('loading-search-criteria').style.display = 'none';
		document.getElementById('search-criteria').style.display = 'block';
	});
}
