$(function() {
	
	$('img.submit').click(function() {
		doSubmit();
	});
	$('#newUserForm').submit(function(event) {
		doSubmit();
		return false;
	});
	
});


function doSubmit() {
	$('.errorBox').fadeOut().remove();
	$.ajax({
		type: "POST",
		url: "new-user.php",
		data: ({
			submit: true,
			certifiedProfessional: $('#certifiedProfessional:checked').val(),
			firstName: $('#firstName').val(),
			lastName: $('#lastName').val(),
			title: $('#title').val(),
			suffix: $('#suffix').val(),
			firmName: $('#firmName').val(),
			crd: $('#crd').val(),
			designation: $('#designation').val(),
			address1: $('#address1').val(),
			address2: $('#address2').val(),
			city: $('#city').val(),
			state: $('#state').val(),
			zip: $('#zip').val(),
			phone: $('#phone').val(),
			fax: $('#fax').val(),
			email: $('#email').val(),
			userid: $('#userid').val(),
			password1: $('#password1').val(),
			password2: $('#password2').val(),
			interest1: $('#interest1:checked').val(),
			interest2: $('#interest2:checked').val(),
			interest3: $('#interest3:checked').val(),
			interest4: $('#interest4:checked').val(),
			interest5: $('#interest5:checked').val(),
			interest6: $('#interest6:checked').val(),
			emailOptIn: $('#emailOptIn:checked').val()
		}),
		dataType: "json",
		success: function(data) {
			$('#newUserForm input, #newUserForm select').css( {
				'border-color' : '#0055A6'
			});
			$('#newUserForm label').css( {
				'color' : '#333'
			});
			if (data.error == "none") {
				window.location.href = window.location.href + "?success=true&login=1";
			}
			else {
				// highlight the problem fields
				var topError = 100000;
				if (data.highlight) {
					$.each(data.highlight, function(key, val) {
						var ctop = $('label[for="' + key + '"]').offset().top;
						if (ctop < topError) {
							topError = ctop - 8;
						}
						$('#' + key).css( {
							'border-color' : '#c00'
						});
						$('label[for="' + key + '"]').css( {
							'color'	:	'#900'
						});
					});
				}
				// display error messages
				if (data.msg) {
					$.each(data.msg, function(key, val) {
						errorBox($('#' + key), val);
					});
				}
				$.scrollTo(topError, 333);
			}
		}
	});	
}

function errorBox(par, msg) {
	if (par.attr("id") == "certifiedProfessional") {
		offset = 0;
	}
	else if (par.attr("id") == "userid" && $('#errorBox_email').html()) {
		offset = 32;
	}
	else if (par.attr("id") == "fax" && $('#errorBox_phone').html()) {
		offset = 32;
	}
	else {
		offset = 17;
	}
	var ctop = par.parent().offset().top + offset;
	var cleft = $('#content').offset().left + 355;
	$('body').append('<div class="errorBox" id="errorBox_' + par.attr("id") + '">' + msg + '</div>');
	$('div.errorBox:last').css({
		'top' : ctop,
		'left' : cleft
	}).fadeIn();
}
