/*	Rnetokil UK COMMON JAVASCRIPT file
		This file underpins much of the functionality on the site, mostly based on jQuery.
		The $(document).ready function will run when the calling page has finished loading.
		This file should be loaded AFTER jQuery and AFTER any jQuery plugins
			
			-v1.0	5 Sept	2011	-	Created by Leyton Jay to underpin Pest Post Sign-up Widget

*/


$(document).ready(function(){

		// Detect and rig carousel
		$("div#carousel").carousel();
	
/////// PEST POST SIGN-UP WIDGET

		// Name not needed when UNsubscibing, hide it
		$("#unsub").click(function()
		{	$("#pestpost_name").hide().css({'marginBottom':'0'});
			$('#send_email').attr('value', 'Unsubscribe');
		});
			
		// Name is needed when subscibing, ensure it's shown
		$("#sub").click(function()
		{	$("#pestpost_name").show().css({'marginBottom':'5px'});	
			$('#send_email').attr('value', 'Subscribe');
		});

		// When SUBSCRIBE is clicked...
		$("#send_email").click(function()
		{	// If email address is invalid...
			if(!validateEmail($("#pestpost_email").val()))
			{	$('#email_error').html('Invalid email address').show();		}
			// If name is empty or the starting condition AND subscribe is checked...
			else if( ( ($("#pestpost_name").val() == '' ) || ( $("#pestpost_name").val() == 'your name')) && ($('input:radio[name=subunsub]:checked').val()=='subscribed') )
			{	$('#email_error').html('Please enter your name').show();	}
			// So if the email is valid AND a name is entered, proceed...
			else
			{	$.ajax({
					type: "POST",
					url: "/static/p/ajax.pestpost_widget.php",
					data: {	"pestpost_email":$("#pestpost_email").val(),
							"action_subunsub":$('input:radio[name=subunsub]:checked').val(),
							"name":$("#pestpost_name").val()	},
					success:
						function(msg)
						{	// Hide the subscription form...
							$("#signup").animate({height:0},300,'swing', function()
							{	$("#signup").hide();
								// If subscribing...
								if($('input:radio[name=subunsub]:checked').val()=='subscribed')
								{	$("#success").show();
									$("#success").html("<p>Thanks for subscribing!</p>")
									.animate({height:37},300,'swing', function(){})
									.css({'padding':'10px 10px 15px'});
								}
								// If unsubscribing...
								else
								{	$("#success").show();
									$("#success").html("<p>You will be unsubscribed shortly.</p>")
									.animate({height:37},300,'swing', function(){})
									.css({'padding':'10px 10px 15px'});
								}
							});
						},
					error: 		
						function(msg) {
							alert("Sorry, there's been a problem. We're unable to complete your request.");
							}
				});
			}
		});
/////// END PEST POST SIGN-UP WIDGET
});

function validateEmail($email)
{	// Is the email address valid? (valid characters, an @ sign and a TLD)
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})+$/;
	if( !emailReg.test( $email ) )
	{	return false;	}
	else
	{	return true;	}
}

