[SPIP] ~version 3.0.7-->3.0.10
[ptitvelo/web/www.git] / www / prive / javascript / ajaxCallback.js
1 jQuery.spip=jQuery.spip || {};
2 jQuery.spip.log = function(){
3 if (jQuery.spip.debug && window.console && window.console.log)
4 window.console.log.apply(this,arguments);
5 }
6 // A plugin that wraps all ajax calls introducing a fixed callback function on ajax complete
7 if(!jQuery.spip.load_handlers) {
8 jQuery.spip.load_handlers = new Array();
9
10 /**
11 * OnAjaxLoad allow to
12 * add a function to the list of those
13 * to be executed on ajax load complete
14 *
15 * most of time function f is applied on the loaded data
16 * if not known, the whole document is targetted
17 *
18 * @param function f
19 */
20 function onAjaxLoad(f) {
21 jQuery.spip.load_handlers.push(f);
22 };
23
24 /**
25 * Call the functions that have been added to onAjaxLoad
26 * @param root
27 */
28 jQuery.spip.triggerAjaxLoad = function (root) {
29 jQuery.spip.log('triggerAjaxLoad');
30 jQuery.spip.log(root);
31 for ( var i = 0; i < jQuery.spip.load_handlers.length; i++ )
32 jQuery.spip.load_handlers[i].apply( root );
33 };
34
35 jQuery.spip.intercepted={};
36
37 // intercept jQuery.fn.load
38 jQuery.spip.intercepted.load = jQuery.fn.load;
39 jQuery.fn.load = function( url, params, callback ) {
40
41 callback = callback || function(){};
42
43 // If the second parameter was provided
44 if ( params ) {
45 // If it's a function
46 if ( params.constructor == Function ) {
47 // We assume that it's the callback
48 callback = params;
49 params = null;
50 }
51 }
52 var callback2 = function() {jQuery.spip.log('jQuery.load');jQuery.spip.triggerAjaxLoad(this);callback.apply(this,arguments);};
53 return jQuery.spip.intercepted.load.apply(this,[url, params, callback2]);
54 };
55
56 // intercept jQuery.fn.ajaxSubmit
57 jQuery.spip.intercepted.ajaxSubmit = jQuery.fn.ajaxSubmit;
58 jQuery.fn.ajaxSubmit = function(options){
59 // find the first parent that will not be removed by formulaire_dyn_ajax
60 // or take the whole document
61 options = options || {};
62 if (typeof options.onAjaxLoad=="undefined" || options.onAjaxLoad!=false) {
63 var me=jQuery(this).parents('div.ajax');
64 if (me.length)
65 me=me.parent();
66 else
67 me = document;
68 if (typeof options=='function')
69 options = { success: options };
70 var callback = options.success || function(){};
71 options.success = function(){callback.apply(this,arguments);jQuery.spip.log('jQuery.ajaxSubmit');jQuery.spip.triggerAjaxLoad(me);}
72 }
73 return jQuery.spip.intercepted.ajaxSubmit.apply(this,[options]);
74 }
75
76 // intercept jQuery.ajax
77 jQuery.spip.intercepted.ajax = jQuery.ajax;
78 jQuery.ajax = function(type) {
79 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, type);
80 var callbackContext = s.context || s;
81 try {
82 if (jQuery.ajax.caller==jQuery.spip.intercepted.load || jQuery.ajax.caller==jQuery.spip.intercepted.ajaxSubmit)
83 return jQuery.spip.intercepted.ajax(type);
84 }
85 catch (err){}
86 var orig_complete = s.complete || function() {};
87 type.complete = function(res,status) {
88 // Do not fire OnAjaxLoad if the dataType is not html
89 var dataType = type.dataType;
90 var ct = (res && (typeof res.getResponseHeader == 'function'))
91 ? res.getResponseHeader("content-type"): '';
92 var xml = !dataType && ct && ct.indexOf("xml") >= 0;
93 orig_complete.call( callbackContext, res, status);
94 if(!dataType && !xml || dataType == "html") {
95 jQuery.spip.log('jQuery.ajax');
96 if (typeof s.onAjaxLoad=="undefined" || s.onAjaxLoad!=false)
97 jQuery.spip.triggerAjaxLoad(s.ajaxTarget?s.ajaxTarget:document);
98 }
99 };
100 return jQuery.spip.intercepted.ajax(type);
101 };
102
103 }
104
105 /**
106 * if not fully visible, scroll the page to position
107 * target block at the top of page
108 * if force = true, allways scroll
109 *
110 * @param bool force
111 */
112 jQuery.fn.positionner = function(force, setfocus) {
113 var offset = jQuery(this).offset();
114 var hauteur = parseInt(jQuery(this).css('height'));
115 var scrolltop = self['pageYOffset'] ||
116 jQuery.boxModel && document.documentElement[ 'scrollTop' ] ||
117 document.body[ 'scrollTop' ];
118 var h = jQuery(window).height();
119 var scroll=0;
120
121 if (force || (offset && offset['top'] - 5 <= scrolltop))
122 scroll = offset['top'] - 5;
123 else if (offset && offset['top'] + hauteur - h + 5 > scrolltop)
124 scroll = Math.min(offset['top'] - 5, offset['top'] + hauteur - h + 15);
125 if (scroll)
126 jQuery('html,body')
127 .animate({scrollTop: scroll}, 300);
128
129 // positionner le curseur dans la premiere zone de saisie
130 if (setfocus!==false)
131 jQuery(jQuery('*', this).filter('input[type=text],textarea')[0]).focus();
132 return this; // don't break the chain
133 }
134
135 // deux fonctions pour rendre l'ajax compatible Jaws
136 jQuery.spip.virtualbuffer_id='spip_virtualbufferupdate';
137 jQuery.spip.initReaderBuffer = function(){
138 if (jQuery('#'+jQuery.spip.virtualbuffer_id).length) return;
139 jQuery('body').append('<p style="float:left;width:0;height:0;position:absolute;left:-5000;top:-5000;"><input type="hidden" name="'+jQuery.spip.virtualbuffer_id+'" id="'+jQuery.spip.virtualbuffer_id+'" value="0" /></p>');
140 }
141 jQuery.spip.updateReaderBuffer = function(){
142 var i = jQuery('#'+jQuery.spip.virtualbuffer_id);
143 if (!i.length) return;
144 // incrementons l'input hidden, ce qui a pour effet de forcer le rafraichissement du
145 // buffer du lecteur d'ecran (au moins dans Jaws)
146 i.attr('value',parseInt(i.attr('value'))+1);
147 }
148
149 jQuery.fn.formulaire_setARIA = function(){
150 if (!this.closest('.ariaformprop').length){
151 // eviter une double execution du js au moment de sa reinsertion dans le DOM par wrap()
152 // cf http://bugs.jquery.com/ticket/7447
153 this.find('script').remove();
154 this.wrap('<div class="ariaformprop" aria-live="assertive" aria-atomic="true"></div>');
155 }
156 return this;
157 }
158 /**
159 * rechargement ajax d'un formulaire dynamique implemente par formulaires/xxx.html
160 * @param target
161 */
162 jQuery.fn.formulaire_dyn_ajax = function(target) {
163 if (this.length)
164 jQuery.spip.initReaderBuffer();
165 return this.each(function() {
166 var scrollwhensubmit = !jQuery(this).is('.noscroll');
167 var cible = target || this;
168 jQuery(cible).formulaire_setARIA();
169 jQuery('form:not(.noajax):not(.bouton_action_post)', this).each(function(){
170 var leform = this;
171 var leclk,leclk_x,leclk_y;
172 jQuery(this).prepend("<input type='hidden' name='var_ajax' value='form' />")
173 .ajaxForm({
174 beforeSubmit: function(){
175 // memoriser le bouton clique, en cas de repost non ajax
176 leclk = leform.clk;
177 if (leclk) {
178 var n = leclk.name;
179 if (n && !leclk.disabled && leclk.type == "image") {
180 leclk_x = leform.clk_x;
181 leclk_y = leform.clk_y;
182 }
183 }
184 jQuery(cible).wrap('<div />');
185 cible = jQuery(cible).parent();
186 jQuery(cible).closest('.ariaformprop').animateLoading();
187 if (scrollwhensubmit)
188 jQuery(cible).positionner(false,false);
189 },
190 success: function(c){
191 if (c=='noajax'){
192 // le serveur ne veut pas traiter ce formulaire en ajax
193 // on resubmit sans ajax
194 jQuery("input[name=var_ajax]",leform).remove();
195 // si on a memorise le nom et la valeur du bouton clique
196 // les reinjecter dans le dom sous forme de input hidden
197 // pour que le serveur les recoive
198 if (leclk){
199 var n = leclk.name;
200 if (n && !leclk.disabled) {
201 jQuery(leform).prepend("<input type='hidden' name='"+n+"' value='"+leclk.value+"' />");
202 if (leclk.type == "image") {
203 jQuery(leform).prepend("<input type='hidden' name='"+n+".x' value='"+leform.clk_x+"' />");
204 jQuery(leform).prepend("<input type='hidden' name='"+n+".y' value='"+leform.clk_y+"' />");
205 }
206 }
207 }
208 jQuery(leform).ajaxFormUnbind().submit();
209 }
210 else {
211 // commencons par vider le cache des urls, si jamais un js au retour
212 // essaye tout de suite de suivre un lien en cache
213 // dans le doute sur la validite du cache il vaut mieux l'invalider
214 var preloaded = jQuery.spip.preloaded_urls;
215 jQuery.spip.preloaded_urls = {};
216 jQuery(cible).html(c);
217 var a = jQuery('a:first',cible).eq(0);
218 var d = jQuery('div.ajax',cible);
219 if (!d.length){
220 // si pas .ajax dans le form, remettre la classe sur le div que l'on a insere
221 jQuery(cible).addClass('ajax');
222 if (!scrollwhensubmit)
223 jQuery(cible).addClass('noscroll');
224 }
225 else {
226 // sinon nettoyer les br ajaxie
227 d.siblings('br.bugajaxie').remove();
228 // desemboiter d'un niveau pour manger le div que l'on a insere
229 cible = jQuery(":first",cible);
230 cible.unwrap();
231 }
232 // chercher une ancre en debut de html pour positionner la page
233 if (a.length
234 && a.is('a[name=ajax_ancre]')
235 && jQuery(a.attr('href'),cible).length){
236 a = a.attr('href');
237 if (jQuery(a,cible).length)
238 setTimeout(function(){
239 jQuery(a,cible).positionner(false);
240 //a = a.split('#');
241 //window.location.hash = a[1];
242 },10);
243 jQuery(cible).closest('.ariaformprop').endLoading(true);
244 }
245 else{
246 //jQuery(cible).positionner(false);
247 if (a.length && a.is('a[name=ajax_redirect]')){
248 a = a.get(0).href;
249 setTimeout(function(){
250 var cur = window.location.href.split('#');
251 document.location.replace(a);
252 // regarder si c'est juste un changement d'ancre : dans ce cas il faut reload
253 // (le faire systematiquement provoque des bugs)
254 if (cur[0]==a.split('#')[0]){
255 window.location.reload();
256 }
257 },10);
258 // ne pas arreter l'etat loading, puisqu'on redirige !
259 // mais le relancer car l'image loading a pu disparaitre
260 jQuery(cible).closest('.ariaformprop').animateLoading();
261 }
262 else {
263 jQuery(cible).closest('.ariaformprop').endLoading(true);
264 }
265 }
266 // si jamais le formulaire n'a pas un retour OK, retablissons le cache
267 // car a priori on a pas fait d'operation en base de donnee
268 if (!jQuery('.reponse_formulaire_ok',cible).length)
269 jQuery.spip.preloaded_urls = preloaded;
270 // mettre a jour le buffer du navigateur pour aider jaws et autres readers
271 // a supprimer ?
272 jQuery.spip.updateReaderBuffer();
273 }
274 },
275 iframe: jQuery.browser.msie
276 })
277 // previent qu'on n'ajaxera pas deux fois le meme formulaire en cas de ajaxload
278 // mais le marquer comme ayant l'ajax au cas ou on reinjecte du contenu ajax dedans
279 .addClass('noajax hasajax')
280 ;
281 });
282 });
283 }
284
285 jQuery.fn.formulaire_verifier = function(callback, champ){
286 var erreurs = {'message_erreur':'form non ajax'};
287 var me=this;
288 // si on est aussi en train de submit pour de vrai, abandonner
289 if (jQuery(me).closest('.ariaformprop').attr('aria-busy')!='true') {
290 if (jQuery(me).is('form.hasajax')){
291 jQuery(me).ajaxSubmit({
292 dataType:"json",
293 data:{formulaire_action_verifier_json:true},
294 success:function(errs){
295 var args = [errs, champ]
296 // si on est aussi en train de submit pour de vrai, abandonner
297 if (jQuery(me).closest('.ariaformprop').attr('aria-busy')!='true')
298 callback.apply(me,args);
299 }
300 });
301 }
302 else
303 callback.apply(me,[erreurs, champ]);
304 }
305 return this;
306 }
307
308 jQuery.fn.formulaire_activer_verif_auto = function(callback){
309 callback = callback || formulaire_actualiser_erreurs;
310 var me = jQuery(this).closest('.ariaformprop');
311 var check = function(){
312 var name=jQuery(this).attr('name');
313 // declencher apres 50ms pour ne pas double submit sur sequence saisie+submit
314 setTimeout(function(){me.find('form').formulaire_verifier(callback,name);},50);
315 }
316 var activer = function(){
317 if (me.find('form').attr('data-verifjson')!='on'){
318 me
319 .find('form')
320 .attr('data-verifjson','on')
321 .find('input,select,textarea')
322 .bind('change',check);
323 }
324 }
325 jQuery(activer);
326 onAjaxLoad(function(){setTimeout(activer,150);});
327 }
328
329 function formulaire_actualiser_erreurs(erreurs){
330 var parent = jQuery(this).closest('.formulaire_spip');
331 if (!parent.length) return;
332 // d'abord effacer tous les messages d'erreurs
333 parent.find('.reponse_formulaire,.erreur_message').fadeOut().remove();
334 parent.find('.erreur').removeClass('erreur');
335 // ensuite afficher les nouveaux messages d'erreur
336 if (erreurs['message_ok'])
337 parent.find('form').before('<p class="reponse_formulaire reponse_formulaire_ok">'+erreurs['message_ok']+'</p>');
338 if (erreurs['message_erreur'])
339 parent.find('form').before('<p class="reponse_formulaire reponse_formulaire_erreur">'+erreurs['message_erreur']+'</p>');
340 for (var k in erreurs){
341 var saisie = parent.find('.editer_'+k);
342 if (saisie.length) {
343 saisie.addClass('erreur');
344 saisie.find('label').after('<span class="erreur_message">'+erreurs[k]+'</span>');
345 }
346 }
347 }
348
349
350 // permettre d'utiliser onclick='return confirm('etes vous sur?');' sur un lien ajax
351 var ajax_confirm=true;
352 var ajax_confirm_date=0;
353 var spip_confirm = window.confirm;
354 function _confirm(message){
355 ajax_confirm = spip_confirm(message);
356 if (!ajax_confirm) {
357 var d = new Date();
358 ajax_confirm_date = d.getTime();
359 }
360 return ajax_confirm;
361 }
362 window.confirm = _confirm;
363
364 /**
365 * rechargement ajax d'une noisette implementee par {ajax}
366 * selecteur personalise, sera defini par defaut a '.pagination a,a.ajax'
367 */
368 var ajaxbloc_selecteur;
369
370 /**
371 * mise en cache des url. Il suffit de vider cete variable pour vider le cache
372 */
373 jQuery.spip.preloaded_urls = {};
374
375 /**
376 * Afficher dans la page
377 * le html d'un bloc ajax charge
378 * @param object blocfrag
379 * @param string c
380 * @param string href
381 * @param bool history
382 */
383 jQuery.spip.on_ajax_loaded = function(blocfrag,c,href,history) {
384 history = history || (history==null);
385 if (typeof href == undefined || href==null)
386 history = false;
387 if (history)
388 jQuery.spip.setHistoryState(blocfrag);
389
390 jQuery(blocfrag)
391 .html(c)
392 .endLoading();
393 if (typeof href != undefined)
394 jQuery(blocfrag).attr('data-url',href);
395 if (history) {
396 jQuery.spip.pushHistoryState(href);
397 jQuery.spip.setHistoryState(blocfrag);
398 }
399
400 var a = jQuery('a:first',jQuery(blocfrag)).eq(0);
401 if (a.length
402 && a.is('a[name=ajax_ancre]')
403 && jQuery(a.attr('href'),blocfrag).length){
404 a = a.attr('href');
405 jQuery(a,blocfrag).positionner(false);
406 }
407 jQuery.spip.log('on_ajax_loaded');
408 jQuery.spip.triggerAjaxLoad(blocfrag);
409 // si le fragment ajax est dans un form ajax,
410 // il faut remettre a jour les evenements attaches
411 // car le fragment peut comporter des submit ou button
412 a = jQuery(blocfrag).parents('form.hasajax')
413 if (a.length)
414 a.eq(0).removeClass('noajax').parents('div.ajax').formulaire_dyn_ajax();
415 jQuery.spip.updateReaderBuffer();
416 }
417
418 jQuery.spip.stateId=0;
419 jQuery.spip.setHistoryState = function(blocfrag){
420 if (!window.history.replaceState) return;
421 // attribuer un id au bloc si il n'en a pas
422 if (!blocfrag.attr('id')){
423 while (jQuery('#ghsid'+jQuery.spip.stateId).length)
424 jQuery.spip.stateId++;
425 blocfrag.attr('id','ghsid'+jQuery.spip.stateId);
426 }
427 var href= blocfrag.attr('data-url') || blocfrag.attr('data-origin');
428 href = jQuery("<"+"a href='"+href+"'></a>").get(0).href;
429 var state={
430 id:blocfrag.attr('id'),
431 href: href
432 };
433 // on remplace la variable qui decrit l'etat courant
434 // initialement vide
435 // -> elle servira a revenir dans l'etat courant
436 window.history.replaceState(state,window.document.title, window.document.location);
437 }
438
439 jQuery.spip.pushHistoryState = function(href, title){
440 if (!window.history.pushState)
441 return false;
442 window.history.pushState({}, title, href);
443 }
444
445 window.onpopstate = function(popState){
446 if (popState.state && popState.state.id){
447 var blocfrag=jQuery('#'+popState.state.id);
448 if (blocfrag.length && popState.state.href) {
449 jQuery.spip.ajaxClick(blocfrag,popState.state.href,{history:false});
450 return true;
451 }
452 }
453 }
454
455 /**
456 * Charger un bloc ajax represente par l'objet jQuery blocajax qui le pointe
457 * avec la requete ajax url, qui represente le lien href
458 * @param object blocfrag
459 * bloc cible
460 * @param string url
461 * url pour la requete ajax
462 * @param string href
463 * url du lien clique
464 * @param object options
465 * bool force : pour forcer la requete sans utiliser le cache
466 * function callback : callback au retour du chargement
467 * bool history : prendre en charge l'histrisation dans l'url
468 */
469 jQuery.spip.loadAjax = function(blocfrag,url, href, options){
470 var force = options.force || false;
471 jQuery(blocfrag).animateLoading();
472 if (jQuery.spip.preloaded_urls[url] && !force) {
473 // si on est deja en train de charger ce fragment, revenir plus tard
474 if (jQuery.spip.preloaded_urls[url]=="<!--loading-->"){
475 setTimeout(function(){jQuery.spip.loadAjax(blocfrag,url,href,options);},100);
476 return;
477 }
478 jQuery.spip.on_ajax_loaded(blocfrag,jQuery.spip.preloaded_urls[url],href,options.history);
479 } else {
480 var d = new Date();
481 jQuery.spip.preloaded_urls[url] = "<!--loading-->";
482 jQuery.ajax({
483 url: parametre_url(url,'var_t',d.getTime()),
484 onAjaxLoad:false,
485 success: function(c){
486 jQuery.spip.on_ajax_loaded(blocfrag,c,href,options.history);
487 jQuery.spip.preloaded_urls[url] = c;
488 if (options.callback && typeof options.callback == "function")
489 options.callback.apply(blocfrag);
490 },
491 error: function(){
492 jQuery.spip.preloaded_urls[url]='';
493 }
494 });
495 }
496 }
497
498 /**
499 * Calculer l'url ajax a partir de l'url du lien
500 * et de la variable d'environnement du bloc ajax
501 * passe aussi l'ancre eventuelle sous forme d'une variable
502 * pour que le serveur puisse la prendre en compte
503 * et la propager jusqu'a la reponse
504 * sous la forme d'un lien cache
505 *
506 * @param string href
507 * @param string ajax_env
508 */
509 jQuery.spip.makeAjaxUrl = function(href,ajax_env){
510 var url = href.split('#');
511 url[0] = parametre_url(url[0],'var_ajax',1);
512 url[0] = parametre_url(url[0],'var_ajax_env',ajax_env);
513 if (url[1])
514 url[0] = parametre_url(url[0],'var_ajax_ancre',url[1]);
515 return url[0];
516 }
517
518 /**
519 * fonction appelee sur l'evenement ajaxReload d'un bloc ajax
520 * que l'on declenche quand on veut forcer sa mise a jour
521 *
522 * @param object blocfrag
523 * @param object options
524 * callback : fonction appelee apres le rechargement
525 * args : arguments passes a l'url rechargee (permet une modif du contexte)
526 * history : bool to specify if navigation history is modified by reload or not (false if not provided)
527 */
528 jQuery.spip.ajaxReload = function(blocfrag, options){
529 var ajax_env = blocfrag.attr('data-ajax-env');
530 if (!ajax_env || ajax_env==undefined) return;
531 var href = blocfrag.attr('data-url') || blocfrag.attr('data-origin');
532 if (href && typeof href != undefined){
533 options == options || {};
534 var callback=options.callback || null;
535 var history=options.history || false;
536 var args = options.args || {};
537 for (var key in args)
538 href = parametre_url(href,key,args[key]==undefined?'':args[key],'&',args[key]==undefined?false:true);
539 var url = jQuery.spip.makeAjaxUrl(href,ajax_env);
540 // recharger sans historisation dans l'url
541 jQuery.spip.loadAjax(blocfrag, url, href, {force:true, callback:callback, history:history});
542 return true;
543 }
544 }
545
546 /**
547 * fonction appelee sur l'evenement click d'un lien ajax
548 *
549 * @param object blocfrag
550 * objet jQuery qui cible le bloc ajax contenant
551 * @param string href
552 * url du lien a suivre
553 * @param object options
554 * force : pour interdire l'utilisation du cache
555 * history : pour interdire la mise en historique
556 */
557 jQuery.spip.ajaxClick = function(blocfrag, href, options){
558 var ajax_env = blocfrag.attr('data-ajax-env');
559 if (!ajax_env || ajax_env==undefined) return;
560 if (!ajax_confirm) {
561 // on rearme pour le prochain clic
562 ajax_confirm=true;
563 var d = new Date();
564 // seule une annulation par confirm() dans les 2 secondes precedentes est prise en compte
565 if ((d.getTime()-ajax_confirm_date)<=2)
566 return false;
567 }
568 var url = jQuery.spip.makeAjaxUrl(href,ajax_env);
569 jQuery.spip.loadAjax(blocfrag, url, href, options);
570 return false;
571 }
572
573 /**
574 * Implementer le comportemant des liens ajax
575 * et boutons post ajax qui se comportent
576 * comme un lien ajax
577 */
578 jQuery.fn.ajaxbloc = function() {
579 // hack accessibilite vieille version de JAWS
580 // a supprimer ?
581 if (this.length)
582 jQuery.spip.initReaderBuffer();
583 if (ajaxbloc_selecteur==undefined)
584 ajaxbloc_selecteur = '.pagination a,a.ajax';
585
586 return this.each(function() {
587 // traiter les enfants d'abord :
588 // un lien ajax provoque le rechargement
589 // du plus petit bloc ajax le contenant
590 jQuery('div.ajaxbloc',this).ajaxbloc();
591 var blocfrag = jQuery(this);
592
593 var ajax_env = blocfrag.attr('data-ajax-env');
594 if (!ajax_env || ajax_env==undefined) return;
595
596 blocfrag.not('.bind-ajaxReload').bind('ajaxReload',function(event, options){
597 if (jQuery.spip.ajaxReload(blocfrag,options))
598 // don't trig reload of parent blocks
599 event.stopPropagation();
600 }).addClass('bind-ajaxReload');
601
602 jQuery(ajaxbloc_selecteur,this).not('.noajax,.bind-ajax')
603 .click(function(){return jQuery.spip.ajaxClick(blocfrag,this.href,{force:jQuery(this).is('.nocache'),history:!(jQuery(this).is('.nohistory')||jQuery(this).closest('.box_modalbox').length)});})
604 .addClass('bind-ajax')
605 .filter('.preload').each(function(){
606 var href = this.href;
607 var url = jQuery.spip.makeAjaxUrl(href,ajax_env);
608 if (!jQuery.spip.preloaded_urls[url]) {
609 jQuery.spip.preloaded_urls[url] = '<!--loading-->';
610 jQuery.ajax({url:url,onAjaxLoad:false,success:function(r){jQuery.spip.preloaded_urls[url]=r;},error:function(){jQuery.spip.preloaded_urls[url]='';}});
611 }
612 }); // previent qu'on ajax pas deux fois le meme lien
613
614 // ajaxer les boutons actions qui sont techniquement des form minimaux
615 // mais se comportent comme des liens
616 jQuery('form.bouton_action_post.ajax', this).not('.noajax,.bind-ajax').each(function(){
617 var leform = this;
618 var url = jQuery(this).attr('action').split('#');
619 jQuery(this)
620 .prepend("<input type='hidden' name='var_ajax' value='1' /><input type='hidden' name='var_ajax_env' value='"+(ajax_env)+"' />"+(url[1]?"<input type='hidden' name='var_ajax_ancre' value='"+url[1]+"' />":""))
621 .ajaxForm({
622 beforeSubmit: function(){
623 jQuery(blocfrag).animateLoading().positionner(false);
624 },
625 onAjaxLoad:false,
626 success: function(c){
627 jQuery.spip.on_ajax_loaded(blocfrag,c);
628 jQuery.spip.preloaded_urls = {}; // on vide le cache des urls car on a fait une action en bdd
629 },
630 iframe: jQuery.browser.msie
631 })
632 .addClass('bind-ajax') // previent qu'on n'ajaxera pas deux fois le meme formulaire en cas de ajaxload
633 ;
634 });
635 });
636 };
637
638 /**
639 * Suivre un lien en simulant le click sur le lien
640 * Si le lien est ajax, on se contente de declencher l'evenement click()
641 * Si le lien est non ajax, on finit en remplacant l'url de la page
642 */
643 jQuery.fn.followLink = function(){
644 $(this).click();
645 if (!$(this).is('.bind-ajax'))
646 window.location.href = $(this).get(0).href;
647 return this;
648 }
649 /**
650 * Recharger un bloc ajax pour le mettre a jour
651 * ajaxid est l'id passe en argument de INCLURE{ajax=ajaxid}
652 * options permet de definir une callbackk ou de passer des arguments a l'url
653 * au rechargement
654 * ajaxReload peut s'utiliser en passant un id :
655 * ajaxReload('xx');
656 * ou sur un objet jQuery
657 * jQuery(this).ajaxReload();
658 * Dans ce dernier cas, le plus petit conteneur ajax est recharge
659 *
660 * @param string ajaxid
661 * @param object options
662 * callback : callback after reloading
663 * args : {arg:value,...} to pass tu the url
664 * history : bool to specify if navigation history is modified by reload or not (false if not provided)
665 */
666 function ajaxReload(ajaxid, options){
667 jQuery('div.ajaxbloc.ajax-id-'+ajaxid).ajaxReload(options);
668 }
669
670 /**
671 * Variante jQuery de ajaxReload pour la syntaxe
672 * jQuery(..).ajaxReload();
673 * cf doc ci-dessus
674 * @param options
675 */
676 jQuery.fn.ajaxReload = function(options){
677 options = options||{};
678 // just trigg the event, as it will bubble up the DOM
679 jQuery(this).trigger('ajaxReload', [options]);
680 return this; // don't break the chain
681 }
682
683 /**
684 * animation du bloc cible pour faire patienter
685 *
686 */
687 jQuery.fn.animateLoading = function() {
688 this.attr('aria-busy','true').addClass('loading').children().css('opacity', 0.5);
689 if (typeof ajax_image_searching != 'undefined'){
690 var i = (this).find('.image_loading');
691 if (i.length) i.eq(0).html(ajax_image_searching);
692 else this.prepend('<span class="image_loading">'+ajax_image_searching+'</span>');
693 }
694 return this; // don't break the chain
695 }
696 // compatibilite avec ancien nommage
697 jQuery.fn.animeajax = jQuery.fn.animateLoading;
698
699 /**
700 * Fin de l'animation
701 * l'argument permet de forcer le raz du contenu si il est inchange
702 * @param hard
703 */
704 jQuery.fn.endLoading = function(hard) {
705 hard = hard || false;
706 this.attr('aria-busy','false').removeClass('loading');
707 if (hard){
708 this.children().css('opacity', '');
709 this.find('.image_loading').html('');
710 }
711 return this; // don't break the chain
712 }
713
714 /**
715 * animation d'un item que l'on supprime :
716 * ajout de la classe remove avec un background tire de cette classe
717 * puis fading vers opacity 0
718 * quand l'element est masque, on retire les classes et css inline
719 *
720 * @param function callback
721 *
722 */
723 jQuery.fn.animateRemove = function(callback){
724 if (this.length){
725 var color = $("<div class='remove'></div>").css('background-color');
726 $(this).addClass('remove').css({backgroundColor: color}).animate({opacity: "0.0"}, 'fast',function(){
727 $(this).removeClass('remove').css({backgroundColor: ''});
728 if (callback)
729 callback.apply(this);
730 });
731 }
732 return this; // don't break the chain
733 }
734
735 /**
736 * animation d'un item que l'on ajoute :
737 * ajout de la classe append
738 * fading vers opacity 1 avec background herite de la classe append,
739 * puis suppression progressive du background pour revenir a la valeur heritee
740 *
741 * @param function callback
742 */
743 jQuery.fn.animateAppend = function(callback){
744 if (this.length){
745 var me=this;
746 // recuperer la couleur portee par la classe append (permet une personalisation)
747 var color = $("<div class='append'></div>").css('background-color');
748 var origin = $(this).css('background-color') || '#ffffff';
749 // pis aller
750 if (origin=='transparent') origin='#ffffff';
751 var sel=$(this);
752 // if target is a tr, include td childrens cause background color on tr doesn't works in a lot of browsers
753 if (sel.is('tr'))
754 sel.add('>td',sel);
755 sel.css('opacity','0.0').addClass('append').css({backgroundColor: color}).animate({opacity: "1.0"}, 1000,function(){
756 sel.animate({backgroundColor: origin}, 3000,function(){
757 sel.removeClass('append').css({backgroundColor: ''});
758 if (callback)
759 callback.apply(me);
760 });
761 });
762 }
763 return this; // don't break the chain
764 }
765
766 /**
767 * Equivalent js de parametre_url php de spip
768 *
769 * Exemples :
770 * parametre_url(url,suite,18) (ajout)
771 * parametre_url(url,suite,'') (supprime)
772 * parametre_url(url,suite) (lit la valeur suite)
773 * parametre_url(url,suite[],1) (tableau valeurs multiples)
774 * @param url
775 * url
776 * @param c
777 * champ
778 * @param v
779 * valeur
780 * @param sep
781 * separateur '&' par defaut
782 * @param force_vide
783 * si true et v='' insere &k= dans l'url au lieu de supprimer le k (false par defaut)
784 * permet de vider une valeur dans une requete ajax (dans un reload)
785 */
786 function parametre_url(url,c,v,sep,force_vide){
787 // Si l'URL n'est pas une chaine, on ne peut pas travailler dessus et on quitte
788 if (typeof(url) == 'undefined'){
789 url = '';
790 }
791
792 var p;
793 // lever l'#ancre
794 var ancre='';
795 var a='./';
796 var args=[];
797 p = url.indexOf('#');
798 if (p!=-1) {
799 ancre=url.substring(p);
800 url = url.substring(0,p);
801 }
802
803 // eclater
804 p=url.indexOf('?');
805 if (p!==-1){
806 // recuperer la base
807 if (p>0) a=url.substring(0,p);
808 args = url.substring(p+1).split('&');
809 }
810 else
811 a=url;
812 var regexp = new RegExp('^(' + c.replace('[]','\[\]') + '\[?\]?)(=.*)?$');
813 var ajouts = [];
814 var u = (typeof(v)!=='object')?encodeURIComponent(v):v;
815 var na = [];
816 // lire les variables et agir
817 for(var n=0;n<args.length;n++){
818 var val = args[n];
819 try {
820 val = decodeURIComponent(val);
821 } catch(e) {}
822 var r=val.match(regexp);
823 if (r && r.length){
824 if (v==null){
825 return (r.length>2)?r[2].substring(1):'';
826 }
827 // suppression
828 else if (!v.length) {
829 }
830 // Ajout. Pour une variable, remplacer au meme endroit,
831 // pour un tableau ce sera fait dans la prochaine boucle
832 else if (r[1].substring(-2) != '[]') {
833 na.push(r[1]+'='+u);
834 ajouts.push(r[1]);
835 }
836 else na.push(args[n]);
837 }
838 else
839 na.push(args[n]);
840 }
841
842 if (v==null) return v; // rien de trouve
843 // traiter les parametres pas encore trouves
844 if (v || v.length || force_vide) {
845 ajouts = "="+ajouts.join("=")+"=";
846 var all=c.split('|');
847 for (n=0;n<all.length;n++){
848 if (ajouts.search("="+all[n]+"=")==-1){
849 if (typeof(v)!=='object'){
850 na.push(all[n] +'='+ u);
851 }
852 else {
853 var id = ((all[n].substring(-2)=='[]')?all[n]:all[n]+"[]");
854 for(p=0;p<v.length;p++)
855 na.push(id +'='+ encodeURIComponent(v[p]));
856 }
857 }
858 }
859 }
860
861 // recomposer l'adresse
862 if (na.length){
863 if (!sep) sep='&';
864 a = a+"?"+na.join(sep);
865 }
866
867 return a + ancre;
868 }
869
870
871
872 // Ajaxer les formulaires qui le demandent, au demarrage
873 if (!window.var_zajax_content)
874 window.var_zajax_content = 'contenu';
875 jQuery(function() {
876 jQuery('form:not(.bouton_action_post)').parents('div.ajax')
877 .formulaire_dyn_ajax();
878 jQuery('div.ajaxbloc').ajaxbloc();
879 jQuery("input[placeholder]:text").placeholderLabel();
880 jQuery('a.popin').click(function(){if (jQuery.modalbox) jQuery.modalbox(parametre_url(this.href,"var_zajax",jQuery(this).attr('data-var_zajax')?jQuery(this).attr('data-var_zajax'):var_zajax_content));return false;});
881 });
882
883 // ... et a chaque fois que le DOM change
884 onAjaxLoad(function() {
885 if (jQuery){
886 jQuery('form:not(.bouton_action_post)', this).parents('div.ajax')
887 .formulaire_dyn_ajax();
888 if (jQuery(this).is('div.ajaxbloc'))
889 jQuery(this).ajaxbloc();
890 else if (jQuery(this).closest('div.ajaxbloc').length)
891 jQuery(this).closest('div.ajaxbloc').ajaxbloc();
892 else
893 jQuery('div.ajaxbloc', this).ajaxbloc();
894 jQuery("input[placeholder]:text",this).placeholderLabel();
895 jQuery('a.popin',this).click(function(){if (jQuery.modalbox) jQuery.modalbox(parametre_url(this.href,"var_zajax",jQuery(this).attr('data-var_zajax')?jQuery(this).attr('data-var_zajax'):var_zajax_content));return false;});
896 }
897 });
898