var enterPressed;
var keyDate;
var seq = '';
var socket;
$(document).ready(
		function(){
			
			$("input[name='number']").on('focus', function (e) {
			    $(this)
			        .one('mouseup', function () {
			            $(this).select();
			            return false;
			        })
			        .select();
			});
			
			addDocumentKeypressedListener();
		}
);


function addDocumentKeypressedListener(){
	$(  document ).keypress(function( event ) {
		var tag = event.target.tagName.toLowerCase();
	    if (   tag != 'input' && tag != 'textarea' && tag != 'select') {
		
	    	resetSequenceIfToMuchTimePassedOrEnterWasPressed(event);
	    	
			if ( event.which == 13 ) {
				enterPressed = 1;
				if ( seq ){
					$( document ).trigger( "wordtyped", [ { originalEvent: event, 'word': seq } ] );
				}
			}else {
				appendCharToSeq(event);
			}
		}
	});	
	
	$( document ).on( "wordtyped", function( event, data ) {
		var word;
		word = data.word;
		if ( word && word.length > 0){
			
			location.href= reception_card_url +'&number=' + word;
			
			
		}
	});
	
	function resetSequenceIfToMuchTimePassedOrEnterWasPressed(){
		var prevDate, timePassed;
		prevDate= keyDate;
		keyDate = new Date().getTime();
		timePassed = keyDate - prevDate;
		if ( enterPressed > 0 || timePassed > 2000 ){
			 seq = '';
			 enterPressed = 0;
		}
	}
	
	function appendCharToSeq(event){
		var code,s;
		code = event.which;
		if ( code ){
			s = String.fromCharCode(code);
			if ( s )
				seq += s;
		}
	}
	
}



function startServer(){
	try{
	socket = new WebSocket("ws://localhost:8025/websockets/qrcode");
	console.info('socket created');
	socket.onmessage = function (event) {
		  console.log(event.data);
		  var msg = JSON.stringify(event.data);
		  if ( msg.msg == 'qrcode'){
			  console.info('qrcode rcvd');
		  }
		}
	}catch(e){
	}

}


//startServer();

function sendMessage(){
	socket.send("Here's some text that the server is urgently awaiting!");
}