////////////////////
//Test functions
////////////////////
function log(msg) {
//console.log(msg)
}
////////////////////
//Hash table
////////////////////
var statusMessage = new Array();
statusMessage[''] = "";
statusMessage['chat'] = "";
statusMessage['away'] = "Away";
statusMessage['xa'] = "Away";
statusMessage['dnd'] = "Busy";
var statusIcons = new Array();
statusIcons[''] = "available";
statusIcons['chat'] = "available";
statusIcons['away'] = "away";
statusIcons['xa'] = "away";
statusIcons['dnd'] = "dnd";
var chatIcons = new Array();
chatIcons[':)'] = "face-smile.png";
chatIcons[':('] = "face-sad.png";
chatIcons['(B)'] = "beer.png";
chatIcons['(C)'] = "clock.png";
chatIcons['(P)'] = "present.png";
chatIcons[':P']= "face-raspberry.png";
chatIcons[':Z']= "face-tired.png";
chatIcons['(R)']= "rain.png";
chatIcons['(S)']= "sun.png";
chatIcons[';)']= "face-wink.png";
////////////////////
//Connect functions
////////////////////
function connectToServerWithCookie(){
try {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.connect(user_jid, cookie, onConnect);
} catch (err) {
//"Handle errors"
return false;
}
}
//Password: Get from chatPassword param if exists, instead try to get from sessionStorage.
function connectToServerWithPassword(chatPassword){
//Get Password
if ((chatPassword!=null)&&(chatPassword!="")){
var password = chatPassword;
} else if ((window.sessionStorage)&&(sessionStorage.getItem("ss_user_pass") != null)) {
var password = sessionStorage.getItem("ss_user_pass");
} else {
return false;
}
try {
//Connect actual user to the chat
connection = new Strophe.Connection(BOSH_SERVICE);
connection.connect(user_jid, password, onConnect);
} catch (err) {
//"Handle errors"
return false;
}
return true;
}
////////////////////
//Reconnect button functions
////////////////////
var connectButtonTimer;
var periodBetweenAttempts=15; //(seg)
var connectButtonTimerCounter=periodBetweenAttempts;
function connectButtonTimerFunction(){
if(connectButtonTimerCounter < periodBetweenAttempts){
connectButtonTimerCounter++;
} else if (connectButtonTimerCounter == periodBetweenAttempts) {
$("#chat_header_title").html('<%=I18n.t('chat.disconnected')%>')
}
}
function requestConnectToChat(){
if (connectButtonTimerCounter > (periodBetweenAttempts-1)) {
connectButtonTimerCounter=0;
$("#chat_header_title").html('<%=I18n.t('chat.connecting')%>')
return true
} else {
return false
}
}
////////////////////
//Strophe functions
////////////////////
//Global variables
var userStatus = "chat";
var awayTimerPeriod = 16000;
var timerPeriod = 5000;
var refreshMinTime = 3*timerPeriod;
var awayTime = 300000;
var awayCounter = 0;
var timerCounter = 0;
var connection = null;
var userConnected = false;
var reconnectAttempts = 3;
var awayTimer;
var timer;
var requestContacts=false;
var cyclesToRefresh = (refreshMinTime/timerPeriod);
function onConnect(status) {
//Status.ERROR An error has occurred
//Status.CONNECTING The connection is currently being made
//Status.CONNFAIL The connection attempt failed
//Status.AUTHENTICATING The connection is authenticating
//Status.AUTHFAIL The authentication attempt failed
//Status.CONNECTED The connection has succeeded
//Status.DISCONNECTED The connection has been terminated
//Status.DISCONNECTING The connection is currently being terminated
//Status.ATTACHED The connection has been attached
log('Strophe onConnect callback call with status ' + status);
if (status == Strophe.Status.ATTACHED){
log('Strophe connection attached');
return;
}
if (status == Strophe.Status.AUTHENTICATING ){
log('Strophe connection AUTHENTICATING');
return;
}
if (status == Strophe.Status.CONNECTING) {
log('Strophe is connecting.');
return;
}
clearTimeout(initialTimer);
if (status == Strophe.Status.CONNFAIL) {
log('Strophe failed to connect.');
userConnected = false;
setTimeout ("onReconnect()", 3000);
} else if (status == Strophe.Status.AUTHFAIL) {
log('Strophe authentication fail.');
if ((window.sessionStorage)&&(sessionStorage.getItem("ss_user_pass") != null)){
sessionStorage.setItem("ss_user_pass",null);
}
userConnected = false;
} else if (status == Strophe.Status.ERROR) {
log('Strophe error.');
userConnected = false;
} else if (status == Strophe.Status.DISCONNECTED) {
log('Strophe is disconnected.');
userConnected = false;
clearTimeout(awayTimer);
setTimeout ("onReconnect()", 3000);
} else if (status == Strophe.Status.CONNECTED) {
log('Strophe is connected.');
log('Presenze stanza send for:' + connection.jid);
connection.addHandler(onMessage, null, 'message', null, null, null);
connection.addHandler(onPresence, null, 'presence', null, null, null);
//addHandler:(callback, namespace to match, stanza name, stanza type, stanza id , stanza from, options)
sendStatus(userStatus);
userConnected = true;
awayTimer = setInterval("awayTimerFunction()", awayTimerPeriod);
timer = setInterval("timerFunction()", timerPeriod);
}
updateChatWindow();
}
function onReconnect(){
if ((connection != null)&&(!userConnected)) {
if (reconnectAttempts>0) {
reconnectAttempts--;
connectToServer(null);
setTimeout ("onReconnect()", 9000);
} else {
//Notify issue to Rails App Server?
}
}
}
function onMessage(msg) {
var to = msg.getAttribute('to');
var from = msg.getAttribute('from');
var type = msg.getAttribute('type');
var elems = msg.getElementsByTagName('body');
if (type == "chat" && elems.length > 0) {
var body = elems[0];
var from_slug = from.split("@")[0];
var from_name = $("#" + from_slug).attr("name");
var from_jid = from_slug + "@" + domain;
if (typeof ($('div.user_presence[slug=' + from_slug + ']').attr('name')) == 'undefined') {
//No connectionBox for this user!
var from_name = from_slug;
refreshChatWindow();
} else {
showConnectionBoxFromSlug(from_slug);
var from_name = $('div.user_presence[slug=' + from_slug + ']').attr('name');
}
if (createChatBox(from_slug,from_name,from_jid,user_name,user_jid)) {
} else {
window[getChatVariableFromSlug(from_slug)].chatbox("option", "boxManager").toggleBox(true);
}
content = parseContent(Strophe.getText(body));
//Send message to chatBox and post-message functions.
$("#" + from_slug).chatbox("option", "boxManager").addMsg(from_name, content);
rotatePriority(from_slug);
blinkTitleOnMessage(from_name);
if (mustPlaySoundForChatWindow(window[getChatVariableFromSlug(from_slug)])){
playSound("onMessageAudio");
}
}
// we must return true to keep the handler alive.
// returning false would remove it after it finishes.
return true;
}
function onPresence(presence) {
//Check presence stanza type
ptype = $(presence).attr('type');
switch (ptype){
case undefined:
processAvailablePresenceStanza(presence)
break;
case "available":
processAvailablePresenceStanza(presence)
break;
case "unavailable":
processUnavailablePresenceStanza(presence)
break;
default :
//Stanza type not recognize
processAvailablePresenceStanza(presence)
}
return true;
}
function processAvailablePresenceStanza(presence){
from = $(presence).attr('from');
slug = from.split("@")[0];
if (slug != user_slug) {
if (getConnectionBoxFromSlug(slug)!=null){
status = $(presence).find('show').text();
setUserIconStatus(slug, status);
if (cacheConnectedUsers.indexOf(slug) != -1) {
showConnectionBoxFromSlug(slug);
}
} else {
setTimeout("refreshChatWindow()", 3000);
}
}
}
function processUnavailablePresenceStanza(presence){
from = $(presence).attr('from');
slug = from.split("@")[0];
if (slug != user_slug) {
if (getConnectionBoxFromSlug(slug)!=null){
hideConnectionBoxFromSlug(slug)
}
}
}
function sendChatMessage(from,to,text){
var type = "chat";
var body= $build("body");
body.t(text);
var message = $msg({to: to, from: from, type: 'chat'}).cnode(body.tree());
connection.send(message.tree());
resumeAwayTimerIfAway();
return true;
}
function authByCookie(){
var authMethod = '<%= SocialStream::Presence.auth_method %>';
return authMethod=="cookie";
}
function authByPassword(){
var authMethod = '<%= SocialStream::Presence.auth_method %>';
return authMethod=="password";
}
function ifCookie(){
return (!(typeof cookie == 'undefined'))
}
///////////////////////////////////////////////////////
// Parser functions
// Allow new features in chat msg like links, images, emoticons, ...
///////////////////////////////////////////////////////
//Patterns
var html_tag_pattern=/.*\<[^>]+>.*/g
var simple_word_pattern=/^[aA-zZ0-9]+$/g
var http_urls_pattern=/(http(s)?:\/\/)([aA-zZ0-9%=_&+?])+([./-][aA-zZ0-9%=_&+?]+)*[/]?/g
var www_urls_pattern = /(www[.])([aA-zZ0-9%=_&+?])+([./-][aA-zZ0-9%=_&+?]+)*[/]?/g
var icons_a_pattern=/\([A-Z]\)/g
var icons_b_pattern=/((:|;)([()A-Z]))/g
var youtube_video_pattern=/(http(s)?:\/\/)?(((youtu.be\/)([aA-zZ0-9]+))|((www.youtube.com\/watch\?v=)([aA-z0-9Z&=.])+))/g
function parseContent(content){
if (content.match(html_tag_pattern)!=null){
content = content.replace(/>/g, ">");
content = content.replace(/" + content + ""
}
words = content.split(" ");
for(i=0; i" + "";
}
function buildYoutubeVideoLink(url){
//Get youtube video id
var youtube_video_id=url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
var youtube_api_url = "http://gdata.youtube.com/feeds/api/videos/" + youtube_video_id
//Get info from the video
$.ajax({
type: "GET",
url: youtube_api_url,
cache: false,
dataType:'jsonp',
success: function(data){
var url_name = url;
var youtube_video_thumbnail = "";
//Video title
var video_title = $(data).find("media\\:title")
if (video_title.length > 0) {
//url_name = url + " (" + $(video_title).text() + ")";
url_name = $(video_title).text()
}
//Thumbnails
var thumbnails = $(data).find("media\\:thumbnail")
if (thumbnails.length>0){
var thumbnail_url = $(thumbnails[0]).attr("url")
if (thumbnail_url!=null){
youtube_video_thumbnail = "