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 "oh" : [/:o/g, /:O/g],
26 "pascontent" : [/>\(/g, />\(/g],
27 "sniff" : [/:\(/g, /:-\(/g],
28 "argn" : [/\[:argn\]/g],
29 "bunny" : [/\[:lapin\]/g],
30 "chat" : [/\[:chat\]/g],
31 "renne" : [/\[:renne\]/g],
32 "lol" : [/\[:lol\]/g],
33 "spliff" : [/\[:spliff\]/g],
34 "star" : [/\[:star\]/g],
35 "triste" : [/\[:triste\]/g],
36 "kirby" : [/\[:kirby\]/g]
40 ///////////////////////////////////////////////////////////////////////////////////////////////////
42 String
.prototype.trim = function()
44 return jQuery
.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
47 String
.prototype.ltrim = function()
49 return this.replace(/^\s+/, "");
52 String
.prototype.rtrim = function()
54 return this.replace(/\s+$/, "");
57 ///////////////////////////////////////////////////////////////////////////////////////////////////
60 * Cette classe regroupe des fonctions utilitaires (helpers).
64 jQuery("#info .fermer").click(function(){
65 jQuery("#info").slideUp(50)
70 * Affiche une boite de dialogue avec un message à l'intérieur.
71 * @param message le message (string)
72 * @param type voir 'messageType'. par défaut messageType.informatif
73 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
74 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
76 Util
.prototype.messageDialogue = function(message
, type
, boutons
)
78 if (type
== undefined)
79 type
= messageType
.informatif
81 if (this.timeoutMessageDialogue
!= undefined)
82 clearTimeout(this.timeoutMessageDialogue
)
84 var fermer = function(){jQuery("#info").slideUp(100)}
87 jQuery("#info .message").html(message
)
90 case messageType
.informatif : jQuery("#info #icone").attr("class", "information"); break
91 case messageType
.question : jQuery("#info #icone").attr("class", "interrogation"); break
92 case messageType
.erreur : jQuery("#info #icone").attr("class", "exclamation"); break
94 jQuery("#info .boutons").html("")
95 for (var b
in boutons
)
96 jQuery("#info .boutons").append("<div>" + b
+ "</div>").find("div:last").click(boutons
[b
]).click(fermer
)
98 jQuery("#info").slideDown(200)
99 this.timeoutMessageDialogue
= setTimeout(fermer
, conf
.tempsAffichageMessageDialogue
)
102 var messageType
= {informatif: 0, question: 1, erreur: 2}
105 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
107 Util
.prototype.jsonVersAction = function(json
)
109 return {action : JSON
.stringify(json
) }
112 Util
.prototype.md5 = function(chaine
)
114 return hex_md5(chaine
)
117 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
118 Util
.prototype.setSelectionRange = function(input
, selectionStart
, selectionEnd
)
120 if (input
.setSelectionRange
)
123 input
.setSelectionRange(selectionStart
, selectionEnd
)
125 else if (input
.createTextRange
)
127 var range
= input
.createTextRange()
129 range
.moveEnd('character', selectionEnd
)
130 range
.moveStart('character', selectionStart
)
135 Util
.prototype.setCaretToEnd = function(input
)
137 this.setSelectionRange(input
, input
.value
.length
, input
.value
.length
)
139 Util
.prototype.setCaretToBegin = function(input
)
141 this.setSelectionRange(input
, 0, 0)
143 Util
.prototype.setCaretToPos = function(input
, pos
)
145 this.setSelectionRange(input
, pos
, pos
)
147 Util
.prototype.selectString = function(input
, string
)
149 var match
= new RegExp(string
, "i").exec(input
.value
)
152 this.setSelectionRange (input
, match
.index
, match
.index
+ match
[0].length
)
155 Util
.prototype.replaceSelection = function(input
, replaceString
) {
156 if (input
.setSelectionRange
)
158 var selectionStart
= input
.selectionStart
159 var selectionEnd
= input
.selectionEnd
160 input
.value
= input
.value
.substring(0, selectionStart
) + replaceString
+ input
.value
.substring(selectionEnd
)
162 if (selectionStart
!= selectionEnd
) // has there been a selection
163 this.setSelectionRange(input
, selectionStart
, selectionStart
+ replaceString
.length
)
165 this.setCaretToPos(input
, selectionStart
+ replaceString
.length
)
167 else if (document
.selection
)
169 var range
= document
.selection
.createRange();
170 if (range
.parentElement() == input
)
172 var isCollapsed
= range
.text
== ''
173 range
.text
= replaceString
176 // there has been a selection
177 // it appears range.select() should select the newly
178 // inserted text but that fails with IE
179 range
.moveStart('character', -replaceString
.length
);
186 Util
.prototype.rot13 = function(chaine
)
188 var ACode
= 'A'.charCodeAt(0)
189 var aCode
= 'a'.charCodeAt(0)
190 var MCode
= 'M'.charCodeAt(0)
191 var mCode
= 'm'.charCodeAt(0)
192 var ZCode
= 'Z'.charCodeAt(0)
193 var zCode
= 'z'.charCodeAt(0)
195 var f = function(ch
, pos
) {
196 if (pos
== ch
.length
)
199 var c
= ch
.charCodeAt(pos
);
200 return String
.fromCharCode(
202 (c
>= ACode
&& c
<= MCode
|| c
>= aCode
&& c
<= mCode
? 13 :
203 (c
> MCode
&& c
<= ZCode
|| c
> mCode
&& c
<= zCode
? -13 : 0))
209 ///////////////////////////////////////////////////////////////////////////////////////////////////
213 this.pageCourante
= null
217 Pages
.prototype.ajouterPage = function(page
)
219 page
.pages
= this // la magie des langages dynamiques : le foutoire
220 this.pages
[page
.nom
] = page
223 Pages
.prototype.afficherPage = function(nomPage
, forcerChargement
)
225 if (forcerChargement
== undefined) forcerChargement
= false
227 var page
= this.pages
[nomPage
]
228 if (page
== undefined || (!forcerChargement
&& page
== this.pageCourante
)) return
230 if (this.pageCourante
!= null && this.pageCourante
.decharger
)
231 this.pageCourante
.decharger()
233 jQuery("#menu div").removeClass("courante")
234 jQuery("#menu div." + nomPage
).addClass("courante")
236 this.pageCourante
= page
237 jQuery("#page").html(this.pageCourante
.contenu()).removeClass().addClass(this.pageCourante
.nom
)
239 if (this.pageCourante
.charger
)
240 this.pageCourante
.charger()
243 ///////////////////////////////////////////////////////////////////////////////////////////////////
247 this.smiles
= conf
.smiles
248 this.protocoles
= "http|https|ed2k"
250 this.regexUrl
= new RegExp("(?:(?:" + this.protocoles
+ ")://|www\\.)[^ ]*", "gi")
251 this.regexImg
= new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
252 this.regexDomaine
= new RegExp("^(?:(?:" + this.protocoles
+ ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
253 this.regexTestProtocoleExiste
= new RegExp("^(?:" + this.protocoles
+ ")://.*$", "i")
254 this.regexNomProtocole
= new RegExp("^(.*?)://")
258 * Formate un pseudo saise par l'utilisateur.
259 * @param pseudo le pseudo brut
260 * @return le pseudo filtré
262 Formateur
.prototype.filtrerInputPseudo = function(pseudo
)
264 return pseudo
.replace(/{|}/g, "").trim()
267 Formateur
.prototype.getSmilesHTML = function()
270 for (var sNom
in this.smiles
)
272 XHTML
+= "<img class=\"" + sNom
+ "\" src=\"img/smileys/" + sNom
+ ".gif\" />"
277 Formateur
.prototype.traitementComplet = function(M
, pseudo
)
279 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.remplacerBalisesHTML(M
), pseudo
)))
283 * Transforme les liens en entités clickables.
284 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
285 * "{5F}" ou 5F est la racine de la conversation.
286 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
288 Formateur
.prototype.traiterLiensConv = function(M
)
294 return "<span class=\"lienConv\">" + lien
+ "</span>"
300 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
302 Formateur
.prototype.traiterSmiles = function(M
)
304 for (var sNom
in this.smiles
)
306 ss
= this.smiles
[sNom
]
307 for (var i
= 0; i
< ss
.length
; i
++)
308 M
= M
.replace(ss
[i
], "<img src=\"img/smileys/" + sNom
+ ".gif\" />")
313 Formateur
.prototype.remplacerBalisesHTML = function(M
)
315 return M
.replace(/</g
, "<").replace(/>/g
, ">")
318 Formateur
.prototype.traiterURL = function(M
, pseudo
)
322 if (pseudo
== undefined)
325 var traitementUrl = function(url
)
327 // si ya pas de protocole on rajoute "http://"
328 if (!thisFormateur
.regexTestProtocoleExiste
.test(url
))
329 url
= "http://" + url
330 var extension
= thisFormateur
.getShort(url
)
331 return "<a " + (extension
[1] ? "title=\"" + thisFormateur
.traiterPourFenetreLightBox(pseudo
, url
) + ": " + thisFormateur
.traiterPourFenetreLightBox(M
, url
) + "\"" + " rel=\"lightbox[groupe]\"" : "") + " href=\"" + url
+ "\" >[" + extension
[0] + "]</a>"
333 return M
.replace(this.regexUrl
, traitementUrl
)
337 * Renvoie une version courte de l'url.
338 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
340 Formateur
.prototype.getShort = function(url
)
342 var estUneImage
= false
343 var versionShort
= null
344 var rechercheImg
= this.regexImg
.exec(url
)
346 if (rechercheImg
!= null)
348 versionShort
= rechercheImg
[1].toLowerCase()
349 if (versionShort
== "jpeg") versionShort
= "jpg" // jpeg -> jpg
354 var rechercheDomaine
= this.regexDomaine
.exec(url
)
355 if (rechercheDomaine
!= null && rechercheDomaine
.length
>= 2)
356 versionShort
= rechercheDomaine
[1]
359 var nomProtocole
= this.regexNomProtocole
.exec(url
)
360 if (nomProtocole
!= null && nomProtocole
.length
>= 2)
361 versionShort
= nomProtocole
[1]
365 return [versionShort
== null ? "url" : versionShort
, estUneImage
]
369 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
371 Formateur
.prototype.traiterPourFenetreLightBox = function(M
, urlCourante
)
374 var traitementUrl = function(url
)
376 return "[" + thisFormateur
.getShort(url
)[0] + (urlCourante
== url
? ": image courante" : "") + "]"
379 return this.remplacerBalisesHTML(M
).replace(this.regexUrl
, traitementUrl
)
383 ///////////////////////////////////////////////////////////////////////////////////////////////////
385 // les statuts possibes du client
387 // mode enregistré, peut poster des messages et modifier son profile
389 // mode identifié, peut poster des messages mais n'a pas accès au profile
390 auth_not_registered : 1,
391 // mode déconnecté, ne peut pas poster de message
395 function Client(util
)
400 this.regexCookie
= new RegExp("^cookie=([^;]*)")
402 // données personnels
403 this.resetDonneesPersonnelles()
405 this.setStatut(statutType
.deconnected
)
407 // le dernier message d'erreur recut du serveur (par exemple une connexion foireuse : "login impossible")
408 this.dernierMessageErreur
= ""
411 Client
.prototype.resetDonneesPersonnelles = function()
413 this.pseudo
= conf
.pseudoDefaut
417 this.css
= jQuery("link#cssPrincipale").attr("href")
419 this.pagePrincipale
= 1
421 // les conversations, une conversation est un objet possédant les attributs suivants :
424 this.conversations
= new Array()
427 Client
.prototype.setCss = function(css
)
433 jQuery("link#cssPrincipale").attr("href", this.css
)
437 Client
.prototype.pageSuivante = function(numConv
)
439 if (numConv
< 0 && this.pagePrincipale
> 1)
440 this.pagePrincipale
-= 1
441 else if (this.conversations
[numConv
].page
> 1)
442 this.conversations
[numConv
].page
-= 1
445 Client
.prototype.pagePrecedente = function(numConv
)
448 this.pagePrincipale
+= 1
450 this.conversations
[numConv
].page
+= 1
454 * Définit la première page pour la conversation donnée.
455 * @return true si la page a changé sinon false
457 Client
.prototype.goPremierePage = function(numConv
)
461 if (this.pagePrincipale
== 1)
463 this.pagePrincipale
= 1
467 if (this.conversations
[numConv
].page
== 1)
469 this.conversations
[numConv
].page
= 1
475 * Ajoute une conversation à la vue de l'utilisateur.
476 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
477 * @param racines la racine de la conversation (integer)
478 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
480 Client
.prototype.ajouterConversation = function(racine
)
482 // vérification s'il elle n'existe pas déjà
483 for (var i
= 0; i
< this.conversations
.length
; i
++)
484 if (this.conversations
[i
].root
== racine
)
487 this.conversations
.push({root : racine
, page : 1})
491 Client
.prototype.supprimerConversation = function(num
)
493 if (num
< 0 || num
>= this.conversations
.length
) return
495 // décalage TODO : supprimer le dernier élément
496 for (var i
= num
; i
< this.conversations
.length
- 1; i
++)
497 this.conversations
[i
] = this.conversations
[i
+1]
498 this.conversations
.pop()
501 Client
.prototype.getJSONLogin = function(login
, password
)
504 "action" : "authentification",
506 "password" : password
510 Client
.prototype.getJSONLoginCookie = function()
513 "action" : "authentification",
514 "cookie" : this.cookie
519 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
520 * de s'autentifier avec (login, password).
522 Client
.prototype.getJSONEnregistrement = function(login
, password
)
524 var mess
= { "action" : "register" }
526 if (login
!= undefined && password
!= undefined)
528 mess
["login"] = login
529 mess
["password"] = password
535 Client
.prototype.getJSONConversations = function()
537 var conversations
= new Array()
538 for (var i
= 0; i
< this.conversations
.length
; i
++)
539 conversations
.push({ "root" : this.conversations
[i
].root
, "page" : this.conversations
[i
].page
})
543 Client
.prototype.getJSONProfile = function()
546 "action" : "set_profile",
547 "cookie" : this.cookie
,
548 "login" : this.login
,
549 "password" : this.password
,
550 "nick" : this.pseudo
,
551 "email" : this.email
,
553 "main_page" : this.pagePrincipale
< 1 ? 1 : this.pagePrincipale
,
554 "conversations" : this.getJSONConversations()
559 * Renvoie null si pas définit.
561 Client
.prototype.getCookie = function()
563 var cookie
= this.regexCookie
.exec(document
.cookie
)
564 if (cookie
== null) this.cookie
= null
565 else this.cookie
= cookie
[1]
568 Client
.prototype.delCookie = function()
570 document
.cookie
= "cookie=; max-age=0"
573 Client
.prototype.setCookie = function(cookie
)
575 if (this.cookie
== null)
579 "cookie="+this.cookie
+
580 "; max-age=" + (60 * 60 * 24 * 365)
583 Client
.prototype.authentifie = function()
585 return this.statut
== statutType
.auth_registered
|| this.statut
== statutType
.auth_not_registered
588 Client
.prototype.setStatut = function(statut
)
591 // conversation en "enum" si en "string"
592 if (typeof(statut
) == "string")
595 statut
== "auth_registered" ?
596 statutType
.auth_registered :
597 (statut
== "auth_not_registered" ? statutType
.auth_not_registered : statutType
.deconnected
)
600 if (statut
== this.statut
) return
607 * Effectue la connexion vers le serveur.
608 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
609 * S'il existe un cookie en local on s'authentifie directement avec lui.
610 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
612 Client
.prototype.connexionCookie = function()
615 if (this.cookie
== null) return false;
616 return this.connexion(this.getJSONLoginCookie())
619 Client
.prototype.connexionLogin = function(login
, password
)
621 return this.connexion(this.getJSONLogin(login
, password
))
624 Client
.prototype.enregistrement = function(login
, password
)
626 if (this.authentifie())
629 this.password
= password
631 this.setStatut(statutType
.auth_registered
)
636 return this.connexion(this.getJSONEnregistrement(login
, password
))
640 Client
.prototype.connexion = function(messageJson
)
642 ;;; dumpObj(messageJson
)
650 data: this.util
.jsonVersAction(messageJson
),
655 thisClient
.chargerDonnees(data
)
659 return this.authentifie()
662 Client
.prototype.deconnexion = function()
664 this.setStatut(statutType
.deconnected
) // deconnexion
665 this.resetDonneesPersonnelles()
669 Client
.prototype.chargerDonnees = function(data
)
671 var thisClient
= this
673 this.setStatut(data
["status"])
675 if (this.authentifie())
677 this.cookie
= data
["cookie"]
680 this.login
= data
["login"]
681 this.pseudo
= data
["nick"]
682 this.email
= data
["email"]
683 this.css
= data
["css"]
685 // la page de la conversation principale
686 this.pagePrincipale
= data
["main_page"] == undefined ? 1 : data
["main_page"]
691 jQuery("link#cssPrincipale").attr("href", this.css
)
695 thisClient
.conversations
= data
["conversations"]
698 this.dernierMessageErreur
= data
["error_message"]
702 * Met à jour les données personne sur serveur.
703 * @param async de manière asynchrone ? défaut = true
704 * @return false si le flush n'a pas pû se faire sinon true
706 Client
.prototype.flush = function(async
)
708 if (async
== undefined)
711 if (!this.authentifie())
715 ;;; dumpObj(this.getJSONProfile())
722 data: this.util
.jsonVersAction(this.getJSONProfile()),
726 //thisClient.util.log(thisClient.util.serializer.serializeToString(data))
730 // TODO : retourner false si un problème est survenu lors de l'update du profile
734 Client
.prototype.majMenu = function()
736 var displayType
= this.css
== "css/3/euphorik.css" ? "block" : "inline" //this.client
738 // met à jour le menu
739 if (this.statut
== statutType
.auth_registered
)
741 jQuery("#menu .profile").css("display", displayType
).text("profile")
742 jQuery("#menu .logout").css("display", displayType
)
743 jQuery("#menu .register").css("display", "none")
745 else if (this.statut
== statutType
.auth_not_registered
)
747 jQuery("#menu .profile").css("display", "none")
748 jQuery("#menu .logout").css("display", displayType
)
749 jQuery("#menu .register").css("display", displayType
)
753 jQuery("#menu .profile").css("display", displayType
).text("login")
754 jQuery("#menu .logout").css("display", "none")
755 jQuery("#menu .register").css("display", displayType
)
759 ///////////////////////////////////////////////////////////////////////////////////////////////////
761 function initialiserListeStyles(client
)
763 jQuery("#menuCss").change(
766 client
.setCss("css/" + jQuery("option:selected", this).attr("value") + "/euphorik.css")
773 // charge dynamiquement le script de debug
774 ;;; jQuery
.ajax({async : false, url : "js/debug.js", dataType : "script"})
777 jQuery(document
).ready(
780 /* FIXME : ce code pose problème sur konqueror, voir : http://www.kde-forum.org/thread.php?threadid=17993
781 var p = new DOMParser();
782 var doc = p.parseFromString("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<action/>", "text/xml")
783 var s = new XMLSerializer()
784 alert(s.serializeToString(doc)) */
786 var util
= new Util()
787 var client
= new Client(util
)
788 var pages
= new Pages()
789 var formateur
= new Formateur()
791 // connexion vers le serveur (utilise un cookie qui traine)
792 client
.connexionCookie()
794 initialiserListeStyles(client
)
796 // TODO : pourquoi jQuery(document).unload ne fonctionne pas ?
797 jQuery(window
).unload(
804 jQuery("#menu .minichat").click(function(){ pages
.afficherPage("minichat") })
805 jQuery("#menu .profile").click(function(){ pages
.afficherPage("profile") })
806 jQuery("#menu .logout").click(function(){
807 util
.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType
.question
,
810 client
.deconnexion();
811 pages
.afficherPage("minichat", true)
817 jQuery("#menu .register").click(function(){ pages
.afficherPage("register") })
818 jQuery("#menu .about").click(function(){ pages
.afficherPage("about") })
820 pages
.ajouterPage(new PageMinichat(client
, formateur
, util
))
821 pages
.ajouterPage(new PageProfile(client
, formateur
, util
))
822 pages
.ajouterPage(new PageRegister(client
, formateur
, util
))
823 pages
.ajouterPage(new PageAbout(client
, formateur
, util
))
824 pages
.afficherPage("minichat")