var word_string, words; 		//String = enthält die Wörter; Array(words) = enthält die Wörter aufgesplittet in einem Array  
var row1_string = ''; 			//enthält die einzugebenen Wörter der 1. Reihe
var i;
var word_pointer = 0; 			//markiert das aktuelle Wort welches getippt werden soll
var user_input_stream = ''; 	//sammelt alle Tastatureingaben des Users
var countdown; 					//zeigt die Zeit an und wird runtergezählt
var row_counter = 0; 			//zählt die Anzahl der Zeilensprünge
var eingabe; 					//prüfvariable => alles was im Inputfeld drinsteht wird hier zwischengespeichert und weiterverarbeitet (manchmal reagiert der Keylistener für das Leerzeichen nicht schnell genug, z.b. "hallo w" wird dann übertragen, daher erfolgt zu erst eine weiterverarbeitung) 
var start_time = 0;				//die Startzeit in Millisekunden
var end_time = 0;				//die Endzeit in Millisekunden
var setval = "";				//die Variable für den Timer/setInterval
var start_time_set = 0;			//wurde die Startzeit auf dem Server mittels Ajax schon gesetzt oder nicht
var line_height = 0;			//Höhe des Zeilensprungs
var loading = 0;

var error_wpm = 0;				//fallback if ajax call fails => user can still see his result
var error_keystrokes = 0;
var error_correct = 0;
var error_wrong = 0;

var keys = {};					//liest die gedrückten Tasten ein, wird genutzt für Mac/Safari "Smart" Reload

$(document).ready(function(){
	restart();
	activate_keylistener();
	
	var win_width = $(window).width();
	
	//mostly for Facebook
	if(win_width < 800)
	{
		$("#words").css('width', win_width-50);
		$("#words").css('margin-left', '10px');
		$("#input-box-space").css('width', '80px');
	}
	
	$(document).keyup(function (event) {
		delete keys[event.which];
	});
	
	$("#reload-btn").live('click', function(){
		restart();
		return false;
	});
	
/* 
    var country = geoplugin_countryName();
    $("#country").append("<option value='1' selected>"+country+"</option>");
 
    var zone = geoplugin_region();
    $("#zone").append("<option value='1' selected>"+zone+"</option>");
 
    var district = geoplugin_city();
    $("#district").append("<option value='1' selected>"+district+"</option>");
*/
});

function restart() {
	//wird beim start und beim klick auf "restart" aufgerufen
	//ruft initialisierungsfunktionen auf und setzt werte zurück auf den startwert
	word_string = '';
	words = '';
	row1_string = '';
	word_pointer = 0;
	user_input_stream = '';
	countdown = 60;
	cd_started = 0;
	previous_position_top = 0;
	row_counter = 0;
	eingabe = '';
	start_time = 0;
	end_time = 0;
	start_time_set = 0;
	
	//just to count everything if the ajax-call fails
	error_wpm = 0;
	error_keystrokes = 0;
	error_correct = 0;
	error_wrong = 0;

		
	$("#timer").text("1:00");
	$("#ajax-load").css('display', 'block');
	$("#reload-box").css('display', 'none');
	$("#row1").css('top', "1px");
	$("#timer").removeClass("off");
	
	window.clearInterval(setval);
    setval = "";
    
	$.ajax({
		type: 'POST',
  		url: "php/engine.php",
  		data: "speedtest_id="+$("#logo").attr("speedtest_id"),
  		cache: false,
  		success: function(data){
  			setTimeout(function() { 
  				$("#ajax-load").css('display', 'none');
	    		$("#reload-box").css('display', 'block');
	    		$("#wordlist").text(data);
	    		
	    		word_string = $('#wordlist').text();
	    		//console.log(data);
				words = word_string.split("|");
				
				fill_line_switcher();

				//initialisiere wichtige Startwerte die abhängig von der Textgröße ist				
				p = $('#row1 span[wordnr="'+word_pointer+'"]').position();
				
				if(p != null)
					previous_position_top = p.top;
				
				line_height = parseInt($('#row1 span[wordnr="'+word_pointer+'"]').css('line-height'));
								
				//springe ins InputField
				$("#inputfield").val('');
				$("#inputfield").focus();
				
				$("#row1").show();
				$("#words").fadeTo('fast', 1.0);
				loading = 0;
				
			}, 500);
  		},
  		error:function(httpRequest, textStatus, errorThrown) { 
			//alert("status=" + textStatus + ",error=" + errorThrown);
			
			/*
			var browser = ''; 
				
			jQuery.each(jQuery.browser, function(i, val) {
		    	browser += i + " : " + val + ' | ';
		    });
			
			//var httpr = jQuery.param(httpRequest);
			var where = "restart_func";
			var error = "status=" + textStatus + ",error=" + errorThrown;
			
			$.ajax({
				type: 'POST',
		  		url: "php/ajax/send_email.php",
		  		cache: false,
		  		dataType: 'json',
		  		data: "where="+where+"&errormsg="+error+"&browser="+browser,
		  		success: function(){
		  		}
			});*/
			
			restart();
		}
	});
}

//wartet auf Eingaben die im #inputfield erfolgen
function activate_keylistener() {
	
	$("input#inputfield").keyup(function(event) {
		if ( loading == 0 ) {
			start_countdown();
			
			//setze die Startzeit auf dem Server
			if(start_time_set == 0)
			{
				$.ajax({
					url: "php/set_start_time.php"
				})
				
				start_time_set = 1;
			}
		}
		
		$("#reload-btn").show();
		
		var input_key = $("#config_input_key").attr("value");
		
		if(event.which == input_key && $("input#inputfield").val() == ' ')
		{
			$("input#inputfield").val('');
		}
		else if (event.which == input_key && loading == 0) { //event.which == 32 => SPACE-Taste
			//evaluate
     		var eingabe = $("input#inputfield").val().split(" ");
     		user_input_stream += eingabe[0]+" ";
			
			$('#row1 span[wordnr="'+word_pointer+'"]').removeClass('highlight-wrong');
			
     		if(eingabe[0] == words[word_pointer])
     		{
     			$('#row1 span[wordnr="'+word_pointer+'"]').removeClass('highlight').addClass('correct');
     			error_correct++;
     			error_keystrokes += words[word_pointer].length;
     			error_keystrokes++; //für jedes SPACE
     		}	
     		else
     		{
     			$('#row1 span[wordnr="'+word_pointer+'"]').removeClass('highlight').addClass('wrong');
     			error_wrong++;
     			error_keystrokes -= Math.round(words[word_pointer].length / 2);
     		}	
     		
     		//process
     		word_pointer++;
     		$('#row1 span[wordnr="'+word_pointer+'"]').addClass('highlight');
     		
     		p = $('#row1 span[wordnr="'+word_pointer+'"]').position();
     		
     		if(p.top > previous_position_top + 5) //"+ 5 ist die Toleranz, damit der Zeilensprung auch funktioniert, wenn User die Schriftart größer gestellt hat, etc."
     		{
     			row_counter++;
     			previous_position_top = p.top;
     			
     			var zeilensprung_hoehe = (-1 * line_height) * row_counter;
     			$("#row1").css('top', zeilensprung_hoehe+"px"); //bei einem zeilensprung wird der text um "line_height" verschoben 
     			$('#row1 span[wordnr="'+word_pointer+'"]').addClass('highlight');
     		}
     		
     		//erase
     		//user_input_stream += $("input#inputfield").val();
     		$("#inputstream").text(user_input_stream);
     		$("input#inputfield").val(eingabe[1]);
   		} else {
	   		//prüfe ob user das wort gerade falsch schreibt (dann zeige es rot an, damit user direkt korrigieren kann)
			if($("input#inputfield").val().replace(/\s/g, '') == words[word_pointer].substr(0, $("input#inputfield").val().length))
				$('#row1 span[wordnr="'+word_pointer+'"]').removeClass('highlight-wrong').addClass('highlight');
			else
				$('#row1 span[wordnr="'+word_pointer+'"]').removeClass('highlight').addClass('highlight-wrong');	
   		}
   		
	});
}

//zählt die Zeit runter und stoppt den Speedtest
function start_countdown() {
	if(cd_started == 0)
	{
		cd_started = 1;
		setval = window.setInterval(count_down, 1000);
		start_time = get_current_time().toString(16);
	}
}

//zählt die Zeit runter
function count_down() {
	countdown--;
	
	var first_part;
	var second_part;
	
	first_part = Math.floor(countdown / 60);
	second_part = countdown % 60;
	
	if(second_part < 10)
		second_part = '0'+second_part;
	
	$("#timer").text(first_part+":"+second_part);
	
  	if(countdown > 9)
	{
		$("#timer").text("0:"+countdown);
	} else if(countdown > 0){
		$("#timer").text("0:0"+countdown);
	} else {
		//ENDE => countdown erreicht 0 Sekunden, stoppe den Countdown und Auswertung mittels Ajax
		$("#timer").text("0:00");
		$("#timer").addClass("off");
		$("#row1").hide();
		$("#words").fadeTo('fast', 0.3);
		
		window.clearInterval(setval);
        setval = "";
		
		end_time = get_current_time().toString(16);
		
		$.ajax({
			type: 'POST',
	  		url: "php/auswertung.php",
	  		cache: false,
	  		dataType: 'json',
	  		data: "sz="+start_time+"&ez="+end_time+"&user_input="+user_input_stream+"&speedtest_id="+$("#logo").attr("speedtest_id"),
	  		success: function(data){
	    		//console.log(data);
	    		
	    		/*
				if(data['notifications'] != '')
					$("#notifications .container").html(data['notifications']);
	    		*/
	    		
	    		$("#auswertung-result").html(data['auswertung_result']);
	    		
				$("a.share-btns#twitter").attr('href', data['twitter_link']);
				$("a.share-btns#facebook").attr('href', data['facebook_link']);
				
	    		$("#auswertung-result").show();
	    		$("#auswertung-share").show();
	    		
	    		$("#badge-box").html(data['badge']);
	    		$("#badge-box").show();
	    		
	    		//hides the secondary main-ad and resizes the "main-ad-box" to fit on the right side next to "result" & "share"
				$("#ad-main-secondary").hide();
	    		$("#ad-main").css('margin', 'none');
	    		$("#ad-main").css('float', 'right');
	    		$("#ad-main").css('width', '340px');
	    		
	    		/*
	    		$.ajax({
					type: "POST",
				  	url: "php/ajax/post_to_facebook.php",
				  	dataType: 'json',
				  	data: "wpm="+data['wpm'],
				  	success: function(data){
				  	},
				  	error:function(httpRequest, textStatus, errorThrown) { 
						//console.log("status=" + textStatus + ",error=" + errorThrown);
					}
				});
				*/
				
				//$("#auswertung").html(ausgabe);
	  		},
	  		error: function(xhr, textStatus, errorThrown) {
	            /*
	            if (jqXHR.status === 0) {
	                error = 'Not connect.\n Verify Network.';
	            } else if (jqXHR.status == 404) {
	                error = 'Requested page not found. [404]';
	            } else if (jqXHR.status == 500) {
	                error = 'Internal Server Error [500].';
	            } else if (exception === 'parsererror') {
	                error = 'Requested JSON parse failed.';
	            } else if (exception === 'timeout') {
	                error = 'Time out error.';
	            } else if (exception === 'abort') {
	                error = 'Ajax request aborted.';
	            } else {
	                error = 'Uncaught Error.\n' + jqXHR.responseText;
	            }
	            
	            var browser = ''; 
				
				jQuery.each(jQuery.browser, function(i, val) {
			    	browser += i + " : " + val + ' | ';
			    });
			    */
			   
				error_wpm = Math.round(error_keystrokes / 5);
	        	$("#error-box #wpm").text(error_wpm);
	        	$("#error-box #keystrokes").text(error_keystrokes);
	        	$("#error-box #correct-words").text(error_correct);
	        	$("#error-box #wrong-words").text(error_wrong);
	    		
	    		$("#error-box").show();
	    	
	        	/*
	        	$.ajax({
					type: 'POST',
			  		url: "php/ajax/send_email.php",
			  		cache: false,
			  		dataType: 'json',
			  		data: "where=ergebnis_func&errormsg=textstatus: "+textStatus+" | errorThrown: "+errorThrown+" | responseText: "+xhr.responseText,
			  		success: function(){
			  		}
				});
	        	*/
	        /*
	  		error:function(httpRequest, textStatus, errorThrown) { 
				var browser = ''; 
				
				jQuery.each(jQuery.browser, function(i, val) {
			    	browser += i + " : " + val + ' | ';
			    });
				
				var where = "ergebnis_func";
				var error = "status=" + textStatus + ",error=" + errorThrown;
				
				$.ajax({
					type: 'POST',
			  		url: "php/ajax/send_email.php",
			  		cache: false,
			  		dataType: 'json',
			  		data: "where="+where+"&errormsg="+error+"&browser="+browser,
			  		success: function(){
			  		}
				});	
			*/
			}
		});
	}	
}

function get_current_time() {
	var d = new Date();
	return d.getTime();
}

//String "Trim" Function
function trim11 (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

//befüllt #row1 und #row2 mit neuen Wörtern
function fill_line_switcher() {
	for(i=0; i < words.length; i++)
		row1_string += '<span wordnr="'+i+'" class="">'+words[i]+'</span> '; //classes = NONE, green, red, highlight
		
	$("#row1").html(row1_string);
	
	$("#row1 span:first").addClass('highlight');
}
