/*
 * newsletter (based on contactable) 1.0 - jQuery Ajax contact form with validation
 *
 * Copyright (c) 2009 Philip Beel (http://www.theodin.co.uk/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Revision: $Id: jquery.contactable.js 2009-08-24 $
 *
 */
 
//extend the plugin
(function($){
	//define the new for the plugin ans how to call it	
	$.fn.newsletter = function(options) {
		//set default options  
		var defaults = {
			name: 'Name',
			email: 'Email',
			message : 'Message',
			subject : 'A Message',
			recievedMsg : 'Thankyou for your message',
			notRecievedMsg : 'Sorry but your message could not be sent, try again later',
			disclaimer: 'Please feel free to get in touch, we value your feedback'
		};

		//call in the default otions
		var options = $.extend(defaults, options);
		
		//make sure we check for the default name
		jQuery.validator.addMethod("checkName", function(value, element) {
			if($('#contactname').val() == 'First name*') {
				return false;
			}
			return true;
		}, "Please enter your first name"); 

		//make sure we check for the default message
		jQuery.validator.addMethod("checkSurname", function(value, element) {
			if($('#contactsurname').val() == 'Last name*') {
				return false;
			}
			return true; 
		}, "Please enter your last name"); 
		
		//make sure we check for the default email
		jQuery.validator.addMethod("checkEmail", function(value, element) {
			if($('#contactemail').val() == 'Email*') {
				return false;
			}
			return true;
		}, "Please enter a valid E-mail address"); 
		
		//act upon the element that is passed into the design    
		return this.each(function(options) {
					
			//validate the form 
			var validator =  $("#contactForm").validate({
				//set the rules for the fild names
				rules: {
					contactname: {
						required: true,
						minlength: 2,
						checkName: true
					},
					contactsurname: {
						required: true,
						minlength: 2,
						checkSurname: true
					},
					contactemail: {
						required: true,
						emailEN: true,
						checkEmail: true,
						minlength: 2
					}
				},
				//set messages to appear inline
				messages: {}, 
				submitHandler: function() {
					$('.holdernewsletterform').hide();
					$('#loading').show();
					$.get('mail.php',{formtypenewsletter: $('#formtypenewsletter').val(), subject:defaults.subject, name:$('#contactname').val(),surname:$('#contactsurname').val(), email:$('#contactemail').val(), country: $('#contactcountry').val()},
					function(data){
						$('#loading').css({display:'none'}); 
						if( data == 'success') {
							$('#callback').show().append(defaults.recievedMsg);
						} else {
							$('#callback').show().append(defaults.notRecievedMsg);
						}
					});		
				}
			});
			//reset the form
			$('#clearbtn').click(function() {
				validator.resetForm();
			});
		});
	};
	//end the plugin call 
})(jQuery);

