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 ///////////////////////////////////////////////////////////////////////////////////////////////////
190 this.pageCourante
= null
194 Pages
.prototype.ajouterPage = function(page
)
196 page
.pages
= this // la magie des langages dynamiques : le foutoire
197 this.pages
[page
.nom
] = page
200 Pages
.prototype.afficherPage = function(nomPage
, forcerChargement
)
202 if (forcerChargement
== undefined) forcerChargement
= false
204 var page
= this.pages
[nomPage
]
205 if (page
== undefined || (!forcerChargement
&& page
== this.pageCourante
)) return
207 if (this.pageCourante
!= null && this.pageCourante
.decharger
)
208 this.pageCourante
.decharger()
210 jQuery("#menu div").removeClass("courante")
211 jQuery("#menu div." + nomPage
).addClass("courante")
213 this.pageCourante
= page
214 jQuery("#page").html(this.pageCourante
.contenu()).removeClass().addClass(this.pageCourante
.nom
)
216 if (this.pageCourante
.charger
)
217 this.pageCourante
.charger()
220 ///////////////////////////////////////////////////////////////////////////////////////////////////
224 this.smiles
= conf
.smiles
225 this.protocoles
= "http|https|ed2k"
227 this.regexUrl
= new RegExp("(?:(?:" + this.protocoles
+ ")://|www\\.)[^ ]*", "gi")
228 this.regexImg
= new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
229 this.regexDomaine
= new RegExp("^(?:(?:" + this.protocoles
+ ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
230 this.regexTestProtocoleExiste
= new RegExp("^(?:" + this.protocoles
+ ")://.*$", "i")
231 this.regexNomProtocole
= new RegExp("^(.*?)://")
235 * Formate un pseudo saise par l'utilisateur.
236 * @param pseudo le pseudo brut
237 * @return le pseudo filtré
239 Formateur
.prototype.filtrerInputPseudo = function(pseudo
)
241 return pseudo
.replace(/{|}/g, "").trim()
244 Formateur
.prototype.getSmilesHTML = function()
247 for (var sNom
in this.smiles
)
249 XHTML
+= "<img class=\"" + sNom
+ "\" src=\"img/smileys/" + sNom
+ ".gif\" />"
254 Formateur
.prototype.traitementComplet = function(M
, pseudo
)
256 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.remplacerBalisesHTML(M
), pseudo
)))
260 * Transforme les liens en entités clickables.
261 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
262 * "{5F}" ou 5F est la racine de la conversation.
263 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
265 Formateur
.prototype.traiterLiensConv = function(M
)
271 return "<span class=\"lienConv\">" + lien
+ "</span>"
277 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
279 Formateur
.prototype.traiterSmiles = function(M
)
281 for (var sNom
in this.smiles
)
283 ss
= this.smiles
[sNom
]
284 for (var i
= 0; i
< ss
.length
; i
++)
285 M
= M
.replace(ss
[i
], "<img src=\"img/smileys/" + sNom
+ ".gif\" />")
290 Formateur
.prototype.remplacerBalisesHTML = function(M
)
292 return M
.replace(/</g
, "<").replace(/>/g
, ">")
295 Formateur
.prototype.traiterURL = function(M
, pseudo
)
299 if (pseudo
== undefined)
302 var traitementUrl = function(url
)
304 // si ya pas de protocole on rajoute "http://"
305 if (!thisFormateur
.regexTestProtocoleExiste
.test(url
))
306 url
= "http://" + url
307 var extension
= thisFormateur
.getShort(url
)
308 return "<a " + (extension
[1] ? "title=\"" + thisFormateur
.traiterPourFenetreLightBox(pseudo
, url
) + ": " + thisFormateur
.traiterPourFenetreLightBox(M
, url
) + "\"" + " rel=\"lightbox[groupe]\"" : "") + " href=\"" + url
+ "\" >[" + extension
[0] + "]</a>"
310 return M
.replace(this.regexUrl
, traitementUrl
)
314 * Renvoie une version courte de l'url.
315 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
317 Formateur
.prototype.getShort = function(url
)
319 var estUneImage
= false
320 var versionShort
= null
321 var rechercheImg
= this.regexImg
.exec(url
)
323 if (rechercheImg
!= null)
325 versionShort
= rechercheImg
[1].toLowerCase()
326 if (versionShort
== "jpeg") versionShort
= "jpg" // jpeg -> jpg
331 var rechercheDomaine
= this.regexDomaine
.exec(url
)
332 if (rechercheDomaine
!= null && rechercheDomaine
.length
>= 2)
333 versionShort
= rechercheDomaine
[1]
336 var nomProtocole
= this.regexNomProtocole
.exec(url
)
337 if (nomProtocole
!= null && nomProtocole
.length
>= 2)
338 versionShort
= nomProtocole
[1]
342 return [versionShort
== null ? "url" : versionShort
, estUneImage
]
346 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
348 Formateur
.prototype.traiterPourFenetreLightBox = function(M
, urlCourante
)
351 var traitementUrl = function(url
)
353 return "[" + thisFormateur
.getShort(url
)[0] + (urlCourante
== url
? ": image courante" : "") + "]"
356 return this.remplacerBalisesHTML(M
).replace(this.regexUrl
, traitementUrl
)
360 ///////////////////////////////////////////////////////////////////////////////////////////////////
362 // les statuts possibes du client
364 // mode enregistré, peut poster des messages et modifier son profile
366 // mode identifié, peut poster des messages mais n'a pas accès au profile
367 auth_not_registered : 1,
368 // mode déconnecté, ne peut pas poster de message
372 function Client(util
)
377 this.regexCookie
= new RegExp("^cookie=([^;]*)")
379 // données personnels
380 this.resetDonneesPersonnelles()
382 this.setStatut(statutType
.deconnected
)
384 // le dernier message d'erreur recut du serveur (par exemple une connexion foireuse : "login impossible")
385 this.dernierMessageErreur
= ""
388 Client
.prototype.resetDonneesPersonnelles = function()
390 this.pseudo
= conf
.pseudoDefaut
394 this.css
= jQuery("link#cssPrincipale").attr("href")
396 this.pagePrincipale
= 1
398 // les conversations, une conversation est un objet possédant les attributs suivants :
401 this.conversations
= new Array()
404 Client
.prototype.setCss = function(css
)
410 jQuery("link#cssPrincipale").attr("href", this.css
)
414 Client
.prototype.pageSuivante = function(numConv
)
416 if (numConv
< 0 && this.pagePrincipale
> 1)
417 this.pagePrincipale
-= 1
418 else if (this.conversations
[numConv
].page
> 1)
419 this.conversations
[numConv
].page
-= 1
422 Client
.prototype.pagePrecedente = function(numConv
)
425 this.pagePrincipale
+= 1
427 this.conversations
[numConv
].page
+= 1
431 * Définit la première page pour la conversation donnée.
432 * @return true si la page a changé sinon false
434 Client
.prototype.goPremierePage = function(numConv
)
438 if (this.pagePrincipale
== 1)
440 this.pagePrincipale
= 1
444 if (this.conversations
[numConv
].page
== 1)
446 this.conversations
[numConv
].page
= 1
452 * Ajoute une conversation à la vue de l'utilisateur.
453 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
454 * @param racines la racine de la conversation (integer)
455 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
457 Client
.prototype.ajouterConversation = function(racine
)
459 // vérification s'il elle n'existe pas déjà
460 for (var i
= 0; i
< this.conversations
.length
; i
++)
461 if (this.conversations
[i
].root
== racine
)
464 this.conversations
.push({root : racine
, page : 1})
468 Client
.prototype.supprimerConversation = function(num
)
470 if (num
< 0 || num
>= this.conversations
.length
) return
472 // décalage TODO : supprimer le dernier élément
473 for (var i
= num
; i
< this.conversations
.length
- 1; i
++)
474 this.conversations
[i
] = this.conversations
[i
+1]
475 this.conversations
.pop()
478 Client
.prototype.getJSONLogin = function(login
, password
)
481 "action" : "authentification",
483 "password" : password
487 Client
.prototype.getJSONLoginCookie = function()
490 "action" : "authentification",
491 "cookie" : this.cookie
496 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
497 * de s'autentifier avec (login, password).
499 Client
.prototype.getJSONEnregistrement = function(login
, password
)
501 var mess
= { "action" : "register" }
503 if (login
!= undefined && password
!= undefined)
505 mess
["login"] = login
506 mess
["password"] = password
512 Client
.prototype.getJSONConversations = function()
514 var conversations
= new Array()
515 for (var i
= 0; i
< this.conversations
.length
; i
++)
516 conversations
.push({ "root" : this.conversations
[i
].root
, "page" : this.conversations
[i
].page
})
520 Client
.prototype.getJSONProfile = function()
523 "action" : "set_profile",
524 "cookie" : this.cookie
,
525 "login" : this.login
,
526 "password" : this.password
,
527 "nick" : this.pseudo
,
528 "email" : this.email
,
530 "main_page" : this.pagePrincipale
< 1 ? 1 : this.pagePrincipale
,
531 "conversations" : this.getJSONConversations()
536 * Renvoie null si pas définit.
538 Client
.prototype.getCookie = function()
540 var cookie
= this.regexCookie
.exec(document
.cookie
)
541 if (cookie
== null) this.cookie
= null
542 else this.cookie
= cookie
[1]
545 Client
.prototype.delCookie = function()
547 document
.cookie
= "cookie=; max-age=0"
550 Client
.prototype.setCookie = function(cookie
)
552 if (this.cookie
== null)
556 "cookie="+this.cookie
+
557 "; max-age=" + (60 * 60 * 24 * 365)
560 Client
.prototype.authentifie = function()
562 return this.statut
== statutType
.auth_registered
|| this.statut
== statutType
.auth_not_registered
565 Client
.prototype.setStatut = function(statut
)
567 // conversation en "enum" si en "string"
568 if (typeof(statut
) == "string")
571 statut
== "auth_registered" ?
572 statutType
.auth_registered :
573 (statut
== "auth_not_registered" ? statutType
.auth_not_registered : statutType
.deconnected
)
576 if (statut
== this.statut
) return
583 * Effectue la connexion vers le serveur.
584 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
585 * S'il existe un cookie en local on s'authentifie directement avec lui.
586 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
588 Client
.prototype.connexionCookie = function()
591 if (this.cookie
== null) return false;
592 return this.connexion(this.getJSONLoginCookie())
595 Client
.prototype.connexionLogin = function(login
, password
)
597 return this.connexion(this.getJSONLogin(login
, password
))
600 Client
.prototype.enregistrement = function(login
, password
)
602 if (this.authentifie())
605 this.password
= password
607 this.setStatut(statutType
.auth_registered
)
612 return this.connexion(this.getJSONEnregistrement(login
, password
))
616 Client
.prototype.connexion = function(messageJson
)
618 ;;; dumpObj(messageJson
)
626 data: this.util
.jsonVersAction(messageJson
),
631 thisClient
.chargerDonnees(data
)
635 return this.authentifie()
638 Client
.prototype.deconnexion = function()
640 this.setStatut(statutType
.deconnected
) // deconnexion
641 this.resetDonneesPersonnelles()
645 Client
.prototype.chargerDonnees = function(data
)
647 var thisClient
= this
649 this.setStatut(data
["status"])
651 if (this.authentifie())
653 this.cookie
= data
["cookie"]
656 this.login
= data
["login"]
657 this.pseudo
= data
["nick"]
658 this.email
= data
["email"]
659 this.css
= data
["css"]
661 // la page de la conversation principale
662 this.pagePrincipale
= data
["main_page"] == undefined ? 1 : data
["main_page"]
667 jQuery("link#cssPrincipale").attr("href", this.css
)
671 thisClient
.conversations
= data
["conversations"]
674 this.dernierMessageErreur
= data
["error_message"]
678 * Met à jour les données personne sur serveur.
679 * @param async de manière asynchrone ? défaut = true
680 * @return false si le flush n'a pas pû se faire sinon true
682 Client
.prototype.flush = function(async
)
684 if (async
== undefined)
687 if (!this.authentifie())
691 ;;; dumpObj(this.getJSONProfile())
698 data: this.util
.jsonVersAction(this.getJSONProfile()),
702 //thisClient.util.log(thisClient.util.serializer.serializeToString(data))
706 // TODO : retourner false si un problème est survenu lors de l'update du profile
710 Client
.prototype.majMenu = function()
712 var displayType
= this.css
== "css/3/euphorik.css" ? "block" : "inline" //this.client
714 // met à jour le menu
715 if (this.statut
== statutType
.auth_registered
)
717 jQuery("#menu .profile").css("display", displayType
).text("profile")
718 jQuery("#menu .logout").css("display", displayType
)
719 jQuery("#menu .register").css("display", "none")
721 else if (this.statut
== statutType
.auth_not_registered
)
723 jQuery("#menu .profile").css("display", "none")
724 jQuery("#menu .logout").css("display", displayType
)
725 jQuery("#menu .register").css("display", displayType
)
729 jQuery("#menu .profile").css("display", displayType
).text("login")
730 jQuery("#menu .logout").css("display", "none")
731 jQuery("#menu .register").css("display", displayType
)
735 ///////////////////////////////////////////////////////////////////////////////////////////////////
737 function initialiserListeStyles(client
)
739 jQuery("#menuCss").change(
742 client
.setCss("css/" + jQuery("option:selected", this).attr("value") + "/euphorik.css")
749 // charge dynamiquement le script de debug
750 ;;; jQuery
.ajax({async : false, url : "js/debug.js", dataType : "script"})
753 jQuery(document
).ready(
756 /* FIXME : ce code pose problème sur konqueror, voir : http://www.kde-forum.org/thread.php?threadid=17993
757 var p = new DOMParser();
758 var doc = p.parseFromString("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<action/>", "text/xml")
759 var s = new XMLSerializer()
760 alert(s.serializeToString(doc)) */
762 var util
= new Util()
763 var client
= new Client(util
)
764 var pages
= new Pages()
765 var formateur
= new Formateur()
767 // connexion vers le serveur (utilise un cookie qui traine)
768 client
.connexionCookie()
770 initialiserListeStyles(client
)
772 // TODO : pourquoi jQuery(document).unload ne fonctionne pas ?
773 jQuery(window
).unload(
781 jQuery("#menu .minichat").click(function(){ pages
.afficherPage("minichat") })
782 jQuery("#menu .profile").click(function(){ pages
.afficherPage("profile") })
783 jQuery("#menu .logout").click(function(){
784 util
.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType
.question
,
787 client
.deconnexion();
788 pages
.afficherPage("minichat", true)
794 jQuery("#menu .register").click(function(){ pages
.afficherPage("register") })
796 pages
.ajouterPage(new PageMinichat(client
, formateur
, util
))
797 pages
.ajouterPage(new PageProfile(client
, formateur
, util
))
798 pages
.ajouterPage(new PageRegister(client
, formateur
, util
))
799 pages
.afficherPage("minichat")