// Settings controls

(function($){
	
	$.fn.initChat = function() {
		var input = $(this);
		var chatview = $('#chatview');
		var hidden = true;
		
		var esc = 27;
		var enter = 13;
		
		var closechat = function() {
		  hidden = true;
			chatview.fadeOut(200, function() {
				chatview.text('');
			});
			input.val('');
		}
		
		input.blur(function(e) {
		  //do not block form focus
		  if(!$(e.target).parent('#instructions form') && !$(e.target).parent('#instructions') ) {
		    setTimeout(function(){input.focus()}, 0.1);
		  } else {
		    //setTimeout(function(){input.focus()}, 10000);
		  }
		});
		
		input.keyup(function(e) {
			var k = e.keyCode;
			if(input.val().length >= 90)
			{
				input.val(input.val().substr(0,90));
			}
						
			if(input.val().length > 0) {
				chatview.text(input.val());
				chatview.css({
					marginLeft: (chatview.width()/2)*-1,
					marginTop: (chatview.height()/2)*-1
				});
				chatview.fadeIn(100);
			} else {
				closechat();
			}
			
			if(!hidden) {
				if(k == keys.esc || k == keys.enter || (k == keys.space && input.val().length > 35)) {
					if(k != keys.esc && input.val().length > 0) {
					    	messageHistory.push(input.val());
			    			messagePointer = messageHistory.length;
						app.sendMessage(input.val());
					}
					closechat();
				}
				
				e.stopPropagation();
			}
			
			if(k == esc || k == enter) {
				if(k == enter && input.val().length > 0) {
					var sendObj = {
						type: 'message',
						value: chatview.text()
					};
					
					app.sendMessage(chatview.text());
				}
				closechat();
			}
		});
		
		input.focus();
	}
	
	$(function() {
    $('#chat').initChat();
	});
})(jQuery);

