$(function() {

	/*
	* Eating Out Tool
	*
	* Various enhancements and client side functionality for the eating out tool
	*/
	
	// Proceede only when on search results page
	if ($('#eating-out-results #search-params-list').length) {
	
		
		/* Initiate plugin to populare all fields for hardcoded discover tool
		 */
		$('form#search_page_53539').eq(0).populateFields();
	

		/* Add "All" to search paramaters if any of the submitted fields are empty
		 */
		// Those with lists
		$('#search-params-list ul').each(function() {
			el = $(this);
			if (!el.text().length) {
				el.text('All');
			}
		});
		// Keywords
		var keywords = $('#search-params-list .keywords p');
		if (!keywords.text().length) {
			keywords.text('No keywords');
		}
	}

	
		
	/*
	* Discover Tool
	*
	* Various enhancements and client side functionality for the discover tool
	*/
	
	/* Add all venues option to 'where'
	 */
	var whereGroup = $('#where-srch');
		whereFields = $('ul input', whereGroup),
		whereMarkup = $('<li><input type="checkbox" name="where-all-venues" id="where-all-venues" /> <label for="where-all-venues">All venues</label></li>').appendTo($('ul', whereGroup)),
		whereField = $('input', whereMarkup);
		
	// Trigger change event for IE
    if ($.browser.msie) {
		whereField.click(function() {
			whereField.blur().focus();
		});
		var label = $("label[for=" + whereField.attr("id") + "]");
		$(label).click(function() {
			whereField.blur().focus();
		});
    }

	// Bind change event to check/uncheck all fields
	whereField.bind('change', function() {
		if ($(this).is(':checked')) {
			whereFields.attr('checked', 'checked');
		}
		else {
			whereFields.removeAttr('checked');
		}
	});
	
	
	// Proceede only when on search results page
	if ($('#discover-tool-results #search-params-list').length) {
	
		
		/* Initiate plugin to populare all fields for hardcoded discover tool
		 */
		$('form#search_page_52434').eq(0).populateFields();
	

		/* Add "All" to search paramaters if any of the submitted fields are empty
		 */
		$('#search-params-list ul').each(function() {
			el = $(this);
			if (!el.html().length) {
				el.text('All');
			}
		});
		

		// Pull in dateJS plugin for the following features
		$.ajaxSetup({ cache: true });
		$.getScript($.variables.datejsPath, function() {
		
			/* Add 'When' paramater to search parameters
			 */
			var when = $(document).getUrlParam('when'),
				whenText = 'All (future)'
			
			switch (when) {
				case 'today' : {
					whenText = 'Today';
				} break;
				
				case 'tomorrow' : {
					whenText = 'Tomorrow';
				} break;
				
				case '7days' : {
					whenText = 'Next 7 days';
				} break;
				
				case '30days' : {
					whenText = 'Next 30 days';
				} break;
				
				case '60days' : {
					whenText = 'Next 60 days';
				} break;
				
				case '3months' : {
					whenText = 'Next 3 months';
				} break;
			};
			
			$('#search-params-list').append($(
				'<div class="when">' +
					'<h3>When:</h3>' +
					'<p>' + whenText + '</p>' +
				'</div>'
			));


			/* Filter discover events by date range provided
			 */
			var today = Date.today();
				
			// Translate when field into date
			if ( (when != 'all') && when) {
				var maxDate = Date.today();
				switch (when) {
					case 'today' : {
						maxDate = Date.today();
					} break;
					
					case 'tomorrow' : {
						maxDate = Date.today().add({ days: 1 });
					} break;
					
					case '7days' : {
						maxDate = Date.today().add({ days: 7 });
					} break;
					
					case '30days' : {
						maxDate = Date.today().add({ days: 30 });
					} break;
					
					case '60days' : {
						maxDate = Date.today().add({ days: 60 });
					} break;
					
					case '3months' : {
						maxDate = Date.today().add({ months: 3 });
					} break;
				};
			}

			resultHelpers = $('.date-helper');
			resultHelpers.each(function() {
				var resultHelper = $(this),
					startDate = Date.parseExact($('.start', resultHelper).text(), 'dMMyyyy')
					endDate = Date.parseExact($('.end', resultHelper).text(), 'dMMyyyy'),
					outsideRange = false;

				// Remove past results
				if (endDate && endDate.isBefore(today)) {
					outsideRange = true;
				}
				else if (startDate && startDate.isBefore(today)) {
					//outsideRange = true;
				}
				
				if ( (when != 'all') && when) {
					// Remove outside of range
					if (endDate && endDate.isAfter(maxDate)) {
						outsideRange = true;
					}
					else if (startDate && startDate.isAfter(maxDate)) {
						//outsideRange = true;
					}
				}
				
				
				// Action result
				if (outsideRange == true) {
					resultHelper.parent('div').remove();
				}
				
				// Add no results message if there are no events left
				if (!$('.event-list .search-result').length) {
					$('.event-list').html('<p class="no-results">Your search for the above criteria returned no events. You may want to search again using less restrictive criteria</p>');
				}
			});
			
			
			/* Paginate results
			 */
			 
			// Function to scroll through event pages
			function eventPageSelectCallback(page_index, resultsWrapper) {
				
				// Wrap pagination for styling nicity
				$.eventPagination.paginationContainer.html($(resultsWrapper).children());
				
				for (var i = page_index * $.eventPagination.itemsPerPage; i < (page_index * $.eventPagination.itemsPerPage) + $.eventPagination.itemsPerPage; i++) {
					$(resultsWrapper).append($('.search-result', $.eventPagination.resultsArray).eq(i).clone());
				}
											
				return false;
			}
			
			// Function to scroll through other pages
			function otherPageSelectCallback(page_index, resultsWrapper) {
				
				// Wrap pagination for styling nicity
				$.otherPagination.paginationContainer.html($(resultsWrapper).children());
				
				for (var i = page_index * $.otherPagination.itemsPerPage; i < (page_index * $.otherPagination.itemsPerPage) + $.otherPagination.itemsPerPage; i++) {
					$(resultsWrapper).append($('.search-result', $.otherPagination.resultsArray).eq(i).clone());
				}
											
				return false;
			}
			
			// Fetch pagination plugin
			$.getScript($.variables.jqueryPagination, function() {
			
				// Initialise pagination plugin for events
				var eventSearchResults = $('.event-list'),
					eventNumResults = $('.search-result', eventSearchResults).length;
					$.eventPagination = {
						resultsArray : eventSearchResults.clone(),
						itemsPerPage : 10,
						paginationContainer : $('<div class="pagination"></div>').insertAfter(eventSearchResults)
					};
				if (eventNumResults > $.eventPagination.itemsPerPage) {
			        eventSearchResults.pagination(eventNumResults, {
						items_per_page : $.eventPagination.itemsPerPage, 
						callback : eventPageSelectCallback,
						next_text : 'Next',
						prev_text : 'Previous',
						next_show_always : false,
						prev_show_always : false
					});
				}
				
				// Initialise pagination plugin for other results
				var otherSearchResults = $('#other-results'),
					otherNumResults = $('.search-result', otherSearchResults).length;
					$.otherPagination = {
						resultsArray : otherSearchResults.clone(),
						itemsPerPage : 2,
						paginationContainer : $('<div class="pagination"></div>').insertAfter(otherSearchResults)
					};
				if (otherNumResults > $.otherPagination.itemsPerPage) {
			        otherSearchResults.pagination(otherNumResults, {
						items_per_page : $.otherPagination.itemsPerPage, 
						callback : otherPageSelectCallback,
						next_text : 'Next',
						prev_text : 'Previous',
						next_show_always : false,
						prev_show_always : false
					});
				}			
			});
			
			/*
			 * Declare that JS is enabled and has loaded
			 */
			$('html')
				.removeClass('js-loading')
				.addClass('js');
			});		
	}
});


 /*
 * Populate hardcoded fields from get paramaters
 *
 * @author: Squiz Australia
 * @example $('form').populateFields();
 *
 */

jQuery.fn.extend({
	populateFields: function(){
	
		var form = this,
			fields = $(':input', form),
			fieldNames = new Array;
		
		// Loop over fields and populate
		$.each(fields, function() {
			var field = $(this),
				fieldName = field.attr('name'),
				fieldType = field.attr("type"),
				fieldValue = $(document).getUrlParam(fieldName);
			
			if (fieldValue != null) {
				// Pre-select/populate
				switch (fieldType) {
					case 'radio' : {
						$('input[value=' + fieldValue + ']').attr('selected', 'selected');
					} break;
					
					case 'checkbox' : {
						field.attr('checked', 'checked');
					} break;
					
					case 'select' :
					case 'select-one' : {
						$('option[value=' + fieldValue + ']').attr('selected', 'selected');
					} break;
					
					case 'text' :
					case 'hidden' : {
						field.val(fieldValue);
					} break;
				};
			}	
		});
		
		return this;
	}
});
