$(document).ready(function() {

	// initialize variables
	var results = $('#pl_results_wrapper');
	var advSearch = $('#pl_search_advanced_box');
	var newSearch = true;
	var offset = 0;
	var advOpen = false;
	
	// hide results container
	results.hide();
	advSearch.hide();
	
	
	// ------------------------------------------------------------------------------------------
	// intercept and process search form submission
	$('#pl_search_form').bind('submit', function(e) {
		
		// stop the default processing of the form
		e.preventDefault();
		
		// if this is a new search, hide the content container and reset the offset
		if (newSearch) {
			results.hide();
			$('#pl_search_offset').attr('value', '0');
			// grab the advanced options open state on a new search
			if (advOpen) {
				$('#pl_search_adv_open').attr('value', '1');
			} else {
				$('#pl_search_adv_open').attr('value', '0');
			}
		}
		
		// set the advOpen field according to the state during a new search
		// the form will always see it as "open" or "closed" until a new search is performed
		// this prevents weird behavior when submitting again when clicking the offset buttons
						
		// use the status indicator to show loading state
		$('#pl_status').addClass('loading');
		
		// fetch the new data and update the results container
		$.ajax({
			url: $('#pl_search_form').attr('action'),
			type: 'POST',
			cache: false,
			data: $('#pl_search_form').serialize(),
			success: function(data){
				results.html(data);
				if (newSearch) results.slideDown();
				$('#pl_status').removeClass('loading');
				newSearch = true;
				getOffsets();
				$(window).trigger('resize');
			}
      	});
	});
	// ------------------------------------------------------------------------------------------
		
	
		
	// ------------------------------------------------------------------------------------------
	// create slide event for expanding / contracting the advanced search box
	$('#pl_search_advanced_toggle').bind('click', function(e){
		e.preventDefault();
		
		if (advOpen) {
			$('#pl_search_toggler').removeClass('open');
			advOpen = false;
		} else {
			$('#pl_search_toggler').addClass('open');
			advOpen = true;
		}
		advSearch.toggle('medium');
	});
	// ------------------------------------------------------------------------------------------
	
	
	// ------------------------------------------------------------------------------------------
	// Function for pagination button clicks
	function getOffsets () {
		$('.page_offset').bind('click', function(e){
				
			// stop the submission from loading a new page
			e.preventDefault();
			
			// set the hidden form field to the new offset
			$('#pl_search_offset').attr('value', $(this).attr('name'));
			
			// this is not a new search
			newSearch = false;
			
			// submit the form with the new offset
			$('#pl_search_form').trigger('submit');
	
		});
	};
	// ------------------------------------------------------------------------------------------

	
});
