FIX légère optimisation du rafraichissement des messages
[euphorik.git] / js / euphorik.js
1 // coding: utf-8
2
3 /**
4 * Contient la base javascript pour le site euphorik.ch.
5 * Chaque page possède son propre fichier js nommé "page<nom de la page>.js".
6 * Auteur : GBurri
7 * Date : 6.11.2007
8 */
9
10
11 /**
12 * La configuration.
13 * Normalement 'const' à la place de 'var' mais non supporté par IE7.
14 */
15 var conf = {
16 nbMessageAffiche : 40, // (par page)
17 pseudoDefaut : "<nick>",
18 tempsAffichageMessageDialogue : 4000, // en ms
19 smiles : {
20 "smile" : [/:\)/g, /:-\)/g],
21 "bigsmile" : [/:D/g, /:-D/g],
22 "clin" : [/;\)/g, /;-\)/g],
23 "cool" : [/8\)/g, /8-\)/g],
24 "eheheh" : [/:P/g, /:-P/g],
25 "lol" : [/\[-lol\]/g],
26 "spliff" : [/\[-spliff\]/g],
27 "oh" : [/:o/g, /:O/g],
28 "heink" : [/\[-heink\]/g],
29 "hum" : [/\[-hum\]/g],
30 "boh" : [/\[-boh\]/g],
31 "sniff" : [/:\(/g, /:-\(/g],
32 "triste" : [/\[-triste\]/g],
33 "pascontent" : [/>\(/g, /&gt;\(/g],
34 "argn" : [/\[-argn\]/g],
35 "redface" : [/\[-redface\]/g],
36 "bunny" : [/\[-lapin\]/g],
37 "chat" : [/\[-chat\]/g],
38 "renne" : [/\[-renne\]/g],
39 "star" : [/\[-star\]/g],
40 "kirby" : [/\[-kirby\]/g],
41 "slurp" : [/\[-slurp\]/g],
42 "agreed" : [/\[-agreed\]/g],
43 "dodo" : [/\[-dodo\]/g],
44 "bn" : [/\[-bn\]/g]
45 }
46 }
47
48 ///////////////////////////////////////////////////////////////////////////////////////////////////
49
50 String.prototype.trim = function()
51 {
52 return jQuery.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
53 }
54
55 String.prototype.ltrim = function()
56 {
57 return this.replace(/^\s+/, "");
58 }
59
60 String.prototype.rtrim = function()
61 {
62 return this.replace(/\s+$/, "");
63 }
64
65 ///////////////////////////////////////////////////////////////////////////////////////////////////
66
67 /**
68 * Cette classe regroupe des fonctions utilitaires (helpers).
69 */
70 function Util()
71 {
72 $("#info .fermer").click(function(){
73 $("#info").slideUp(50)
74 })
75 }
76
77 var messageType = {informatif: 0, question: 1, erreur: 2}
78
79 /**
80 * Affiche une boite de dialogue avec un message à l'intérieur.
81 * @param message le message (string)
82 * @param type voir 'messageType'. par défaut messageType.informatif
83 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
84 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
85 */
86 Util.prototype.messageDialogue = function(message, type, boutons)
87 {
88 if (type == undefined)
89 type = messageType.informatif
90
91 if (this.timeoutMessageDialogue != undefined)
92 clearTimeout(this.timeoutMessageDialogue)
93
94 var fermer = function(){$("#info").slideUp(100)}
95 fermer()
96
97 $("#info .message").html(message)
98 switch(type)
99 {
100 case messageType.informatif : $("#info #icone").attr("class", "information"); break
101 case messageType.question : $("#info #icone").attr("class", "interrogation"); break
102 case messageType.erreur : $("#info #icone").attr("class", "exclamation"); break
103 }
104 $("#info .boutons").html("")
105 for (var b in boutons)
106 $("#info .boutons").append("<div>" + b + "</div>").find("div:last").click(boutons[b]).click(fermer)
107
108 $("#info").slideDown(200)
109 this.timeoutMessageDialogue = setTimeout(fermer, conf.tempsAffichageMessageDialogue)
110 }
111
112 /**
113 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
114 */
115 Util.prototype.jsonVersAction = function(json)
116 {
117 return {action : JSON.stringify(json) }
118 }
119
120 Util.prototype.md5 = function(chaine)
121 {
122 return hex_md5(chaine)
123 }
124
125 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
126 Util.prototype.setSelectionRange = function(input, selectionStart, selectionEnd)
127 {
128 if (input.setSelectionRange)
129 {
130 input.focus()
131 input.setSelectionRange(selectionStart, selectionEnd)
132 }
133 else if (input.createTextRange)
134 {
135 var range = input.createTextRange()
136 range.collapse(true)
137 range.moveEnd('character', selectionEnd)
138 range.moveStart('character', selectionStart)
139 range.select()
140 }
141 }
142
143 Util.prototype.setCaretToEnd = function(input)
144 {
145 this.setSelectionRange(input, input.value.length, input.value.length)
146 }
147 Util.prototype.setCaretToBegin = function(input)
148 {
149 this.setSelectionRange(input, 0, 0)
150 }
151 Util.prototype.setCaretToPos = function(input, pos)
152 {
153 this.setSelectionRange(input, pos, pos)
154 }
155 Util.prototype.selectString = function(input, string)
156 {
157 var match = new RegExp(string, "i").exec(input.value)
158 if (match)
159 {
160 this.setSelectionRange (input, match.index, match.index + match[0].length)
161 }
162 }
163 Util.prototype.replaceSelection = function(input, replaceString) {
164 if (input.setSelectionRange)
165 {
166 var selectionStart = input.selectionStart
167 var selectionEnd = input.selectionEnd
168 input.value = input.value.substring(0, selectionStart) + replaceString + input.value.substring(selectionEnd)
169
170 if (selectionStart != selectionEnd) // has there been a selection
171 this.setSelectionRange(input, selectionStart, selectionStart + replaceString.length)
172 else // set caret
173 this.setCaretToPos(input, selectionStart + replaceString.length)
174 }
175 else if (document.selection)
176 {
177 var range = document.selection.createRange();
178 if (range.parentElement() == input)
179 {
180 var isCollapsed = range.text == ''
181 range.text = replaceString
182 if (!isCollapsed)
183 {
184 // there has been a selection
185 // it appears range.select() should select the newly
186 // inserted text but that fails with IE
187 range.moveStart('character', -replaceString.length);
188 range.select();
189 }
190 }
191 }
192 }
193
194 Util.prototype.rot13 = function(chaine)
195 {
196 var ACode = 'A'.charCodeAt(0)
197 var aCode = 'a'.charCodeAt(0)
198 var MCode = 'M'.charCodeAt(0)
199 var mCode = 'm'.charCodeAt(0)
200 var ZCode = 'Z'.charCodeAt(0)
201 var zCode = 'z'.charCodeAt(0)
202
203 var f = function(ch, pos) {
204 if (pos == ch.length)
205 return ""
206
207 var c = ch.charCodeAt(pos);
208 return String.fromCharCode(
209 c +
210 (c >= ACode && c <= MCode || c >= aCode && c <= mCode ? 13 :
211 (c > MCode && c <= ZCode || c > mCode && c <= zCode ? -13 : 0))
212 ) + f(ch, pos + 1)
213 }
214 return f(chaine, 0)
215 }
216
217 ///////////////////////////////////////////////////////////////////////////////////////////////////
218
219 function Pages()
220 {
221 this.pageCourante = null
222 this.pages = {}
223 }
224
225 Pages.prototype.ajouterPage = function(page)
226 {
227 page.pages = this // la magie des langages dynamiques : le foutoire
228 this.pages[page.nom] = page
229 }
230
231 Pages.prototype.afficherPage = function(nomPage, forcerChargement)
232 {
233 if (forcerChargement == undefined) forcerChargement = false
234
235 var page = this.pages[nomPage]
236 if (page == undefined || (!forcerChargement && page == this.pageCourante)) return
237
238 if (this.pageCourante != null && this.pageCourante.decharger)
239 this.pageCourante.decharger()
240
241 $("#menu div").removeClass("courante")
242 $("#menu div." + nomPage).addClass("courante")
243
244 this.pageCourante = page
245 $("#page").html(this.pageCourante.contenu()).removeClass().addClass(this.pageCourante.nom)
246
247 if (this.pageCourante.charger)
248 this.pageCourante.charger()
249 }
250
251 ///////////////////////////////////////////////////////////////////////////////////////////////////
252
253 function Formateur()
254 {
255 this.smiles = conf.smiles
256 this.protocoles = "http|https|ed2k"
257
258 this.regexUrl = new RegExp("(?:(?:" + this.protocoles + ")://|www\\.)[^ ]*", "gi")
259 this.regexImg = new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
260 this.regexDomaine = new RegExp("^(?:(?:" + this.protocoles + ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
261 this.regexTestProtocoleExiste = new RegExp("^(?:" + this.protocoles + ")://.*$", "i")
262 this.regexNomProtocole = new RegExp("^(.*?)://")
263 }
264
265 /**
266 * Formate un pseudo saise par l'utilisateur.
267 * @param pseudo le pseudo brut
268 * @return le pseudo filtré
269 */
270 Formateur.prototype.filtrerInputPseudo = function(pseudo)
271 {
272 return pseudo.replace(/{|}/g, "").trim()
273 }
274
275 Formateur.prototype.getSmilesHTML = function()
276 {
277 var XHTML = ""
278 for (var sNom in this.smiles)
279 {
280 XHTML += "<img class=\"" + sNom + "\" src=\"img/smileys/" + sNom + ".gif\" />"
281 }
282 return XHTML
283 }
284
285 /**
286 * Formatage complet d'un texte.
287 * @M le message
288 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
289 */
290 Formateur.prototype.traitementComplet = function(M, pseudo)
291 {
292 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.remplacerBalisesHTML(M), pseudo)))
293 }
294
295 /**
296 * Transforme les liens en entités clickables.
297 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
298 * "{5F}" ou 5F est la racine de la conversation.
299 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
300 */
301 Formateur.prototype.traiterLiensConv = function(M)
302 {
303 return M.replace(
304 /\{\w+\}/g,
305 function(lien)
306 {
307 return "<span class=\"lienConv\">" + lien + "</span>"
308 }
309 )
310 }
311
312 /**
313 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
314 * moyenne su échantillon : 234ms
315 */
316 Formateur.prototype.traiterSmiles = function(M)
317 {
318 for (var sNom in this.smiles)
319 {
320 ss = this.smiles[sNom]
321 for (var i = 0; i < ss.length; i++)
322 M = M.replace(ss[i], "<img src=\"img/smileys/" + sNom + ".gif\" />")
323 }
324 return M
325 }
326
327 Formateur.prototype.remplacerBalisesHTML = function(M)
328 {
329 return M.replace(/</g, "&lt;").replace(/>/g, "&gt;")
330 }
331
332 Formateur.prototype.traiterURL = function(M, pseudo)
333 {
334 thisFormateur = this
335
336 var traitementUrl = function(url)
337 {
338 // si ya pas de protocole on rajoute "http://"
339 if (!thisFormateur.regexTestProtocoleExiste.test(url))
340 url = "http://" + url
341 var extension = thisFormateur.getShort(url)
342 return "<a " + (extension[1] ? "title=\"" + (pseudo == undefined ? "" : thisFormateur.traiterPourFenetreLightBox(pseudo, url) + ": ") + thisFormateur.traiterPourFenetreLightBox(M, url) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url + "\" >[" + extension[0] + "]</a>"
343 }
344 return M.replace(this.regexUrl, traitementUrl)
345 }
346
347 /**
348 * Renvoie une version courte de l'url.
349 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
350 */
351 Formateur.prototype.getShort = function(url)
352 {
353 var estUneImage = false
354 var versionShort = null
355 var rechercheImg = this.regexImg.exec(url)
356
357 if (rechercheImg != null)
358 {
359 versionShort = rechercheImg[1].toLowerCase()
360 if (versionShort == "jpeg") versionShort = "jpg" // jpeg -> jpg
361 estUneImage = true
362 }
363 else
364 {
365 var rechercheDomaine = this.regexDomaine.exec(url)
366 if (rechercheDomaine != null && rechercheDomaine.length >= 2)
367 versionShort = rechercheDomaine[1]
368 else
369 {
370 var nomProtocole = this.regexNomProtocole.exec(url)
371 if (nomProtocole != null && nomProtocole.length >= 2)
372 versionShort = nomProtocole[1]
373 }
374 }
375
376 return [versionShort == null ? "url" : versionShort, estUneImage]
377 }
378
379 /**
380 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
381 */
382 Formateur.prototype.traiterPourFenetreLightBox = function(M, urlCourante)
383 {
384 thisFormateur = this
385 var traitementUrl = function(url)
386 {
387 return "[" + thisFormateur.getShort(url)[0] + (urlCourante == url ? "*" : "") + "]"
388 }
389
390 return this.remplacerBalisesHTML(M).replace(this.regexUrl, traitementUrl)
391 }
392
393
394 ///////////////////////////////////////////////////////////////////////////////////////////////////
395
396 // les statuts possibes du client
397 var statutType = {
398 // mode enregistré, peut poster des messages et modifier son profile
399 auth_registered : 0,
400 // mode identifié, peut poster des messages mais n'a pas accès au profile
401 auth_not_registered : 1,
402 // mode déconnecté, ne peut pas poster de message
403 deconnected : 2
404 }
405
406 function Client(util)
407 {
408 this.util = util
409
410 this.cookie = null
411 this.regexCookie = new RegExp("^cookie=([^;]*)")
412
413 // données personnels
414 this.resetDonneesPersonnelles()
415
416 this.setStatut(statutType.deconnected)
417 }
418
419 Client.prototype.resetDonneesPersonnelles = function()
420 {
421 this.id = 0
422 this.pseudo = conf.pseudoDefaut
423 this.login = ""
424 this.password = ""
425 this.email = ""
426 this.css = $("link#cssPrincipale").attr("href")
427 this.nickFormat = "nick"
428 this.cookie = undefined
429
430 this.pagePrincipale = 1
431 this.ekMaster = false
432
433 // les conversations, une conversation est un objet possédant les attributs suivants :
434 // - racine (entier)
435 // - page (entier)
436 this.conversations = new Array()
437 }
438
439 Client.prototype.setCss = function(css)
440 {
441 if (this.css == css || css == "")
442 return
443
444 this.css = css
445 $("link#cssPrincipale").attr("href", this.css)
446 this.majMenu()
447 }
448
449 Client.prototype.pageSuivante = function(numConv)
450 {
451 if (numConv < 0 && this.pagePrincipale > 1)
452 this.pagePrincipale -= 1
453 else if (this.conversations[numConv].page > 1)
454 this.conversations[numConv].page -= 1
455 }
456
457 Client.prototype.pagePrecedente = function(numConv)
458 {
459 if (numConv < 0)
460 this.pagePrincipale += 1
461 else
462 this.conversations[numConv].page += 1
463 }
464
465 /**
466 * Définit la première page pour la conversation donnée.
467 * @return true si la page a changé sinon false
468 */
469 Client.prototype.goPremierePage = function(numConv)
470 {
471 if (numConv < 0)
472 {
473 if (this.pagePrincipale == 1)
474 return false
475 this.pagePrincipale = 1
476 }
477 else
478 {
479 if (this.conversations[numConv].page == 1)
480 return false
481 this.conversations[numConv].page = 1
482 }
483 return true
484 }
485
486 /**
487 * Ajoute une conversation à la vue de l'utilisateur.
488 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
489 * @param racines la racine de la conversation (integer)
490 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
491 */
492 Client.prototype.ajouterConversation = function(racine)
493 {
494 // vérification s'il elle n'existe pas déjà
495 for (var i = 0; i < this.conversations.length; i++)
496 if (this.conversations[i].root == racine)
497 return false
498
499 this.conversations.push({root : racine, page : 1})
500 return true
501 }
502
503 Client.prototype.supprimerConversation = function(num)
504 {
505 if (num < 0 || num >= this.conversations.length) return
506
507 // décalage TODO : supprimer le dernier élément
508 for (var i = num; i < this.conversations.length - 1; i++)
509 this.conversations[i] = this.conversations[i+1]
510 this.conversations.pop()
511 }
512
513 Client.prototype.getJSONLogin = function(login, password)
514 {
515 return {
516 "action" : "authentification",
517 "login" : login,
518 "password" : password
519 }
520 }
521
522 Client.prototype.getJSONLoginCookie = function()
523 {
524 return {
525 "action" : "authentification",
526 "cookie" : this.cookie
527 }
528 }
529
530 /**
531 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
532 * de s'autentifier avec (login, password).
533 */
534 Client.prototype.getJSONEnregistrement = function(login, password)
535 {
536 var mess = { "action" : "register" }
537
538 if (login != undefined && password != undefined)
539 {
540 mess["login"] = login
541 mess["password"] = password
542 }
543
544 return mess;
545 }
546
547 Client.prototype.getJSONConversations = function()
548 {
549 var conversations = new Array()
550 for (var i = 0; i < this.conversations.length; i++)
551 conversations.push({ "root" : this.conversations[i].root, "page" : this.conversations[i].page})
552 return conversations
553 }
554
555 Client.prototype.getJSONProfile = function()
556 {
557 return {
558 "action" : "set_profile",
559 "cookie" : this.cookie,
560 "login" : this.login,
561 "password" : this.password,
562 "nick" : this.pseudo,
563 "email" : this.email,
564 "css" : this.css,
565 "nick_format" : this.nickFormat,
566 "main_page" : this.pagePrincipale < 1 ? 1 : this.pagePrincipale,
567 "conversations" : this.getJSONConversations()
568 }
569 }
570
571 /**
572 * Renvoie null si pas définit.
573 */
574 Client.prototype.getCookie = function()
575 {
576 var cookie = this.regexCookie.exec(document.cookie)
577 if (cookie == null) this.cookie = null
578 else this.cookie = cookie[1]
579 }
580
581 Client.prototype.delCookie = function()
582 {
583 document.cookie = "cookie=; max-age=0"
584 }
585
586 Client.prototype.setCookie = function(cookie)
587 {
588 if (this.cookie == null)
589 return
590
591 document.cookie =
592 "cookie="+this.cookie+
593 "; max-age=" + (60 * 60 * 24 * 365)
594 }
595
596 Client.prototype.authentifie = function()
597 {
598 return this.statut == statutType.auth_registered || this.statut == statutType.auth_not_registered
599 }
600
601 Client.prototype.setStatut = function(statut)
602 {
603 // conversation en "enum" si en "string"
604 if (typeof(statut) == "string")
605 {
606 statut =
607 statut == "auth_registered" ?
608 statutType.auth_registered :
609 (statut == "auth_not_registered" ? statutType.auth_not_registered : statutType.deconnected)
610 }
611
612 if (statut == this.statut) return
613
614 this.statut = statut
615 this.majMenu()
616 }
617
618 /**
619 * Effectue la connexion vers le serveur.
620 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
621 * S'il existe un cookie en local on s'authentifie directement avec lui.
622 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
623 */
624 Client.prototype.connexionCookie = function()
625 {
626 this.getCookie()
627 if (this.cookie == null) return false;
628 return this.connexion(this.getJSONLoginCookie())
629 }
630
631 Client.prototype.connexionLogin = function(login, password)
632 {
633 return this.connexion(this.getJSONLogin(login, password))
634 }
635
636 Client.prototype.enregistrement = function(login, password)
637 {
638 if (this.authentifie())
639 {
640 this.login = login
641 this.password = password
642 if(this.flush())
643 {
644 this.setStatut(statutType.auth_registered)
645 return true
646 }
647 return false
648 }
649 else
650 {
651 return this.connexion(this.getJSONEnregistrement(login, password))
652 }
653 }
654
655 Client.prototype.connexion = function(messageJson)
656 {
657 ;;; dumpObj(messageJson)
658 thisClient = this
659 jQuery.ajax(
660 {
661 async: false,
662 type: "POST",
663 url: "request",
664 dataType: "json",
665 data: this.util.jsonVersAction(messageJson),
666 success:
667 function(data)
668 {
669 ;;; dumpObj(data)
670 if (data["reply"] == "error")
671 thisClient.util.messageDialogue(data["error_message"])
672 else
673 thisClient.chargerDonnees(data)
674 }
675 }
676 )
677 return this.authentifie()
678 }
679
680 Client.prototype.deconnexion = function()
681 {
682 this.flush(true)
683 this.delCookie()
684 this.resetDonneesPersonnelles()
685 this.setStatut(statutType.deconnected) // deconnexion
686 }
687
688 Client.prototype.chargerDonnees = function(data)
689 {
690 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
691 // de l'état ekMaster
692 this.ekMaster = data["ek_master"] != undefined ? data["ek_master"] : false
693
694 this.setStatut(data["status"])
695
696 if (this.authentifie())
697 {
698 this.cookie = data["cookie"]
699 this.setCookie()
700
701 this.id = data["id"]
702 this.login = data["login"]
703 this.pseudo = data["nick"]
704 this.email = data["email"]
705 this.setCss(data["css"])
706 this.nickFormat = data["nick_format"]
707
708 // la page de la conversation principale
709 this.pagePrincipale = data["main_page"] == undefined ? 1 : data["main_page"]
710
711 // les conversations
712 this.conversations = data["conversations"]
713 }
714 }
715
716 /**
717 * Met à jour les données personne sur serveur.
718 * @param async de manière asynchrone ? défaut = true
719 * @return false si le flush n'a pas pû se faire sinon true
720 */
721 Client.prototype.flush = function(async)
722 {
723 if (async == undefined)
724 async = false
725
726 if (!this.authentifie())
727 return false
728
729 var thisClient = this
730 var ok = true
731
732 ;;; dumpObj(this.getJSONProfile())
733 jQuery.ajax(
734 {
735 async: async,
736 type: "POST",
737 url: "request",
738 dataType: "json",
739 data: this.util.jsonVersAction(this.getJSONProfile()),
740 success:
741 function(data)
742 {
743 ;;; dumpObj(data)
744 if (data["reply"] == "error")
745 {
746 thisClient.util.messageDialogue(data["error_message"])
747 ok = false
748 }
749 }
750 }
751 )
752
753 return ok
754 }
755
756 Client.prototype.majMenu = function()
757 {
758 // TODO : à virer : ne plus changer de style de display ... spa beau .. ou trouver une autre méthode
759 var displayType = this.css == "css/3/euphorik.css" ? "block" : "inline" //this.client
760
761 $("#menu .admin").css("display", this.ekMaster ? "inline" : "none")
762
763 // met à jour le menu
764 if (this.statut == statutType.auth_registered)
765 {
766 $("#menu .profile").css("display", displayType).text("profile")
767 $("#menu .logout").css("display", displayType)
768 $("#menu .register").css("display", "none")
769 }
770 else if (this.statut == statutType.auth_not_registered)
771 {
772 $("#menu .profile").css("display", "none")
773 $("#menu .logout").css("display", displayType)
774 $("#menu .register").css("display", displayType)
775 }
776 else
777 {
778 $("#menu .profile").css("display", displayType).text("login")
779 $("#menu .logout").css("display", "none")
780 $("#menu .register").css("display", displayType)
781 }
782 }
783
784 Client.prototype.slap = function(userId, raison)
785 {
786 var thisClient = this
787
788 jQuery.ajax({
789 type: "POST",
790 url: "request",
791 dataType: "json",
792 data: this.util.jsonVersAction(
793 {
794 "action" : "slap",
795 "cookie" : thisClient.cookie,
796 "user_id" : userId,
797 "reason" : raison
798 }),
799 success:
800 function(data)
801 {
802 if (data["reply"] == "error")
803 thisClient.util.messageDialogue(data["error_message"])
804 }
805 })
806 }
807
808 Client.prototype.ban = function(userId, raison, minutes)
809 {
810 var thisClient = this
811
812 // par défaut un ban correspond à 3 jours
813 if (typeof(minutes) == "undefined")
814 minutes = 60 * 24 * 3
815
816 jQuery.ajax({
817 type: "POST",
818 url: "request",
819 dataType: "json",
820 data: this.util.jsonVersAction(
821 {
822 "action" : "ban",
823 "cookie" : thisClient.cookie,
824 "duration" : minutes,
825 "user_id" : userId,
826 "reason" : raison
827 }),
828 success:
829 function(data)
830 {
831 if (data["reply"] == "error")
832 thisClient.util.messageDialogue(data["error_message"])
833 }
834 })
835 }
836
837 Client.prototype.kick = function(userId, raison)
838 {
839 this.ban(userId, raison, 15)
840 }
841
842 ///////////////////////////////////////////////////////////////////////////////////////////////////
843
844 /**
845 * classe permettant de gérer les événements (push serveur).
846 * @page la page
847 */
848 function PageEvent(page, util)
849 {
850 this.page = page
851 this.util = util
852
853 // l'objet JSONHttpRequest représentant la connexion d'attente
854 this.attenteCourante = null
855 }
856
857 /**
858 * Arrête l'attente courante s'il y en a une.
859 */
860 PageEvent.prototype.stopAttenteCourante = function()
861 {
862 if (this.attenteCourante != null)
863 this.attenteCourante.abort()
864 }
865
866 /**
867 * Attend un événement lié à la page.
868 * @funSend une fonction renvoyant les données json à envoyer
869 * @funReceive une fonction qui accepte un paramètre correspondant au données reçues
870 */
871 PageEvent.prototype.waitEvent = function(funSend, funReceive)
872 {
873 var thisPageEvent = this
874
875 this.stopAttenteCourante()
876
877 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veux dans l'ordre définit dans le protocole)
878 // TODO : ya pas mieux ?
879 var dataToSend =
880 {
881 "action" : "wait_event",
882 "page" : this.page
883 }
884 var poulpe = funSend()
885 for (v in poulpe)
886 dataToSend[v] = poulpe[v]
887
888 ;;; dumpObj(dataToSend)
889 this.attenteCourante = jQuery.ajax({
890 type: "POST",
891 url: "request",
892 dataType: "json",
893 data: this.util.jsonVersAction(dataToSend),
894 success:
895 function(data)
896 {
897 ;;; dumpObj(data)
898
899 funReceive(data)
900
901 // rappel de la fonction dans 100 ms
902 setTimeout(function(){ thisPageEvent.waitEvent(funSend, funReceive) }, 100);
903 },
904 error:
905 function(XMLHttpRequest, textStatus, errorThrown)
906 {
907 setTimeout(function(){ thisPageEvent.rafraichirMessages(funSend, funReceive) }, 1000);
908 }
909 })
910
911 }
912
913 ///////////////////////////////////////////////////////////////////////////////////////////////////
914
915 function initialiserListeStyles(client)
916 {
917 $("#menuCss").change(
918 function()
919 {
920 client.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
921 }
922 )
923 }
924
925 // charge dynamiquement le script de debug
926 ;;; jQuery.ajax({async : false, url : "js/debug.js", dataType : "script"})
927
928 // le main
929 $(document).ready(
930 function()
931 {
932 var util = new Util()
933 var client = new Client(util)
934 var pages = new Pages()
935 var formateur = new Formateur()
936
937 // connexion vers le serveur (utilise un cookie qui traine)
938 client.connexionCookie()
939
940 initialiserListeStyles(client)
941
942 // TODO : pourquoi $(document).unload ne fonctionne pas ?
943 $(window).unload(function(){client.flush()})
944
945 $("#menu .minichat").click(function(){ pages.afficherPage("minichat") })
946 $("#menu .admin").click(function(){ pages.afficherPage("admin") })
947 $("#menu .profile").click(function(){ pages.afficherPage("profile") })
948 $("#menu .logout").click(function(){
949 util.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType.question,
950 {"Oui" : function()
951 {
952 client.deconnexion();
953 pages.afficherPage("minichat", true)
954 },
955 "Non" : function(){}
956 }
957 )
958 })
959 $("#menu .register").click(function(){ pages.afficherPage("register") })
960 $("#menu .about").click(function(){ pages.afficherPage("about") })
961
962 pages.ajouterPage(new PageMinichat(client, formateur, util))
963 pages.ajouterPage(new PageAdmin(client, formateur, util))
964 pages.ajouterPage(new PageProfile(client, formateur, util))
965 pages.ajouterPage(new PageRegister(client, formateur, util))
966 pages.ajouterPage(new PageAbout(client, formateur, util))
967 pages.afficherPage("minichat")
968 }
969 )