2 // Copyright 2008 Grégory Burri
4 // This file is part of Euphorik.
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.
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.
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/>.
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".
29 * Normalement 'const' à la place de 'var' mais non supporté par IE7.
32 nbMessageAffiche : 40, // (par page)
33 pseudoDefaut : "<nick>",
34 tempsAffichageMessageDialogue : 4000, // en ms
36 "smile" : [/:\)/g, /:-\)/g],
37 "bigsmile" : [/:D/g, /:-D/g],
38 "clin" : [/;\)/g, /;-\)/g],
39 "cool" : [/8\)/g, /8-\)/g],
40 "eheheh" : [/:P/g, /:-P/g],
41 "lol" : [/\[-lol\]/g],
42 "spliff" : [/\[-spliff\]/g],
43 "oh" : [/:o/g, /:O/g],
44 "heink" : [/\[-heink\]/g],
45 "hum" : [/\[-hum\]/g],
46 "boh" : [/\[-boh\]/g],
47 "sniff" : [/:\(/g, /:-\(/g],
48 "triste" : [/\[-triste\]/g],
49 "pascontent" : [/>\(/g, />\(/g],
50 "argn" : [/\[-argn\]/g],
51 "redface" : [/\[-redface\]/g],
52 "bunny" : [/\[-lapin\]/g],
53 "chat" : [/\[-chat\]/g],
54 "renne" : [/\[-renne\]/g],
55 "star" : [/\[-star\]/g],
56 "kirby" : [/\[-kirby\]/g],
57 "slurp" : [/\[-slurp\]/g],
58 "agreed" : [/\[-agreed\]/g],
59 "dodo" : [/\[-dodo\]/g],
64 ///////////////////////////////////////////////////////////////////////////////////////////////////
66 String
.prototype.trim = function()
68 return jQuery
.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
71 String
.prototype.ltrim = function()
73 return this.replace(/^\s+/, "");
76 String
.prototype.rtrim = function()
78 return this.replace(/\s+$/, "");
81 ///////////////////////////////////////////////////////////////////////////////////////////////////
84 * Cette classe regroupe des fonctions utilitaires (helpers).
85 * @formateur est permet de formater les messages affichés à l'aide de messageDialogue (facultatif)
87 function Util(formateur
)
89 $("#info .fermer").click(function(){
90 $("#info").slideUp(50)
93 this.formateur
= formateur
96 var messageType
= {informatif: 0, question: 1, erreur: 2}
99 * Affiche une boite de dialogue avec un message à l'intérieur.
100 * @param message le message (string)
101 * @param type voir 'messageType'. par défaut messageType.informatif
102 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
103 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
104 * @param formate faut-il formaté le message ? true par défaut
106 Util
.prototype.messageDialogue = function(message
, type
, boutons
, formate
)
110 if (type
== undefined)
111 type
= messageType
.informatif
113 if (formate
== undefined)
116 if (this.timeoutMessageDialogue
!= undefined)
117 clearTimeout(this.timeoutMessageDialogue
)
119 var fermer = function(){$("#info").slideUp(100)}
122 $("#info .message").html(thisUtil
.formateur
== undefined || !formate
? message : thisUtil
.formateur
.traitementComplet(message
))
125 case messageType
.informatif : $("#info #icone").attr("class", "information"); break
126 case messageType
.question : $("#info #icone").attr("class", "interrogation"); break
127 case messageType
.erreur : $("#info #icone").attr("class", "exclamation"); break
129 $("#info .boutons").html("")
130 for (var b
in boutons
)
131 $("#info .boutons").append("<div>" + b
+ "</div>").find("div:last").click(boutons
[b
]).click(fermer
)
133 $("#info").slideDown(200)
134 this.timeoutMessageDialogue
= setTimeout(fermer
, conf
.tempsAffichageMessageDialogue
)
138 * Affiche un info bulle lorsque le curseur survole l'élément donné.
139 * FIXME : le width de element ne tient pas compte du padding !?
141 Util
.prototype.infoBulle = function(message
, element
)
143 var virerMess = function()
145 $("#flecheBulle").remove()
146 $("#messageBulle").remove()
149 element
.click(virerMess
)
154 f
= $('<div id="flecheBulle"></div>').appendTo("body")
155 m
= $('<div id="messageBulle"><p>' + message
+ '</p></div>').appendTo("body")
156 var positionFleche
= {
157 left : element
.offset().left
+ element
.width() / 2 - f
.width() / 2,
158 top : element
.offset().top
- f
.height()
160 var positionMessage
= {
161 left : element
.offset().left
+ element
.width() / 2 - m
.width() / 2,
162 top : element
.offset().top
- f
.height() - m
.height()
164 var depassementDroit
= (positionMessage
.left
+ m
.width()) - $("body").width()
165 if (depassementDroit
> 0)
166 positionMessage
.left
-= depassementDroit
169 if (positionMessage
.left
< 0)
170 positionMessage
.left
= 0
173 m
.css("top", positionMessage
.top
).css("left", positionMessage
.left
).show()
174 f
.css("top", positionFleche
.top
).css("left", positionFleche
.left
).show()
181 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
183 Util
.prototype.jsonVersAction = function(json
)
185 return {action : JSON
.stringify(json
) }
188 Util
.prototype.md5 = function(chaine
)
190 return hex_md5(chaine
)
193 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
194 Util
.prototype.setSelectionRange = function(input
, selectionStart
, selectionEnd
)
196 if (input
.setSelectionRange
)
199 input
.setSelectionRange(selectionStart
, selectionEnd
)
201 else if (input
.createTextRange
)
203 var range
= input
.createTextRange()
205 range
.moveEnd('character', selectionEnd
)
206 range
.moveStart('character', selectionStart
)
211 Util
.prototype.setCaretToEnd = function(input
)
213 this.setSelectionRange(input
, input
.value
.length
, input
.value
.length
)
215 Util
.prototype.setCaretToBegin = function(input
)
217 this.setSelectionRange(input
, 0, 0)
219 Util
.prototype.setCaretToPos = function(input
, pos
)
221 this.setSelectionRange(input
, pos
, pos
)
223 Util
.prototype.selectString = function(input
, string
)
225 var match
= new RegExp(string
, "i").exec(input
.value
)
228 this.setSelectionRange (input
, match
.index
, match
.index
+ match
[0].length
)
231 Util
.prototype.replaceSelection = function(input
, replaceString
) {
232 if (input
.setSelectionRange
)
234 var selectionStart
= input
.selectionStart
235 var selectionEnd
= input
.selectionEnd
236 input
.value
= input
.value
.substring(0, selectionStart
) + replaceString
+ input
.value
.substring(selectionEnd
)
238 if (selectionStart
!= selectionEnd
) // has there been a selection
239 this.setSelectionRange(input
, selectionStart
, selectionStart
+ replaceString
.length
)
241 this.setCaretToPos(input
, selectionStart
+ replaceString
.length
)
243 else if (document
.selection
)
245 var range
= document
.selection
.createRange();
246 if (range
.parentElement() == input
)
248 var isCollapsed
= range
.text
== ''
249 range
.text
= replaceString
252 // there has been a selection
253 // it appears range.select() should select the newly
254 // inserted text but that fails with IE
255 range
.moveStart('character', -replaceString
.length
);
262 Util
.prototype.rot13 = function(chaine
)
264 var ACode
= 'A'.charCodeAt(0)
265 var aCode
= 'a'.charCodeAt(0)
266 var MCode
= 'M'.charCodeAt(0)
267 var mCode
= 'm'.charCodeAt(0)
268 var ZCode
= 'Z'.charCodeAt(0)
269 var zCode
= 'z'.charCodeAt(0)
271 var f = function(ch
, pos
) {
272 if (pos
== ch
.length
)
275 var c
= ch
.charCodeAt(pos
);
276 return String
.fromCharCode(
278 (c
>= ACode
&& c
<= MCode
|| c
>= aCode
&& c
<= mCode
? 13 :
279 (c
> MCode
&& c
<= ZCode
|| c
> mCode
&& c
<= zCode
? -13 : 0))
285 ///////////////////////////////////////////////////////////////////////////////////////////////////
289 this.pageCourante
= null
293 Pages
.prototype.ajouterPage = function(page
)
295 page
.pages
= this // la magie des langages dynamiques : le foutoire
296 this.pages
[page
.nom
] = page
299 Pages
.prototype.afficherPage = function(nomPage
, forcerChargement
)
301 if (forcerChargement
== undefined) forcerChargement
= false
303 var page
= this.pages
[nomPage
]
304 if (page
== undefined || (!forcerChargement
&& page
== this.pageCourante
)) return
306 if (this.pageCourante
!= null && this.pageCourante
.decharger
)
307 this.pageCourante
.decharger()
309 $("#menu li").removeClass("courante")
310 $("#menu li." + nomPage
).addClass("courante")
312 this.pageCourante
= page
313 $("#page").html(this.pageCourante
.contenu()).removeClass().addClass(this.pageCourante
.nom
)
315 if (this.pageCourante
.charger
)
316 this.pageCourante
.charger()
319 ///////////////////////////////////////////////////////////////////////////////////////////////////
322 * Classe permettant de formater du texte par exemple pour la substitution des liens dans les
323 * message par "[url]".
324 * TODO : améliorer l'efficacité des méthods notamment lié au smiles.
328 this.smiles
= conf
.smiles
329 this.protocoles
= "http|https|ed2k"
331 this.regexUrl
= new RegExp("(?:(?:" + this.protocoles
+ ")://|www\\.)[^ ]*", "gi")
332 this.regexImg
= new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
333 this.regexDomaine
= new RegExp("^(?:(?:" + this.protocoles
+ ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
334 this.regexTestProtocoleExiste
= new RegExp("^(?:" + this.protocoles
+ ")://.*$", "i")
335 this.regexNomProtocole
= new RegExp("^(.*?)://")
339 * Formate un pseudo saise par l'utilisateur.
340 * @param pseudo le pseudo brut
341 * @return le pseudo filtré
343 Formateur
.prototype.filtrerInputPseudo = function(pseudo
)
345 return pseudo
.replace(/{|}/g, "").trim()
348 Formateur
.prototype.getSmilesHTML = function()
351 for (var sNom
in this.smiles
)
353 XHTML
+= "<img class=\"" + sNom
+ "\" src=\"img/smileys/" + sNom
+ ".gif\" alt =\"" + sNom
+ "\" />"
359 * Formatage complet d'un texte.
361 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
363 Formateur
.prototype.traitementComplet = function(M
, pseudo
)
365 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.traiterWikiSyntaxe(this.remplacerBalisesHTML(M
)), pseudo
)))
369 * Transforme les liens en entités clickables.
370 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
371 * "{5F}" ou 5F est la racine de la conversation.
372 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
374 Formateur
.prototype.traiterLiensConv = function(M
)
380 return "<span class=\"lienConv\">" + lien
+ "</span>"
386 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
387 * moyenne sur échantillon : 234ms
389 Formateur
.prototype.traiterSmiles = function(M
)
391 for (var sNom
in this.smiles
)
393 ss
= this.smiles
[sNom
]
394 for (var i
= 0; i
< ss
.length
; i
++)
395 M
= M
.replace(ss
[i
], "<img src=\"img/smileys/" + sNom
+ ".gif\" alt =\"" + sNom
+ "\" />")
400 Formateur
.prototype.remplacerBalisesHTML = function(M
)
402 return M
.replace(/</g
, "<").replace(/>/g
, ">").replace(/"/g, ""
;")
405 Formateur.prototype.traiterURL = function(M, pseudo)
409 var traitementUrl = function(url)
411 // si ya pas de protocole on rajoute "http://"
412 if (!thisFormateur
.regexTestProtocoleExiste
.test(url
))
413 url
= "http://" + url
414 var extension
= thisFormateur
.getShort(url
)
415 return "<a " + (extension
[1] ? "title=\"" + (pseudo
== undefined ? "" : thisFormateur
.traiterPourFenetreLightBox(pseudo
, url
) + ": ") + thisFormateur
.traiterPourFenetreLightBox(M
, url
) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url
+ "\" >[" + extension
[0] + "]</a>"
417 return M
.replace(this.regexUrl
, traitementUrl
)
421 * Formatage en utilisant un sous-ensemble des règles de mediwiki.
422 * par exemple ''italic'' devient <i>italic</i>
424 Formateur
.prototype.traiterWikiSyntaxe = function(M
)
428 function(texte
, capture
)
430 return "<b>" + capture
+ "</b>"
434 function(texte
, capture
)
436 return "<i>" + capture
+ "</i>"
442 * Renvoie une version courte de l'url.
443 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
445 Formateur
.prototype.getShort = function(url
)
447 var estUneImage
= false
448 var versionShort
= null
449 var rechercheImg
= this.regexImg
.exec(url
)
451 if (rechercheImg
!= null)
453 versionShort
= rechercheImg
[1].toLowerCase()
454 if (versionShort
== "jpeg") versionShort
= "jpg" // jpeg -> jpg
459 var rechercheDomaine
= this.regexDomaine
.exec(url
)
460 if (rechercheDomaine
!= null && rechercheDomaine
.length
>= 2)
461 versionShort
= rechercheDomaine
[1]
464 var nomProtocole
= this.regexNomProtocole
.exec(url
)
465 if (nomProtocole
!= null && nomProtocole
.length
>= 2)
466 versionShort
= nomProtocole
[1]
470 return [versionShort
== null ? "url" : versionShort
, estUneImage
]
474 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
476 Formateur
.prototype.traiterPourFenetreLightBox = function(M
, urlCourante
)
479 var traitementUrl = function(url
)
481 return "[" + thisFormateur
.getShort(url
)[0] + (urlCourante
== url
? "*" : "") + "]"
484 return this.remplacerBalisesHTML(M
).replace(this.regexUrl
, traitementUrl
)
488 ///////////////////////////////////////////////////////////////////////////////////////////////////
490 // les statuts possibes du client
492 // mode enregistré, peut poster des messages et modifier son profile
494 // mode identifié, peut poster des messages mais n'a pas accès au profile
495 auth_not_registered : 1,
496 // mode déconnecté, ne peut pas poster de message
500 function Client(util
)
505 this.regexCookie
= new RegExp("^cookie=([^;]*)")
507 // données personnels
508 this.resetDonneesPersonnelles()
510 this.setStatut(statutType
.deconnected
)
512 // si true alors chaque modification du client est mémorisé sur le serveur
513 this.autoflush
= $.browser
["opera"]
516 Client
.prototype.resetDonneesPersonnelles = function()
519 this.pseudo
= conf
.pseudoDefaut
523 this.css
= $("link#cssPrincipale").attr("href")
524 this.nickFormat
= "nick"
525 this.cookie
= undefined
527 this.pagePrincipale
= 1
528 this.ekMaster
= false
530 // les conversations, une conversation est un objet possédant les attributs suivants :
533 this.conversations
= new Array()
536 Client
.prototype.setCss = function(css
)
538 if (this.css
== css
|| css
== "")
542 $("link#cssPrincipale").attr("href", this.css
)
545 if (this.autoflush
) this.flush(true)
548 Client
.prototype.pageSuivante = function(numConv
)
550 if (numConv
< 0 && this.pagePrincipale
> 1)
551 this.pagePrincipale
-= 1
552 else if (this.conversations
[numConv
].page
> 1)
553 this.conversations
[numConv
].page
-= 1
556 Client
.prototype.pagePrecedente = function(numConv
)
559 this.pagePrincipale
+= 1
561 this.conversations
[numConv
].page
+= 1
565 * Définit la première page pour la conversation donnée.
566 * @return true si la page a changé sinon false
568 Client
.prototype.goPremierePage = function(numConv
)
572 if (this.pagePrincipale
== 1)
574 this.pagePrincipale
= 1
578 if (this.conversations
[numConv
].page
== 1)
580 this.conversations
[numConv
].page
= 1
586 * Ajoute une conversation à la vue de l'utilisateur.
587 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
588 * @param racines la racine de la conversation (integer)
589 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
591 Client
.prototype.ajouterConversation = function(racine
)
593 // vérification s'il elle n'existe pas déjà
594 for (var i
= 0; i
< this.conversations
.length
; i
++)
595 if (this.conversations
[i
].root
== racine
)
598 this.conversations
.push({root : racine
, page : 1})
600 if (this.autoflush
) this.flush(true)
605 Client
.prototype.supprimerConversation = function(num
)
607 if (num
< 0 || num
>= this.conversations
.length
) return
609 // décalage TODO : supprimer le dernier élément
610 for (var i
= num
; i
< this.conversations
.length
- 1; i
++)
611 this.conversations
[i
] = this.conversations
[i
+1]
612 this.conversations
.pop()
614 if (this.autoflush
) this.flush(true)
617 Client
.prototype.getJSONLogin = function(login
, password
)
620 "action" : "authentification",
622 "password" : password
626 Client
.prototype.getJSONLoginCookie = function()
629 "action" : "authentification",
630 "cookie" : this.cookie
635 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
636 * de s'autentifier avec (login, password).
638 Client
.prototype.getJSONEnregistrement = function(login
, password
)
640 var mess
= { "action" : "register" }
642 if (login
!= undefined && password
!= undefined)
644 mess
["login"] = login
645 mess
["password"] = password
651 Client
.prototype.getJSONConversations = function()
653 var conversations
= new Array()
654 for (var i
= 0; i
< this.conversations
.length
; i
++)
655 conversations
.push({ "root" : this.conversations
[i
].root
, "page" : this.conversations
[i
].page
})
659 Client
.prototype.getJSONProfile = function()
662 "action" : "set_profile",
663 "cookie" : this.cookie
,
664 "login" : this.login
,
665 "password" : this.password
,
666 "nick" : this.pseudo
,
667 "email" : this.email
,
669 "nick_format" : this.nickFormat
,
670 "main_page" : this.pagePrincipale
< 1 ? 1 : this.pagePrincipale
,
671 "conversations" : this.getJSONConversations()
676 * Renvoie null si pas définit.
678 Client
.prototype.getCookie = function()
680 var cookie
= this.regexCookie
.exec(document
.cookie
)
681 if (cookie
== null) this.cookie
= null
682 else this.cookie
= cookie
[1]
685 Client
.prototype.delCookie = function()
687 document
.cookie
= "cookie=; max-age=0"
690 Client
.prototype.setCookie = function(cookie
)
692 if (this.cookie
== null)
696 "cookie="+this.cookie
+
697 "; max-age=" + (60 * 60 * 24 * 365)
700 Client
.prototype.authentifie = function()
702 return this.statut
== statutType
.auth_registered
|| this.statut
== statutType
.auth_not_registered
705 Client
.prototype.setStatut = function(statut
)
707 // conversation en "enum" si en "string"
708 if (typeof(statut
) == "string")
711 statut
== "auth_registered" ?
712 statutType
.auth_registered :
713 (statut
== "auth_not_registered" ? statutType
.auth_not_registered : statutType
.deconnected
)
716 if (statut
== this.statut
) return
723 * Effectue la connexion vers le serveur.
724 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
725 * S'il existe un cookie en local on s'authentifie directement avec lui.
726 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
728 Client
.prototype.connexionCookie = function()
731 if (this.cookie
== null) return false;
732 return this.connexion(this.getJSONLoginCookie())
735 Client
.prototype.connexionLogin = function(login
, password
)
737 return this.connexion(this.getJSONLogin(login
, password
))
740 Client
.prototype.enregistrement = function(login
, password
)
742 if (this.authentifie())
745 this.password
= password
748 this.setStatut(statutType
.auth_registered
)
755 return this.connexion(this.getJSONEnregistrement(login
, password
))
759 Client
.prototype.connexion = function(messageJson
)
761 ;;; dumpObj(messageJson
)
769 data: this.util
.jsonVersAction(messageJson
),
774 if (data
["reply"] == "error")
775 thisClient
.util
.messageDialogue(data
["error_message"])
777 thisClient
.chargerDonnees(data
)
781 return this.authentifie()
784 Client
.prototype.deconnexion = function()
788 this.resetDonneesPersonnelles()
789 this.setStatut(statutType
.deconnected
) // deconnexion
792 Client
.prototype.chargerDonnees = function(data
)
794 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
795 // de l'état ekMaster
796 this.ekMaster
= data
["ek_master"] != undefined ? data
["ek_master"] : false
798 this.setStatut(data
["status"])
800 if (this.authentifie())
802 this.cookie
= data
["cookie"]
806 this.login
= data
["login"]
807 this.pseudo
= data
["nick"]
808 this.email
= data
["email"]
809 this.setCss(data
["css"])
810 this.nickFormat
= data
["nick_format"]
812 // la page de la conversation principale
813 this.pagePrincipale
= data
["main_page"] == undefined ? 1 : data
["main_page"]
816 this.conversations
= data
["conversations"]
821 * Met à jour les données personne sur serveur.
822 * @param async de manière asynchrone ? défaut = true
823 * @return false si le flush n'a pas pû se faire sinon true
825 Client
.prototype.flush = function(async
)
827 if (async
== undefined)
830 if (!this.authentifie())
833 var thisClient
= this
836 ;;; dumpObj(this.getJSONProfile())
843 data: this.util
.jsonVersAction(this.getJSONProfile()),
848 if (data
["reply"] == "error")
850 thisClient
.util
.messageDialogue(data
["error_message"])
860 Client
.prototype.majMenu = function()
862 // TODO : à virer : ne plus changer de style de display ... spa beau .. ou trouver une autre méthode
863 // var displayType = this.css == "css/3/euphorik.css" ? "block" : "inline" //this.client
864 displayType
= "block"
866 $("#menu .admin").css("display", this.ekMaster
? displayType : "none")
868 // met à jour le menu
869 if (this.statut
== statutType
.auth_registered
)
871 $("#menu .profile").css("display", displayType
).text("profile")
872 $("#menu .logout").css("display", displayType
)
873 $("#menu .register").css("display", "none")
875 else if (this.statut
== statutType
.auth_not_registered
)
877 $("#menu .profile").css("display", "none")
878 $("#menu .logout").css("display", displayType
)
879 $("#menu .register").css("display", displayType
)
883 $("#menu .profile").css("display", displayType
).text("login")
884 $("#menu .logout").css("display", "none")
885 $("#menu .register").css("display", displayType
)
889 Client
.prototype.slap = function(userId
, raison
)
891 var thisClient
= this
897 data: this.util
.jsonVersAction(
900 "cookie" : thisClient
.cookie
,
907 if (data
["reply"] == "error")
908 thisClient
.util
.messageDialogue(data
["error_message"])
913 Client
.prototype.ban = function(userId
, raison
, minutes
)
915 var thisClient
= this
917 // par défaut un ban correspond à 3 jours
918 if (typeof(minutes
) == "undefined")
919 minutes
= 60 * 24 * 3
925 data: this.util
.jsonVersAction(
928 "cookie" : thisClient
.cookie
,
929 "duration" : minutes
,
936 if (data
["reply"] == "error")
937 thisClient
.util
.messageDialogue(data
["error_message"])
942 Client
.prototype.kick = function(userId
, raison
)
944 this.ban(userId
, raison
, 15)
947 ///////////////////////////////////////////////////////////////////////////////////////////////////
950 * classe permettant de gérer les événements (push serveur).
953 function PageEvent(page
, util
)
958 // l'objet JSONHttpRequest représentant la connexion d'attente
959 this.attenteCourante
= null
961 // le multhreading du pauvre, merci javascript de m'offrire autant de primitives pour la gestion de la concurrence...
966 * Arrête l'attente courante s'il y en a une.
968 PageEvent
.prototype.stopAttenteCourante = function()
972 if (this.attenteCourante
!= null)
974 this.attenteCourante
.abort()
979 * Attend un événement lié à la page.
980 * @funSend une fonction renvoyant les données json à envoyer
981 * @funReceive une fonction qui accepte un paramètre correspondant au données reçues
983 PageEvent
.prototype.waitEvent = function(funSend
, funReceive
)
985 this.stopAttenteCourante()
989 var thisPageEvent
= this
991 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veut dans l'ordre définit dans le protocole)
992 // TODO : ya pas mieux ?
995 "action" : "wait_event",
998 var poulpe
= funSend()
1000 dataToSend
[v
] = poulpe
[v
]
1002 ;;; dumpObj(dataToSend
)
1004 this.attenteCourante
= jQuery
.ajax({
1008 data: this.util
.jsonVersAction(dataToSend
),
1016 // rappel de la fonction dans 100 ms
1017 setTimeout(function(){ thisPageEvent
.waitEvent2(funSend
, funReceive
) }, 100)
1020 function(XMLHttpRequest
, textStatus
, errorThrown
)
1022 setTimeout(function(){ thisPageEvent
.waitEvent2(funSend
, funReceive
) }, 1000)
1028 * Si un stopAttenteCourante survient un peu n'importe quand il faut imédiatement arreter de boucler.
1030 PageEvent
.prototype.waitEvent2 = function(funSend
, funReceive
)
1034 this.waitEvent(funSend
, funReceive
)
1037 ///////////////////////////////////////////////////////////////////////////////////////////////////
1039 function initialiserListeStyles(client
)
1041 $("#menuCss").change(
1044 client
.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
1049 // charge dynamiquement le script de debug
1050 ;;; jQuery
.ajax({async : false, url : "js/debug.js", dataType : "script"})
1056 var formateur
= new Formateur()
1057 var util
= new Util(formateur
)
1058 var client
= new Client(util
)
1059 var pages
= new Pages()
1061 // connexion vers le serveur (utilise un cookie qui traine)
1062 client
.connexionCookie()
1064 initialiserListeStyles(client
)
1066 // FIXME : ne fonctionne pas sous opera
1067 // voir : http://dev.jquery.com/ticket/2892#preview
1068 $(window
).unload(function(){client
.flush()})
1070 $("#menu .minichat").click(function(){ pages
.afficherPage("minichat") })
1071 $("#menu .admin").click(function(){ pages
.afficherPage("admin") })
1072 $("#menu .profile").click(function(){ pages
.afficherPage("profile") })
1073 $("#menu .logout").click(function(){
1074 util
.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType
.question
,
1077 client
.deconnexion();
1078 pages
.afficherPage("minichat", true)
1080 "Non" : function(){}
1084 $("#menu .register").click(function(){ pages
.afficherPage("register") })
1085 $("#menu .about").click(function(){ pages
.afficherPage("about") })
1087 pages
.ajouterPage(new PageMinichat(client
, formateur
, util
))
1088 pages
.ajouterPage(new PageAdmin(client
, formateur
, util
))
1089 pages
.ajouterPage(new PageProfile(client
, formateur
, util
))
1090 pages
.ajouterPage(new PageRegister(client
, formateur
, util
))
1091 pages
.ajouterPage(new PageAbout(client
, formateur
, util
))
1092 pages
.afficherPage("minichat")