4 * Contient la base javascript pour le site euphorik.ch.
5 * Chaque page possède son propre fichier js nommé "page<nom de la page>.js".
13 * Normalement 'const' à la place de 'var' mais non supporté par IE7.
16 nbMessageAffiche : 10, // (par page)
17 pseudoDefaut : "<nick>",
18 tempsAffichageMessageDialogue : 4000, // en ms
20 "smile" : [/:\)/g, /:-\)/g],
21 "bigsmile" : [/:D/g, /:-D/g],
22 "clin" : [/;\)/g, /;-\)/g],
23 "cool" : [/8\)/g, /8-\)/g],
24 "eheheh" : [/:P/g, /:-P/g],
25 "lol" : [/\[-lol\]/g],
26 "spliff" : [/\[-spliff\]/g],
27 "oh" : [/:o/g, /:O/g],
28 "heink" : [/\[-heink\]/g],
29 "hum" : [/\[-hum\]/g],
30 "boh" : [/\[-boh\]/g],
31 "sniff" : [/:\(/g, /:-\(/g],
32 "triste" : [/\[-triste\]/g],
33 "pascontent" : [/>\(/g, />\(/g],
34 "argn" : [/\[-argn\]/g],
35 "redface" : [/\[-redface\]/g],
36 "bunny" : [/\[-lapin\]/g],
37 "chat" : [/\[-chat\]/g],
38 "renne" : [/\[-renne\]/g],
39 "star" : [/\[-star\]/g],
40 "kirby" : [/\[-kirby\]/g],
41 "slurp" : [/\[-slurp\]/g],
42 "agreed" : [/\[-agreed\]/g],
43 "dodo" : [/\[-dodo\]/g],
48 ///////////////////////////////////////////////////////////////////////////////////////////////////
50 String
.prototype.trim = function()
52 return jQuery
.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
55 String
.prototype.ltrim = function()
57 return this.replace(/^\s+/, "");
60 String
.prototype.rtrim = function()
62 return this.replace(/\s+$/, "");
65 ///////////////////////////////////////////////////////////////////////////////////////////////////
68 * Cette classe regroupe des fonctions utilitaires (helpers).
72 jQuery("#info .fermer").click(function(){
73 jQuery("#info").slideUp(50)
78 * Affiche une boite de dialogue avec un message à l'intérieur.
79 * @param message le message (string)
80 * @param type voir 'messageType'. par défaut messageType.informatif
81 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
82 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
84 Util
.prototype.messageDialogue = function(message
, type
, boutons
)
86 if (type
== undefined)
87 type
= messageType
.informatif
89 if (this.timeoutMessageDialogue
!= undefined)
90 clearTimeout(this.timeoutMessageDialogue
)
92 var fermer = function(){jQuery("#info").slideUp(100)}
95 jQuery("#info .message").html(message
)
98 case messageType
.informatif : jQuery("#info #icone").attr("class", "information"); break
99 case messageType
.question : jQuery("#info #icone").attr("class", "interrogation"); break
100 case messageType
.erreur : jQuery("#info #icone").attr("class", "exclamation"); break
102 jQuery("#info .boutons").html("")
103 for (var b
in boutons
)
104 jQuery("#info .boutons").append("<div>" + b
+ "</div>").find("div:last").click(boutons
[b
]).click(fermer
)
106 jQuery("#info").slideDown(200)
107 this.timeoutMessageDialogue
= setTimeout(fermer
, conf
.tempsAffichageMessageDialogue
)
110 var messageType
= {informatif: 0, question: 1, erreur: 2}
113 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
115 Util
.prototype.jsonVersAction = function(json
)
117 return {action : JSON
.stringify(json
) }
120 Util
.prototype.md5 = function(chaine
)
122 return hex_md5(chaine
)
125 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
126 Util
.prototype.setSelectionRange = function(input
, selectionStart
, selectionEnd
)
128 if (input
.setSelectionRange
)
131 input
.setSelectionRange(selectionStart
, selectionEnd
)
133 else if (input
.createTextRange
)
135 var range
= input
.createTextRange()
137 range
.moveEnd('character', selectionEnd
)
138 range
.moveStart('character', selectionStart
)
143 Util
.prototype.setCaretToEnd = function(input
)
145 this.setSelectionRange(input
, input
.value
.length
, input
.value
.length
)
147 Util
.prototype.setCaretToBegin = function(input
)
149 this.setSelectionRange(input
, 0, 0)
151 Util
.prototype.setCaretToPos = function(input
, pos
)
153 this.setSelectionRange(input
, pos
, pos
)
155 Util
.prototype.selectString = function(input
, string
)
157 var match
= new RegExp(string
, "i").exec(input
.value
)
160 this.setSelectionRange (input
, match
.index
, match
.index
+ match
[0].length
)
163 Util
.prototype.replaceSelection = function(input
, replaceString
) {
164 if (input
.setSelectionRange
)
166 var selectionStart
= input
.selectionStart
167 var selectionEnd
= input
.selectionEnd
168 input
.value
= input
.value
.substring(0, selectionStart
) + replaceString
+ input
.value
.substring(selectionEnd
)
170 if (selectionStart
!= selectionEnd
) // has there been a selection
171 this.setSelectionRange(input
, selectionStart
, selectionStart
+ replaceString
.length
)
173 this.setCaretToPos(input
, selectionStart
+ replaceString
.length
)
175 else if (document
.selection
)
177 var range
= document
.selection
.createRange();
178 if (range
.parentElement() == input
)
180 var isCollapsed
= range
.text
== ''
181 range
.text
= replaceString
184 // there has been a selection
185 // it appears range.select() should select the newly
186 // inserted text but that fails with IE
187 range
.moveStart('character', -replaceString
.length
);
194 Util
.prototype.rot13 = function(chaine
)
196 var ACode
= 'A'.charCodeAt(0)
197 var aCode
= 'a'.charCodeAt(0)
198 var MCode
= 'M'.charCodeAt(0)
199 var mCode
= 'm'.charCodeAt(0)
200 var ZCode
= 'Z'.charCodeAt(0)
201 var zCode
= 'z'.charCodeAt(0)
203 var f = function(ch
, pos
) {
204 if (pos
== ch
.length
)
207 var c
= ch
.charCodeAt(pos
);
208 return String
.fromCharCode(
210 (c
>= ACode
&& c
<= MCode
|| c
>= aCode
&& c
<= mCode
? 13 :
211 (c
> MCode
&& c
<= ZCode
|| c
> mCode
&& c
<= zCode
? -13 : 0))
217 ///////////////////////////////////////////////////////////////////////////////////////////////////
221 this.pageCourante
= null
225 Pages
.prototype.ajouterPage = function(page
)
227 page
.pages
= this // la magie des langages dynamiques : le foutoire
228 this.pages
[page
.nom
] = page
231 Pages
.prototype.afficherPage = function(nomPage
, forcerChargement
)
233 if (forcerChargement
== undefined) forcerChargement
= false
235 var page
= this.pages
[nomPage
]
236 if (page
== undefined || (!forcerChargement
&& page
== this.pageCourante
)) return
238 if (this.pageCourante
!= null && this.pageCourante
.decharger
)
239 this.pageCourante
.decharger()
241 jQuery("#menu div").removeClass("courante")
242 jQuery("#menu div." + nomPage
).addClass("courante")
244 this.pageCourante
= page
245 jQuery("#page").html(this.pageCourante
.contenu()).removeClass().addClass(this.pageCourante
.nom
)
247 if (this.pageCourante
.charger
)
248 this.pageCourante
.charger()
251 ///////////////////////////////////////////////////////////////////////////////////////////////////
255 this.smiles
= conf
.smiles
256 this.protocoles
= "http|https|ed2k"
258 this.regexUrl
= new RegExp("(?:(?:" + this.protocoles
+ ")://|www\\.)[^ ]*", "gi")
259 this.regexImg
= new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
260 this.regexDomaine
= new RegExp("^(?:(?:" + this.protocoles
+ ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
261 this.regexTestProtocoleExiste
= new RegExp("^(?:" + this.protocoles
+ ")://.*$", "i")
262 this.regexNomProtocole
= new RegExp("^(.*?)://")
266 * Formate un pseudo saise par l'utilisateur.
267 * @param pseudo le pseudo brut
268 * @return le pseudo filtré
270 Formateur
.prototype.filtrerInputPseudo = function(pseudo
)
272 return pseudo
.replace(/{|}/g, "").trim()
275 Formateur
.prototype.getSmilesHTML = function()
278 for (var sNom
in this.smiles
)
280 XHTML
+= "<img class=\"" + sNom
+ "\" src=\"img/smileys/" + sNom
+ ".gif\" />"
285 Formateur
.prototype.traitementComplet = function(M
, pseudo
)
287 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.remplacerBalisesHTML(M
), pseudo
)))
291 * Transforme les liens en entités clickables.
292 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
293 * "{5F}" ou 5F est la racine de la conversation.
294 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
296 Formateur
.prototype.traiterLiensConv = function(M
)
302 return "<span class=\"lienConv\">" + lien
+ "</span>"
308 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
310 Formateur
.prototype.traiterSmiles = function(M
)
312 for (var sNom
in this.smiles
)
314 ss
= this.smiles
[sNom
]
315 for (var i
= 0; i
< ss
.length
; i
++)
316 M
= M
.replace(ss
[i
], "<img src=\"img/smileys/" + sNom
+ ".gif\" />")
321 Formateur
.prototype.remplacerBalisesHTML = function(M
)
323 return M
.replace(/</g
, "<").replace(/>/g
, ">")
326 Formateur
.prototype.traiterURL = function(M
, pseudo
)
330 if (pseudo
== undefined)
333 var traitementUrl = function(url
)
335 // si ya pas de protocole on rajoute "http://"
336 if (!thisFormateur
.regexTestProtocoleExiste
.test(url
))
337 url
= "http://" + url
338 var extension
= thisFormateur
.getShort(url
)
339 return "<a " + (extension
[1] ? "title=\"" + thisFormateur
.traiterPourFenetreLightBox(pseudo
, url
) + ": " + thisFormateur
.traiterPourFenetreLightBox(M
, url
) + "\"" + " rel=\"lightbox[groupe]\"" : "") + " href=\"" + url
+ "\" >[" + extension
[0] + "]</a>"
341 return M
.replace(this.regexUrl
, traitementUrl
)
345 * Renvoie une version courte de l'url.
346 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
348 Formateur
.prototype.getShort = function(url
)
350 var estUneImage
= false
351 var versionShort
= null
352 var rechercheImg
= this.regexImg
.exec(url
)
354 if (rechercheImg
!= null)
356 versionShort
= rechercheImg
[1].toLowerCase()
357 if (versionShort
== "jpeg") versionShort
= "jpg" // jpeg -> jpg
362 var rechercheDomaine
= this.regexDomaine
.exec(url
)
363 if (rechercheDomaine
!= null && rechercheDomaine
.length
>= 2)
364 versionShort
= rechercheDomaine
[1]
367 var nomProtocole
= this.regexNomProtocole
.exec(url
)
368 if (nomProtocole
!= null && nomProtocole
.length
>= 2)
369 versionShort
= nomProtocole
[1]
373 return [versionShort
== null ? "url" : versionShort
, estUneImage
]
377 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
379 Formateur
.prototype.traiterPourFenetreLightBox = function(M
, urlCourante
)
382 var traitementUrl = function(url
)
384 return "[" + thisFormateur
.getShort(url
)[0] + (urlCourante
== url
? ": image courante" : "") + "]"
387 return this.remplacerBalisesHTML(M
).replace(this.regexUrl
, traitementUrl
)
391 ///////////////////////////////////////////////////////////////////////////////////////////////////
393 // les statuts possibes du client
395 // mode enregistré, peut poster des messages et modifier son profile
397 // mode identifié, peut poster des messages mais n'a pas accès au profile
398 auth_not_registered : 1,
399 // mode déconnecté, ne peut pas poster de message
403 function Client(util
)
408 this.regexCookie
= new RegExp("^cookie=([^;]*)")
410 // données personnels
411 this.resetDonneesPersonnelles()
413 this.setStatut(statutType
.deconnected
)
415 // le dernier message d'erreur recut du serveur (par exemple une connexion foireuse : "login impossible")
416 this.dernierMessageErreur
= ""
419 Client
.prototype.resetDonneesPersonnelles = function()
421 this.pseudo
= conf
.pseudoDefaut
425 this.css
= jQuery("link#cssPrincipale").attr("href")
426 this.nickFormat
= "nick"
428 this.pagePrincipale
= 1
430 // les conversations, une conversation est un objet possédant les attributs suivants :
433 this.conversations
= new Array()
436 Client
.prototype.setCss = function(css
)
442 jQuery("link#cssPrincipale").attr("href", this.css
)
446 Client
.prototype.pageSuivante = function(numConv
)
448 if (numConv
< 0 && this.pagePrincipale
> 1)
449 this.pagePrincipale
-= 1
450 else if (this.conversations
[numConv
].page
> 1)
451 this.conversations
[numConv
].page
-= 1
454 Client
.prototype.pagePrecedente = function(numConv
)
457 this.pagePrincipale
+= 1
459 this.conversations
[numConv
].page
+= 1
463 * Définit la première page pour la conversation donnée.
464 * @return true si la page a changé sinon false
466 Client
.prototype.goPremierePage = function(numConv
)
470 if (this.pagePrincipale
== 1)
472 this.pagePrincipale
= 1
476 if (this.conversations
[numConv
].page
== 1)
478 this.conversations
[numConv
].page
= 1
484 * Ajoute une conversation à la vue de l'utilisateur.
485 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
486 * @param racines la racine de la conversation (integer)
487 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
489 Client
.prototype.ajouterConversation = function(racine
)
491 // vérification s'il elle n'existe pas déjà
492 for (var i
= 0; i
< this.conversations
.length
; i
++)
493 if (this.conversations
[i
].root
== racine
)
496 this.conversations
.push({root : racine
, page : 1})
500 Client
.prototype.supprimerConversation = function(num
)
502 if (num
< 0 || num
>= this.conversations
.length
) return
504 // décalage TODO : supprimer le dernier élément
505 for (var i
= num
; i
< this.conversations
.length
- 1; i
++)
506 this.conversations
[i
] = this.conversations
[i
+1]
507 this.conversations
.pop()
510 Client
.prototype.getJSONLogin = function(login
, password
)
513 "action" : "authentification",
515 "password" : password
519 Client
.prototype.getJSONLoginCookie = function()
522 "action" : "authentification",
523 "cookie" : this.cookie
528 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
529 * de s'autentifier avec (login, password).
531 Client
.prototype.getJSONEnregistrement = function(login
, password
)
533 var mess
= { "action" : "register" }
535 if (login
!= undefined && password
!= undefined)
537 mess
["login"] = login
538 mess
["password"] = password
544 Client
.prototype.getJSONConversations = function()
546 var conversations
= new Array()
547 for (var i
= 0; i
< this.conversations
.length
; i
++)
548 conversations
.push({ "root" : this.conversations
[i
].root
, "page" : this.conversations
[i
].page
})
552 Client
.prototype.getJSONProfile = function()
555 "action" : "set_profile",
556 "cookie" : this.cookie
,
557 "login" : this.login
,
558 "password" : this.password
,
559 "nick" : this.pseudo
,
560 "email" : this.email
,
562 "nick_format" : this.nickFormat
,
563 "main_page" : this.pagePrincipale
< 1 ? 1 : this.pagePrincipale
,
564 "conversations" : this.getJSONConversations()
569 * Renvoie null si pas définit.
571 Client
.prototype.getCookie = function()
573 var cookie
= this.regexCookie
.exec(document
.cookie
)
574 if (cookie
== null) this.cookie
= null
575 else this.cookie
= cookie
[1]
578 Client
.prototype.delCookie = function()
580 document
.cookie
= "cookie=; max-age=0"
583 Client
.prototype.setCookie = function(cookie
)
585 if (this.cookie
== null)
589 "cookie="+this.cookie
+
590 "; max-age=" + (60 * 60 * 24 * 365)
593 Client
.prototype.authentifie = function()
595 return this.statut
== statutType
.auth_registered
|| this.statut
== statutType
.auth_not_registered
598 Client
.prototype.setStatut = function(statut
)
601 // conversation en "enum" si en "string"
602 if (typeof(statut
) == "string")
605 statut
== "auth_registered" ?
606 statutType
.auth_registered :
607 (statut
== "auth_not_registered" ? statutType
.auth_not_registered : statutType
.deconnected
)
610 if (statut
== this.statut
) return
617 * Effectue la connexion vers le serveur.
618 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
619 * S'il existe un cookie en local on s'authentifie directement avec lui.
620 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
622 Client
.prototype.connexionCookie = function()
625 if (this.cookie
== null) return false;
626 return this.connexion(this.getJSONLoginCookie())
629 Client
.prototype.connexionLogin = function(login
, password
)
631 return this.connexion(this.getJSONLogin(login
, password
))
634 Client
.prototype.enregistrement = function(login
, password
)
636 if (this.authentifie())
639 this.password
= password
641 this.setStatut(statutType
.auth_registered
)
646 return this.connexion(this.getJSONEnregistrement(login
, password
))
650 Client
.prototype.connexion = function(messageJson
)
652 ;;; dumpObj(messageJson
)
660 data: this.util
.jsonVersAction(messageJson
),
665 thisClient
.chargerDonnees(data
)
669 return this.authentifie()
672 Client
.prototype.deconnexion = function()
675 this.setStatut(statutType
.deconnected
) // deconnexion
676 this.resetDonneesPersonnelles()
680 Client
.prototype.chargerDonnees = function(data
)
682 var thisClient
= this
684 this.setStatut(data
["status"])
686 if (this.authentifie())
688 this.cookie
= data
["cookie"]
691 this.login
= data
["login"]
692 this.pseudo
= data
["nick"]
693 this.email
= data
["email"]
694 this.css
= data
["css"]
695 this.nickFormat
= data
["nick_format"]
697 // la page de la conversation principale
698 this.pagePrincipale
= data
["main_page"] == undefined ? 1 : data
["main_page"]
703 jQuery("link#cssPrincipale").attr("href", this.css
)
707 thisClient
.conversations
= data
["conversations"]
710 this.dernierMessageErreur
= data
["error_message"]
714 * Met à jour les données personne sur serveur.
715 * @param async de manière asynchrone ? défaut = true
716 * @return false si le flush n'a pas pû se faire sinon true
718 Client
.prototype.flush = function(async
)
720 if (async
== undefined)
723 if (!this.authentifie())
727 ;;; dumpObj(this.getJSONProfile())
734 data: this.util
.jsonVersAction(this.getJSONProfile()),
738 //thisClient.util.log(thisClient.util.serializer.serializeToString(data))
742 // TODO : retourner false si un problème est survenu lors de l'update du profile
746 Client
.prototype.majMenu = function()
748 var displayType
= this.css
== "css/3/euphorik.css" ? "block" : "inline" //this.client
750 // met à jour le menu
751 if (this.statut
== statutType
.auth_registered
)
753 jQuery("#menu .profile").css("display", displayType
).text("profile")
754 jQuery("#menu .logout").css("display", displayType
)
755 jQuery("#menu .register").css("display", "none")
757 else if (this.statut
== statutType
.auth_not_registered
)
759 jQuery("#menu .profile").css("display", "none")
760 jQuery("#menu .logout").css("display", displayType
)
761 jQuery("#menu .register").css("display", displayType
)
765 jQuery("#menu .profile").css("display", displayType
).text("login")
766 jQuery("#menu .logout").css("display", "none")
767 jQuery("#menu .register").css("display", displayType
)
771 ///////////////////////////////////////////////////////////////////////////////////////////////////
773 function initialiserListeStyles(client
)
775 jQuery("#menuCss").change(
778 client
.setCss("css/" + jQuery("option:selected", this).attr("value") + "/euphorik.css")
785 // charge dynamiquement le script de debug
786 ;;; jQuery
.ajax({async : false, url : "js/debug.js", dataType : "script"})
789 jQuery(document
).ready(
792 var util
= new Util()
793 var client
= new Client(util
)
794 var pages
= new Pages()
795 var formateur
= new Formateur()
797 // connexion vers le serveur (utilise un cookie qui traine)
798 client
.connexionCookie()
800 initialiserListeStyles(client
)
802 // TODO : pourquoi jQuery(document).unload ne fonctionne pas ?
803 jQuery(window
).unload(function(){client
.flush(false)})
805 jQuery("#menu .minichat").click(function(){ pages
.afficherPage("minichat") })
806 jQuery("#menu .profile").click(function(){ pages
.afficherPage("profile") })
807 jQuery("#menu .logout").click(function(){
808 util
.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType
.question
,
811 client
.deconnexion();
812 pages
.afficherPage("minichat", true)
818 jQuery("#menu .register").click(function(){ pages
.afficherPage("register") })
819 jQuery("#menu .about").click(function(){ pages
.afficherPage("about") })
821 pages
.ajouterPage(new PageMinichat(client
, formateur
, util
))
822 pages
.ajouterPage(new PageProfile(client
, formateur
, util
))
823 pages
.ajouterPage(new PageRegister(client
, formateur
, util
))
824 pages
.ajouterPage(new PageAbout(client
, formateur
, util
))
825 pages
.afficherPage("minichat")