$(document).ready(function(){

	/*
		Displays the filter options on the event listing.
	*/
	var filterOptionsVisible = false;
	
	$.fn.toggleFilterOptions = function()
	{
		if (!filterOptionsVisible)
		{
			$('#event_filter_options').show();
			$('#event_filter_options').animate({
				opacity:1,
				height:'200px',
				border:'1px'
			}, 500, function(){
				filterOptionsVisible = true;
				$('#btn_toggle_filters').html('Hide filters');
			});
		}
		else
		{
			$('#event_filter_options').animate({
				opacity:0,
				height:'0px',
				border:'0px'
			}, 200, function(){
				filterOptionsVisible = false;
				$('#event_filter_options').hide();
				$('#btn_toggle_filters').html('Show filters');
			});
		}
		
		
	};
	
	// -------------------------------------------------------------------------
	/*
		called when typing an event name into the event form.
	*/
	$.fn.searchEventsDropdown = function()
	{
		var postdata = 'keyword='+ $('#name').textfieldVal();
		
		$.ajax(
		{
			type: 'POST',
			url: '/event/search_events_dropdown',
			data: postdata,
			datatype: 'xml',
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#events_dropdown').html(json.successHTML);
					$('#events_dropdown').showDropDown('#name');
				}
			}
		});
	};
	
	// -------------------------------------------------------------------------
	
	$.fn.gotoEventForm = function(eventId)
	{
		window.location = '/event/event_form/'+ eventId;
	}
	
	// -------------------------------------------------------------------------
	
	$.fn.handleEventForm = function(eventId)
	{
		var postdata = 'name='								+ $('#name').textfieldVal();
		postdata 	+= '&address_1='						+ $('#address_1').textfieldVal();
		postdata 	+= '&address_2='						+ $('#address_2').textfieldVal();
		postdata 	+= '&city='								+ $('#city').textfieldVal();
		postdata 	+= '&county_id='						+ $('#county_id').val();
		postdata 	+= '&postcode='							+ $('#postcode').textfieldVal();
		
		postdata 	+= '&latitude='							+ $('#latitude').val();
		postdata 	+= '&longitude='						+ $('#longitude').val();
		
		postdata 	+= '&dog_status='						+ $('#dog_status').val();
		postdata 	+= '&refreshment_status='				+ $('#refreshment_status').val();
		postdata 	+= '&toilet_status='					+ $('#toilet_status').val();
		postdata 	+= '&stall_status='						+ $('#stall_status').val();
		postdata 	+= '&parking_status='					+ $('#parking_status').val();
		postdata 	+= '&parking_desc='						+ $('#parking_desc').textfieldVal();
		
		postdata 	+= '&year_start='						+ $('#year_start').textfieldVal();
		postdata 	+= '&year_end='							+ $('#year_end').textfieldVal();
		postdata 	+= '&regular_desc='						+ $('#regular_desc').textfieldVal();
		
		postdata 	+= '&buyer_entry_fee='					+ $('#buyer_entry_fee').textfieldVal();
		postdata 	+= '&seller_car_fee='					+ $('#seller_car_fee').textfieldVal();
		postdata 	+= '&seller_van_fee='					+ $('#seller_van_fee').textfieldVal();
		
		postdata 	+= '&buyer_start_time='					+ $('#buyer_start_time').textfieldVal();
		postdata 	+= '&seller_start_time='				+ $('#seller_start_time').textfieldVal();
		postdata 	+= '&end_time='							+ $('#end_time').textfieldVal();
		
		if ($('#is_fund_raiser').is(':checked'))
		{
			postdata 	+= '&is_fund_raiser=1';
			postdata 	+= '&fund_raiser_cause='			+ $('#fund_raiser_cause').textfieldVal();
			
			if ($('#fund_raiser_buyer_fee').is(':checked'))
			{
				postdata 	+= '&fund_raiser_buyer_fee=1';
			}
			
			if ($('#fund_raiser_seller_fee').is(':checked'))
			{
				postdata 	+= '&fund_raiser_seller_fee=1';
			}
			
			if ($('#fund_raiser_seller_profit').is(':checked'))
			{
				postdata 	+= '&fund_raiser_seller_profit=1';
			}
			
			if ($('#fund_raiser_refreshment').is(':checked'))
			{
				postdata 	+= '&fund_raiser_refreshment=1';
			}
		}
		else
		{
			postdata 	+= '&is_fund_raiser=0';
		}
		
		postdata 	+= '&website='				+ encodeURIComponent($('#website').textfieldVal());
		postdata 	+= '&additional_info='		+ $('#additional_info').textfieldVal();
		postdata 	+= '&admin_note='			+ $('#admin_note').textfieldVal();
		
		if (eventId != null)
		{
			postdata	+= '&event_id=' + eventId;
		}
		
		postdata += '&revision_id='+ $('#revision_id').val();
		
		if ($('#captcha').length > 0)
		{
			postdata += '&recaptcha_challenge_field='+ $('#recaptcha_challenge_field').val();
			postdata += '&recaptcha_response_field='+ $('#recaptcha_response_field').val();
		}
		
		$.ajax(
		{
			type: 'POST',
			url: '/event/handle_event_form',
			data: postdata,
			datatype: 'xml',
			
			beforesend: function()
			{
				$('.form_error').remove();
			},
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					var errors = $(xml).find('errors');
					var errorCount = $(errors).attr('count');
					
					if (errorCount > 0)
					{
						$('.form_error').html('');
						
						
						$('*').each(function(){
							$(this).removeClass('input_error');
							$(this).removeClass('form_success');
						});
						
						
						errors.children().each(function(){						
							$('#'+ this.tagName).after('<span class="form_error">'+ $(this).text() + '</span>');
						});
					}
					else
					{
						window.location = '/event/'+ json.successHTML;
					}
					
				}
			}
		});
		
	};
	
	// -------------------------------------------------------------------------
	
	$.fn.toggleFundRaiserOptions = function()
	{
		if ($('#is_fund_raiser').is(':checked'))
		{
			$('#fund_raiser_cause').attr('disabled', '');
			$('#fund_raiser_buyer_fee').attr('disabled', '');
			$('#fund_raiser_seller_fee').attr('disabled', '');
			$('#fund_raiser_seller_profit').attr('disabled', '');
			$('#fund_raiser_refreshment').attr('disabled', '');
		}
		else
		{
			$('#fund_raiser_cause').attr('disabled', 'disabled');
			$('#fund_raiser_buyer_fee').attr('disabled', 'disabled');
			$('#fund_raiser_seller_fee').attr('disabled', 'disabled');
			$('#fund_raiser_seller_profit').attr('disabled', 'disabled');
			$('#fund_raiser_refreshment').attr('disabled', 'disabled');
		}
	}
	
	// -------------------------------------------------------------------------
	
	$.fn.getEventPostcode = function()
	{
		var postcode = $('#postcode').textfieldVal();
		
		var latLng = $(this).getLatLngFromPostcode(postcode, function(result, status){
			
			if (status)
			{
				$('#postcode_error').html('Located.');
				$('#postcode_error').addClass('form_success');
				
				$('#latitude').val(result.lat());
				$('#longitude').val(result.lng());
			}
		});
	}
	
	// -------------------------------------------------------------------------
	
	$.fn.voteRevisionAccurate = function(revisionId)
	{
		var postdata = 'revision_id='+ revisionId;
		
		$.ajax(
		{
			type: 'POST',
			url: '/event/vote_revision_accurate',
			data: postdata,
			datatype: 'xml',
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#btn_mark_revision_accurate').html('Accepted.');
					$('#btn_mark_revision_accurate').attr('disabled', 'disabled');
				}
			}
		});
	}
	
	// -------------------------------------------------------------------------
	
	$.fn.setRevisionMaster = function(revisionId)
	{
		var postdata = 'revision_id='+ revisionId;
		
		$.ajax(
		{
			type: 'POST',
			url: '/event/set_revision_master',
			data: postdata,
			datatype: 'xml',
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#btn_set_revision_master').html('Updated.');
					$('#btn_set_revision_master').fadeOut(500);
				}
			}
		});
	}
	
	// -------------------------------------------------------------------------
	
	$.fn.checkTimeFormat = function(elemId)
	{
		var time = $('#' + elemId).val();
		
		time = time.replace('.', ':');
		
		$('#' + elemId).val(time);
		$('#' + elemId + '_error').html('');
		
		if (time.length > 0)
		{
			var regEx = /[0-9]{1,2}:{1}[0-9]{2}/i;
		
			if (!regEx.test(time))
			{
				$('#' + elemId + '_error').html('Incorrect time syntax (00:00)');
			}
			else
			{
				if (time.length == 4)
				{
					// Prepend 0 if length is 'invalid'
					time = '0' + time;
					$('#' + elemId).val(time);
				}
				
				// Check numerical values are within range
				var pieces = time.split(':');
				
				if (pieces[0] > 23 || pieces[0] < 0 || pieces[1] > 59 || pieces[1] < 0)
				{
					$('#' + elemId + '_error').html('Invalid value - out of range.');
				}
			}
		}
	};
	
	// -------------------------------------------------------------------------
	
	$.fn.checkMoneyFormat = function(elemId)
	{
		var money = $('#' + elemId).val();
		
		money = money.replace(':', '.');
		
		$('#' + elemId).val(money);
		$('#' + elemId + '_error').html('');
		
		if (money.length > 0)
		{
			var regEx = /[0-9]{1,2}.{1}[0-9]{2}/i;
		
			if ( !regEx.test(money) )
			{
				$('#' + elemId + '_error').html('Invalid money syntax (00.00)');
			}
		}
	}
	
	// -------------------------------------------------------------------------
	// Calendar edit controls
	// -------------------------------------------------------------------------
	
	$.fn.showEventEditCalendar = function()
	{
		$('#calendar_edit_dialog').fadeIn(200);
		//$('#login_user_name').focus();
	};
	
	$.fn.hideEventEditCalendar = function()
	{
		$('#calendar_edit_dialog').fadeOut(500);
	};
	
	$.fn.handleEventEditCalendar = function()
	{
		
	};
	
	// -------------------------------------------------------------------------
	
	$.fn.eventCalendarSelectDay = function(dayNo)
	{
		if ($('#day_'+ dayNo).hasClass('calendar_selected_day'))
		{
			$('#day_'+ dayNo).removeClass('calendar_selected_day');
		}
		else
		{
			$('#day_'+ dayNo).addClass('calendar_selected_day');
		}
	};
	
	// -------------------------------------------------------------------------
	
	$.fn.handleEventCalendarSelectedDays = function()
	{
		var days = [];
		var dayNoStr = '';
		
		$('.calendar_selected_day').each(function()
		{
			dayNoStr = $(this).attr('id');
			
			days.push(dayNoStr.replace('day_', ''));
		});
		
		var postdata = 'days='+ $(this).arrayToPostdata(days);
		
		$.ajax(
		{
			type: 'POST',
			url: '/event/handle_event_calendar_selected_days',
			data: postdata,
			datatype: 'xml',
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#event_schedule_desc').html(json.successHTML);
				}
			}
		});
	};
	
	// -------------------------------------------------------------------------
	
	$.fn.handleEventWatch = function(eventId)
	{
		var postdata = 'event_id='+ eventId;
		
		$.ajax(
		{
			type: 'POST',
			url: '/event/handle_event_watch',
			data: postdata,
			datatype: 'xml',
			
			beforeSend: function()
			{
				$('#btn_watch_event').attr('disabled', true);
				$('#event_watch_indicator').html($('#icon_loading').html());
			},
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#btn_watch_event').html(json.successHTML);
				}
				
				$('#btn_watch_event').removeAttr('disabled');
				$('#event_watch_indicator').html('');
			}
		});
	};
	
	
	
	// -------------------------------------------------------------------------
	// Listing filters
	// -------------------------------------------------------------------------
	
	/*
	$.fn.filterEvents = function()
	{
		var filter_country = $('#filter_country').val();
		var filter_county = $('#filter_county').val();
		var filter_city = $('#filter_city').val();
		
		if (filter_country == null) filter_country = 0;
		if (filter_county == null) filter_county = 0;
		if (filter_city == null) filter_city = 0;
		
		var postdata = 'country_id='+ filter_country;
		postdata 	+= '&county_id='+ filter_county;
		postdata 	+= '&city_id='+ filter_city;
		
		$.ajax(
		{
			type: 'POST',
			url: '/listing/filter',
			data: postdata,
			datatype: 'xml',
			
			beforeSend: function()
			{
				
			},
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#event_wrapper').html(json.successHTML);
					$('#filter_county').html(json.html1);
					$('#filter_city').html(json.html2);
					
					if (filter_county > 0)
					{
						$('#filter_county').val(filter_county).attr('selected', 'selected');
					}
					
					if (filter_city > 0)
					{
						$('#filter_city').val(filter_city).attr('selected', 'selected');
					}
					
					var filter = $(xml).find('filter');
					var title = $(filter).find('title').text();
					var count = $(filter).find('count').text();
					
					$('#filters').html(count + ' events in '+ title);
					
				}
			}
		});
	}
	*/
	
	$.fn.filterEventsByCountry = function()
	{
		var filter_country = $('#filter_country').val();
		
		if (filter_country == null) filter_country = 0;
		
		var postdata = 'country_id='+ filter_country;
		
		$.ajax(
		{
			type: 'POST',
			url: '/listing/filter',
			data: postdata,
			datatype: 'xml',
			
			beforeSend: function()
			{
				$('#filters').html($('#icon_loading').html());
				$('#event_wrapper').html('');
			},
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#event_wrapper').html(json.successHTML);
					$('#filter_county').html(json.html1);
					$('#filter_city').html('');
					
					var title = $(xml).find('title').text();
					$('#filters').html(title);
				}
			}
		});
	}
	
	
	$.fn.filterEventsByCounty = function()
	{
		var filter_county = $('#filter_county').val();
		
		if (filter_county == null) filter_county = 0;
		
		var postdata = 'county_id='+ filter_county;
		
		$.ajax(
		{
			type: 'POST',
			url: '/listing/filter',
			data: postdata,
			datatype: 'xml',
			
			beforeSend: function()
			{
				$('#filters').html($('#icon_loading').html());
				$('#event_wrapper').html('');
			},
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#event_wrapper').html(json.successHTML);
					$('#filter_city').html(json.html2);
					
					var title = $(xml).find('title').text();
					$('#filters').html(title);
				}
			}
		});
	}
	
	
	$.fn.filterEventsByCity = function()
	{
		var filter_city = $('#filter_city').val();
		
		if (filter_city == null) filter_city = 0;
		
		var postdata = 'city_id='+ filter_city;
		
		$.ajax(
		{
			type: 'POST',
			url: '/listing/filter',
			data: postdata,
			datatype: 'xml',
			
			beforeSend: function()
			{
				$('#filters').html($('#icon_loading').html());
				$('#event_wrapper').html('');
			},
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#event_wrapper').html(json.successHTML);
					
					var title = $(xml).find('title').text();
					$('#filters').html(title);
				}
			}
		});
	}
	
	
	$.fn.searchEvents = function()
	{
		var keyword = $('#event_search').val();
		var postdata = 'keyword='+ keyword;
		
		$.ajax(
		{
			type: 'POST',
			url: '/listing/search',
			data: postdata,
			datatype: 'xml',
			
			beforeSend: function()
			{
				$('#filters').html($('#icon_loading').html());
				$('#event_wrapper').html('');
			},
			
			success: function(xml)
			{
				var json = $(this).parseXMLResponse(xml);
	
				if (json.status == 0)
				{
					alert(json.statusMsg);
				}
				else
				{
					$('#event_wrapper').html(json.successHTML);
					
					var title = $(xml).find('title').text();
					$('#filters').html(title);
				}
			}
		});
		
		
	}
	
	
	
});
