var unread = 0;
focus = true;

var socket = new Pusher(Pusher.key, 'room_' + channel);

title = document.title;

socket.bind('send_msg', function(thing) {
 	$('#chat').append(thing);
 	
 	if(focus == false){
 		unread = unread+1;
 		 		
 		document.title = '(' + unread + ') ' + title;
 	}
 	
 	
	$('#chat').scrollTo($('#chat')[0].scrollHeight, 100);
});

socket.bind('join_room', function(person) {
 	$('#people').append('<li>' + person + '</li>');
});
	
	
$(function(){	
	$('#chat').scrollTo($('#chat')[0].scrollHeight, 100);
	
	$([document, window	]).bind("blur", function(){
		focus = false;
	});
	
	$([document, window]).bind("focus", function(){
		focus = true;
		unread = 0;
		
		document.title = 'h4xr.org';
	});

	//Send join room
	/*
$.post('/home/joinroom',{
		channel: channel,
		name: $('#name').val()
	}, function(d){
		
		if(d.error){
			alert('Could not send');
		}
		
		//$('#people').append('<li>' + name + ' (You)</li>');
		
	}, 'json');	
*/
	
	$('#msg').keypress(function(e){	
		
		if(e.keyCode == 13){
			e.preventDefault();
			
			$.post('/home/send_message',{
				channel: channel,
				name: $('#name').val(),
				msg: $('#msg').val()
			}, function(d){
				
				if(d.error){
					alert('Could not send');
				}
				
			}, 'json');
			
			location.href = '#end';
			
			$('#status').text('sent');
			$('#msg').focus().val('');
		}
		
	});


/*
$(window).bind("beforeunload", function(e){
	e.returnValue = "Unsaved changes.";
});
*/

});
