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]
47 ///////////////////////////////////////////////////////////////////////////////////////////////////
49 String
.prototype.trim = function()
51 return jQuery
.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
54 String
.prototype.ltrim = function()
56 return this.replace(/^\s+/, "");
59 String
.prototype.rtrim = function()
61 return this.replace(/\s+$/, "");
64 ///////////////////////////////////////////////////////////////////////////////////////////////////
67 * Cette classe regroupe des fonctions utilitaires (helpers).
71 jQuery("#info .fermer").click(function(){
72 jQuery("#info").slideUp(50)
77 * Affiche une boite de dialogue avec un message à l'intérieur.
78 * @param message le message (string)
79 * @param type voir 'messageType'. par défaut messageType.informatif
80 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
81 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
83 Util
.prototype.messageDialogue = function(message
, type
, boutons
)
85 if (type
== undefined)
86 type
= messageType
.informatif
88 if (this.timeoutMessageDialogue
!= undefined)
89 clearTimeout(this.timeoutMessageDialogue
)
91 var fermer = function(){jQuery("#info").slideUp(100)}
94 jQuery("#info .message").html(message
)
97 case messageType
.informatif : jQuery("#info #icone").attr("class", "information"); break
98 case messageType
.question : jQuery("#info #icone").attr("class", "interrogation"); break
99 case messageType
.erreur : jQuery("#info #icone").attr("class", "exclamation"); break
101 jQuery("#info .boutons").html("")
102 for (var b
in boutons
)
103 jQuery("#info .boutons").append("<div>" + b
+ "</div>").find("div:last").click(boutons
[b
]).click(fermer
)
105 jQuery("#info").slideDown(200)
106 this.timeoutMessageDialogue
= setTimeout(fermer
, conf
.tempsAffichageMessageDialogue
)
109 var messageType
= {informatif: 0, question: 1, erreur: 2}
112 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
114 Util
.prototype.jsonVersAction = function(json
)
116 return {action : JSON
.stringify(json
) }
119 Util
.prototype.md5 = function(chaine
)
121 return hex_md5(chaine
)
124 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
125 Util
.prototype.setSelectionRange = function(input
, selectionStart
, selectionEnd
)
127 if (input
.setSelectionRange
)
130 input
.setSelectionRange(selectionStart
, selectionEnd
)
132 else if (input
.createTextRange
)
134 var range
= input
.createTextRange()
136 range
.moveEnd('character', selectionEnd
)
137 range
.moveStart('character', selectionStart
)
142 Util
.prototype.setCaretToEnd = function(input
)
144 this.setSelectionRange(input
, input
.value
.length
, input
.value
.length
)
146 Util
.prototype.setCaretToBegin = function(input
)
148 this.setSelectionRange(input
, 0, 0)
150 Util
.prototype.setCaretToPos = function(input
, pos
)
152 this.setSelectionRange(input
, pos
, pos
)
154 Util
.prototype.selectString = function(input
, string
)
156 var match
= new RegExp(string
, "i").exec(input
.value
)
159 this.setSelectionRange (input
, match
.index
, match
.index
+ match
[0].length
)
162 Util
.prototype.replaceSelection = function(input
, replaceString
) {
163 if (input
.setSelectionRange
)
165 var selectionStart
= input
.selectionStart
166 var selectionEnd
= input
.selectionEnd
167 input
.value
= input
.value
.substring(0, selectionStart
) + replaceString
+ input
.value
.substring(selectionEnd
)
169 if (selectionStart
!= selectionEnd
) // has there been a selection
170 this.setSelectionRange(input
, selectionStart
, selectionStart
+ replaceString
.length
)
172 this.setCaretToPos(input
, selectionStart
+ replaceString
.length
)
174 else if (document
.selection
)
176 var range
= document
.selection
.createRange();
177 if (range
.parentElement() == input
)
179 var isCollapsed
= range
.text
== ''
180 range
.text
= replaceString
183 // there has been a selection
184 // it appears range.select() should select the newly
185 // inserted text but that fails with IE
186 range
.moveStart('character', -replaceString
.length
);
193 Util
.prototype.rot13 = function(chaine
)
195 var ACode
= 'A'.charCodeAt(0)
196 var aCode
= 'a'.charCodeAt(0)
197 var MCode
= 'M'.charCodeAt(0)
198 var mCode
= 'm'.charCodeAt(0)
199 var ZCode
= 'Z'.charCodeAt(0)
200 var zCode
= 'z'.charCodeAt(0)
202 var f = function(ch
, pos
) {
203 if (pos
== ch
.length
)
206 var c
= ch
.charCodeAt(pos
);
207 return String
.fromCharCode(
209 (c
>= ACode
&& c
<= MCode
|| c
>= aCode
&& c
<= mCode
? 13 :
210 (c
> MCode
&& c
<= ZCode
|| c
> mCode
&& c
<= zCode
? -13 : 0))
216 ///////////////////////////////////////////////////////////////////////////////////////////////////
220 this.pageCourante
= null
224 Pages
.prototype.ajouterPage = function(page
)
226 page
.pages
= this // la magie des langages dynamiques : le foutoire
227 this.pages
[page
.nom
] = page
230 Pages
.prototype.afficherPage = function(nomPage
, forcerChargement
)
232 if (forcerChargement
== undefined) forcerChargement
= false
234 var page
= this.pages
[nomPage
]
235 if (page
== undefined || (!forcerChargement
&& page
== this.pageCourante
)) return
237 if (this.pageCourante
!= null && this.pageCourante
.decharger
)
238 this.pageCourante
.decharger()
240 jQuery("#menu div").removeClass("courante")
241 jQuery("#menu div." + nomPage
).addClass("courante")
243 this.pageCourante
= page
244 jQuery("#page").html(this.pageCourante
.contenu()).removeClass().addClass(this.pageCourante
.nom
)
246 if (this.pageCourante
.charger
)
247 this.pageCourante
.charger()
250 ///////////////////////////////////////////////////////////////////////////////////////////////////
254 this.smiles
= conf
.smiles
255 this.protocoles
= "http|https|ed2k"
257 this.regexUrl
= new RegExp("(?:(?:" + this.protocoles
+ ")://|www\\.)[^ ]*", "gi")
258 this.regexImg
= new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
259 this.regexDomaine
= new RegExp("^(?:(?:" + this.protocoles
+ ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
260 this.regexTestProtocoleExiste
= new RegExp("^(?:" + this.protocoles
+ ")://.*$", "i")
261 this.regexNomProtocole
= new RegExp("^(.*?)://")
265 * Formate un pseudo saise par l'utilisateur.
266 * @param pseudo le pseudo brut
267 * @return le pseudo filtré
269 Formateur
.prototype.filtrerInputPseudo = function(pseudo
)
271 return pseudo
.replace(/{|}/g, "").trim()
274 Formateur
.prototype.getSmilesHTML = function()
277 for (var sNom
in this.smiles
)
279 XHTML
+= "<img class=\"" + sNom
+ "\" src=\"img/smileys/" + sNom
+ ".gif\" />"
284 Formateur
.prototype.traitementComplet = function(M
, pseudo
)
286 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.remplacerBalisesHTML(M
), pseudo
)))
290 * Transforme les liens en entités clickables.
291 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
292 * "{5F}" ou 5F est la racine de la conversation.
293 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
295 Formateur
.prototype.traiterLiensConv = function(M
)
301 return "<span class=\"lienConv\">" + lien
+ "</span>"
307 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
309 Formateur
.prototype.traiterSmiles = function(M
)
311 for (var sNom
in this.smiles
)
313 ss
= this.smiles
[sNom
]
314 for (var i
= 0; i
< ss
.length
; i
++)
315 M
= M
.replace(ss
[i
], "<img src=\"img/smileys/" + sNom
+ ".gif\" />")
320 Formateur
.prototype.remplacerBalisesHTML = function(M
)
322 return M
.replace(/</g
, "<").replace(/>/g
, ">")
325 Formateur
.prototype.traiterURL = function(M
, pseudo
)
329 if (pseudo
== undefined)
332 var traitementUrl = function(url
)
334 // si ya pas de protocole on rajoute "http://"
335 if (!thisFormateur
.regexTestProtocoleExiste
.test(url
))
336 url
= "http://" + url
337 var extension
= thisFormateur
.getShort(url
)
338 return "<a " + (extension
[1] ? "title=\"" + thisFormateur
.traiterPourFenetreLightBox(pseudo
, url
) + ": " + thisFormateur
.traiterPourFenetreLightBox(M
, url
) + "\"" + " rel=\"lightbox[groupe]\"" : "") + " href=\"" + url
+ "\" >[" + extension
[0] + "]</a>"
340 return M
.replace(this.regexUrl
, traitementUrl
)
344 * Renvoie une version courte de l'url.
345 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
347 Formateur
.prototype.getShort = function(url
)
349 var estUneImage
= false
350 var versionShort
= null
351 var rechercheImg
= this.regexImg
.exec(url
)
353 if (rechercheImg
!= null)
355 versionShort
= rechercheImg
[1].toLowerCase()
356 if (versionShort
== "jpeg") versionShort
= "jpg" // jpeg -> jpg
361 var rechercheDomaine
= this.regexDomaine
.exec(url
)
362 if (rechercheDomaine
!= null && rechercheDomaine
.length
>= 2)
363 versionShort
= rechercheDomaine
[1]
366 var nomProtocole
= this.regexNomProtocole
.exec(url
)
367 if (nomProtocole
!= null && nomProtocole
.length
>= 2)
368 versionShort
= nomProtocole
[1]
372 return [versionShort
== null ? "url" : versionShort
, estUneImage
]
376 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
378 Formateur
.prototype.traiterPourFenetreLightBox = function(M
, urlCourante
)
381 var traitementUrl = function(url
)
383 return "[" + thisFormateur
.getShort(url
)[0] + (urlCourante
== url
? ": image courante" : "") + "]"
386 return this.remplacerBalisesHTML(M
).replace(this.regexUrl
, traitementUrl
)
390 ///////////////////////////////////////////////////////////////////////////////////////////////////
392 // les statuts possibes du client
394 // mode enregistré, peut poster des messages et modifier son profile
396 // mode identifié, peut poster des messages mais n'a pas accès au profile
397 auth_not_registered : 1,
398 // mode déconnecté, ne peut pas poster de message
402 function Client(util
)
407 this.regexCookie
= new RegExp("^cookie=([^;]*)")
409 // données personnels
410 this.resetDonneesPersonnelles()
412 this.setStatut(statutType
.deconnected
)
414 // le dernier message d'erreur recut du serveur (par exemple une connexion foireuse : "login impossible")
415 this.dernierMessageErreur
= ""
418 Client
.prototype.resetDonneesPersonnelles = function()
420 this.pseudo
= conf
.pseudoDefaut
424 this.css
= jQuery("link#cssPrincipale").attr("href")
425 this.nickFormat
= "nick"
427 this.pagePrincipale
= 1
429 // les conversations, une conversation est un objet possédant les attributs suivants :
432 this.conversations
= new Array()
435 Client
.prototype.setCss = function(css
)
441 jQuery("link#cssPrincipale").attr("href", this.css
)
445 Client
.prototype.pageSuivante = function(numConv
)
447 if (numConv
< 0 && this.pagePrincipale
> 1)
448 this.pagePrincipale
-= 1
449 else if (this.conversations
[numConv
].page
> 1)
450 this.conversations
[numConv
].page
-= 1
453 Client
.prototype.pagePrecedente = function(numConv
)
456 this.pagePrincipale
+= 1
458 this.conversations
[numConv
].page
+= 1
462 * Définit la première page pour la conversation donnée.
463 * @return true si la page a changé sinon false
465 Client
.prototype.goPremierePage = function(numConv
)
469 if (this.pagePrincipale
== 1)
471 this.pagePrincipale
= 1
475 if (this.conversations
[numConv
].page
== 1)
477 this.conversations
[numConv
].page
= 1
483 * Ajoute une conversation à la vue de l'utilisateur.
484 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
485 * @param racines la racine de la conversation (integer)
486 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
488 Client
.prototype.ajouterConversation = function(racine
)
490 // vérification s'il elle n'existe pas déjà
491 for (var i
= 0; i
< this.conversations
.length
; i
++)
492 if (this.conversations
[i
].root
== racine
)
495 this.conversations
.push({root : racine
, page : 1})
499 Client
.prototype.supprimerConversation = function(num
)
501 if (num
< 0 || num
>= this.conversations
.length
) return
503 // décalage TODO : supprimer le dernier élément
504 for (var i
= num
; i
< this.conversations
.length
- 1; i
++)
505 this.conversations
[i
] = this.conversations
[i
+1]
506 this.conversations
.pop()
509 Client
.prototype.getJSONLogin = function(login
, password
)
512 "action" : "authentification",
514 "password" : password
518 Client
.prototype.getJSONLoginCookie = function()
521 "action" : "authentification",
522 "cookie" : this.cookie
527 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
528 * de s'autentifier avec (login, password).
530 Client
.prototype.getJSONEnregistrement = function(login
, password
)
532 var mess
= { "action" : "register" }
534 if (login
!= undefined && password
!= undefined)
536 mess
["login"] = login
537 mess
["password"] = password
543 Client
.prototype.getJSONConversations = function()
545 var conversations
= new Array()
546 for (var i
= 0; i
< this.conversations
.length
; i
++)
547 conversations
.push({ "root" : this.conversations
[i
].root
, "page" : this.conversations
[i
].page
})
551 Client
.prototype.getJSONProfile = function()
554 "action" : "set_profile",
555 "cookie" : this.cookie
,
556 "login" : this.login
,
557 "password" : this.password
,
558 "nick" : this.pseudo
,
559 "email" : this.email
,
561 "nick_format" : this.nickFormat
,
562 "main_page" : this.pagePrincipale
< 1 ? 1 : this.pagePrincipale
,
563 "conversations" : this.getJSONConversations()
568 * Renvoie null si pas définit.
570 Client
.prototype.getCookie = function()
572 var cookie
= this.regexCookie
.exec(document
.cookie
)
573 if (cookie
== null) this.cookie
= null
574 else this.cookie
= cookie
[1]
577 Client
.prototype.delCookie = function()
579 document
.cookie
= "cookie=; max-age=0"
582 Client
.prototype.setCookie = function(cookie
)
584 if (this.cookie
== null)
588 "cookie="+this.cookie
+
589 "; max-age=" + (60 * 60 * 24 * 365)
592 Client
.prototype.authentifie = function()
594 return this.statut
== statutType
.auth_registered
|| this.statut
== statutType
.auth_not_registered
597 Client
.prototype.setStatut = function(statut
)
600 // conversation en "enum" si en "string"
601 if (typeof(statut
) == "string")
604 statut
== "auth_registered" ?
605 statutType
.auth_registered :
606 (statut
== "auth_not_registered" ? statutType
.auth_not_registered : statutType
.deconnected
)
609 if (statut
== this.statut
) return
616 * Effectue la connexion vers le serveur.
617 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
618 * S'il existe un cookie en local on s'authentifie directement avec lui.
619 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
621 Client
.prototype.connexionCookie = function()
624 if (this.cookie
== null) return false;
625 return this.connexion(this.getJSONLoginCookie())
628 Client
.prototype.connexionLogin = function(login
, password
)
630 return this.connexion(this.getJSONLogin(login
, password
))
633 Client
.prototype.enregistrement = function(login
, password
)
635 if (this.authentifie())
638 this.password
= password
640 this.setStatut(statutType
.auth_registered
)
645 return this.connexion(this.getJSONEnregistrement(login
, password
))
649 Client
.prototype.connexion = function(messageJson
)
651 ;;; dumpObj(messageJson
)
659 data: this.util
.jsonVersAction(messageJson
),
664 thisClient
.chargerDonnees(data
)
668 return this.authentifie()
671 Client
.prototype.deconnexion = function()
674 this.setStatut(statutType
.deconnected
) // deconnexion
675 this.resetDonneesPersonnelles()
679 Client
.prototype.chargerDonnees = function(data
)
681 var thisClient
= this
683 this.setStatut(data
["status"])
685 if (this.authentifie())
687 this.cookie
= data
["cookie"]
690 this.login
= data
["login"]
691 this.pseudo
= data
["nick"]
692 this.email
= data
["email"]
693 this.css
= data
["css"]
694 this.nickFormat
= data
["nick_format"]
696 // la page de la conversation principale
697 this.pagePrincipale
= data
["main_page"] == undefined ? 1 : data
["main_page"]
702 jQuery("link#cssPrincipale").attr("href", this.css
)
706 thisClient
.conversations
= data
["conversations"]
709 this.dernierMessageErreur
= data
["error_message"]
713 * Met à jour les données personne sur serveur.
714 * @param async de manière asynchrone ? défaut = true
715 * @return false si le flush n'a pas pû se faire sinon true
717 Client
.prototype.flush = function(async
)
719 if (async
== undefined)
722 if (!this.authentifie())
726 ;;; dumpObj(this.getJSONProfile())
733 data: this.util
.jsonVersAction(this.getJSONProfile()),
737 //thisClient.util.log(thisClient.util.serializer.serializeToString(data))
741 // TODO : retourner false si un problème est survenu lors de l'update du profile
745 Client
.prototype.majMenu = function()
747 var displayType
= this.css
== "css/3/euphorik.css" ? "block" : "inline" //this.client
749 // met à jour le menu
750 if (this.statut
== statutType
.auth_registered
)
752 jQuery("#menu .profile").css("display", displayType
).text("profile")
753 jQuery("#menu .logout").css("display", displayType
)
754 jQuery("#menu .register").css("display", "none")
756 else if (this.statut
== statutType
.auth_not_registered
)
758 jQuery("#menu .profile").css("display", "none")
759 jQuery("#menu .logout").css("display", displayType
)
760 jQuery("#menu .register").css("display", displayType
)
764 jQuery("#menu .profile").css("display", displayType
).text("login")
765 jQuery("#menu .logout").css("display", "none")
766 jQuery("#menu .register").css("display", displayType
)
770 ///////////////////////////////////////////////////////////////////////////////////////////////////
772 function initialiserListeStyles(client
)
774 jQuery("#menuCss").change(
777 client
.setCss("css/" + jQuery("option:selected", this).attr("value") + "/euphorik.css")
784 // charge dynamiquement le script de debug
785 ;;; jQuery
.ajax({async : false, url : "js/debug.js", dataType : "script"})
788 jQuery(document
).ready(
791 var util
= new Util()
792 var client
= new Client(util
)
793 var pages
= new Pages()
794 var formateur
= new Formateur()
796 // connexion vers le serveur (utilise un cookie qui traine)
797 client
.connexionCookie()
799 initialiserListeStyles(client
)
801 // TODO : pourquoi jQuery(document).unload ne fonctionne pas ?
802 jQuery(window
).unload(
809 jQuery("#menu .minichat").click(function(){ pages
.afficherPage("minichat") })
810 jQuery("#menu .profile").click(function(){ pages
.afficherPage("profile") })
811 jQuery("#menu .logout").click(function(){
812 util
.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType
.question
,
815 client
.deconnexion();
816 pages
.afficherPage("minichat", true)
822 jQuery("#menu .register").click(function(){ pages
.afficherPage("register") })
823 jQuery("#menu .about").click(function(){ pages
.afficherPage("about") })
825 pages
.ajouterPage(new PageMinichat(client
, formateur
, util
))
826 pages
.ajouterPage(new PageProfile(client
, formateur
, util
))
827 pages
.ajouterPage(new PageRegister(client
, formateur
, util
))
828 pages
.ajouterPage(new PageAbout(client
, formateur
, util
))
829 pages
.afficherPage("minichat")