$().ready(function()  {
	$("#mailing-list-subscribe-form").validate({
		rules: {
			'mailing-list-email': {
				email: true,
				required: true,
			},
		},
		messages: { 
			'mailing-list-email': {
				email: 'Please enter a valid email address.',
				required: 'Please enter an email address.'
			},
		},
		errorPlacement: function(error, element)  {
			element.parent().next().html('');
			error.appendTo( element.parent().next() );
		},
		submitHandler: componentMailingListSubscribe
	});
});

/**
 * shakenandstirred - mailing-list.js - componentMailingList()
 * 
 * 
 * @author					Brent McDowell brent@nuguru.com
 * @author					Daniel Mullin daniel@nuguru.com
 * @version					1.0
 * @todo					UAT
 * 
 * @param		string		username
 * 
 * @return		bool
 * 
 */
function componentMailingListSubscribe() {
	var email = $('#mailing-list-email').val();
	var emailExists = userByEmail(email);
	$.ajaxSetup({ async: true });
	if(emailExists) { 
		$('#modal-login').jqm({modal : true, overlay: 90}).jqmShow();
		return false;
	} else {
		if(componentMailingListUserSubscribe(email)) {
			$('#mailing-list-subscribe').hide();
			$('#mailing-list-subscribed').show();		
		} else {
			// an error occurred
		}
		return false;
	}
}

function componentMailingListUserSubscribe(email, firstName, lastName)
{
	//firstName
	if(typeof firstName == 'undefined') {
		firstName = '';
	}	
	
	//lastName
	if(typeof lastName == 'undefined') {
		lastName = '';
	}
	jsonUrl = 'http://' + document.location.hostname + '/api/users/mailingListSubscribe?email=' + email + '&firstName=' + firstName + '&lastName=' + lastName;
	return $.ajax({type: "GET", url: jsonUrl, async: false}).responseText;	// can be asynchronous
}


/**
 * shakenandstirred - mailing-list.js - userByEmail()
 * 
 * Check if the username is already in use.
 * 
 * @author					Brent McDowell brent@nuguru.com
 * @version					0.1
 * @todo					UAT
 * 
 * @param		string		username
 * 
 * @return		bool
 * 
 */
function userByEmail(email)
{
	$.ajaxSetup({ async: false });
	$.getJSON('http://' + document.location.hostname + '/api/users/byEmail?email=' + email + '&select[]=user_id', function(data) 
	{
		if (data[0]['userId'] && data[0]['userId'] > 0)
		{
			result = true;
		}
		else
		{
			result = false;
		}	
	});
	return result;
}


