REPORT de la branche 1.0 (tag 1.0.1)
[euphorik.git] / js / euphorik.js
1 // coding: utf-8
2 // Copyright 2008 Grégory Burri
3 //
4 // This file is part of Euphorik.
5 //
6 // Euphorik is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // Euphorik is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with Euphorik. If not, see <http://www.gnu.org/licenses/>.
18
19 /**
20 * Contient la base javascript pour le site euphorik.ch.
21 * Chaque page possède son propre fichier js nommé "page<nom de la page>.js".
22 * Auteur : GBurri
23 * Date : 6.11.2007
24 */
25
26
27 /**
28 * La configuration.
29 * Normalement 'const' à la place de 'var' mais non supporté par IE7.
30 */
31 var conf = {
32 nbMessageAffiche : 40, // (par page)
33 pseudoDefaut : "<nick>",
34 tempsAffichageMessageDialogue : 4000, // en ms
35 tempsKick : 15, // en minute
36 tempsBan : 60 * 24 * 3, // en minutes (3jours)
37 smiles : {
38 "smile" : [/:\)/g, /:-\)/g],
39 "bigsmile" : [/:D/g, /:-D/g],
40 "clin" : [/;\)/g, /;-\)/g],
41 "cool" : [/8\)/g, /8-\)/g],
42 "eheheh" : [/:P/g, /:-P/g],
43 "lol" : [/\[-lol\]/g],
44 "spliff" : [/\[-spliff\]/g],
45 "oh" : [/:o/g, /:O/g],
46 "heink" : [/\[-heink\]/g],
47 "hum" : [/\[-hum\]/g],
48 "boh" : [/\[-boh\]/g],
49 "sniff" : [/:\(/g, /:-\(/g],
50 "triste" : [/\[-triste\]/g],
51 "pascontent" : [/>\(/g, /&gt;\(/g],
52 "argn" : [/\[-argn\]/g],
53 "redface" : [/\[-redface\]/g],
54 "bunny" : [/\[-lapin\]/g],
55 "chat" : [/\[-chat\]/g],
56 "renne" : [/\[-renne\]/g],
57 "star" : [/\[-star\]/g],
58 "kirby" : [/\[-kirby\]/g],
59 "slurp" : [/\[-slurp\]/g],
60 "agreed" : [/\[-agreed\]/g],
61 "dodo" : [/\[-dodo\]/g],
62 "bn" : [/\[-bn\]/g]
63 }
64 }
65
66 ///////////////////////////////////////////////////////////////////////////////////////////////////
67
68 String.prototype.trim = function()
69 {
70 return jQuery.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
71 }
72
73 String.prototype.ltrim = function()
74 {
75 return this.replace(/^\s+/, "");
76 }
77
78 String.prototype.rtrim = function()
79 {
80 return this.replace(/\s+$/, "");
81 }
82
83 ///////////////////////////////////////////////////////////////////////////////////////////////////
84
85 /**
86 * Cette classe regroupe des fonctions utilitaires (helpers).
87 * @formateur est permet de formater les messages affichés à l'aide de messageDialogue (facultatif)
88 */
89 function Util(formateur)
90 {
91 $("#info .fermer").click(function(){
92 $("#info").slideUp(50)
93 })
94
95 $("body").append('<div id="flecheBulle"></div>').append('<div id="messageBulle"><p></p></div>')
96
97 this.formateur = formateur
98 this.bulleActive = true
99 }
100
101 var messageType = {informatif: 0, question: 1, erreur: 2}
102
103 /**
104 * Affiche une boite de dialogue avec un message à l'intérieur.
105 * @param message le message (string)
106 * @param type voir 'messageType'. par défaut messageType.informatif
107 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
108 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
109 * @param formate faut-il formaté le message ? true par défaut
110 */
111 Util.prototype.messageDialogue = function(message, type, boutons, formate)
112 {
113 var thisUtil = this
114
115 if (type == undefined)
116 type = messageType.informatif
117
118 if (formate == undefined)
119 formate = true
120
121 if (this.timeoutMessageDialogue != undefined)
122 clearTimeout(this.timeoutMessageDialogue)
123
124 var fermer = function(){$("#info").slideUp(100)}
125 fermer()
126
127 $("#info .message").html(thisUtil.formateur == undefined || !formate ? message : thisUtil.formateur.traitementComplet(message))
128 switch(type)
129 {
130 case messageType.informatif : $("#info #icone").attr("class", "information"); break
131 case messageType.question : $("#info #icone").attr("class", "interrogation"); break
132 case messageType.erreur : $("#info #icone").attr("class", "exclamation"); break
133 }
134 $("#info .boutons").html("")
135 for (var b in boutons)
136 $("#info .boutons").append("<div>" + b + "</div>").find("div:last").click(boutons[b]).click(fermer)
137
138 $("#info").slideDown(200)
139 this.timeoutMessageDialogue = setTimeout(fermer, conf.tempsAffichageMessageDialogue)
140 }
141
142 /**
143 * Affiche un info bulle lorsque le curseur survole l'élément donné.
144 * FIXME : le width de element ne tient pas compte du padding !?
145 */
146 Util.prototype.infoBulle = function(message, element)
147 {
148 var thisUtil = this
149
150 var cacherBulle = function()
151 {
152 $("#flecheBulle").hide()
153 $("#messageBulle").hide()
154 }
155
156 element.hover(
157 function(e)
158 {
159 if (!thisUtil.bulleActive)
160 return
161
162 var m = $("#messageBulle")
163 var f = $("#flecheBulle")
164
165 // remplie le paragraphe de la bulle avec le message
166 $("p", m).html(message)
167
168 // réinitialise la position, évite le cas ou la boite est collé à droite et remplie avec un texte la faisant dépassé
169 // dans ce cas la hauteur n'est pas calculé correctement
170 m.css("top", 0).css("left", 0)
171
172 var positionFleche = {
173 left : element.offset().left + element.width() / 2 - f.width() / 2,
174 top : element.offset().top - f.height()
175 }
176 var positionMessage = {
177 left : element.offset().left + element.width() / 2 - m.width() / 2,
178 top : element.offset().top - f.height() - m.height()
179 }
180 var depassementDroit = (positionMessage.left + m.width()) - $("body").width()
181 if (depassementDroit > 0)
182 positionMessage.left -= depassementDroit
183 else
184 {
185 if (positionMessage.left < 0)
186 positionMessage.left = 0
187 }
188
189 m.css("top", positionMessage.top).css("left", positionMessage.left).show()
190 f.css("top", positionFleche.top).css("left", positionFleche.left).show()
191 },
192 cacherBulle
193 ).click(cacherBulle)
194 }
195
196 /**
197 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
198 */
199 Util.prototype.jsonVersAction = function(json)
200 {
201 return {action : JSON.stringify(json) }
202 }
203
204 Util.prototype.md5 = function(chaine)
205 {
206 return hex_md5(chaine)
207 }
208
209 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
210 Util.prototype.setSelectionRange = function(input, selectionStart, selectionEnd)
211 {
212 if (input.setSelectionRange)
213 {
214 input.focus()
215 input.setSelectionRange(selectionStart, selectionEnd)
216 }
217 else if (input.createTextRange)
218 {
219 var range = input.createTextRange()
220 range.collapse(true)
221 range.moveEnd('character', selectionEnd)
222 range.moveStart('character', selectionStart)
223 range.select()
224 }
225 }
226
227 Util.prototype.setCaretToEnd = function(input)
228 {
229 this.setSelectionRange(input, input.value.length, input.value.length)
230 }
231 Util.prototype.setCaretToBegin = function(input)
232 {
233 this.setSelectionRange(input, 0, 0)
234 }
235 Util.prototype.setCaretToPos = function(input, pos)
236 {
237 this.setSelectionRange(input, pos, pos)
238 }
239 Util.prototype.selectString = function(input, string)
240 {
241 var match = new RegExp(string, "i").exec(input.value)
242 if (match)
243 {
244 this.setSelectionRange (input, match.index, match.index + match[0].length)
245 }
246 }
247 Util.prototype.replaceSelection = function(input, replaceString) {
248 if (input.setSelectionRange)
249 {
250 var selectionStart = input.selectionStart
251 var selectionEnd = input.selectionEnd
252 input.value = input.value.substring(0, selectionStart) + replaceString + input.value.substring(selectionEnd)
253
254 if (selectionStart != selectionEnd) // has there been a selection
255 this.setSelectionRange(input, selectionStart, selectionStart + replaceString.length)
256 else // set caret
257 this.setCaretToPos(input, selectionStart + replaceString.length)
258 }
259 else if (document.selection)
260 {
261 input.focus()
262 var range = document.selection.createRange()
263 if (range.parentElement() == input)
264 {
265 var isCollapsed = range.text == ''
266 range.text = replaceString
267 if (!isCollapsed)
268 {
269 range.moveStart('character', -replaceString.length);
270 }
271 }
272 }
273 }
274
275 Util.prototype.rot13 = function(chaine)
276 {
277 var ACode = 'A'.charCodeAt(0)
278 var aCode = 'a'.charCodeAt(0)
279 var MCode = 'M'.charCodeAt(0)
280 var mCode = 'm'.charCodeAt(0)
281 var ZCode = 'Z'.charCodeAt(0)
282 var zCode = 'z'.charCodeAt(0)
283
284 var f = function(ch, pos) {
285 if (pos == ch.length)
286 return ""
287
288 var c = ch.charCodeAt(pos);
289 return String.fromCharCode(
290 c +
291 (c >= ACode && c <= MCode || c >= aCode && c <= mCode ? 13 :
292 (c > MCode && c <= ZCode || c > mCode && c <= zCode ? -13 : 0))
293 ) + f(ch, pos + 1)
294 }
295 return f(chaine, 0)
296 }
297
298 ///////////////////////////////////////////////////////////////////////////////////////////////////
299
300 function Pages()
301 {
302 this.pageCourante = null
303 this.pages = {}
304 }
305
306 /**
307 * Accepte soit un objet soit un string.
308 * un string correspond au nom de la page, par exemple : "page" -> "page.html"
309 */
310 Pages.prototype.ajouterPage = function(page)
311 {
312 if (typeof page == "string")
313 {
314 this.pages[page] = page
315 }
316 else
317 {
318 page.pages = this // la magie des langages dynamiques : le foutoire
319 this.pages[page.nom] = page
320 }
321 }
322
323 Pages.prototype.afficherPage = function(nomPage, forcerChargement)
324 {
325 if (forcerChargement == undefined) forcerChargement = false
326
327 var page = this.pages[nomPage]
328 if (page == undefined || (!forcerChargement && page == this.pageCourante)) return
329
330 if (this.pageCourante != null && this.pageCourante.decharger)
331 this.pageCourante.decharger()
332
333 $("#menu li").removeClass("courante")
334 $("#menu li." + nomPage).addClass("courante")
335
336 this.pageCourante = page
337 var contenu = ""
338 if (typeof page == "string")
339 $.ajax({async: false, url: "pages/" + page + ".html", success : function(page) { contenu += page }})
340 else
341 contenu += this.pageCourante.contenu()
342 $("#page").html(contenu).removeClass().addClass(this.pageCourante.nom)
343
344 if (this.pageCourante.charger)
345 this.pageCourante.charger()
346 }
347
348 ///////////////////////////////////////////////////////////////////////////////////////////////////
349
350 /**
351 * Classe permettant de formater du texte par exemple pour la substitution des liens dans les
352 * message par "[url]".
353 * TODO : améliorer l'efficacité des méthods notamment lié au smiles.
354 */
355 function Formateur()
356 {
357 this.smiles = conf.smiles
358 this.protocoles = "http|https|ed2k"
359
360 this.regexUrl = new RegExp("(?:(?:" + this.protocoles + ")://|www\\.)[^ ]*", "gi")
361 this.regexImg = new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
362 this.regexDomaine = new RegExp("^(?:(?:" + this.protocoles + ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
363 this.regexTestProtocoleExiste = new RegExp("^(?:" + this.protocoles + ")://.*$", "i")
364 this.regexNomProtocole = new RegExp("^(.*?)://")
365 }
366
367 /**
368 * Formate un pseudo saise par l'utilisateur.
369 * @param pseudo le pseudo brut
370 * @return le pseudo filtré
371 */
372 Formateur.prototype.filtrerInputPseudo = function(pseudo)
373 {
374 return pseudo.replace(/{|}/g, "").trim()
375 }
376
377 Formateur.prototype.getSmilesHTML = function()
378 {
379 var XHTML = ""
380 for (var sNom in this.smiles)
381 {
382 XHTML += "<img class=\"" + sNom + "\" src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />"
383 }
384 return XHTML
385 }
386
387 /**
388 * Formatage complet d'un texte.
389 * @M le message
390 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
391 */
392 Formateur.prototype.traitementComplet = function(M, pseudo)
393 {
394 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.traiterWikiSyntaxe(this.remplacerBalisesHTML(M)), pseudo)))
395 }
396
397 /**
398 * Transforme les liens en entités clickables.
399 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
400 * "{5F}" ou 5F est la racine de la conversation.
401 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
402 */
403 Formateur.prototype.traiterLiensConv = function(M)
404 {
405 return M.replace(
406 /\{\w+\}/g,
407 function(lien)
408 {
409 return "<span class=\"lienConv\">" + lien + "</span>"
410 }
411 )
412 }
413
414 /**
415 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
416 * moyenne sur échantillon : 234ms
417 */
418 Formateur.prototype.traiterSmiles = function(M)
419 {
420 for (var sNom in this.smiles)
421 {
422 ss = this.smiles[sNom]
423 for (var i = 0; i < ss.length; i++)
424 M = M.replace(ss[i], "<img src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />")
425 }
426 return M
427 }
428
429 Formateur.prototype.remplacerBalisesHTML = function(M)
430 {
431 return M.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
432 }
433
434 Formateur.prototype.traiterURL = function(M, pseudo)
435 {
436 thisFormateur = this
437
438 var traitementUrl = function(url)
439 {
440 // si ya pas de protocole on rajoute "http://"
441 if (!thisFormateur.regexTestProtocoleExiste.test(url))
442 url = "http://" + url
443 var extension = thisFormateur.getShort(url)
444 return "<a " + (extension[1] ? "title=\"" + (pseudo == undefined ? "" : thisFormateur.traiterPourFenetreLightBox(pseudo, url) + ": ") + thisFormateur.traiterPourFenetreLightBox(M, url) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url + "\" >[" + extension[0] + "]</a>"
445 }
446 return M.replace(this.regexUrl, traitementUrl)
447 }
448
449 /**
450 * Formatage en utilisant un sous-ensemble des règles de mediwiki.
451 * par exemple ''italic'' devient <i>italic</i>
452 */
453 Formateur.prototype.traiterWikiSyntaxe = function(M)
454 {
455 return M.replace(
456 /'''(.*?)'''/g,
457 function(texte, capture)
458 {
459 return "<b>" + capture + "</b>"
460 }
461 ).replace(
462 /''(.*?)''/g,
463 function(texte, capture)
464 {
465 return "<i>" + capture + "</i>"
466 }
467 )
468 }
469
470 /**
471 * Renvoie une version courte de l'url.
472 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
473 */
474 Formateur.prototype.getShort = function(url)
475 {
476 var estUneImage = false
477 var versionShort = null
478 var rechercheImg = this.regexImg.exec(url)
479
480 if (rechercheImg != null)
481 {
482 versionShort = rechercheImg[1].toLowerCase()
483 if (versionShort == "jpeg") versionShort = "jpg" // jpeg -> jpg
484 estUneImage = true
485 }
486 else
487 {
488 var rechercheDomaine = this.regexDomaine.exec(url)
489 if (rechercheDomaine != null && rechercheDomaine.length >= 2)
490 versionShort = rechercheDomaine[1]
491 else
492 {
493 var nomProtocole = this.regexNomProtocole.exec(url)
494 if (nomProtocole != null && nomProtocole.length >= 2)
495 versionShort = nomProtocole[1]
496 }
497 }
498
499 return [versionShort == null ? "url" : versionShort, estUneImage]
500 }
501
502 /**
503 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
504 */
505 Formateur.prototype.traiterPourFenetreLightBox = function(M, urlCourante)
506 {
507 thisFormateur = this
508 var traitementUrl = function(url)
509 {
510 return "[" + thisFormateur.getShort(url)[0] + (urlCourante == url ? "*" : "") + "]"
511 }
512
513 return this.remplacerBalisesHTML(M).replace(this.regexUrl, traitementUrl)
514 }
515
516
517 ///////////////////////////////////////////////////////////////////////////////////////////////////
518
519 // les statuts possibes du client
520 var statutType = {
521 // mode enregistré, peut poster des messages et modifier son profile
522 auth_registered : 0,
523 // mode identifié, peut poster des messages mais n'a pas accès au profile
524 auth_not_registered : 1,
525 // mode déconnecté, ne peut pas poster de message
526 deconnected : 2
527 }
528
529 function Client(util)
530 {
531 this.util = util
532
533 this.cookie = null
534 this.regexCookie = new RegExp("^cookie=([^;]*)")
535
536 // données personnels
537 this.resetDonneesPersonnelles()
538
539 this.setStatut(statutType.deconnected)
540
541 // si true alors chaque modification du client est mémorisé sur le serveur
542 this.autoflush = $.browser["opera"]
543 }
544
545 Client.prototype.resetDonneesPersonnelles = function()
546 {
547 this.id = 0
548 this.pseudo = conf.pseudoDefaut
549 this.login = ""
550 this.password = ""
551 this.email = ""
552 this.css = $("link#cssPrincipale").attr("href")
553 this.nickFormat = "nick"
554 this.viewTimes = true
555 this.viewTooltips = true
556 this.cookie = undefined
557
558 this.pagePrincipale = 1
559 this.ekMaster = false
560
561 // les conversations, une conversation est un objet possédant les attributs suivants :
562 // - racine (entier)
563 // - page (entier)
564 this.conversations = new Array()
565 }
566
567 Client.prototype.setCss = function(css)
568 {
569 if (this.css == css || css == "")
570 return
571
572 this.css = css
573 $("link#cssPrincipale").attr("href", this.css)
574 if (this.autoflush) this.flush(true)
575 }
576
577 Client.prototype.pageSuivante = function(numConv)
578 {
579 if (numConv < 0 && this.pagePrincipale > 1)
580 this.pagePrincipale -= 1
581 else if (this.conversations[numConv].page > 1)
582 this.conversations[numConv].page -= 1
583 }
584
585 Client.prototype.pagePrecedente = function(numConv)
586 {
587 if (numConv < 0)
588 this.pagePrincipale += 1
589 else
590 this.conversations[numConv].page += 1
591 }
592
593 /**
594 * Définit la première page pour la conversation donnée.
595 * @return true si la page a changé sinon false
596 */
597 Client.prototype.goPremierePage = function(numConv)
598 {
599 if (numConv < 0)
600 {
601 if (this.pagePrincipale == 1)
602 return false
603 this.pagePrincipale = 1
604 }
605 else
606 {
607 if (this.conversations[numConv].page == 1)
608 return false
609 this.conversations[numConv].page = 1
610 }
611 return true
612 }
613
614 /**
615 * Ajoute une conversation à la vue de l'utilisateur.
616 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
617 * @param racines la racine de la conversation (integer)
618 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
619 */
620 Client.prototype.ajouterConversation = function(racine)
621 {
622 // vérification s'il elle n'existe pas déjà
623 for (var i = 0; i < this.conversations.length; i++)
624 if (this.conversations[i].root == racine)
625 return false
626
627 this.conversations.push({root : racine, page : 1})
628
629 if (this.autoflush) this.flush(true)
630
631 return true
632 }
633
634 Client.prototype.supprimerConversation = function(num)
635 {
636 if (num < 0 || num >= this.conversations.length) return
637
638 // décalage TODO : supprimer le dernier élément
639 for (var i = num; i < this.conversations.length - 1; i++)
640 this.conversations[i] = this.conversations[i+1]
641 this.conversations.pop()
642
643 if (this.autoflush) this.flush(true)
644 }
645
646 Client.prototype.getJSONLogin = function(login, password)
647 {
648 return {
649 "action" : "authentification",
650 "login" : login,
651 "password" : password
652 }
653 }
654
655 Client.prototype.getJSONLoginCookie = function()
656 {
657 return {
658 "action" : "authentification",
659 "cookie" : this.cookie
660 }
661 }
662
663 /**
664 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
665 * de s'autentifier avec (login, password).
666 */
667 Client.prototype.getJSONEnregistrement = function(login, password)
668 {
669 var mess = { "action" : "register" }
670
671 if (login != undefined && password != undefined)
672 {
673 mess["login"] = login
674 mess["password"] = password
675 }
676
677 return mess;
678 }
679
680 Client.prototype.getJSONConversations = function()
681 {
682 var conversations = new Array()
683 for (var i = 0; i < this.conversations.length; i++)
684 conversations.push({ "root" : this.conversations[i].root, "page" : this.conversations[i].page})
685 return conversations
686 }
687
688 Client.prototype.getJSONProfile = function()
689 {
690 return {
691 "action" : "set_profile",
692 "cookie" : this.cookie,
693 "login" : this.login,
694 "password" : this.password,
695 "nick" : this.pseudo,
696 "email" : this.email,
697 "css" : this.css,
698 "nick_format" : this.nickFormat,
699 "view_times" : this.viewTimes,
700 "view_tooltips" : this.viewTooltips,
701 "main_page" : this.pagePrincipale < 1 ? 1 : this.pagePrincipale,
702 "conversations" : this.getJSONConversations()
703 }
704 }
705
706 /**
707 * Renvoie null si pas définit.
708 */
709 Client.prototype.getCookie = function()
710 {
711 var cookie = this.regexCookie.exec(document.cookie)
712 if (cookie == null) this.cookie = null
713 else this.cookie = cookie[1]
714 }
715
716 Client.prototype.delCookie = function()
717 {
718 document.cookie = "cookie=; max-age=0"
719 }
720
721 Client.prototype.setCookie = function()
722 {
723 if (this.cookie == null || this.cookie == undefined)
724 return
725
726 // ne fonctionne pas sous IE....
727 /*document.cookie = "cookie=" + this.cookie + "; max-age=" + (60 * 60 * 24 * 365) */
728
729 document.cookie =
730 "cookie="+this.cookie+"; expires=" + new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365).toUTCString()
731 }
732
733 Client.prototype.authentifie = function()
734 {
735 return this.statut == statutType.auth_registered || this.statut == statutType.auth_not_registered
736 }
737
738 Client.prototype.setStatut = function(statut)
739 {
740 // conversation en "enum" si en "string"
741 if (typeof(statut) == "string")
742 {
743 statut =
744 statut == "auth_registered" ?
745 statutType.auth_registered :
746 (statut == "auth_not_registered" ? statutType.auth_not_registered : statutType.deconnected)
747 }
748
749 if (statut == this.statut) return
750
751 this.statut = statut
752 this.majMenu()
753 }
754
755 /**
756 * Effectue la connexion vers le serveur.
757 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
758 * S'il existe un cookie en local on s'authentifie directement avec lui.
759 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
760 */
761 Client.prototype.connexionCookie = function()
762 {
763 this.getCookie()
764 if (this.cookie == null) return false;
765 return this.connexion(this.getJSONLoginCookie())
766 }
767
768 Client.prototype.connexionLogin = function(login, password)
769 {
770 return this.connexion(this.getJSONLogin(login, password))
771 }
772
773 Client.prototype.enregistrement = function(login, password)
774 {
775 if (this.authentifie())
776 {
777 this.login = login
778 this.password = password
779 if(this.flush())
780 {
781 this.setStatut(statutType.auth_registered)
782 return true
783 }
784 return false
785 }
786 else
787 {
788 return this.connexion(this.getJSONEnregistrement(login, password))
789 }
790 }
791
792 Client.prototype.connexion = function(messageJson)
793 {
794 ;; dumpObj(messageJson)
795 thisClient = this
796 jQuery.ajax(
797 {
798 async: false,
799 type: "POST",
800 url: "request",
801 dataType: "json",
802 data: this.util.jsonVersAction(messageJson),
803 success:
804 function(data)
805 {
806 ;; dumpObj(data)
807 if (data["reply"] == "error")
808 thisClient.util.messageDialogue(data["error_message"])
809 else
810 thisClient.chargerDonnees(data)
811 }
812 }
813 )
814 return this.authentifie()
815 }
816
817 Client.prototype.deconnexion = function()
818 {
819 this.flush(true)
820 this.delCookie()
821 this.resetDonneesPersonnelles()
822 this.setStatut(statutType.deconnected) // deconnexion
823 }
824
825 Client.prototype.chargerDonnees = function(data)
826 {
827 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
828 // de l'état ekMaster
829 this.ekMaster = data["ek_master"] != undefined ? data["ek_master"] : false
830
831 this.setStatut(data["status"])
832
833 if (this.authentifie())
834 {
835 this.cookie = data["cookie"]
836 this.setCookie()
837
838 this.id = data["id"]
839 this.login = data["login"]
840 this.pseudo = data["nick"]
841 this.email = data["email"]
842 this.setCss(data["css"])
843 this.nickFormat = data["nick_format"]
844 this.viewTimes = data["view_times"]
845 this.viewTooltips = data["view_tooltips"]
846
847 // la page de la conversation principale
848 this.pagePrincipale = data["main_page"] == undefined ? 1 : data["main_page"]
849
850 // les conversations
851 this.conversations = data["conversations"]
852
853 this.majBulle()
854 this.majCssSelectionee()
855 }
856 }
857
858 /**
859 * Met à jour les données personne sur serveur.
860 * @param async de manière asynchrone ? défaut = true
861 * @return false si le flush n'a pas pû se faire sinon true
862 */
863 Client.prototype.flush = function(async)
864 {
865 if (async == undefined)
866 async = false
867
868 if (!this.authentifie())
869 return false
870
871 var thisClient = this
872 var ok = true
873
874 ;; dumpObj(this.getJSONProfile())
875 jQuery.ajax(
876 {
877 async: async,
878 type: "POST",
879 url: "request",
880 dataType: "json",
881 data: this.util.jsonVersAction(this.getJSONProfile()),
882 success:
883 function(data)
884 {
885 ;; dumpObj(data)
886 if (data["reply"] == "error")
887 {
888 thisClient.util.messageDialogue(data["error_message"])
889 ok = false
890 }
891 else
892 {
893 thisClient.majBulle()
894 }
895 }
896 }
897 )
898
899 return ok
900 }
901
902 Client.prototype.majMenu = function()
903 {
904 displayType = "block"
905
906 $("#menu .admin").css("display", this.ekMaster ? displayType : "none")
907
908 // met à jour le menu
909 if (this.statut == statutType.auth_registered)
910 {
911 $("#menu .profile").css("display", displayType).text("profile")
912 $("#menu .logout").css("display", displayType)
913 $("#menu .register").css("display", "none")
914 }
915 else if (this.statut == statutType.auth_not_registered)
916 {
917 $("#menu .profile").css("display", "none")
918 $("#menu .logout").css("display", displayType)
919 $("#menu .register").css("display", displayType)
920 }
921 else
922 {
923 $("#menu .profile").css("display", displayType).text("login")
924 $("#menu .logout").css("display", "none")
925 $("#menu .register").css("display", displayType)
926 }
927 }
928
929 /**
930 * Met à jour l'affichage des infos bulles en fonction du profile.
931 */
932 Client.prototype.majBulle = function()
933 {
934 this.util.bulleActive = this.viewTooltips
935 }
936
937 /**
938 * Met à jour la css sélectionnée, lors du chargement des données.
939 */
940 Client.prototype.majCssSelectionee = function()
941 {
942 // extraction du numéro de la css courante
943 var numCssCourante = this.css.match(/^.*?\/(\d)\/.*$/)
944 if (numCssCourante[1] != undefined)
945 {
946 $("#menuCss option").removeAttr("selected")
947 $("#menuCss option[value=" + numCssCourante[1]+ "]").attr("selected", "selected")
948 }
949 }
950
951 Client.prototype.slap = function(userId, raison)
952 {
953 var thisClient = this
954
955 jQuery.ajax({
956 type: "POST",
957 url: "request",
958 dataType: "json",
959 data: this.util.jsonVersAction(
960 {
961 "action" : "slap",
962 "cookie" : thisClient.cookie,
963 "user_id" : userId,
964 "reason" : raison
965 }),
966 success:
967 function(data)
968 {
969 if (data["reply"] == "error")
970 thisClient.util.messageDialogue(data["error_message"])
971 }
972 })
973 }
974
975 Client.prototype.ban = function(userId, raison, minutes)
976 {
977 var thisClient = this
978
979 // par défaut un ban correspond à 3 jours
980 if (typeof(minutes) == "undefined")
981 minutes = conf.tempsBan;
982
983 jQuery.ajax({
984 type: "POST",
985 url: "request",
986 dataType: "json",
987 data: this.util.jsonVersAction(
988 {
989 "action" : "ban",
990 "cookie" : thisClient.cookie,
991 "duration" : minutes,
992 "user_id" : userId,
993 "reason" : raison
994 }),
995 success:
996 function(data)
997 {
998 if (data["reply"] == "error")
999 thisClient.util.messageDialogue(data["error_message"])
1000 }
1001 })
1002 }
1003
1004 Client.prototype.kick = function(userId, raison)
1005 {
1006 this.ban(userId, raison, conf.tempsKick)
1007 }
1008
1009 ///////////////////////////////////////////////////////////////////////////////////////////////////
1010
1011 /**
1012 * classe permettant de gérer les événements (push serveur).
1013 * l'information envoyé est sous la forme :
1014 * {
1015 * "action" : "wait_event"
1016 * "page" : <page>
1017 * [..]
1018 * }
1019 * l'information reçu est sous la forme :
1020 * {
1021 * "reply" : <reply>
1022 * }
1023 * @page la page
1024 */
1025 function PageEvent(page, util)
1026 {
1027 this.page = page
1028 this.util = util
1029
1030 // l'objet JSONHttpRequest représentant la connexion d'attente
1031 this.attenteCourante = null
1032
1033 // le multhreading du pauvre, merci javascript de m'offrire autant de primitives pour la gestion de la concurrence...
1034 this.stop = false
1035 }
1036
1037 /**
1038 * Arrête l'attente courante s'il y en a une.
1039 */
1040 PageEvent.prototype.stopAttenteCourante = function()
1041 {
1042 this.stop = true
1043
1044 if (this.attenteCourante != null)
1045 {
1046 this.attenteCourante.abort()
1047 }
1048 }
1049
1050 /**
1051 * Attend un événement lié à la page.
1052 * @funSend une fonction renvoyant les données json à envoyer
1053 * @funsReceive est un objet comprenant les fonctions à appeler en fonction du "reply"
1054 * les fonctions acceptent un paramètre correspondant au données reçues.
1055 * exemple : {"new_message" : function(data){ ... }}
1056 */
1057 PageEvent.prototype.waitEvent = function(funSend, funsReceive)
1058 {
1059 this.stopAttenteCourante()
1060
1061 this.stop = false
1062
1063 var thisPageEvent = this
1064
1065 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veut dans l'ordre définit dans le protocole)
1066 // TODO : ya pas mieux ?
1067 var dataToSend =
1068 {
1069 "action" : "wait_event",
1070 "page" : this.page
1071 }
1072 var poulpe = funSend()
1073 for (v in poulpe)
1074 dataToSend[v] = poulpe[v]
1075
1076 ;; dumpObj(dataToSend)
1077
1078 this.attenteCourante = jQuery.ajax({
1079 type: "POST",
1080 url: "request",
1081 dataType: "json",
1082 timeout: 300000, // timeout de 5min. Gros HACK pas beau. FIXME problème décrit ici : http://groups.google.com/group/jquery-en/browse_thread/thread/8724e64af3333a76
1083 // Obsolète (voir TODO)
1084 //timeout: 300000, // timeout de 5min. Gros HACK pas beau. FIXME problème décrit ici : http://groups.google.com/group/jquery-en/browse_thread/thread/8724e64af3333a76
1085 data: this.util.jsonVersAction(dataToSend),
1086 success:
1087 function(data)
1088 {
1089 ;; dumpObj(data)
1090
1091 funsReceive[data["reply"]](data)
1092
1093 // rappel de la fonction dans 100 ms
1094 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funsReceive) }, 100)
1095 },
1096 error:
1097 function(XMLHttpRequest, textStatus, errorThrown)
1098 {
1099 ;; console.log("Connexion perdue dans waitEvent")
1100 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funsReceive) }, 1000)
1101 }
1102 })
1103 }
1104
1105 /**
1106 * Si un stopAttenteCourante survient un peu n'importe quand il faut imédiatement arreter de boucler.
1107 */
1108 PageEvent.prototype.waitEvent2 = function(funSend, funsReceive)
1109 {
1110 if (this.stop)
1111 return
1112 this.waitEvent(funSend, funsReceive)
1113 }
1114
1115 ///////////////////////////////////////////////////////////////////////////////////////////////////
1116
1117 function initialiserListeStyles(client)
1118 {
1119 $("#menuCss").change(
1120 function()
1121 {
1122 client.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
1123 }
1124 )
1125 }
1126
1127 // charge dynamiquement le script de debug
1128 ;; jQuery.ajax({async : false, url : "js/debug.js", dataType : "script"})
1129
1130 // le main
1131 $(document).ready(
1132 function()
1133 {
1134 var formateur = new Formateur()
1135 var util = new Util(formateur)
1136 var client = new Client(util)
1137 var pages = new Pages()
1138
1139 // connexion vers le serveur (utilise un cookie qui traine)
1140 client.connexionCookie()
1141
1142 initialiserListeStyles(client)
1143
1144 // FIXME : ne fonctionne pas sous opera
1145 // voir : http://dev.jquery.com/ticket/2892#preview
1146 $(window).unload(function(){client.flush()})
1147
1148 $("#menu .minichat").click(function(){ pages.afficherPage("minichat") })
1149 $("#menu .admin").click(function(){ pages.afficherPage("admin") })
1150 $("#menu .profile").click(function(){ pages.afficherPage("profile") })
1151 $("#menu .logout").click(function(){
1152 util.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType.question,
1153 {"Oui" : function()
1154 {
1155 client.deconnexion();
1156 pages.afficherPage("minichat", true)
1157 },
1158 "Non" : function(){}
1159 }
1160 )
1161 })
1162 $("#menu .register").click(function(){ pages.afficherPage("register") })
1163 $("#menu .about").click(function(){ pages.afficherPage("about") })
1164
1165 // TODO : simplifier et pouvoir créer des liens par exemple : <span class="lien" href="conditions">Conditions d'utilisation</span>
1166 $("#footer .conditions").click(function(){ pages.afficherPage("conditions_utilisation") })
1167
1168 pages.ajouterPage(new PageMinichat(client, formateur, util))
1169 pages.ajouterPage(new PageAdmin(client, formateur, util))
1170 pages.ajouterPage(new PageProfile(client, formateur, util))
1171 pages.ajouterPage(new PageRegister(client, formateur, util))
1172 pages.ajouterPage(new PageAbout(client, formateur, util))
1173 pages.ajouterPage("conditions_utilisation")
1174
1175 pages.afficherPage("minichat")
1176 }
1177 )