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 nickDefaut : "<nick>",
33 nbMessageAffiche : 40, // (par page)
34 pseudoDefaut : "<nick>",
35 tempsAffichageMessageDialogue : 4000, // en ms
36 tempsKick : 15, // en minute
37 tempsBan : 60 * 24 * 3, // en minutes (3jours)
39 "smile" : [/:\)/g, /:-\)/g],
40 "bigsmile" : [/:D/g, /:-D/g],
41 "clin" : [/;\)/g, /;-\)/g],
42 "cool" : [/8\)/g, /8-\)/g],
43 "eheheh" : [/:P/g, /:-P/g],
44 "lol" : [/\[-lol\]/g],
45 "spliff" : [/\[-spliff\]/g],
46 "oh" : [/:o/g, /:O/g],
47 "heink" : [/\[-heink\]/g],
48 "hum" : [/\[-hum\]/g],
49 "boh" : [/\[-boh\]/g],
50 "sniff" : [/:\(/g, /:-\(/g],
51 "triste" : [/\[-triste\]/g],
52 "pascontent" : [/>\(/g, />\(/g],
53 "argn" : [/\[-argn\]/g],
54 "redface" : [/\[-redface\]/g],
55 "bunny" : [/\[-lapin\]/g],
56 "chat" : [/\[-chat\]/g],
57 "renne" : [/\[-renne\]/g],
58 "star" : [/\[-star\]/g],
59 "kirby" : [/\[-kirby\]/g],
60 "slurp" : [/\[-slurp\]/g],
61 "agreed" : [/\[-agreed\]/g],
62 "dodo" : [/\[-dodo\]/g],
67 ///////////////////////////////////////////////////////////////////////////////////////////////////
69 String
.prototype.trim = function()
71 return jQuery
.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
74 String
.prototype.ltrim = function()
76 return this.replace(/^\s+/, "");
79 String
.prototype.rtrim = function()
81 return this.replace(/\s+$/, "");
84 ///////////////////////////////////////////////////////////////////////////////////////////////////
87 * Cette classe regroupe des fonctions utilitaires (helpers).
88 * @formateur est permet de formater les messages affichés à l'aide de messageDialogue (facultatif)
90 function Util(formateur
)
92 $("#info .fermer").click(function(){
93 $("#info").slideUp(50)
96 $("body").append('<div id="flecheBulle"></div>').append('<div id="messageBulle"><p></p></div>')
98 this.formateur
= formateur
99 this.bulleActive
= true
102 var messageType
= {informatif: 0, question: 1, erreur: 2}
105 * Affiche une boite de dialogue avec un message à l'intérieur.
106 * @param message le message (string)
107 * @param type voir 'messageType'. par défaut messageType.informatif
108 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
109 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
110 * @param formate faut-il formaté le message ? true par défaut
112 Util
.prototype.messageDialogue = function(message
, type
, boutons
, formate
)
116 if (type
== undefined)
117 type
= messageType
.informatif
119 if (formate
== undefined)
122 if (this.timeoutMessageDialogue
!= undefined)
123 clearTimeout(this.timeoutMessageDialogue
)
125 var fermer = function(){$("#info").slideUp(100)}
128 $("#info .message").html(thisUtil
.formateur
== undefined || !formate
? message : thisUtil
.formateur
.traitementComplet(message
))
131 case messageType
.informatif : $("#info #icone").attr("class", "information"); break
132 case messageType
.question : $("#info #icone").attr("class", "interrogation"); break
133 case messageType
.erreur : $("#info #icone").attr("class", "exclamation"); break
135 $("#info .boutons").html("")
136 for (var b
in boutons
)
137 $("#info .boutons").append("<div>" + b
+ "</div>").find("div:last").click(boutons
[b
]).click(fermer
)
139 $("#info").slideDown(200)
140 this.timeoutMessageDialogue
= setTimeout(fermer
, conf
.tempsAffichageMessageDialogue
)
144 * Affiche un info bulle lorsque le curseur survole l'élément donné.
145 * FIXME : le width de element ne tient pas compte du padding !?
147 Util
.prototype.infoBulle = function(message
, element
)
151 var cacherBulle = function()
153 $("#flecheBulle").hide()
154 $("#messageBulle").hide()
160 if (!thisUtil
.bulleActive
)
163 var m
= $("#messageBulle")
164 var f
= $("#flecheBulle")
166 // remplie le paragraphe de la bulle avec le message
167 $("p", m
).html(message
)
169 // réinitialise la position, évite le cas ou la boite est collé à droite et remplie avec un texte la faisant dépassé
170 // dans ce cas la hauteur n'est pas calculé correctement
171 m
.css("top", 0).css("left", 0)
173 var positionFleche
= {
174 left : element
.offset().left
+ element
.width() / 2 - f
.width() / 2,
175 top : element
.offset().top
- f
.height()
177 var positionMessage
= {
178 left : element
.offset().left
+ element
.width() / 2 - m
.width() / 2,
179 top : element
.offset().top
- f
.height() - m
.height()
181 var depassementDroit
= (positionMessage
.left
+ m
.width()) - $("body").width()
182 if (depassementDroit
> 0)
183 positionMessage
.left
-= depassementDroit
186 if (positionMessage
.left
< 0)
187 positionMessage
.left
= 0
190 m
.css("top", positionMessage
.top
).css("left", positionMessage
.left
).show()
191 f
.css("top", positionFleche
.top
).css("left", positionFleche
.left
).show()
198 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
200 Util
.prototype.jsonVersAction = function(json
)
202 return {action : JSON
.stringify(json
) }
205 Util
.prototype.md5 = function(chaine
)
207 return hex_md5(chaine
)
210 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
211 Util
.prototype.setSelectionRange = function(input
, selectionStart
, selectionEnd
)
213 if (input
.setSelectionRange
)
216 input
.setSelectionRange(selectionStart
, selectionEnd
)
218 else if (input
.createTextRange
)
220 var range
= input
.createTextRange()
222 range
.moveEnd('character', selectionEnd
)
223 range
.moveStart('character', selectionStart
)
228 Util
.prototype.setCaretToEnd = function(input
)
230 this.setSelectionRange(input
, input
.value
.length
, input
.value
.length
)
232 Util
.prototype.setCaretToBegin = function(input
)
234 this.setSelectionRange(input
, 0, 0)
236 Util
.prototype.setCaretToPos = function(input
, pos
)
238 this.setSelectionRange(input
, pos
, pos
)
240 Util
.prototype.selectString = function(input
, string
)
242 var match
= new RegExp(string
, "i").exec(input
.value
)
245 this.setSelectionRange (input
, match
.index
, match
.index
+ match
[0].length
)
248 Util
.prototype.replaceSelection = function(input
, replaceString
) {
249 if (input
.setSelectionRange
)
251 var selectionStart
= input
.selectionStart
252 var selectionEnd
= input
.selectionEnd
253 input
.value
= input
.value
.substring(0, selectionStart
) + replaceString
+ input
.value
.substring(selectionEnd
)
255 if (selectionStart
!= selectionEnd
) // has there been a selection
256 this.setSelectionRange(input
, selectionStart
, selectionStart
+ replaceString
.length
)
258 this.setCaretToPos(input
, selectionStart
+ replaceString
.length
)
260 else if (document
.selection
)
263 var range
= document
.selection
.createRange()
264 if (range
.parentElement() == input
)
266 var isCollapsed
= range
.text
== ''
267 range
.text
= replaceString
270 range
.moveStart('character', -replaceString
.length
);
276 Util
.prototype.rot13 = function(chaine
)
278 var ACode
= 'A'.charCodeAt(0)
279 var aCode
= 'a'.charCodeAt(0)
280 var MCode
= 'M'.charCodeAt(0)
281 var mCode
= 'm'.charCodeAt(0)
282 var ZCode
= 'Z'.charCodeAt(0)
283 var zCode
= 'z'.charCodeAt(0)
285 var f = function(ch
, pos
) {
286 if (pos
== ch
.length
)
289 var c
= ch
.charCodeAt(pos
);
290 return String
.fromCharCode(
292 (c
>= ACode
&& c
<= MCode
|| c
>= aCode
&& c
<= mCode
? 13 :
293 (c
> MCode
&& c
<= ZCode
|| c
> mCode
&& c
<= zCode
? -13 : 0))
299 ///////////////////////////////////////////////////////////////////////////////////////////////////
303 this.pageCourante
= null
308 * Accepte soit un objet soit un string.
309 * un string correspond au nom de la page, par exemple : "page" -> "page.html"
311 Pages
.prototype.ajouterPage = function(page
)
313 if (typeof page
== "string")
315 this.pages
[page
] = page
319 page
.pages
= this // la magie des langages dynamiques : le foutoire
320 this.pages
[page
.nom
] = page
324 Pages
.prototype.afficherPage = function(nomPage
, forcerChargement
)
326 if (forcerChargement
== undefined) forcerChargement
= false
328 var page
= this.pages
[nomPage
]
329 if (page
== undefined || (!forcerChargement
&& page
== this.pageCourante
)) return
331 if (this.pageCourante
!= null && this.pageCourante
.decharger
)
332 this.pageCourante
.decharger()
334 $("#menu li").removeClass("courante")
335 $("#menu li." + nomPage
).addClass("courante")
337 this.pageCourante
= page
339 if (typeof page
== "string")
340 $.ajax({async: false, url: "pages/" + page
+ ".html", success : function(page
) { contenu
+= page
}})
342 contenu
+= this.pageCourante
.contenu()
343 $("#page").html(contenu
).removeClass().addClass(this.pageCourante
.nom
)
345 if (this.pageCourante
.charger
)
346 this.pageCourante
.charger()
349 ///////////////////////////////////////////////////////////////////////////////////////////////////
352 * Classe permettant de formater du texte par exemple pour la substitution des liens dans les
353 * message par "[url]".
354 * TODO : améliorer l'efficacité des méthods notamment lié au smiles.
358 this.smiles
= conf
.smiles
359 this.protocoles
= "http|https|ed2k"
361 this.regexUrl
= new RegExp("(?:(?:" + this.protocoles
+ ")://|www\\.)[^ ]*", "gi")
362 this.regexImg
= new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
363 this.regexDomaine
= new RegExp("^(?:(?:" + this.protocoles
+ ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
364 this.regexTestProtocoleExiste
= new RegExp("^(?:" + this.protocoles
+ ")://.*$", "i")
365 this.regexNomProtocole
= new RegExp("^(.*?)://")
369 * Formate un pseudo saise par l'utilisateur.
370 * @param pseudo le pseudo brut
371 * @return le pseudo filtré
373 Formateur
.prototype.filtrerInputPseudo = function(pseudo
)
375 return pseudo
.replace(/{|}/g, "").trim()
378 Formateur
.prototype.getSmilesHTML = function()
381 for (var sNom
in this.smiles
)
383 XHTML
+= "<img class=\"" + sNom
+ "\" src=\"img/smileys/" + sNom
+ ".gif\" alt =\"" + sNom
+ "\" />"
389 * Formatage complet d'un texte.
391 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
393 Formateur
.prototype.traitementComplet = function(M
, pseudo
)
395 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.traiterWikiSyntaxe(this.remplacerBalisesHTML(M
)), pseudo
)))
399 * Transforme les liens en entités clickables.
400 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
401 * "{5F}" ou 5F est la racine de la conversation.
402 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
404 Formateur
.prototype.traiterLiensConv = function(M
)
410 return "<span class=\"lienConv\">" + lien
+ "</span>"
416 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
417 * moyenne sur échantillon : 234ms
419 Formateur
.prototype.traiterSmiles = function(M
)
421 for (var sNom
in this.smiles
)
423 ss
= this.smiles
[sNom
]
424 for (var i
= 0; i
< ss
.length
; i
++)
425 M
= M
.replace(ss
[i
], "<img src=\"img/smileys/" + sNom
+ ".gif\" alt =\"" + sNom
+ "\" />")
430 Formateur
.prototype.remplacerBalisesHTML = function(M
)
432 return M
.replace(/</g
, "<").replace(/>/g
, ">").replace(/"/g, ""
;")
435 Formateur.prototype.traiterURL = function(M, pseudo)
439 var traitementUrl = function(url)
441 // si ya pas de protocole on rajoute "http://"
442 if (!thisFormateur
.regexTestProtocoleExiste
.test(url
))
443 url
= "http://" + url
444 var extension
= thisFormateur
.getShort(url
)
445 return "<a " + (extension
[1] ? "title=\"" + (pseudo
== undefined ? "" : thisFormateur
.traiterPourFenetreLightBox(pseudo
, url
) + ": ") + thisFormateur
.traiterPourFenetreLightBox(M
, url
) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url
+ "\" >[" + extension
[0] + "]</a>"
447 return M
.replace(this.regexUrl
, traitementUrl
)
451 * Formatage en utilisant un sous-ensemble des règles de mediwiki.
452 * par exemple ''italic'' devient <i>italic</i>
454 Formateur
.prototype.traiterWikiSyntaxe = function(M
)
458 function(texte
, capture
)
460 return "<b>" + capture
+ "</b>"
464 function(texte
, capture
)
466 return "<i>" + capture
+ "</i>"
472 * Renvoie une version courte de l'url.
473 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
475 Formateur
.prototype.getShort = function(url
)
477 var estUneImage
= false
478 var versionShort
= null
479 var rechercheImg
= this.regexImg
.exec(url
)
481 if (rechercheImg
!= null)
483 versionShort
= rechercheImg
[1].toLowerCase()
484 if (versionShort
== "jpeg") versionShort
= "jpg" // jpeg -> jpg
489 var rechercheDomaine
= this.regexDomaine
.exec(url
)
490 if (rechercheDomaine
!= null && rechercheDomaine
.length
>= 2)
491 versionShort
= rechercheDomaine
[1]
494 var nomProtocole
= this.regexNomProtocole
.exec(url
)
495 if (nomProtocole
!= null && nomProtocole
.length
>= 2)
496 versionShort
= nomProtocole
[1]
500 return [versionShort
== null ? "url" : versionShort
, estUneImage
]
504 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
506 Formateur
.prototype.traiterPourFenetreLightBox = function(M
, urlCourante
)
509 var traitementUrl = function(url
)
511 return "[" + thisFormateur
.getShort(url
)[0] + (urlCourante
== url
? "*" : "") + "]"
514 return this.remplacerBalisesHTML(M
).replace(this.regexUrl
, traitementUrl
)
518 ///////////////////////////////////////////////////////////////////////////////////////////////////
520 // les statuts possibes du client
522 // mode enregistré, peut poster des messages et modifier son profile
524 // mode identifié, peut poster des messages mais n'a pas accès au profile
525 auth_not_registered : 1,
526 // mode déconnecté, ne peut pas poster de message
530 function Client(util
)
535 this.regexCookie
= new RegExp("^cookie=([^;]*)")
537 // données personnels
538 this.resetDonneesPersonnelles()
540 this.setStatut(statutType
.deconnected
)
542 // si true alors chaque modification du client est mémorisé sur le serveur
543 this.autoflush
= $.browser
["opera"]
546 Client
.prototype.resetDonneesPersonnelles = function()
549 this.pseudo
= conf
.pseudoDefaut
553 this.css
= $("link#cssPrincipale").attr("href")
554 this.nickFormat
= "nick"
555 this.viewTimes
= true
556 this.viewTooltips
= true
557 this.cookie
= undefined
559 this.pagePrincipale
= 1
560 this.ekMaster
= false
562 // les conversations, une conversation est un objet possédant les attributs suivants :
565 this.conversations
= new Array()
568 Client
.prototype.setCss = function(css
)
570 if (this.css
== css
|| css
== "")
574 $("link#cssPrincipale").attr("href", this.css
)
575 if (this.autoflush
) this.flush(true)
578 Client
.prototype.pageSuivante = function(numConv
)
580 if (numConv
< 0 && this.pagePrincipale
> 1)
581 this.pagePrincipale
-= 1
582 else if (this.conversations
[numConv
].page
> 1)
583 this.conversations
[numConv
].page
-= 1
586 Client
.prototype.pagePrecedente = function(numConv
)
589 this.pagePrincipale
+= 1
591 this.conversations
[numConv
].page
+= 1
595 * Définit la première page pour la conversation donnée.
596 * @return true si la page a changé sinon false
598 Client
.prototype.goPremierePage = function(numConv
)
602 if (this.pagePrincipale
== 1)
604 this.pagePrincipale
= 1
608 if (this.conversations
[numConv
].page
== 1)
610 this.conversations
[numConv
].page
= 1
616 * Ajoute une conversation à la vue de l'utilisateur.
617 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
618 * @param racines la racine de la conversation (integer)
619 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
621 Client
.prototype.ajouterConversation = function(racine
)
623 // vérification s'il elle n'existe pas déjà
624 for (var i
= 0; i
< this.conversations
.length
; i
++)
625 if (this.conversations
[i
].root
== racine
)
628 this.conversations
.push({root : racine
, page : 1})
630 if (this.autoflush
) this.flush(true)
635 Client
.prototype.supprimerConversation = function(num
)
637 if (num
< 0 || num
>= this.conversations
.length
) return
639 // décalage TODO : supprimer le dernier élément
640 for (var i
= num
; i
< this.conversations
.length
- 1; i
++)
641 this.conversations
[i
] = this.conversations
[i
+1]
642 this.conversations
.pop()
644 if (this.autoflush
) this.flush(true)
647 Client
.prototype.getJSONLogin = function(login
, password
)
650 "action" : "authentification",
652 "password" : password
656 Client
.prototype.getJSONLoginCookie = function()
659 "action" : "authentification",
660 "cookie" : this.cookie
665 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
666 * de s'autentifier avec (login, password).
668 Client
.prototype.getJSONEnregistrement = function(login
, password
)
670 var mess
= { "action" : "register" }
672 if (login
!= undefined && password
!= undefined)
674 mess
["login"] = login
675 mess
["password"] = password
681 Client
.prototype.getJSONConversations = function()
683 var conversations
= new Array()
684 for (var i
= 0; i
< this.conversations
.length
; i
++)
685 conversations
.push({ "root" : this.conversations
[i
].root
, "page" : this.conversations
[i
].page
})
689 Client
.prototype.getJSONProfile = function()
692 "action" : "set_profile",
693 "cookie" : this.cookie
,
694 "login" : this.login
,
695 "password" : this.password
,
696 "nick" : this.pseudo
,
697 "email" : this.email
,
699 "nick_format" : this.nickFormat
,
700 "view_times" : this.viewTimes
,
701 "view_tooltips" : this.viewTooltips
,
702 "main_page" : this.pagePrincipale
< 1 ? 1 : this.pagePrincipale
,
703 "conversations" : this.getJSONConversations()
708 * Renvoie null si pas définit.
710 Client
.prototype.getCookie = function()
712 var cookie
= this.regexCookie
.exec(document
.cookie
)
713 if (cookie
== null) this.cookie
= null
714 else this.cookie
= cookie
[1]
717 Client
.prototype.delCookie = function()
719 document
.cookie
= "cookie=; max-age=0"
722 Client
.prototype.setCookie = function()
724 if (this.cookie
== null || this.cookie
== undefined)
727 // ne fonctionne pas sous IE....
728 /*document.cookie = "cookie=" + this.cookie + "; max-age=" + (60 * 60 * 24 * 365) */
731 "cookie="+this.cookie
+"; expires=" + new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365).toUTCString()
734 Client
.prototype.authentifie = function()
736 return this.statut
== statutType
.auth_registered
|| this.statut
== statutType
.auth_not_registered
739 Client
.prototype.setStatut = function(statut
)
741 // conversation en "enum" si en "string"
742 if (typeof(statut
) == "string")
745 statut
== "auth_registered" ?
746 statutType
.auth_registered :
747 (statut
== "auth_not_registered" ? statutType
.auth_not_registered : statutType
.deconnected
)
750 if (statut
== this.statut
) return
757 * Effectue la connexion vers le serveur.
758 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
759 * S'il existe un cookie en local on s'authentifie directement avec lui.
760 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
762 Client
.prototype.connexionCookie = function()
765 if (this.cookie
== null) return false;
766 return this.connexion(this.getJSONLoginCookie())
769 Client
.prototype.connexionLogin = function(login
, password
)
771 return this.connexion(this.getJSONLogin(login
, password
))
774 Client
.prototype.enregistrement = function(login
, password
)
776 if (this.authentifie())
779 this.password
= password
782 this.setStatut(statutType
.auth_registered
)
789 return this.connexion(this.getJSONEnregistrement(login
, password
))
793 Client
.prototype.connexion = function(messageJson
)
795 ;; dumpObj(messageJson
)
803 data: this.util
.jsonVersAction(messageJson
),
808 if (data
["reply"] == "error")
809 thisClient
.util
.messageDialogue(data
["error_message"])
811 thisClient
.chargerDonnees(data
)
815 return this.authentifie()
818 Client
.prototype.deconnexion = function()
822 this.resetDonneesPersonnelles()
823 this.setStatut(statutType
.deconnected
) // deconnexion
826 Client
.prototype.chargerDonnees = function(data
)
828 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
829 // de l'état ekMaster
830 this.ekMaster
= data
["ek_master"] != undefined ? data
["ek_master"] : false
832 this.setStatut(data
["status"])
834 if (this.authentifie())
836 this.cookie
= data
["cookie"]
840 this.login
= data
["login"]
841 this.pseudo
= data
["nick"]
842 this.email
= data
["email"]
843 this.setCss(data
["css"])
844 this.nickFormat
= data
["nick_format"]
845 this.viewTimes
= data
["view_times"]
846 this.viewTooltips
= data
["view_tooltips"]
848 // la page de la conversation principale
849 this.pagePrincipale
= data
["main_page"] == undefined ? 1 : data
["main_page"]
852 this.conversations
= data
["conversations"]
855 this.majCssSelectionee()
860 * Met à jour les données personne sur serveur.
861 * @param async de manière asynchrone ? défaut = true
862 * @return false si le flush n'a pas pû se faire sinon true
864 Client
.prototype.flush = function(async
)
866 if (async
== undefined)
869 if (!this.authentifie())
872 var thisClient
= this
875 ;; dumpObj(this.getJSONProfile())
882 data: this.util
.jsonVersAction(this.getJSONProfile()),
887 if (data
["reply"] == "error")
889 thisClient
.util
.messageDialogue(data
["error_message"])
894 thisClient
.majBulle()
903 Client
.prototype.majMenu = function()
905 displayType
= "block"
907 $("#menu .admin").css("display", this.ekMaster
? displayType : "none")
909 // met à jour le menu
910 if (this.statut
== statutType
.auth_registered
)
912 $("#menu .profile").css("display", displayType
).text("profile")
913 $("#menu .logout").css("display", displayType
)
914 $("#menu .register").css("display", "none")
916 else if (this.statut
== statutType
.auth_not_registered
)
918 $("#menu .profile").css("display", "none")
919 $("#menu .logout").css("display", displayType
)
920 $("#menu .register").css("display", displayType
)
924 $("#menu .profile").css("display", displayType
).text("login")
925 $("#menu .logout").css("display", "none")
926 $("#menu .register").css("display", displayType
)
931 * Met à jour l'affichage des infos bulles en fonction du profile.
933 Client
.prototype.majBulle = function()
935 this.util
.bulleActive
= this.viewTooltips
939 * Met à jour la css sélectionnée, lors du chargement des données.
941 Client
.prototype.majCssSelectionee = function()
943 // extraction du numéro de la css courante
944 var numCssCourante
= this.css
.match(/^.*?\/(\d)\/.*$/)
945 if (numCssCourante
[1] != undefined)
947 $("#menuCss option").removeAttr("selected")
948 $("#menuCss option[value=" + numCssCourante
[1]+ "]").attr("selected", "selected")
952 Client
.prototype.slap = function(userId
, raison
)
954 var thisClient
= this
960 data: this.util
.jsonVersAction(
963 "cookie" : thisClient
.cookie
,
970 if (data
["reply"] == "error")
971 thisClient
.util
.messageDialogue(data
["error_message"])
976 Client
.prototype.ban = function(userId
, raison
, minutes
)
978 var thisClient
= this
980 // par défaut un ban correspond à 3 jours
981 if (typeof(minutes
) == "undefined")
982 minutes
= conf
.tempsBan
;
988 data: this.util
.jsonVersAction(
991 "cookie" : thisClient
.cookie
,
992 "duration" : minutes
,
999 if (data
["reply"] == "error")
1000 thisClient
.util
.messageDialogue(data
["error_message"])
1005 Client
.prototype.kick = function(userId
, raison
)
1007 this.ban(userId
, raison
, conf
.tempsKick
)
1010 ///////////////////////////////////////////////////////////////////////////////////////////////////
1013 * classe permettant de gérer les événements (push serveur).
1014 * l'information envoyé est sous la forme :
1016 * "action" : "wait_event"
1020 * l'information reçu est sous la forme :
1026 function PageEvent(page
, util
)
1031 // l'objet JSONHttpRequest représentant la connexion d'attente
1032 this.attenteCourante
= null
1034 // le multhreading du pauvre, merci javascript de m'offrire autant de primitives pour la gestion de la concurrence...
1039 * Arrête l'attente courante s'il y en a une.
1041 PageEvent
.prototype.stopAttenteCourante = function()
1045 if (this.attenteCourante
!= null)
1047 this.attenteCourante
.abort()
1052 * Attend un événement lié à la page.
1053 * @funSend une fonction renvoyant les données json à envoyer
1054 * @funsReceive est un objet comprenant les fonctions à appeler en fonction du "reply"
1055 * les fonctions acceptent un paramètre correspondant au données reçues.
1056 * exemple : {"new_message" : function(data){ ... }}
1058 PageEvent
.prototype.waitEvent = function(funSend
, funsReceive
)
1060 this.stopAttenteCourante()
1064 var thisPageEvent
= this
1066 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veut dans l'ordre définit dans le protocole)
1067 // TODO : ya pas mieux ?
1070 "action" : "wait_event",
1073 var poulpe
= funSend()
1075 dataToSend
[v
] = poulpe
[v
]
1077 ;; dumpObj(dataToSend
)
1079 this.attenteCourante
= jQuery
.ajax({
1083 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
1084 // Obsolète (voir TODO)
1085 //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
1086 data: this.util
.jsonVersAction(dataToSend
),
1092 funsReceive
[data
["reply"]](data
)
1094 // rappel de la fonction dans 100 ms
1095 setTimeout(function(){ thisPageEvent
.waitEvent2(funSend
, funsReceive
) }, 100)
1098 function(XMLHttpRequest
, textStatus
, errorThrown
)
1100 ;; console
.log("Connexion perdue dans waitEvent")
1101 setTimeout(function(){ thisPageEvent
.waitEvent2(funSend
, funsReceive
) }, 1000)
1107 * Si un stopAttenteCourante survient un peu n'importe quand il faut imédiatement arreter de boucler.
1109 PageEvent
.prototype.waitEvent2 = function(funSend
, funsReceive
)
1113 this.waitEvent(funSend
, funsReceive
)
1116 ///////////////////////////////////////////////////////////////////////////////////////////////////
1118 function initialiserListeStyles(client
)
1120 $("#menuCss").change(
1123 client
.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
1128 // charge dynamiquement le script de debug
1129 ;; jQuery
.ajax({async : false, url : "js/debug.js", dataType : "script"})
1135 var formateur
= new Formateur()
1136 var util
= new Util(formateur
)
1137 var client
= new Client(util
)
1138 var pages
= new Pages()
1140 // connexion vers le serveur (utilise un cookie qui traine)
1141 client
.connexionCookie()
1143 initialiserListeStyles(client
)
1145 // FIXME : ne fonctionne pas sous opera
1146 // voir : http://dev.jquery.com/ticket/2892#preview
1147 $(window
).unload(function(){client
.flush()})
1149 $("#menu .minichat").click(function(){ pages
.afficherPage("minichat") })
1150 $("#menu .admin").click(function(){ pages
.afficherPage("admin") })
1151 $("#menu .profile").click(function(){ pages
.afficherPage("profile") })
1152 $("#menu .logout").click(function(){
1153 util
.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType
.question
,
1156 client
.deconnexion();
1157 pages
.afficherPage("minichat", true)
1159 "Non" : function(){}
1163 $("#menu .register").click(function(){ pages
.afficherPage("register") })
1164 $("#menu .about").click(function(){ pages
.afficherPage("about") })
1166 // TODO : simplifier et pouvoir créer des liens par exemple : <span class="lien" href="conditions">Conditions d'utilisation</span>
1167 $("#footer .conditions").click(function(){ pages
.afficherPage("conditions_utilisation") })
1169 pages
.ajouterPage(new PageMinichat(client
, formateur
, util
))
1170 pages
.ajouterPage(new PageAdmin(client
, formateur
, util
))
1171 pages
.ajouterPage(new PageProfile(client
, formateur
, util
))
1172 pages
.ajouterPage(new PageRegister(client
, formateur
, util
))
1173 pages
.ajouterPage(new PageAbout(client
, formateur
, util
))
1174 pages
.ajouterPage("conditions_utilisation")
1176 pages
.afficherPage("minichat")