chatboxmanager.js
2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Need this to make IE happy
// see http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
var chatboxManager = function() {
// list of all opened boxes
var boxList = new Array();
// list of boxes shown on the page
var showList = new Array();
// list of first names, for in-page demo
var nameList = new Array();
var config = {
width : 200, //px
gap : 20,
maxBoxes : 4,
messageSent : function(id,dest, msg) {
// override this
$("#" + id).chatbox("option", "boxManager").addMsg(dest, msg);
}
};
var init = function(options) {
$.extend(config, options)
};
var delBox = function(id) {
// TODO
};
var getNextOffset = function() {
return (config.width + config.gap) * showList.length;
};
var boxClosedCallback = function(id) {
// close button in the titlebar is clicked
var idx = showList.indexOf(id);
if(idx != -1) {
showList.splice(idx, 1);
diff = config.width + config.gap;
for(var i = idx; i < showList.length; i++) {
offset = $("#" + showList[i]).chatbox("option", "offset");
$("#" + showList[i]).chatbox("option", "offset", offset - diff);
}
}
else {
alert("should not happen: " + id);
}
};
// caller should guarantee the uniqueness of id
var addBox = function(id, user, name) {
var idx1 = showList.indexOf(id);
var idx2 = boxList.indexOf(id);
if(idx1 != -1) {
// found one in show box, do nothing
}
else if(idx2 != -1) {
// exists, but hidden
// show it and put it back to showList
$("#"+id).chatbox("option", "offset", getNextOffset());
var manager = $("#"+id).chatbox("option", "boxManager");
manager.toggleBox();
showList.push(id);
}
else{
var el = document.createElement('div');
el.setAttribute('id', id);
$(el).chatbox({id : id,
user : user,
title : user.first_name + " " + user.last_name,
hidden : false,
width : config.width,
offset : getNextOffset(),
messageSent : messageSentCallback,
boxClosed : boxClosedCallback
});
boxList.push(id);
showList.push(id);
nameList.push(user.first_name);
}
};
var messageSentCallback = function(id, user, msg) {
var idx = boxList.indexOf(id);
config.messageSent(id,nameList[idx], msg);
};
// not used in demo
var dispatch = function(id, user, msg) {
$("#" + id).chatbox("option", "boxManager").addMsg(user.first_name, msg);
}
return {
init : init,
addBox : addBox,
delBox : delBox,
dispatch : dispatch
};
}();