	
	// Javascript to operate Opt-in form
	
	$(document).ready(function() {
		
		//if submit button is clicked
		$('#optin-button').click(function () {		
			
			//Get the data from all the fields
			var forename 	= $('input[name=optin-forename]');
			var email 		= $('input[name=optin-email]');
			var city 		= $('input[name=optin-city]');
			
			var valid		= true;
			var emailreg  	= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			
			//Simple validation to make sure user entered something
			//If error found, add hightlight class to the text field
			if (forename.val()=='') {
				forename.addClass('caution');
				valid = false;
			} else forename.removeClass('caution');
			
			if (!email.val().match(emailreg)) {
				email.addClass('caution');
				valid = false;
			} else email.removeClass('caution');
			
			if (!valid) return false;
			
			//organize the data properly
			var data = 'action=optin&forename=' + forename.val() + '&email=' + email.val() + '&city=' + city.val();
			
			//hide the submit button
			$('#optin-button').hide();
			
			//show the loading sign
			$('.loading').show();
			
			//start the ajax
			$.ajax({
				//this is the php file that processes the data and send mail
				url: "/matchmakers/actions.php",
				
				//GET method is used
				type: "GET",
	
				//pass the data			
				data: data,		
				
				//Do not cache the page
				cache: false,
				
				//success
				success: function (html) {
					// if php response is not empty
					if (html!='') {					
						//hide the form
						$('#fieldset').hide();			
						
						//finished loading
						$('.loading').hide();
						
						//show the success message
						$('.results').html(html);
						$('.results').fadeIn('slow');
						
					// if php response is empty/didnt work
					} else alert('Sorry, unexpected error. Please try again later.');				
				}
			});
			
			//cancel the submit button default behaviours
			return false;
		});	
	});	
