PageRenderTime 19ms CodeModel.GetById 1ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/static/js/jchat.js

http://django-jchat.googlecode.com/
JavaScript | 183 lines | 116 code | 21 blank | 46 comment | 14 complexity | 20ad5faf3081ec93b885c79fc643ecd0 MD5 | raw file
  1var chat_room_id = undefined;
  2var last_received = 0;
  3
  4/**
  5 * Initialize chat:
  6 * - Set the room id
  7 * - Generate the html elements (chat box, forms & inputs, etc)
  8 * - Sync with server
  9 * @param chat_room_id the id of the chatroom
 10 * @param html_el_id the id of the html element where the chat html should be placed
 11 * @return
 12 */
 13function init_chat(chat_id, html_el_id) {
 14	chat_room_id = chat_id;
 15	layout_and_bind(html_el_id);
 16	sync_messages();
 17}
 18
 19var img_dir = "/static/img/";
 20
 21/**
 22 * Asks the server which was the last message sent to the room, and stores it's id.
 23 * This is used so that when joining the user does not request the full list of
 24 * messages, just the ones sent after he logged in. 
 25 * @return
 26 */
 27function sync_messages() {
 28    $.ajax({
 29        type: 'POST',
 30        data: {id:window.chat_room_id},
 31        url:'/chat/sync/',
 32		dataType: 'json',
 33		success: function (json) {
 34        	last_received = json.last_message_id;
 35		}        
 36    });
 37	
 38	setTimeout("get_messages()", 2000);
 39}
 40
 41/**
 42 * Generate the Chat box's HTML and bind the ajax events
 43 * @param target_div_id the id of the html element where the chat will be placed 
 44 */
 45function layout_and_bind(html_el_id) {
 46		// layout stuff
 47		var html = '<div id="chat-messages-container">'+
 48		'<div id="chat-messages"> </div>'+
 49		'<div id="chat-last"> </div>'+
 50		'</div>'+
 51		'<form id="chat-form">'+
 52		'<input name="message" type="text" class="message" />'+
 53		'<input type="submit" value="Say!!!"/>'+
 54		'</form>';
 55		
 56		$("#"+html_el_id).append(html);
 57		
 58		// event stuff
 59    	$("#chat-form").submit( function () {
 60            var $inputs = $(this).children('input');
 61            var values = {};
 62            
 63            $inputs.each(function(i,el) { 
 64            	values[el.name] = $(el).val();
 65            });
 66			values['chat_room_id'] = window.chat_room_id;
 67        	
 68        	$.ajax({
 69                data: values,
 70                dataType: 'json',
 71                type: 'post',
 72                url: '/chat/send/'
 73            });
 74            $('#chat-form .message').val('');
 75            return false;
 76	});
 77};
 78
 79/**
 80 * Gets the list of messages from the server and appends the messages to the chatbox
 81 */
 82function get_messages() {
 83    $.ajax({
 84        type: 'POST',
 85        data: {id:window.chat_room_id, offset: window.last_received},
 86        url:'/chat/receive/',
 87		dataType: 'json',
 88		success: function (json) {
 89			var scroll = false;
 90		
 91			// first check if we are at the bottom of the div, if we are, we shall scroll once the content is added
 92			var $containter = $("#chat-messages-container");
 93			if ($containter.scrollTop() == $containter.attr("scrollHeight") - $containter.height())
 94				scroll = true;
 95			
 96			// add messages
 97			$.each(json, function(i,m){
 98				// filter message for bad bad stuff (XSS injections for instance)
 99				m.message = clean_message(m.message);
100				// depending on the message type, present it in a different manner
101				if (m.type == 's')
102					$('#chat-messages').append('<div class="system">' + replace_emoticons(m.message) + '</div>');
103				else if (m.type == 'm') 	
104					$('#chat-messages').append('<div class="message"><div class="author">'+m.author+'</div>'+replace_emoticons(m.message) + '</div>');
105				else if (m.type == 'j') 	
106					$('#chat-messages').append('<div class="join">'+m.author+' has joined</div>');
107				else if (m.type == 'l') 	
108					$('#chat-messages').append('<div class="leave">'+m.author+' has left</div>');
109					
110				last_received = m.id;
111			})
112			
113			// scroll to bottom
114			if (scroll)
115				$("#chat-messages-container").animate({ scrollTop: $("#chat-messages-container").attr("scrollHeight") }, 500);
116		}        
117    });
118    
119    // wait for next
120    setTimeout("get_messages()", 2000);
121}
122
123/**
124 * Tells the chat app that we are joining
125 */
126function chat_join() {
127	$.ajax({
128		async: false,
129        type: 'POST',
130        data: {chat_room_id:window.chat_room_id},
131        url:'/chat/join/',
132    });
133}
134
135/**
136 * Tells the chat app that we are leaving
137 */
138function chat_leave() {
139	$.ajax({
140		async: false,
141        type: 'POST',
142        data: {chat_room_id:window.chat_room_id},
143        url:'/chat/leave/',
144    });
145}
146
147// attach join and leave events
148$(window).load(function(){chat_join()});
149$(window).unload(function(){chat_leave()});
150
151// emoticons
152var emoticons = {                 
153	'>:D' : 'emoticon_evilgrin.png',
154	':D' : 'emoticon_grin.png',
155	'=D' : 'emoticon_happy.png',
156	':\\)' : 'emoticon_smile.png',
157	':O' : 'emoticon_surprised.png',
158	':P' : 'emoticon_tongue.png',
159	':\\(' : 'emoticon_unhappy.png',
160	':3' : 'emoticon_waii.png',
161	';\\)' : 'emoticon_wink.png',
162	'\\(ball\\)' : 'sport_soccer.png'
163}
164
165/**
166 * Regular expression maddness!!!
167 * Replace the above strings for their img counterpart
168 */
169function replace_emoticons(text) {
170	$.each(emoticons, function(char, img) {
171		re = new RegExp(char,'g');
172		// replace the following at will
173		text = text.replace(re, '<img src="'+img_dir+img+'" />');
174	});
175	return text;
176}
177
178/**
179 * Clean unwanted characters from message string to prevent code injection
180 */ 
181function clean_message(text) {
182	return text.replace(/</g,"&lt;").replace(/>/g,"&gt;")
183}