$(document).ready(function() {
	
	var name;
	var email;
	
	/**********
	Deal with the text message help text
	**********/
	
	var textInfo = $('#textInfo');
	var textHelp = $('#textHelp');
	
	$(textInfo).hide();
	
	$(textHelp).bind('mouseenter mouseleave focusin focusout', function () {
		$(textInfo).stop(true, true).slideToggle('fast');
	});
	
	$('body').bind('mouseover', function(e) {
		if ($(this).hasClass('cLink')) {
			alert('link!');
		}
	});
	
	/**********
	Deal with the text message options
	**********/
	
	var text = $('#text');
	var textOptions = $('#textOptions');
	
	function options() {	
		if ($(text).is(':checked')) {
			$(textOptions).show('');
		}
		else {
			$(textOptions).hide();
		}
	}
	
	options();
	
	$(text).change(function() {
		if ($(this).is(':checked')) {
			$(textOptions).slideDown('slow');
		}
		else {
			$(textOptions).slideUp('slow');
		}
	});
	
	/**********
	Deal with replaced checkboxes
	**********/
	
	// Make CROWNWeb email updates checked when page is refreshed
	$('#ealert').attr('checked', 'checked').siblings('a').addClass('checked')
	
	// If user clicks the checkbox
	$('.checkbox a').bind('click', function() {
		
		// The checkbox element
		var input = $(this).siblings('input');
		
		// If it is already checked
		if ($(input).is(':checked')) {
			$(this).removeClass('checked');
			$(input).attr('checked', '');
		}
		// If it is not checked
		else {
			$(this).addClass('checked');
			$(input).attr('checked', 'checked');
		}
	});
	
	// If user clicks the label
	$('input[type="checkbox"]').bind('change', function() {
		
		// If it is checked
		if ($(this).is(':checked')) {
			$(this).siblings('a').addClass('checked');
		}
		// If it is not checked
		else {
			$(this).siblings('a').removeClass('checked');
		}
	});
	
	/**********
	When a user hits the submit button
	
	
	$('#submit').click(function() {
		$('div.error').hide();
		$('input, select').removeClass('error');
		var hasError = false;
		
		// validate fname
		var fname = $('#fname').val();
		if (fname.length == 0) {
			$('#fname').siblings('div.error').html('Please enter a first name').show();
			$('#fname').addClass('error');
			hasError = true;
		}
		else if (fname.length > 50) {
			$('#fname').siblings('div.error').html('First name must be less than 50 characters').show();
			$('#fname').addClass('error');
			hasError = true;
		}
		
		// validate lname
		var lname = $('#lname').val();
		if (fname.length == 0) {
			$('#lname').siblings('div.error').html('Please enter a last name').show();
			$('#lname').addClass('error');
			hasError = true;
		}
		else if (lname.length > 50) {
			$('#lname').siblings('div.error').html('Last name must be less than 50 characters').show();
			$('#lname').addClass('error');
			hasError = true;
		}
		
		// validate email
		var email = $('#email').val();
		var emailc = $('#emailc').val();
		var emailReg = /^(?=.{5,254})(?:(?:\"[^\"]{1,62}\")|(?:(?!\.)(?!.*\.[.@])[a-z0-9!#$%&'*+\/=?^_`{|}~^.-]{1,64}))@(?:(?:\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\])|(?:(?!-)(?!.*-\$)(?!.*-\.)(?!.*\.-)(?!.*[^n]--)(?!.*[^x]n--)(?!n--)(?!.*[^.]xn--)(?:[a-z0-9-]{1,63}\.){1,127}(?:[a-z0-9-]{1,63})))$/i;
		var emailSplit = email.split('@');
		var emailDomain = emailSplit[1];
		
		if (email == '') {
			$('#email').siblings('div.error').html('No email given').show();
			$('#email').addClass('error');
			hasError = true;
		}
		
		else if(!emailReg.test(email)) {
			$('#email').siblings('div.error').html('Invalid email').show();
			$('#email').addClass('error');
			hasError = true;
		}
		
		if (email != emailc) {
			$('#emailc').siblings('div.error').html('Email does not match previous email address').show();
			$('#emailc').addClass('error');
			hasError = true;
		}
		
		// Phone number
		var phone = $('#phone').val();
		var phoneReg = /^[0-9]{3}-[0-9]{3}-[0-9]{4}/;
		if (phone.length < 12) {
			$('#phone').siblings('div.error').html('Please enter a phone number').show();
			$('#phone').addClass('error');
			hasError = true;
		}
		else if (!phoneReg.test(phone)) {
			$('#phone').siblings('div.error').html('Invalid phone number').show();
			$('#phone').addClass('error');
			hasError = true;
		}
		
		// CROWNWeb email alerts
		if ($('#ealert').is(':checked')) {
			var ealert = 'yes';
		}
		else {
			var ealert = 'no';
		}
		
		// CROWNWeb alerts (text messages)
		if ($('#text').is(':checked')) {
			var text = 'yes';
			var cell = $('#cell').val();

			if (cell.length < 12) {
				$('#cell').siblings('div.error').html('Please enter a cell number').show();
				$('#cell').addClass('error');
				hasError = true;
			}
			else if (!phoneReg.test(cell)) {
				$('#cell').siblings('div.error').html('Invalid cell number').show();
				$('#cell').addClass('error');
				hasError = true;
			}
			
			var carrier = $('#carrier').val();
			if (carrier == '') {
				$('#carrier').siblings('div.error').html('Please enter a cell carrier').show();
				$('#carrier').addClass('error');
				hasError = true;
			}
		}
		else {
			var text = 'no';
			var cell = '';
			var carrier = '';
		}
		
		// Business type
		var btype = $('#btype').val();
		if (btype == '') {
			$('#btype').siblings('div.error').html('Please enter a business type').show();
			$('#btype').addClass('error');
			hasError = true;
		}

		// Make sure business type and email address are in aggreement
		if (btype == 'Network') {
			var btypeReg = /^(nw){1}[0-9]{0,2}(\.esrd\.net)$/;
			if (!btypeReg.test(emailDomain)) {
				$('#btype').siblings('div.error').html('Business type does not match email. Please us an ESRD email address.').show();
				$('#btype').addClass('error');
				hasError = true;
			}
		}
		
		if (btype == 'Corporate Dialysis Facility') {
			if (!(emailDomain == 'fmc-na.com' || emailDomain == 'davita.com' || emailDomain == 'dciinc.org')) {
				$('#btype').siblings('div.error').html('Business type does not match email. Please use your dialysis facility email address.').show();
				$('#btype').addClass('error');
				hasError = true;
			}
		}
		
		if (btype == 'CMS Users') {
			if (emailDomain != 'cms.hhs.gov') {
				$('#btype').siblings('div.error').html('Business type does not match email. Please use your hhs.gov email address.').show();
				$('#btype').addClass('error');
				hasError = true;
			}
		}
		
		if (btype == 'CMS Contractor') {
			var btypeReg = /^(nw){1}[0-9]{0,2}(\.esrd\.net)$/;
			if (!(emailDomain == 'cgifederal.com' || emailDomain == 'csc.com' || emailDomain == 'edaptivesys.com' || emailDomain == 'esource.net' || emailDomain == 'umich.edu' || emailDomain == 'arborresearch.org' || btypeReg.test(emailDomain) )) {
				$('#btype').siblings('div.error').html('Business type does not match email. Please use correct email address.').show();
				$('#btype').addClass('error');
				hasError = true;
			}
		}

		// Orginization
		var organization = $('#organization').val();
		
		// Provider Number
		var pnum = $('#pnum').val();
		
		// Username
		var username = $('#username').val();
		if (username.length == 0) {
			$('#username').siblings('div.error').html('Please enter a username').show();
			$('#username').addClass('error');
			hasError = true;
		}
		
		$.post('resources/php/checkUsername.php', {
			submit: 'true',
			username: username,
			ajax: 'true'
		},
		// Callback data goes here
		function(data){
			numResults = data;
			if (numResults > 0) {
				$('#username').siblings('div.error').html('Username taken. Please choose another username.').show();
				$('#username').addClass('error');
				hasError = true;
			}
		});
		
		// Password
		var password = $('#password').val();
		var passwordc = $('#passwordc').val();
		if (password.length == 0) {
			$('#password').siblings('div.error').html('Please enter a password').show();
			$('#password').addClass('error');
			hasError = true;
		}
		if (password != passwordc) {
			$('#passwordc').siblings('div.error').html('Passwwords do not match').show();
			$('#passwordc').addClass('error');
			hasError = true;
		}
		
		// Security question
		var question = $('#question').val();
		if (question == '') {
			$('#question').siblings('div.error').html('Please select a security question').show();
			$('#question').addClass('error');
			hasError = true;
		}
		
		// Security answer
		var answer = $('#answer').val();
		if (answer == '') {
			$('#answer').siblings('div.error').html('Please answer a security question').show();
			$('#answer').addClass('error');
			hasError = true;
		}
		
		// We want to set a delay so there is enough time for the AJAX callback
		var timeout = setTimeout(checkErrors, 500);
		
		function checkErrors() {
			// If no errors, validate data using the power of AJAX
			
			if (hasError == false) {
				
				$(this).attr('value', 'Working..').css('opacity', '.5');
				$('#results').hide();
				
				// Do it!
				$.post('resources/php/userRegistration.php', {
					submit: 'true',
					fname: fname,
					lname: lname,
					email: email,
					emailc: emailc,
					phone: phone,
					ealert: ealert,
					text: text,
					cell: cell,
					carrier: carrier,
					btype: btype,
					organization: organization,
					pnum: pnum,
					username: username,
					password: password,
					passwordc: passwordc,
					question: question,
					answer: answer,
					ajax: 'true'
				},
				// Callback data goes here
				function(data){
					
					// If the callback data is not the string 'false'
					if (data != 'false') {
						// Create a clean JSON object
						var jsonObject = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
						data.replace(/"(\\.|[^"\\])*"/g, ''))) &&
						eval('(' + data + ')');
						
						// Remember the variables at the beginning of the script?
						name = jsonObject.name;
						email = jsonObject.email;
						
						if (name == undefined) {
							alert('JSON Error: ' + data);
						}
						
						var successMessage =
						'Dear ' + name + ',<br/>Your registration for the CROWNWeb Learning Management System (LMS) was successful.<br/>Thanks,<br/>The CROWNWeb Team';
						
						// Hide form and show success message
						$('form').slideUp('slow', function() {
							$('#results').html(successMessage).addClass('success').slideDown('slow');
						});

					}
					else {
						var errorMessage = 'We are sorry. There was a problem with your registration. Please go back and try again.'
						
						// Hide form and show error message
						$('form').slideUp('slow', function() {
							$('#results').html(errorMessage).addClass('error').slideDown('slow');
						});
					}
				});
				
				// Return 'false' so the form does not continue on as specified in the form attribute 'action'
				return false;

			}
			else {
				$('#results').addClass('error').html('There have been some errors. Please review the registration form.').show();
			
			}
		}
		
		
		
		return false;
	});
	**********/
	
	$('form').submit(function() {
		var submitButton = ('#submit');
		$('div.error').hide();
		$('input.error, select.error').removeClass('error');
		
		$.ajax({
			url: 'resources/php/validate.php',
			type: "POST",
			data: ({
		    	fname: $('#fname').val(),
		    	lname: $('#lname').val(),
		    	email: $('#email').val(),
		    	emailc: $('#emailc').val(),
		    	phone: $('#phone').val(),
				btype: $('#btype').val(),
				orginization: $('#orginization').val(),
				pnum: $('#pnum').val(),
				username: $('#username').val(),
				password: $('#password').val(),
				passwordc: $('#passwordc').val(),
				question: $('#question').val(),
				answer: $('#answer').val(),
				ealert: $('#ealert:checked').val(),
				ajax: 'true'
			}),
		    dataType: 'json',
		    
		    // Before we send the AJAX request
		    beforeSend: function() {
				$(submitButton).attr({
					value: 'processing...',
					disabled: 'disabled'
				});
			},
			
			// If the AJAX call is successful
			success: function(data){
				var hasError = false;
				
				for(key in data) {
					var name = data[key]['name'];
					var error = data[key]['error'];
		        	
					if (error != null) {
						var input = $('#' + name);
						hasError = true;
						$(input).addClass('error');
						$(input).siblings('.error').html(error).hide().slideDown('slow');
					}
				}
				
				// If we found an error
		        if (hasError == true) {
		        	var errorMessage = 'There was a problem with your registration. Please correct all errors above.';
					$('#results').html(errorMessage).addClass('error').slideDown('slow');
				}
		        // If we did not find an error
		        else {
		        	var successMessage = 'Dear ' + data.value + ',<br/>Your registration for the CROWNWeb Learning Management System (LMS) was successful.<br/>Thanks,<br/>The CROWNWeb Team';
		        	$('form').slideUp('slow', function() {
						$('#results').html(successMessage).addClass('success').slideDown('slow');
					});
		        	//alert();
				}
			},
			
			// After the AJAX is complete (either on error or success)
			complete: function() {
				$(submitButton).attr({
					value: 'submit',
					disabled: ''
				});
			}
		});
		
		
		return false;
	});
	
});
