Chat SCF Behavior Script
Release 1.1 - ...
|
|
|
|---|---|
/*
Chat Smartlet enrichment script
*/
$j.scf.behavior.add('sml_chat_Behavior', {
attach: function(e,settings,j){
var frm = j.find('form'); // find form element under jQuery selector
// create/extend settings object passed to the behavior
// using Object extension
settings = Object.extend({
joinMessage: 'Joined the chat',
createMessage: 'New chat started!'
}, settings);
var smartlet = $j.scf.smartlet.get(e); // get Smartlet object from div with Smartlet ID.
var div = $j('.ChatHistory', e), speak = $j('.Speak', e), send = $j('.Send', e);
var clear = $j('.Clear', e), tmr;
// setup focus and blur event handlers
speak.focus(function(){
clearTimeout(tmr); // do not poll when textbox has focus
send.attr('value', 'Send'); // update the Send button
});
speak.blur(function(){
tmr = setTimeout(update, 5000); // reset poll timeout
send.attr('value', 'Refresh'); // update the Send button
});
// Add message to conversation div
function addData(html){
if(html && typeof(html) == 'string' && html.trim().length){
// create and fade in new line(s) of text
var row = $j(html).hide();
div.append(row);
row.fadeIn(200);
// scroll last line into view
if(row && row[row.length-1] && row[row.length-1].scrollIntoView)
row[row.length-1].scrollIntoView();
}
}
// update user interface
function update(){
clearTimeout(tmr); // clear timer
if(settings.isAnonymous)
return;
// Do the actual Ajax call to the server-side Smartlet
// and update the user interface with conversation data
// if returned
smartlet.ajax(function(o){
addData(smartlet.get('data'));
// reset the refresh poll interval
tmr = setTimeout(update, settings.refreshInterval || 5000);
});
}
// send message to server-side chat room
function sendString(phrase, sysmsg){
smartlet.set('sysmsg', (sysmsg==true)); // is it a system message?
smartlet.set('phrase', phrase); // the line of text to send
speak.val(''); // clear the message textbox
update(); // update user-interface
smartlet.set('phrase',''); //clear message
}
// modify standard form submit handler for Ajax
frm.submit(function(event){
var s = speak.val().trim(); // get message from textbox
if(s && s.length)
sendString(s); // send it
return false; // suppress standard form submit handler
});
// setup event handler for Clear button
clear.click(function(event){
if(!(settings.confirmClear==true) || confirm(settings.confirmClearMessage || 'Clear window?')){
div.html(''); // clear the conversation pane
sendString(''); // send empty string to update user message index
}
return false;
});
// send join/create message at startup, depending on the message count in the current chat room.
setTimeout(function(){
sendString((settings.firstPost==-1) ? (settings.count ? settings.joinMessage : settings.createMessage) : '', true);
}, 1);
// disable user interface if no user logged on
if(settings.isAnonymous){
if(!settings.allowAnonymous)
$j('.sml_chat .Control').attr('disabled', true);
}
}
});
|
|