var feedbackTabClosed = true;
var stackDepth = 0;
var maxStackDepth = 3;

$(function() {
	// Create "We value your feedback" tab
	var $feedbackTab = $('<div />');
	$feedbackTab.attr('id','feedback-tab');
	
	// Add a link to the feedback tab
	var $feedbackTabLink = $('<a />');
	$feedbackTabLink.attr({
		'href': '#',
		'title': 'We value your feedback'
	});
	$feedbackTabLink.addClass('feedback-tab-link');
	// Animate the feedback form into view when the tab is clicked
	$feedbackTabLink.click(function(e){
		e.preventDefault();
		
		toggleFeedbackFormTab();
	});
	$feedbackTab.append( $feedbackTabLink );
	
	// Create feedback form container
	var $feedbackForm = $('<div />');
	$feedbackForm.attr('id','feedback-form');
	
	// Create content of feedback form container and insert it
	var $feedbackFormContainer = $('<div />');
	$feedbackFormContainer.load('/forms/feedback-tab/', '', function ( response, status ) {
		
		// When the form contents has been returned, hijack the submit function for ajax
		$('#feedback-form-submit').click( function (e) {
			e.preventDefault();
			
			// Make these fields into something we can check easily and send over ajax
			var fields = $(this).parents('#feedback-form #feedback').serializeArray();
			var errors = validateFeedbackFields( fields );
			
			if ( errors.length < 1 )
			{
				// No errors, so let's submit this thing!
				$.ajax({
					url: '/forms/feedback-tab/',
					data: fields,
					type: 'get',
					dataType: 'html',
					success: function ( data, status ) {
						// Swap out the form for the returned HTML
						$feedbackFormContainer.html( data );
						$('#SurveyFinish').click( function (e) {
							e.preventDefault();
							$('#feedback-form .feedback-form-close').trigger('click');
						});
					}
				});
			}
		});
		
		// Inject system info into the feedback form
		$('#feedback-form-systimestamp').val( sysinfo.timestamp );
		$('#feedback-form-sysbrowser').val( sysinfo.browser );
		$('#feedback-form-sysos').val( sysinfo.os );
		$('#feedback-form-sysres').val( sysinfo.screen.width + 'x' + sysinfo.screen.height );
		$('#feedback-form-syswindow').val( sysinfo.window.width + 'x' + sysinfo.window.height );
	});
	$feedbackForm.append( $feedbackFormContainer );
	
	// Add a close button to the feedback form container
	var $feedbackFormCloseButton = $('<a />');
	$feedbackFormCloseButton.attr({
		'href': '#',
		'title': 'Close'
	});
	$feedbackFormCloseButton.addClass('feedback-form-close');
	// Animate the feedback form away when the close button is clicked
	$feedbackFormCloseButton.click(function(e){
		e.preventDefault();
		
		toggleFeedbackFormTab();
	});
	$feedbackForm.prepend( $feedbackFormCloseButton );
	// Extra credit: pressing the Esc key triggers the close button too
	$(document).keydown(function(e) {
		if ( e.which == 27 )
		{
			if ( $('#feedback-form').css('right').replace('px','') >= 0)
			{
				$('#feedback-form .feedback-form-close').trigger('click');
			}
		}
	});
	
	// Inject the various objects into the document
	$('body').append( $feedbackTab );
	$('body').append( $feedbackForm );
	
	// Collect system info to be injected into the feedback form
	var sysnow = new Date();
	var sysinfo = {
		'timestamp': sysnow.toString(),
		'browser': navigator.userAgent,
		'os': navigator.platform,
		'screen': {
			'width': screen.width,
			'height': screen.height
		},
		'window': {
			'width': $(window).width(),
			'height': $(window).height()
		}
	};
});

function validateFeedbackFields( fields )
{
	var errors = [];
	
	// Set all fields we expect to have data
	var requiredFields = new Array( 'feedback-form-feel', 'feedback-form-topic', 'feedback-form-comments' );
	
	// Hide any errors that were displayed from a previous submit attempt
	for ( var i = 0; i < requiredFields.length; i++ )
	{
		$('#' + requiredFields[i] + '-error').fadeOut('fast');
	}
	
	// Check all fields
	for ( var i = 0; i < fields.length; i++  )
	{
		// If the field is in required fields, we can remove it from there as we know we have it
		// Unfortunately due to IE missing an indexOf method on Arrays, we do this the long way
		var idx = null;
		for ( var j = 0; j < requiredFields.length; j++ )
		{
			if ( requiredFields[j] == fields[i].name )
			{
				idx = j;
			}
		}
		if ( idx != null )
		{
			var spliced = requiredFields.splice( idx, 1 );
		}
		
		// Check if the field actually has a non-blank value
		if ( fields[i].value == "" )
		{
			errors.push( fields[i].name );
		}
	}
	
	// Add any fields that didn't show up but were required to the list of errors
	if ( requiredFields.length > 0 )
	{
		for ( var i = 0; i < requiredFields.length; i++ )
		{
			errors.push( requiredFields[i] );
		}
	}
	
	// Show error messages for fields with errors
	for ( var i = 0; i < errors.length; i++ )
	{
		$('#' + errors[i] + '-error').fadeIn('slow');
	}
	
	return errors;
}

function toggleFeedbackFormTab()
{
	if ( feedbackTabClosed )
	{
		$('#feedback-tab').animate(
			{
				'right': '-38px'
			},
			300,
			function() {
			}
		);
		$('#feedback-form').animate(
			{
				'right': 0
			},
			300,
			function() {
			}
		);
		feedbackTabClosed = false;
	}
	else
	{
		$('#feedback-tab').animate(
			{
				'right': 0
			},
			300,
			function() {
			}
		);
		$('#feedback-form').animate(
			{
				'right': '-412px'
			},
			300,
			function() {
			}
		);
		feedbackTabClosed = true;
	}
}

function listProps( o, f )
{
	stackDepth++;
	var r = ( f != 'list' ? '[' : '<ul>' );
	for ( p in o )
	{
		r += ( f != 'list' ? '{' : '<li>' ) + '"' + p + '"' + ':' + '"' + o[p] + '",';
		if ( typeof o[p] == 'object' )
		{
			if ( stackDepth < maxStackDepth)
			{
				try {
					r += listProps( o[p], f );
				} catch (ex) {
					if ( f == 'list' )
					{
						r += '<ul><li>..!</li></ul>';
					}
				}
			}
			else
			{
				if ( f == 'list' )
				{
					r += '<ul><li>...</li></ul>';
				}
			}
		}
		if ( f != 'list' )
		{
			r = r.substring( 0, r.length - 1 );
		}
		r += ( f != 'list' ? '},' : '</li>' );
	}
	if ( f != 'list' )
	{
		r = r.substring( 0, r.length - 1 );
	}
	r += ( f != 'list' ? ']' : '</ul>' );
	stackDepth--;
	return r;
}

