summaryrefslogtreecommitdiff
path: root/static/pichat.js
blob: 87bca75ec5632c8435adc7deede1787ac1727fa7 (plain)
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
function handleMsgError(resp) {
    var respText = resp.responseText ? resp.responseText.trim() : false;
    if (respText  == 'UNKNOWN_USER') {
        alert("Can't send message! Please login.");
    } else if (respText) {
        alert("Cannot send message! (" + respText + ")");
    } else {
        alert("Cannot send message!");
    }
}

function escapeHtml(txt) {
    if (!txt) { return "" }
    else { return $("<span>").text(txt).html(); }
}

function buildUserDiv(user) {
    return '<div class="username"><a href="/u/' + escapeHtml(user) + '"><img src="/static/cat.jpeg" width="50" height="50">' + escapeHtml(user) + '</a></div>';
}

// http://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript
function linkify(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
    return text.replace(exp,"<a href='$1'>$1</a>");
}

// http://snippets.dzone.com/posts/show/6995
var URLRegex = /((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i;
var PicRegex = /\.(jpg|jpeg|png|gif|bmp)$/i;

function buildMsgContent(content) {
    content = $.trim(content);
    var match = URLRegex.exec(content)
    if (match && PicRegex.test(match[0])) {
        return '<a href="' + match[0] + '" target="_blank">'
            + '<img src="'+ match[0] + '" /></a>';
    } else {
        return linkify(escapeHtml(content));
    }
}    

function buildMessageDiv(msg) {
    var nick = escapeHtml(msg.nick);
    return '<div class="msgDiv"><b><a href="/u/' + nick + ' ">' + nick + '</a>: </b>'
        + buildMsgContent(msg.content) + '</div>';
}

function submitMessage() {
    var content = $('#msgInput').val();
    if (content ==  '') { return; }
    
    $('#msgInput, #msgSubmit').attr('disabled', 'disabled');    
    var onSuccess = function(json) {
        $('#msgInput, #msgSubmit').removeAttr('disabled');
        $('#msgInput').val('');
    };

    var onError = function(resp, textStatus, errorThrown) {        
        $('#msgInput, #msgSubmit').removeAttr('disabled');
        handleMsgError(resp);
    };

   $.ajax({
       type: 'GET',
       timeout: 5000,
       url: 'msg',
       data: { 'content': content },
       cache: false,
       dataType: 'json',
       success: onSuccess,
       error: onError
   });
    
    updateUI([{ 'nick': Nick || "me", 'content': content}], null);
}

function ifEnter(fn) {
    return function(e) {
        if (e.keyCode == 13) { fn(); }
    };
}

function isScrolledToBottom(div) {
    return Math.abs(div.scrollTop - (div.scrollHeight - div.offsetHeight)) <= 3;
}

function scrollToBottom(div) {
    div.scrollTop = div.scrollHeight;
}

// Give images time to start loading before scrolling.
// Needed until server knows size of images.
function delayedScrollToBottom(delay) {
    setTimeout(scrollToBottom, delay, $('#messageList')[0]);
}

function updateUI(msgs, users) {
    if (msgs && msgs.length > 0) {      
        var msgStr = $.map(msgs, buildMessageDiv).join('');
        var wasScrolledToBottom = isScrolledToBottom($('#messageList')[0]);
        $('#messageList').append(msgStr);
        
        if (wasScrolledToBottom) {
            delayedScrollToBottom(500);
        }
    }
    if (users && users.length > 0) {
        $("#userList").html($.map(users, buildUserDiv).join(''));
    }
}

function refresh() {
    var onSuccess = function(json) {
        var messages = $.grep(
            json.messages,
            function(m) { return m.nick != Nick });
        updateUI(messages, json.users);
        setTimeout(refresh, 1000);
    };
    var onError = function(resp, textStatus, errorThrown) {
        setTimeout(refresh, 1000);
    };

    $.ajax({
        type: 'GET',
        timeout: 5000,
        url: 'refresh',
        cache: false,
        dataType: 'json',
        success: onSuccess,
        error: onError
    });
}

function initChat() {
    $('.msgDiv .content').each(function() {
        var t = $(this);
        t.html(buildMsgContent(t.text()));
    });

    $('#msgInput').keyup(ifEnter(submitMessage));
    $('msgSubmit').click(submitMessage);

    delayedScrollToBottom(500);
    setTimeout(refresh, 1000);
}

function initProfile() {
    $('.logged-dump .content').each(function() {
        var t = $(this);
        t.html(buildMsgContent(t.text()));
    });

    var onSubmit = function(original_element, edit, old) {
        edit = $.trim(edit);
        if (edit == old) { return old };
        // MAJOR TODO: Prevent entering script tags
        if (original_element == 'avatar' && edit.indexOf("<") != -1) {
            return old;
        }
        $.ajax({
            type: "GET",
            timeout: 5000,
            url: "/update-profile",
            data: { 'attr': original_element, 'val': edit }
        });
        if (original_element == 'avatar') {            
            var s = '<img id="avatarPic" src="' + edit + '" width="150" />';
            $('#avatarPic').replaceWith(s);
        }
        return escapeHtml(edit);
    };

    var opt = { 'default_text': 'Enter here!',
                'callback': onSubmit,
                'field_type': 'text',
                'callbackShowErrors': false };    
    $('#avatar.editable').editInPlace(opt);


    opt['field_type'] = 'textarea';
    $('#contact.editable, #bio.editable').editInPlace(opt);

};