
	/* ----------------- DOCUMENT READY FUNCTIONS ----------------- */
	$(document).ready(function() {

		// hides the commentbox as soon as the DOM is ready
		// (a little sooner than page load)
		hideCommentForm();
		
		// hide login form
		hideLoginForm();
		
		// hide register form
		hideRegisterForm();
		
		// hide password reminder form
		hideReminderForm();
		
		hideStatusContainer();


		// limit comments textarea to 500 characters
		$(function(){
			$('#usercomments').keyup(function(){
				limitChars('usercomments', 500, 'charlimitinfo');
			})
		});
 

		// assign button handlers
		$('#loginuser').click(function() { loginUser();} );
		$('#registeruser').click(function() { registerUser();} );
		$('#sendreminder').click(function() { sendReminder(); });
		$('#submitcomments').click(function() { sendComments(); });
		$('#resetcomments').click(function() { resetComments(); });
		$('#submitcomingsoon').click(function() { sendComingSoonNotificationRequest(); });
		$('#suggestion_submit').click(function() { submitSuggestion(); });
		$('#screen_name_submit').click(function() { setScreenName(); });
		$('#close-screen-name-form').click(function() { closeScreenNameForm(); });

		// log out user
		$('a#logout-link').click(function() { 
			logoutUser();
			return false;
		});

		// shows the commentbox on clicking the noted link
		$('a#comment-link').click(function() {
			showCommentForm();
			return false;
		});

		// hides the commentbox on clicking the noted link
		$('a#comment-hide').click(function() {
			hideCommentForm();
			return false;
		});

		// shows the login form on clicking the noted link
		$('a#login-link').click(function() {
			showLoginForm();
			return false;
		});

		// shows the register form on clicking the noted link
		$('a#register-link').click(function() {
			showRegisterForm();
			return false;
		});
		
		$('a#register-link-from-login').click(function() {
			showRegisterForm();
			return false;
		});
		
		$('a#password-reminder-link').click(function() {
			showReminderForm();
			return false;
		});
		
	}); // end document.ready


	/* ----------------- DISPLAY FUNCTIONS ----------------- */

	function showCursor(which) {
		$('body').css({cursor: which});
	}
	
	function closeScreenNameForm() {
		$('#select-screen-name').dialog('close');
	}
	
	function hideStatusContainer() {
		$('#status-message-container').hide(400);
	}
	
	function showLoginForm() {
		// hide other forms if they're open
		$('#register-form-container').hide(400);
		$('#commentbox').hide(400);
		$('#reminder-form-container').hide(400);

		hideStatusContainer();
		
		// show login form
		$('#login-form-container').show('fast');
	}
	
	function hideLoginForm() {
		$('#login-form-container').hide(400);
	}
	
	function showRegisterForm() {
		// hide the other forms if they're open
		$('#commentbox').hide(400);
		$('#login-form-container').hide(400);
		$('#reminder-form-container').hide(400);
		
		hideStatusContainer();
		
		// show register form
		$('#register-form-container').show('fast');
		
	}	
	
	function hideRegisterForm() {
		$('#register-form-container').hide(400);
	}
	
	function showReminderForm() {
		// hide the other forms if they're open
		$('#commentbox').hide(400);
		$('#login-form-container').hide(400);
		$('#register-form-container').hide(400);
		hideStatusContainer();
		
		$('#reminder-form-container').show('fast');
	}
	
	function hideReminderForm() {
		$('#reminder-form-container').hide(400);
	}
	
	function showCommentForm() {
		// hide the other forms if they're open
		hideStatusContainer();
		$('#register-form-container').hide(400);
		$('#login-form-container').hide(400);
		$('#reminder-form-container').hide(400);
		hideStatusContainer();
		
		// show comment form
		$('#commentbox').show('fast');
	}
	
	function hideCommentForm() {
		$('#commentbox').hide(400);
	}


	/* ----------------- UTILITY FUNCTIONS ----------------- */
	function limitChars(textid, limit, infodiv) {

		var text = $('#'+textid).val(); 
		var textlength = text.length;
		if(textlength > limit) {
			$('#' + infodiv).html( 'There is a '+limit+' character limit');
			$('#'+textid).val(text.substr(0,limit));
			return false;
		} else {
			$('#' + infodiv).html( 'Characters remaining:  '+ (limit - textlength) );
			return true;
		}
	}


	/* ----------------- AJAX FUNCTIONS ----------------- */
	function genericError(xhr, reason, ex) {
		showCursor('auto');
		alert('There was an error processing your request.  Please try again later.');
	}
	
	function loginUser() {
		// submit form to server for processing
		// first check form to make sure all fields are entered
		if (loginFormValidates()) {
			showCursor('progress');
			
			// form validates - configure post request to send to server
			$.ajax({
				type: 'POST',
				url: '/login.php',
				data: {
					loginemail: $('#loginemail').val(), 
					loginpassword: $('#loginpassword').val()
					},
				timeout: 5000,
				success: handleLoginUser,
				error: genericError
			});

		}
	}

	function handleLoginUser(data, status) {
		// handle data returned by server
		// data strings returned are valid || invalid
		
		showCursor('auto');

		if (data == 'invalid') {

			alert('The login information presented is not valid.  Please try again.');

		} else if (data == 'needs-screen-name') {
			
			// hide login/register links
			$('#account-links').hide();
			// show comment link
			$('#post-links').show();
			// show comment form
			showCommentForm();

			// show form to set screen name
			$('#select-screen-name').dialog('open');
			
		} else {
			
			// hide login/register links
			$('#account-links').hide();
			// show comment link
			$('#post-links').show();
			// show comment form
			showCommentForm();
			
		}
	}

	function sendReminder() {
		// submit form to server for processing
		// first check form to make sure email is entered
		
		if (reminderFormValidates()) {
			
			showCursor('progress');
			// form validates - configure post request to send to server
			$.ajax({
				type: 'POST',
				url: '/password-reminder.php',
				data: {
					email: $('#remindemail').val(), 
				},
				timeout: 5000,
				success: handleRemindUser,
				error: genericError
			});

		}
	}
	
	function handleRemindUser(data, status) {
		// handle data returned by server
		// data is string indicating status of request
		
		var message;

		showCursor('auto');

		switch(data) {
			
			case 'invalid-request':
				message = 'No email address supplied.  Please try again.';
				break;
				
			case 'reset-email-sent':
				message = 'Your password has been reset.  Please check your email.';
				break;
				
			case 'reminder-email-sent':
				message = 'Your password reminder has been sent.  Please check your email.';
				break;
				
			case 'error-too-many-attempts':
				message = 'You have attempted too many password reminders.  Please contact QImaging for assistance.';
				break;
				
			case 'error-email-not-on-file':
				message = 'This email address is not on file.  Please enter a new address.';
				break;
				
			case 'error-sending-reminder-email':
			case 'error-sending-reset-email':
				// don't break - fall through to default

			default:
				message = 'There was an error processing your request.  Please try again later.';
		}
		
		alert(message);
	}
	
	
	function registerUser() {
		// submit form to server for processing
		// first check form to make sure all fields are entered
		if (registerFormValidates()) {
			
			showCursor('progress');

			// build data object
			var formdata = {
				email: $('#registeremail').val(),
				screen_name: $('#screenname').val(),
				password: $('#registerpassword').val(),
				confirm_password: $('#confirmpassword').val(),
				first_name: $('#first_name').val(),
				last_name: $('#last_name').val(),
				user_location: $('#user_location').val(),
				company: $('#company').val(),
				job_title: $('#job_title').val(),
				street1: $('#street1').val(),
				street2: $('#street2').val(),
				city: $('#city').val(),
				zip: $('#zip').val(),
				phone: $('#phone').val(),
				fax: $('#fax').val(),
				interests: $('#interests').val(),
				addtolist:  $('#addtolist:checked').length,
				source: 'QI QTube registration'
			};

			// form validates - configure post request to send to server
			$.ajax({
				type: 'POST',
				url: '/register.php',
				data: formdata,
				timeout: 10000,
				success: handleRegisterUser,
				error: genericError
			});

		}
	}

	function handleRegisterUser(data, status) {
		// handle data returned by server
		// data strings returned are success || use-password-reminder || error || missing-data

		showCursor('auto');

		switch (data) {
			
			case 'duplicate-screen-name':
				alert('Screen name is already in use.  Please select a new screen name');
				break;
				
			case 'missing-data':
				alert('Please fill out form completely and try again.');
				break;
				
			case 'password-mismatch':
				alert('Please make sure your password and confirm password match');
				break;
				
			case 'success':
			
				// set text for user
				$('#message-head').html('<span class="bluebold14">Thank you.</span>');
				$('#message-content').html('<p>Your account has been activated. </p><p>If you have chosen to be added to our mailing list, you will receive a separate opt-in email. Please click the confirmation link to activate your membership.</p>');
				
				// you have to show the text when you set it
				$('#status-message-container').show('fast');
				
				// and hide the registration form...
				hideRegisterForm();
				
				// hide login/register links
				$('#account-links').hide();
				
				// show comment link
				$('#post-links').show();
				
				
				
				break;
				
			case 'use-password-reminder':
			
				// account exists - set reminder email to register email
				var email = $('#registeremail').val();
				$('#remindemail').val(email);
				
				// show the reminder form in case there's an error
				showReminderForm();
				
				// trigger email reminder code instead
				sendReminder();
				
				break;
				
			case 'error':
				// don't break - error and default handled together
				
			default:
				alert('There was an error processing your request.  Please try again later.');			
				break;
		}
		
	}

	function sendComments() {

		if ($('#usercomments').val() == '') {
			alert('Please enter a comment.');
			return false;
		}
		showCursor('progress');
		var formdata = {
			comments: $('#usercomments').val(),
			movie: $('#movie_id').val()
		};
		
		// submit to server
		$.ajax({
			type: 'POST',
			url: 'qtubecomments.php',
			data: formdata,
			timeout: 5000,
			success: handleSendComments,
			error: genericError
		});
	}
	
	function handleSendComments(data, status) {
		// data = success || fail, give appropriate response
		showCursor('auto');

		switch (data) {
			
			case 'success':
				// give success message and hide form
				$('#message-head').html('<span class="bluebold14">Thank you.</span>');
				$('#message-content').html('<p>Your comment has been sent to the QTube moderator.  It will be posted as soon as it is approved.</p>');
				
				// you have to show the text when you set it
				$('#status-message-container').show('fast');
				
				hideCommentForm();
				break;
				
			case 'fail':
				// don't break - default is fail
			default:
				alert('There was an error processing your request.  Please try again later.');
		}

	}
	
	function resetComments() {
		$('#usercomments').val('');
	}
	
	function sendComingSoonNotificationRequest() {

		if (comingSoonFormValidates()) {
			
			// package up the data and send it to the server
			
			showCursor('progress');

			var formdata = {
				movie: $('#cs_movie_id').val(),
				comments: $('#cs_comments').val(),
				name: $('#cs_name').val(),
				email: $('#cs_email').val()
			};
			
			// submit to server
			$.ajax({
				type: 'POST',
				url: 'qtube-notify-coming-soon.php',
				data: formdata,
				timeout: 5000,
				success: handleComingSoonNotificationRequest,
				error: genericError
			});
				
		}
	}
	
	function handleComingSoonNotificationRequest(data, status) {
		// data = success || fail, give appropriate response
		showCursor('auto');

		switch (data) {
			
			case 'success':
				// give success message and hide form
				$('#qtube-mainleft-comingsoonform').hide(400);
				$('#qtube-mainleft-comingsoonform-success').show('fast');
				break;
				
			case 'fail':
				// don't break - default is fail
			default:
				alert('There was an error processing your request.  Please try again later.');
		}
	}

	function handleSubmitSuggestion(data, status) {
		// replace form with suggestion received text
		showCursor('auto');
		switch (data) {
			case 'missing-data':
				alert('Please fill out form completely and try again.');
				break;
				
			case 'success':
			
				// set text for user
				$('#suggestion_box').html('<p>Thank you for submitting a video suggestion.</p><p>We appreciate your input and will add your request to our list for consideration.</p>');
				
				break;
				
				
			case 'fail':
				// don't break - error and default handled together
				
			default:
				alert('There was an error processing your request.  Please try again later.');			
				break;
		}
	}
	
	function submitSuggestion() {
		// submit form to server for processing
		// first check form to make sure all fields are entered
		if (suggestionFormValidates()) {
			
			showCursor('progress');

			// form validates - configure post request to send to server
			$.ajax({
				type: 'POST',
				url: 'suggestions.php', // relative - so in qtube directory
				data: {
					email: $('#suggestion_email').val(), 
					name: $('#suggestion_name').val(),
					suggestion: $('#suggestion_text').val()
					},
				timeout: 5000,
				success: handleSubmitSuggestion
			});

		}
	
	}

	function logoutUser() {
		// hit the logout script
		showCursor('progress');
			
		$.ajax({
			type: 'POST',
			url: '/logout.php',
			timeout: 5000,
			success: handleLogoutUser,
			error: genericError
		});

	}

	function handleLogoutUser(data, status) {
		// NO data returned by server

		showCursor('auto');
		
		// hide comment/logout links
		$('#post-links').hide();
		
		// show login/register links
		$('#account-links').show();
		
		// hide the comment form
		hideCommentForm();
		
		// show results
		// set text for user
		$('#message-head').html('<span class="bluebold14">You have been logged out of your account.</span>');
		$('#message-content').html('<p>Use the links above if you would like to log in again or register a new account.</p>');
		
		// you have to show the text when you set it
		$('#status-message-container').show('fast');

	}

	function setScreenName() {
		// hit the logout script
			
		if (screenNameFormValidates()) {

			showCursor('progress');
			
			$.ajax({
				type: 'POST',
				url: '/set-screen-name.php',
				data: { screen_name: $('#set_screen_name').val() },
				timeout: 5000,
				success: handleSetScreenName,
				error: genericError
			});
		}

	}

	function handleSetScreenName(data, status) {

		showCursor('auto');
		
		// handle data: duplicate || success || error
		
		switch (data) {
			
			case 'duplicate':
				$('#select-screen-name-intro').text("The screen name you've chosen is already in use.  Please try again.");
				break;
				
			case 'success':
				$('#select-screen-name-intro').text("Your screen name has been set.");
				
				// hide form
				$('#screen_name_form').hide(400);
				
				// show close button for dialogue box
				$('#close-screen-name-form').show('fast');
				
				break;

			case 'error':
				// don't break - default handles error
			default:
				alert('There was an error processing your request.  Please try again later.');
				break;
		}
		

	}
