var kb = 
{
	BACKSPACE :  8,
	TAB       :  9,
	ENTER     : 13,
	SHIFT     : 16,
	CONTROL   : 17,
	ALT       : 18,
	CAPSLOCK  : 20,
	ESCAPE    : 27,
	SPACE     : 32,
	PGUP      : 33,
	PGDN      : 34,
	END       : 35,
	HOME      : 36,
	LEFT      : 37,
	UP        : 38,
	RIGHT     : 39,
	DOWN      : 40,
	INSERT    : 45,
	DELETEKEY : 46
};

//
// Таймер отсчета оставшегося времени
//
function timer() 
{  
	seconds++;

	$('#timer').html( time_limit - seconds);

	// Если время вышло, сбрасываем таймер и показываем результат
	if ( seconds >= time_limit && start < 2 )
	{
		clearInterval( activeTimer );
		$('#welcome').hide();
		start = 2;
		result(); 
	}
}

//
// Показать результаты теста 
//
function result()
{
	var goals = 0;

	for ( j=0; j < mode.length; j++ )
	{
		if(mode[j] == 0)
			goals -= words[j].length;
		else if(mode[j] == 1)
			goals += words[j].length;  
	}

	$('#top').html("");

	////getElementById('total').style.display = 'block';
	$('#total').show();
	$('#total').html( '<img src="img/ajax-loader-big.gif" alt="" width="40" height="40" />' );

	if ( num_letters > 2 ) // Если была попытка набора текста
	{
		var pars = {
			'symbols_typed' : $('#symbols_typed').html(),
			'typed_right'   : $('#typed_right').html(),
			'typed_wrong'   : $('#typed_wrong').html(),
			'goals'         : goals,
			'name'          : encodeURIComponent( your_name )
		};
		
		$.get( 'total.php', pars, function( data ) 
		{
			$('#total').html( data );
			
			//$("#input_name").change( function(e){ check_name(); return false; } );
			$("#input_name").keypress( function(e) 
			{
				if ( e.which == kb.ENTER ) 
				{
					e.preventDefault();
					check_name(); 
					return false;
				}
			} );
			
			$.get( 'get_stat.php',  
				{
					'id'     : parseInt( $('#id').text() ), 
					'balls'  : parseInt( $('#balls').text() ), 
					'rating' : parseInt( $('#your_place').text() ), 
					'name'   : encodeURIComponent( your_name )
				},
				function( data )
				{
					$("#total").append( data );
				}, "html");
			
		}, "html");
	}
	else
	{
		document.location.reload();
	}

}

//
// Обработка нажатий клавиш
//
function key_updown( e, down ) 
{
	var key_pressed = e.which; 
	
	//
	// Нажатия модификаторов игнорируются
	//
	if ( key_pressed==kb.SHIFT || key_pressed==kb.CONTROL || key_pressed==kb.ALT )
		return;

	if ( start == 0 )
	{
		////getElementById('restart').style.display = 'inline';
		$('#restart').css( "display", "inline" );
		//activeTimer = setInterval('timeк()',1000);
		activeTimer = setInterval( timer, 1000 );
		start = 1;
	}
	if ( ! down ) 
	{
		num_letters++;
	}
	
	if ( down ? key_pressed != kb.ENTER : key_pressed != kb.SPACE )
		return;

	type_string = $('#enter').val();

	if ( key_pressed==kb.SPACE )
	{
		while ( type_string.indexOf(" ") != -1 )  
		{
			mode[wordsCounter] = (type_string.substr(0, words[wordsCounter].length+1) == words[wordsCounter]+' ') 
									? 1 
									: 0;
			type_string  =   type_string.replace(/^[^ ]* /, "");
			typed_right +=   mode[wordsCounter];
			typed_wrong += ! mode[wordsCounter];
			wordsCounter++;
			check();
		}
	}
	else if ( key_pressed==kb.ENTER )
	{
		mode[wordsCounter] = (type_string.substr(0, words[wordsCounter].length) == words[wordsCounter]) ? 1 : 0;
		type_string   =   "";
		typed_right  +=   mode[wordsCounter];
		typed_wrong  += ! mode[wordsCounter];
		wordsCounter++;
		check();
	}
	
	$('#enter').val( type_string );

	if ( ! down ) 
	{
		$('#symbols_typed').html( num_letters );
		$('#typed_right').html( typed_right );
		$('#typed_wrong').html( typed_wrong );
	}
	
	e.stopPropagation();
}

function check() 
{
	var preview = 0;	

	if (((wordsCounter+1) % sampleSize) == 0)
		runner++;

	if (runner > 1)
		preview = -1;

	var typed_words = '';

	for ( i=(preview+((runner-1)*sampleSize)); i<(sampleSize*runner); i++ )
	{
		if (wordsCounter == i)
			typed_words += '<span style="background: #ddd;">'+words[i]+'</span> ';
		else
		{ 
			if(mode[i] == 0)
				typed_words += '<span style="color:red">'+words[i]+'</span>'+' ';
			else if(mode[i] == 1)
				typed_words += '<span style="color:green">'+words[i]+'</span>'+' ';  
			else
				typed_words += words[i]+' ';
		}
	}

	$('#sample').html( typed_words );
}

function check_name()
{
	var new_name = $('#input_name').val();
	
	if ( new_name.length > 0 )
	{
		$('#incognito').html( new_name );
		your_name = new_name;
		//$('#input_name').attr( "disabled", true );
		// прячем поле ввода имени
		$('#yourname').hide();
	}
	else
	{
		$('#incognito').html( your_name );
		//return false;
	}
	
	var pars = {
		'id'   : $('#id').html(), 
		'name' : encodeURIComponent( your_name )
	};
	
	var backup = $('#total').html();
	
	$.get( 'save_name.php', pars, function( data ) 
	{
		$('#total').html( backup );
		$('#incognito').html( data );
		// и обновляем статистику - с новым именем
		$.get( 'get_stat.php',  
			{
				'id'     : parseInt( $('#id').text() ), 
				'balls'  : parseInt( $('#balls').text() ), 
				'rating' : parseInt( $('#your_place').text() ), 
				'name'   : encodeURIComponent( your_name )
			},
			function( data )
			{
				$("#best").remove();
				$("#total").append( data );
			}, 
			"html"
		);
	}, "html");
	
	return true;
}


