function checkMail(mail) {
   var emailFilter=/^.+@.+\.(.{2,3}|info|museum|museum|aero|asia|coop|jobs|mobi|name|travel|arpa)$/;
   var err = null;
   if (!(emailFilter.test(mail))) {
      return false;
   }
   /* var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;*/
   var illegalChars= /[\~\`\!\#\$\%\^\&\*\(\)\=\+\{\}\|\:\;\"\'\\\/\?\,\|\[\]]/;
   if (mail.match(illegalChars)) {
      return false;
   }
   return true;
}


(function($){
	$(document).ready(function(){
		var options = {
			cookie_life: 1000*60*60*24*30,	/* 1 month */
			timeout: 10000	/* ms */
		};

		
		$(".mgn-subscribe input[type='text']").each(function(){
			$(this).attr("value", $(this).attr("rel"));		
			$(this).focus(function(){				
				var val = ($(this).attr("value") == $(this).attr("rel")) ? '' : $(this).attr("value");
				$(this).attr("value", val);
			}).blur(function(){
				var val = ($(this).attr("value") == '') ? $(this).attr("rel") : $(this).attr("value");
				$(this).attr("value", val);
			});
		
		});
		
		
		function closePopupNewsletter(){
			var now = new Date();
			var expires_date = new Date( now.getTime() + options.cookie_life );							
			document.cookie = 'MGPopupClosed=yes;expires=' + expires_date.toGMTString()+';path=/';
			$("#MG-placeholder").fadeOut('fast');	
		};
		
		
		$("#subscribe").submit(function(event){		
			event.preventDefault();
			
			switch ($("#subscribe input[name='firstname']").attr("value")){
				case '':				
					jAlert('Please enter your name');				
					return false;
					break;
				case $("#subscribe input[name='firstname']").attr("rel"):				
					jAlert('Please enter your name');
					return false;
					break;
				default:
					break;			
			};
			
			
			if (!checkMail($("#subscribe input[name='email']").attr("value"))){
				jAlert('Email not valid');
				return false;
			};
			
			var form = this;	
			
			
			closePopupNewsletter();
			
			$.ajax({
				type: "POST",
				url: "post.php",
				data: $(form).serialize(),
				success: function(msg){
					$(".mgn-subscribe").replaceWith(msg);
					jAlert(msg);				
				}
			});		
			
		});
		
		

		$('#MG-placeholder').each(function(){
			var show = true;
			var cks = document.cookie.split( ';' );
			for(i=0;i<cks.length;i++){
				parts = cks[i].split('=');
				if( parts[0].indexOf('MGPopupClosed') != -1 ) show = false;
			};
			
			if (show === true){
				setTimeout(
					function(){
						$('#MG-placeholder').fadeIn('slow', function(){
							$("#mg_embed_close").click(function(event){
								closePopupNewsletter();
								event.preventDefault();
							});
						});
					},
					options.timeout);
			};
		});
	});
})(jQuery);
