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 versionProtocole : 3, // version du protcole
33 nickDefaut : "<nick>",
34 nbMessageAffiche : 60, // (par page)
35 pseudoDefaut : "<nick>",
36 tempsAffichageMessageDialogue : 4000, // en ms
37 tempsKick : 15, // en minute
38 tempsBan : 60 * 24 * 3, // en minutes (3jours)
40 "smile" : [/:\)/g, /:-\)/g],
41 "bigsmile" : [/:D/g, /:-D/g],
42 "clin" : [/;\)/g, /;-\)/g],
43 "cool" : [/8\)/g, /8-\)/g],
44 "eheheh" : [/:P/g, /:-P/g],
45 "lol" : [/\[-lol\]/g],
47 "spliff" : [/\[-spliff\]/g],
48 "oh" : [/:o/g, /:O/g],
49 "heink" : [/\[-heink\]/g],
50 "hum" : [/\[-hum\]/g],
51 "boh" : [/\[-boh\]/g],
52 "sniff" : [/:\(/g, /:-\(/g],
53 "triste" : [/\[-triste\]/g],
54 "pascontent" : [/>\(/g, />\(/g],
55 "argn" : [/\[-argn\]/g],
56 "redface" : [/\[-redface\]/g],
57 "bunny" : [/\[-lapin\]/g],
58 "chat" : [/\[-chat\]/g],
59 "renne" : [/\[-renne\]/g],
60 "star" : [/\[-star\]/g],
61 "kirby" : [/\[-kirby\]/g],
62 "slurp" : [/\[-slurp\]/g],
63 "agreed" : [/\[-agreed\]/g],
64 "dodo" : [/\[-dodo\]/g],
69 ///////////////////////////////////////////////////////////////////////////////////////////////////
71 String
.prototype.trim = function()
73 return jQuery
.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
76 String
.prototype.ltrim = function()
78 return this.replace(/^\s+/, "");
81 String
.prototype.rtrim = function()
83 return this.replace(/\s+$/, "");
86 ///////////////////////////////////////////////////////////////////////////////////////////////////
89 * Cette classe regroupe des fonctions utilitaires (helpers).
90 * @formateur est permet de formater les messages affichés à l'aide de messageDialogue (facultatif)
92 function Util(formateur
)
94 $("#info .fermer").click(function(){
95 $("#info").slideUp(50)
98 $("body").append('<div id="flecheBulle"></div>').append('<div id="messageBulle"><p></p></div>')
100 this.formateur
= formateur
101 this.bulleActive
= true
104 var messageType
= {informatif: 0, question: 1, erreur: 2}
107 * Affiche une boite de dialogue avec un message à l'intérieur.
108 * @param message le message (string)
109 * @param type voir 'messageType'. par défaut messageType.informatif
110 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
111 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
112 * @param formate faut-il formaté le message ? true par défaut
114 Util
.prototype.messageDialogue = function(message
, type
, boutons
, formate
)
118 if (type
== undefined)
119 type
= messageType
.informatif
121 if (formate
== undefined)
124 if (this.timeoutMessageDialogue
!= undefined)
125 clearTimeout(this.timeoutMessageDialogue
)
127 var fermer = function(){$("#info").slideUp(100)}
130 $("#info .message").html(thisUtil
.formateur
== undefined || !formate
? message : thisUtil
.formateur
.traitementComplet(message
))
133 case messageType
.informatif : $("#info #icone").attr("class", "information"); break
134 case messageType
.question : $("#info #icone").attr("class", "interrogation"); break
135 case messageType
.erreur : $("#info #icone").attr("class", "exclamation"); break
137 $("#info .boutons").html("")
138 for (var b
in boutons
)
139 $("#info .boutons").append("<div>" + b
+ "</div>").find("div:last").click(boutons
[b
]).click(fermer
)
141 $("#info").slideDown(200)
142 this.timeoutMessageDialogue
= setTimeout(fermer
, conf
.tempsAffichageMessageDialogue
)
145 var positionTypeX
= {gauche: 0, gaucheRecouvrement: 1, centre: 2, droiteRecouvrement: 3, droite: 4}
146 var positionTypeY
= {haut: 0, hautRecouvrement: 1, centre: 2, basRecouvrement: 3, bas: 4}
149 * Afficher une boite flottante (élément) par rapport à une cible.
150 * La boite est affichée de manière à ne pas dépasser de la fenêtre.
151 * @boite l'élément à afficher
152 * @cible l'élément sur lequel est affiché la boite
153 * @positionX de type positionTypeX
154 * @positionY de type positionTypeY
156 Util
.prototype.afficherBoite = function(boite
, cible
, positionX
, positionY
)
158 var positionCible
= cible
.offset()
161 left : positionX
== positionTypeX
.gauche
? positionCible
.left
- boite
.width() :
162 (positionX
== positionTypeX
.gaucheRecouvrement
? positionCible
.left
- boite
.width() + cible
.width() :
163 (positionX
== positionTypeX
.droitelsRecouvrement
? positionCible
.left :
164 (positionX
== positionTypeX
.droite
? positionCible
.left
+ cible
.width() :
165 positionCible
.left
+ cible
.width() / 2 - boite
.width() / 2 ))), // centre
166 top : positionY
== positionTypeY
.haut
? positionCible
.top
- boite
.height() :
167 (positionY
== positionTypeY
.hautRecouvrement
? positionCible
.top
- boite
.height() + cible
.height() :
168 (positionY
== positionTypeY
.basRecouvrement
? positionCible
.top :
169 (positionY
== positionTypeY
.bas
? positionCible
.top
+ cible
.height() :
170 positionCible
.top
+ cible
.height() / 2 - boite
.height() / 2 ))) // centre
173 // calcul les décalages en x et en y pour éviter que la boite ne sorte de la fenêtre, tient compte de la position des barres de défilement
175 positionBoite
.left
= positionBoite
.left
< marge
+ window
.pageXOffset
? marge
+ window
.pageXOffset :
176 (boite
.width() - $(window
).width() + (positionBoite
.left
- window
.pageXOffset
) + marge
> 0 ? $(window
).width() - boite
.width() - marge
+ window
.pageXOffset : positionBoite
.left
)
177 positionBoite
.top
= positionBoite
.top
< marge
+ window
.pageYOffset
? marge
+ window
.pageYOffset :
178 (boite
.height() - $(window
).height() + (positionBoite
.top
- window
.pageYOffset
) + marge
> 0 ? $(window
).height() - boite
.height() - marge
+ window
.pageYOffset : positionBoite
.top
)
180 boite
.css("top", positionBoite
.top
).css("left", positionBoite
.left
).show()
184 * Affiche un info bulle lorsque le curseur survole l'élément donné.
185 * FIXME : le width de element ne tient pas compte du padding !?
187 Util
.prototype.infoBulle = function(message
, element
)
191 var cacherBulle = function()
193 $("#flecheBulle").hide()
194 $("#messageBulle").hide()
200 if (!thisUtil
.bulleActive
)
203 var m
= $("#messageBulle")
204 var f
= $("#flecheBulle")
206 // remplie le paragraphe de la bulle avec le message
207 $("p", m
).html(message
)
209 // réinitialise la position, évite le cas ou la boite est collé à droite et remplie avec un texte la faisant dépassé
210 // dans ce cas la hauteur n'est pas calculé correctement
211 m
.css("top", 0).css("left", 0)
213 var positionFleche
= {
214 left : element
.offset().left
+ element
.innerWidth() / 2 - f
.width() / 2,
215 top : element
.offset().top
- f
.height()
217 var positionMessage
= {
218 left : element
.offset().left
+ element
.width() / 2 - m
.width() / 2,
219 top : element
.offset().top
- f
.height() - m
.height()
221 var depassementDroit
= (positionMessage
.left
+ m
.width()) - $("body").width()
222 if (depassementDroit
> 0)
223 positionMessage
.left
-= depassementDroit
226 if (positionMessage
.left
< 0)
227 positionMessage
.left
= 0
230 m
.css("top", positionMessage
.top
).css("left", positionMessage
.left
).show()
231 f
.css("top", positionFleche
.top
).css("left", positionFleche
.left
).show()
238 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
240 Util
.prototype.jsonVersAction = function(json
)
242 return {action : JSON
.stringify(json
) }
245 Util
.prototype.md5 = function(chaine
)
247 return hex_md5(chaine
)
250 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
251 Util
.prototype.setSelectionRange = function(input
, selectionStart
, selectionEnd
)
253 if (input
.setSelectionRange
)
256 input
.setSelectionRange(selectionStart
, selectionEnd
)
258 else if (input
.createTextRange
)
260 var range
= input
.createTextRange()
262 range
.moveEnd('character', selectionEnd
)
263 range
.moveStart('character', selectionStart
)
268 Util
.prototype.setCaretToEnd = function(input
)
270 this.setSelectionRange(input
, input
.value
.length
, input
.value
.length
)
272 Util
.prototype.setCaretToBegin = function(input
)
274 this.setSelectionRange(input
, 0, 0)
276 Util
.prototype.setCaretToPos = function(input
, pos
)
278 this.setSelectionRange(input
, pos
, pos
)
280 Util
.prototype.selectString = function(input
, string
)
282 var match
= new RegExp(string
, "i").exec(input
.value
)
285 this.setSelectionRange (input
, match
.index
, match
.index
+ match
[0].length
)
288 Util
.prototype.replaceSelection = function(input
, replaceString
) {
289 if (input
.setSelectionRange
)
291 var selectionStart
= input
.selectionStart
292 var selectionEnd
= input
.selectionEnd
293 input
.value
= input
.value
.substring(0, selectionStart
) + replaceString
+ input
.value
.substring(selectionEnd
)
295 if (selectionStart
!= selectionEnd
) // has there been a selection
296 this.setSelectionRange(input
, selectionStart
, selectionStart
+ replaceString
.length
)
298 this.setCaretToPos(input
, selectionStart
+ replaceString
.length
)
300 else if (document
.selection
)
303 var range
= document
.selection
.createRange()
304 if (range
.parentElement() == input
)
306 var isCollapsed
= range
.text
== ''
307 range
.text
= replaceString
310 range
.moveStart('character', -replaceString
.length
);
316 Util
.prototype.rot13 = function(chaine
)
318 var ACode
= 'A'.charCodeAt(0)
319 var aCode
= 'a'.charCodeAt(0)
320 var MCode
= 'M'.charCodeAt(0)
321 var mCode
= 'm'.charCodeAt(0)
322 var ZCode
= 'Z'.charCodeAt(0)
323 var zCode
= 'z'.charCodeAt(0)
325 var f = function(ch
, pos
) {
326 if (pos
== ch
.length
)
329 var c
= ch
.charCodeAt(pos
);
330 return String
.fromCharCode(
332 (c
>= ACode
&& c
<= MCode
|| c
>= aCode
&& c
<= mCode
? 13 :
333 (c
> MCode
&& c
<= ZCode
|| c
> mCode
&& c
<= zCode
? -13 : 0))
339 ///////////////////////////////////////////////////////////////////////////////////////////////////
343 this.pageCourante
= null
348 * Accepte soit un objet soit un string.
349 * un string correspond au nom de la page, par exemple : "page" -> "page.html"
351 Pages
.prototype.ajouterPage = function(page
)
353 if (typeof page
== "string")
355 this.pages
[page
] = page
359 page
.pages
= this // la magie des langages dynamiques : le foutoire
360 this.pages
[page
.nom
] = page
364 Pages
.prototype.afficherPage = function(nomPage
, forcerChargement
)
366 if (forcerChargement
== undefined) forcerChargement
= false
368 var page
= this.pages
[nomPage
]
369 if (page
== undefined || (!forcerChargement
&& page
== this.pageCourante
)) return
371 if (this.pageCourante
!= null && this.pageCourante
.decharger
)
372 this.pageCourante
.decharger()
374 $("#menu li").removeClass("courante")
375 $("#menu li." + nomPage
).addClass("courante")
377 this.pageCourante
= page
379 if (typeof page
== "string")
380 $.ajax({async: false, url: "pages/" + page
+ ".html", success : function(page
) { contenu
+= page
}})
382 contenu
+= this.pageCourante
.contenu()
383 $("#page").html(contenu
).removeClass().addClass(this.pageCourante
.nom
)
385 if (this.pageCourante
.charger
)
386 this.pageCourante
.charger()
389 ///////////////////////////////////////////////////////////////////////////////////////////////////
392 * Classe permettant de formater du texte par exemple pour la substitution des liens dans les
393 * message par "[url]".
394 * TODO : améliorer l'efficacité des méthods notamment lié au smiles.
398 this.smiles
= conf
.smiles
399 this.protocoles
= "http|https|ed2k"
401 this.regexUrl
= new RegExp("(?:(?:" + this.protocoles
+ ")://|www\\.)[^ ]*", "gi")
402 this.regexImg
= new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
403 this.regexDomaine
= new RegExp("^(?:(?:" + this.protocoles
+ ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
404 this.regexTestProtocoleExiste
= new RegExp("^(?:" + this.protocoles
+ ")://.*$", "i")
405 this.regexNomProtocole
= new RegExp("^(.*?)://")
409 * Formate un pseudo saise par l'utilisateur.
410 * @param pseudo le pseudo brut
411 * @return le pseudo filtré
413 Formateur
.prototype.filtrerInputPseudo = function(pseudo
)
415 return pseudo
.replace(/{|}/g, "").trim()
418 Formateur
.prototype.getSmilesHTML = function()
421 for (var sNom
in this.smiles
)
423 XHTML
+= "<img class=\"" + sNom
+ "\" src=\"img/smileys/" + sNom
+ ".gif\" alt =\"" + sNom
+ "\" />"
429 * Formatage complet d'un texte.
431 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
433 Formateur
.prototype.traitementComplet = function(M
, pseudo
)
435 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.traiterWikiSyntaxe(this.remplacerBalisesHTML(M
)), pseudo
)))
439 * Transforme les liens en entités clickables.
440 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
441 * "{5F}" ou 5F est la racine de la conversation.
442 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
444 Formateur
.prototype.traiterLiensConv = function(M
)
450 return "<span class=\"lienConv\">" + lien
+ "</span>"
456 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
457 * moyenne sur échantillon : 234ms
459 Formateur
.prototype.traiterSmiles = function(M
)
461 for (var sNom
in this.smiles
)
463 ss
= this.smiles
[sNom
]
464 for (var i
= 0; i
< ss
.length
; i
++)
465 M
= M
.replace(ss
[i
], "<img src=\"img/smileys/" + sNom
+ ".gif\" alt =\"" + sNom
+ "\" />")
470 Formateur
.prototype.remplacerBalisesHTML = function(M
)
472 return M
.replace(/</g
, "<").replace(/>/g
, ">").replace(/"/g, ""
;")
475 Formateur.prototype.traiterURL = function(M, pseudo)
479 var traitementUrl = function(url)
481 // si ya pas de protocole on rajoute "http://"
482 if (!thisFormateur
.regexTestProtocoleExiste
.test(url
))
483 url
= "http://" + url
484 var extension
= thisFormateur
.getShort(url
)
485 return "<a " + (extension
[1] ? "title=\"" + (pseudo
== undefined ? "" : thisFormateur
.traiterPourFenetreLightBox(pseudo
, url
) + ": ") + thisFormateur
.traiterPourFenetreLightBox(M
, url
) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url
+ "\" >[" + extension
[0] + "]</a>"
487 return M
.replace(this.regexUrl
, traitementUrl
)
491 * Formatage en utilisant un sous-ensemble des règles de mediwiki.
492 * par exemple ''italic'' devient <i>italic</i>
494 Formateur
.prototype.traiterWikiSyntaxe = function(M
)
498 function(texte
, capture
)
500 return "<b>" + capture
+ "</b>"
504 function(texte
, capture
)
506 return "<i>" + capture
+ "</i>"
512 * Renvoie une version courte de l'url.
513 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
515 Formateur
.prototype.getShort = function(url
)
517 var estUneImage
= false
518 var versionShort
= null
519 var rechercheImg
= this.regexImg
.exec(url
)
521 if (rechercheImg
!= null)
523 versionShort
= rechercheImg
[1].toLowerCase()
524 if (versionShort
== "jpeg") versionShort
= "jpg" // jpeg -> jpg
529 var rechercheDomaine
= this.regexDomaine
.exec(url
)
530 if (rechercheDomaine
!= null && rechercheDomaine
.length
>= 2)
531 versionShort
= rechercheDomaine
[1]
534 var nomProtocole
= this.regexNomProtocole
.exec(url
)
535 if (nomProtocole
!= null && nomProtocole
.length
>= 2)
536 versionShort
= nomProtocole
[1]
540 return [versionShort
== null ? "url" : versionShort
, estUneImage
]
544 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
546 Formateur
.prototype.traiterPourFenetreLightBox = function(M
, urlCourante
)
549 var traitementUrl = function(url
)
551 return "[" + thisFormateur
.getShort(url
)[0] + (urlCourante
== url
? "*" : "") + "]"
554 return this.remplacerBalisesHTML(M
).replace(this.regexUrl
, traitementUrl
)
558 ///////////////////////////////////////////////////////////////////////////////////////////////////
560 // les statuts possibes du client
562 // mode enregistré, peut poster des messages et modifier son profile
564 // mode identifié, peut poster des messages mais n'a pas accès au profile
565 auth_not_registered : 1,
566 // mode déconnecté, ne peut pas poster de message
570 function Client(util
)
575 this.regexCookie
= new RegExp("^cookie=([^;]*)")
577 // données personnels
578 this.resetDonneesPersonnelles()
580 this.setStatut(statutType
.deconnected
)
582 // si true alors chaque modification du client est mémorisé sur le serveur
583 this.autoflush
= $.browser
["opera"]
586 Client
.prototype.resetDonneesPersonnelles = function()
589 this.pseudo
= conf
.pseudoDefaut
593 this.css
= $("link#cssPrincipale").attr("href")
594 this.nickFormat
= "nick"
595 this.viewTimes
= true
596 this.viewTooltips
= true
597 this.cookie
= undefined
599 this.pagePrincipale
= 1
600 this.ekMaster
= false
601 this.ostentatiousMaster
= "light"
603 // les conversations, une conversation est un objet possédant les attributs suivants :
607 this.conversations
= []
610 Client
.prototype.setCss = function(css
)
612 if (this.css
== css
|| css
== "")
616 $("link#cssPrincipale").attr("href", this.css
)
617 if (this.autoflush
) this.flush(true)
620 Client
.prototype.pageSuivante = function(numConv
)
622 if (numConv
< 0 && this.pagePrincipale
> 1)
623 this.pagePrincipale
-= 1
624 else if (this.conversations
[numConv
].page
> 1)
625 this.conversations
[numConv
].page
-= 1
628 Client
.prototype.pagePrecedente = function(numConv
)
631 this.pagePrincipale
+= 1
633 this.conversations
[numConv
].page
+= 1
637 * Définit la première page pour la conversation donnée.
638 * @return true si la page a changé sinon false
640 Client
.prototype.goPremierePage = function(numConv
)
644 if (this.pagePrincipale
== 1)
646 this.pagePrincipale
= 1
650 if (this.conversations
[numConv
].page
== 1)
652 this.conversations
[numConv
].page
= 1
658 * Ajoute une conversation à la vue de l'utilisateur.
659 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
660 * @param racines la racine de la conversation (integer)
661 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
663 Client
.prototype.ajouterConversation = function(racine
)
665 // vérification s'il elle n'existe pas déjà
666 for (var i
= 0; i
< this.conversations
.length
; i
++)
667 if (this.conversations
[i
].root
== racine
)
670 this.conversations
.push({root : racine
, page : 1, reduit : false})
671 if (this.autoflush
) this.flush(true)
676 Client
.prototype.supprimerConversation = function(num
)
678 if (num
< 0 || num
>= this.conversations
.length
) return
680 // décalage TODO : supprimer le dernier élément
681 for (var i
= num
; i
< this.conversations
.length
- 1; i
++)
682 this.conversations
[i
] = this.conversations
[i
+1]
683 this.conversations
.pop()
685 if (this.autoflush
) this.flush(true)
688 Client
.prototype.getJSONLogin = function(login
, password
)
691 "header" : { "action" : "authentification", "version" : conf
.versionProtocole
},
693 "password" : password
697 Client
.prototype.getJSONLoginCookie = function()
700 "header" : { "action" : "authentification", "version" : conf
.versionProtocole
},
701 "cookie" : this.cookie
706 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
707 * de s'autentifier avec (login, password).
709 Client
.prototype.getJSONEnregistrement = function(login
, password
)
711 var mess
= { "header" : { "action" : "register", "version" : conf
.versionProtocole
}}
713 if (login
!= undefined && password
!= undefined)
715 mess
["login"] = login
716 mess
["password"] = password
722 Client
.prototype.getJSONConversations = function()
724 var conversations
= new Array()
725 for (var i
= 0; i
< this.conversations
.length
; i
++)
726 conversations
.push({root : this.conversations
[i
].root
, minimized : this.conversations
[i
].reduit
})
730 Client
.prototype.getJSONProfile = function()
733 "header" : { "action" : "set_profile", "version" : conf
.versionProtocole
},
734 "cookie" : this.cookie
,
735 "login" : this.login
,
736 "password" : this.password
,
737 "nick" : this.pseudo
,
738 "email" : this.email
,
740 "nick_format" : this.nickFormat
,
741 "view_times" : this.viewTimes
,
742 "view_tooltips" : this.viewTooltips
,
743 "conversations" : this.getJSONConversations(),
744 "ostentatious_master" : this.ostentatiousMaster
749 * Renvoie null si pas définit.
751 Client
.prototype.getCookie = function()
753 var cookie
= this.regexCookie
.exec(document
.cookie
)
754 if (cookie
== null) this.cookie
= null
755 else this.cookie
= cookie
[1]
758 Client
.prototype.delCookie = function()
760 document
.cookie
= "cookie=; max-age=0"
763 Client
.prototype.setCookie = function()
765 if (this.cookie
== null || this.cookie
== undefined)
768 // ne fonctionne pas sous IE....
769 /*document.cookie = "cookie=" + this.cookie + "; max-age=" + (60 * 60 * 24 * 365) */
772 "cookie="+this.cookie
+"; expires=" + new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365).toUTCString()
775 Client
.prototype.authentifie = function()
777 return this.statut
== statutType
.auth_registered
|| this.statut
== statutType
.auth_not_registered
780 Client
.prototype.setStatut = function(statut
)
782 // conversation en "enum" si en "string"
783 if (typeof(statut
) == "string")
786 statut
== "auth_registered" ?
787 statutType
.auth_registered :
788 (statut
== "auth_not_registered" ? statutType
.auth_not_registered : statutType
.deconnected
)
791 if (statut
== this.statut
) return
799 * Effectue la connexion vers le serveur.
800 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
801 * S'il existe un cookie en local on s'authentifie directement avec lui.
802 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
804 Client
.prototype.connexionCookie = function()
807 if (this.cookie
== null) return false;
808 return this.connexion(this.getJSONLoginCookie())
811 Client
.prototype.connexionLogin = function(login
, password
)
813 return this.connexion(this.getJSONLogin(login
, password
))
816 Client
.prototype.enregistrement = function(login
, password
)
818 if (this.authentifie())
821 this.password
= password
824 this.setStatut(statutType
.auth_registered
)
831 return this.connexion(this.getJSONEnregistrement(login
, password
))
835 Client
.prototype.connexion = function(messageJson
)
844 data: this.util
.jsonVersAction(messageJson
),
848 if (data
["reply"] == "error")
850 thisClient
.util
.messageDialogue(data
["error_message"])
851 // suppression du cookie actuel, cas où le cookie du client ne permet pas une authentification
852 thisClient
.delCookie()
855 thisClient
.chargerDonnees(data
)
859 return this.authentifie()
862 Client
.prototype.deconnexion = function()
866 this.resetDonneesPersonnelles()
867 this.setStatut(statutType
.deconnected
) // deconnexion
870 Client
.prototype.chargerDonnees = function(data
)
872 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
873 // de l'état ekMaster
874 this.ekMaster
= data
["ek_master"] != undefined ? data
["ek_master"] : false
876 this.setStatut(data
["status"])
878 if (this.authentifie())
880 this.cookie
= data
["cookie"]
884 this.login
= data
["login"]
885 this.pseudo
= data
["nick"]
886 this.email
= data
["email"]
887 this.setCss(data
["css"])
888 this.nickFormat
= data
["nick_format"]
889 this.viewTimes
= data
["view_times"]
890 this.viewTooltips
= data
["view_tooltips"]
891 this.ostentatiousMaster
= data
["ostentatious_master"]
893 // la page de la conversation principale
894 this.pagePrincipale
= 1
897 this.conversations
= data
["conversations"]
898 for (var i
= 0; i
< this.conversations
.length
; i
++)
899 this.conversations
[i
] = {root : this.conversations
[i
].root
, page : 1, reduit : this.conversations
[i
].minimized
}
902 this.majCssSelectionee()
908 * Met à jour les données personne sur serveur.
909 * @param async de manière asynchrone ? défaut = true
910 * @return false si le flush n'a pas pû se faire sinon true
912 Client
.prototype.flush = function(async
)
914 if (async
== undefined)
917 if (!this.authentifie())
920 var thisClient
= this
929 data: this.util
.jsonVersAction(this.getJSONProfile()),
933 if (data
["reply"] == "error")
935 thisClient
.util
.messageDialogue(data
["error_message"])
940 thisClient
.majBulle()
949 Client
.prototype.majMenu = function()
951 displayType
= "block"
953 $("#menu .admin").css("display", this.ekMaster
? displayType : "none")
955 // met à jour le menu
956 if (this.statut
== statutType
.auth_registered
)
958 $("#menu .profile").css("display", displayType
).text("profile")
959 $("#menu .logout").css("display", displayType
)
960 $("#menu .register").css("display", "none")
962 else if (this.statut
== statutType
.auth_not_registered
)
964 $("#menu .profile").css("display", "none")
965 $("#menu .logout").css("display", displayType
)
966 $("#menu .register").css("display", displayType
)
970 $("#menu .profile").css("display", displayType
).text("login")
971 $("#menu .logout").css("display", "none")
972 $("#menu .register").css("display", displayType
)
977 * Met à jour l'affichage des infos bulles en fonction du profile.
979 Client
.prototype.majBulle = function()
981 this.util
.bulleActive
= this.viewTooltips
985 * Met à jour la css sélectionnée, lors du chargement des données.
987 Client
.prototype.majCssSelectionee = function()
989 // extraction du numéro de la css courante
990 var numCssCourante
= this.css
.match(/^.*?\/(\d)\/.*$/)
991 if (numCssCourante
!= null && numCssCourante
[1] != undefined)
993 $("#menuCss option").removeAttr("selected")
994 $("#menuCss option[value=" + numCssCourante
[1]+ "]").attr("selected", "selected")
999 * Change la "class" du logo en fonction du statut de ekMaster.
1001 Client
.prototype.majLogo = function()
1004 $("#logo").addClass("ekMaster")
1006 $("#logo").removeClass("ekMaster")
1010 Client
.prototype.slap = function(userId
, raison
)
1012 var thisClient
= this
1018 data: this.util
.jsonVersAction(
1020 "header" : { "action" : "slap", "version" : conf
.versionProtocole
},
1021 "cookie" : thisClient
.cookie
,
1028 if (data
["reply"] == "error")
1029 thisClient
.util
.messageDialogue(data
["error_message"])
1034 Client
.prototype.ban = function(userId
, raison
, minutes
)
1036 var thisClient
= this
1038 // par défaut un ban correspond à 3 jours
1039 if (typeof(minutes
) == "undefined")
1040 minutes
= conf
.tempsBan
;
1046 data: this.util
.jsonVersAction(
1048 "header" : { "action" : "ban", "version" : conf
.versionProtocole
},
1049 "cookie" : thisClient
.cookie
,
1050 "duration" : minutes
,
1057 if (data
["reply"] == "error")
1058 thisClient
.util
.messageDialogue(data
["error_message"])
1063 Client
.prototype.kick = function(userId
, raison
)
1065 this.ban(userId
, raison
, conf
.tempsKick
)
1068 ///////////////////////////////////////////////////////////////////////////////////////////////////
1071 * classe permettant de gérer les événements (push serveur).
1072 * l'information envoyé est sous la forme :
1074 * "header" : {"action" : "wait_event", "version" : <v> },
1078 * l'information reçu est sous la forme :
1084 function PageEvent(page
, util
)
1089 // l'objet JSONHttpRequest représentant la connexion d'attente
1090 this.attenteCourante
= null
1092 // le multhreading du pauvre, merci javascript de m'offrire autant de primitives pour la gestion de la concurrence...
1097 * Arrête l'attente courante s'il y en a une.
1099 PageEvent
.prototype.stopAttenteCourante = function()
1103 if (this.attenteCourante
!= null)
1105 this.attenteCourante
.abort()
1110 * Attend un événement lié à la page.
1111 * @funSend une fonction renvoyant les données json à envoyer
1112 * @funsReceive est un objet comprenant les fonctions à appeler en fonction du "reply"
1113 * les fonctions acceptent un paramètre correspondant au données reçues.
1114 * exemple : {"new_message" : function(data){ ... }}
1116 PageEvent
.prototype.waitEvent = function(funSend
, funsReceive
)
1118 this.stopAttenteCourante()
1122 var thisPageEvent
= this
1124 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veut dans l'ordre définit dans le protocole)
1125 // TODO : ya pas mieux ?
1128 "header" : { "action" : "wait_event", "version" : conf
.versionProtocole
},
1131 var poulpe
= funSend()
1133 dataToSend
[v
] = poulpe
[v
]
1135 this.attenteCourante
= jQuery
.ajax({
1139 // TODO : doit disparaitre
1140 timeout: 180000, // timeout de 3min. Gros HACK pas beau. FIXME problème décrit ici : http://groups.google.com/group/jquery-en/browse_thread/thread/8724e64af3333a76
1141 data: this.util
.jsonVersAction(dataToSend
),
1145 funsReceive
[data
["reply"]](data
)
1147 // rappel de la fonction dans 100 ms
1148 setTimeout(function(){ thisPageEvent
.waitEvent2(funSend
, funsReceive
) }, 100)
1151 function(XMLHttpRequest
, textStatus
, errorThrown
)
1153 ;; console
.log("Connexion perdue dans waitEvent")
1154 setTimeout(function(){ thisPageEvent
.waitEvent2(funSend
, funsReceive
) }, 1000)
1160 * Si un stopAttenteCourante survient un peu n'importe quand il faut imédiatement arreter de boucler.
1162 PageEvent
.prototype.waitEvent2 = function(funSend
, funsReceive
)
1166 this.waitEvent(funSend
, funsReceive
)
1169 ///////////////////////////////////////////////////////////////////////////////////////////////////
1171 function initialiserListeStyles(client
)
1173 $("#menuCss").change(
1176 client
.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
1181 // charge dynamiquement le script de debug
1182 ;; jQuery
.ajax({async : false, url : "js/debug.js", dataType : "script"})
1188 var formateur
= new Formateur()
1189 var util
= new Util(formateur
)
1190 var client
= new Client(util
)
1191 var pages
= new Pages()
1193 // connexion vers le serveur (utilise un cookie qui traine)
1194 client
.connexionCookie()
1196 initialiserListeStyles(client
)
1198 // FIXME : ne fonctionne pas sous opera
1199 // voir : http://dev.jquery.com/ticket/2892#preview
1200 $(window
).unload(function(){client
.flush()})
1202 $("#menu .minichat").click(function(){ pages
.afficherPage("minichat") })
1203 $("#menu .admin").click(function(){ pages
.afficherPage("admin") })
1204 $("#menu .profile").click(function(){ pages
.afficherPage("profile") })
1205 $("#menu .logout").click(function(){
1206 util
.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType
.question
,
1209 client
.deconnexion();
1210 pages
.afficherPage("minichat", true)
1212 "Non" : function(){}
1216 $("#menu .register").click(function(){ pages
.afficherPage("register") })
1217 $("#menu .about").click(function(){ pages
.afficherPage("about") })
1219 // TODO : simplifier et pouvoir créer des liens par exemple : <span class="lien" href="conditions">Conditions d'utilisation</span>
1220 $("#footer .conditions").click(function(){ pages
.afficherPage("conditions_utilisation") })
1222 pages
.ajouterPage(new PageMinichat(client
, formateur
, util
))
1223 pages
.ajouterPage(new PageAdmin(client
, formateur
, util
))
1224 pages
.ajouterPage(new PageProfile(client
, formateur
, util
))
1225 pages
.ajouterPage(new PageRegister(client
, formateur
, util
))
1226 pages
.ajouterPage(new PageAbout(client
, formateur
, util
))
1227 pages
.ajouterPage("conditions_utilisation")
1229 pages
.afficherPage("minichat")