// jQuery mailing list actions
$(document).ready(function(){
	
	// set form height
	$('#mailing_list').css({ minHeight: '30px' });
	
	// bind ajaxForm to FreeForm
	$('#mailing_list').ajaxForm( {
		target: '#form_response',
		beforeSubmit: function() {
			
			// simple form validatation
			$('#mailing_list input[type="text"]').css({ backgroundColor:'#fff' });
			
			var n = $('input#name');
			var e = $('input#email');
			
			// if fields are empty
			if (n.val() == '' && e.val() == '') {
				n.css({ backgroundColor:'#FDF3F3' });
				e.css({ backgroundColor:'#FDF3F3' });
				n.focus();
				return false;
			} else if (n.val() == '') {
				n.css({ backgroundColor:'#FDF3F3' });
				n.focus();
				return false;
			} else if (e.val() == '') {
				e.css({ backgroundColor:'#FDF3F3' });
				e.focus();
				return false;
			}
		
			// check email address
			str = e.val();
			var s = $.trim(str);
			var at = "@";
			var dot = ".";
			var lat = s.indexOf(at);
			var lstr = s.length;
			var ldot = s.indexOf(dot);

			if (s.indexOf(at)==-1 ||
				(s.indexOf(at)==-1 || s.indexOf(at)==0 || s.indexOf(at)==lstr) ||
				(s.indexOf(dot)==-1 || s.indexOf(dot)==0 || s.indexOf(dot)==lstr) ||
				(s.indexOf(at,(lat+1))!=-1) ||
				(s.substring(lat-1,lat)==dot || s.substring(lat+1,lat+2)==dot) ||
				(s.indexOf(dot,(lat+2))==-1) ||
				(s.indexOf(" ")!=-1)) {
	
				e.css({ backgroundColor:'#FDF3F3' });
				e.focus();
				return false;
			}
			
			// send form
			$('#mailing_list fieldset').hide();
			$('#form_status').html('<img class="wait" src="/themes/site_themes/default/images/wait.gif" width="20" height="20" alt="" />');
		},
		success:function(rtn) {
			if(rtn == 'success') {
				$('#mailing_list').css({ height: 'auto' });
				$('#form_status').html('<p>Thanks for signing up! You’ll receive a confirmation email shortly.</p>');
			} else {
				$('#mailing_list fieldset').show();
				$('#form_status').html( '<ul>' + $('#form_response ul').html() + '</ul>');
			}
		}
	});
});