TZR.linkAlert=function(url){
  var reg=/&(_bdx|_raw|_ajax|_)=[^&]+/g;
  alert(url.replace(reg,""));
}
TZR.applyFunction=function(form,data,selectonly,conf,popup){
  if(typeof(form)=="string") form=document.forms[form];
  if(selectonly){
    if(!TZR.checkBoxesIsChecked(form)){
      alert(TZR._noobjectselected);
      return;
    }
  }
  if(conf){
    if(!confirm(conf)) return false;
  }
  if(data){
    for(var attr in data){
      if(form[attr]) form[attr].value=data[attr];
      else jQuery(form).append('<input type="hidden" name="'+attr+'" value="'+data[attr]+'">');
    }
  }
  if(popup){
    window.open('','tzrpopup','width=650,height=550,scrollbars=yes,location=no,resizable=yes');
    form.target='tzrpopup';
    form.method='post';
    return form.submit();
  }else{
    return TZR.ajaxSubmitForm(form);
  }
}

/// Fonctions de gestion des evenements sur un container
TZR.Event=new Object();
TZR.Event.events=new Object();
// Ajoute un listener (id:uniqid, t:type de l'evenement, f:fonction, p:parametres
TZR.Event.add=function(id,t,f,p){
  if(!TZR.Event.events[t]){
    TZR.Event.events[t]={};
    jQuery(document).bind(t,TZR.Event.execute);
  }
  if(!TZR.Event.events[t][id]) TZR.Event.events[t][id]=[];
  TZR.Event.events[t][id].push({f:f,p:p});
}
TZR.Event.execute=function(e){
  var ret=true;
  for(id in TZR.Event.events[e.type]){
    var evs=TZR.Event.events[e.type][id];
    if(document.getElementById('cv8-uniqdiv-'+id)){
      for(j in evs){
	if(evs[j].f(e,id,evs[j].p)===false){
	  ret=false;
	  break;
	}
      }
    }else{
      delete TZR.Event.events[e.type][id];
    }
  }
  return ret;
}
// Fonctions de nettoyage des objets
TZR.initObjCleaner=function(){
  if(!TZR.objCleaner) TZR.objCleaner=setInterval(function(){TZR.checkObjCleaner();},30000);
}
TZR.stopObjCleaner=function(){
  if(TZR.objCleaner) clearInterval(TZR.objCleaner);
}
TZR.addToObjCleaner=function(id,jso,f){
  if(!TZR.objToClean) TZR.objToClean=new Object();
  if(!f) f=TZR.cleanObj;
  TZR.objToClean[id]={o:jso,f:f};
}
TZR.checkObjCleaner=function(){
  for(var i in TZR.objToClean){
    if(!document.getElementById(i)){
      TZR.objToClean[i].f(TZR.objToClean[i].o);
      delete TZR.objToClean[i];
    }
  }
}
TZR.cleanObj=function(o){
  if(!delete o) o=undefined;
}
// Change le titre de la fenetre courante
TZR.setDocumentTitle=function(title,noprefix){
  if(!TZR.title) TZR.title=document.title;
  if(noprefix) document.title=title;
  else document.title=TZR.title+" : "+title;
  jQuery('#cv8-pagetitle').html(TZR.maintitle);
}

// Redimensionne l'interface (width : taille de la zone centrale ou toggle pour switcher entre plein ecran/taille d'origine
TZR.resizeTo=function(width){
  if(!width) return;
  var jc=jQuery('#cv8-content');
  var jc2=jQuery('#cv8-container');
  if(width=='toggle'){
    var toadd=jQuery(window).width()-jc2.width();
    toadd-=5;
    if(toadd!=0){
      var w1=jc.width()+toadd;
      var w2=jc2.width()+toadd;
    }
    if(toadd==0 || w1<750){
      var w1='';
      var w2='';
    }
  }else{
    var w1=width;
    var w2=jc2.width()+width-jc.width();
    var sw=screen.availWidth;
    if(w1+jc.offset().left>sw){
      TZR.resizeTo('toggle');
      return;
    }
  }
  jc.width(w1);
  jc2.width(w2);
  jQuery('div.cv8-contenu-haut,#cv8-top').width('100%');
  return w1;
}

// Fonction pour appliquer l'alernance de couleur et le hover sur les tables .cv8_tablelist
TZR.applyAlternate=function(what,table){
  if(table==undefined){
    if(what==undefined) var what=document;
    var jts=jQuery('table.cv8_tablelist',what);
  }else{
    jts=jQuery(table);
  }
  jts.each(function(){
    if(!jQuery(this).hasClass('nohover')) jQuery('tbody:first>tr:visible',this).alternate({odd:'odd', even:'even', hover:'hover'});
    else jQuery('tbody:first>tr:visible',this).alternate({odd:'odd', even:'even'});
  });
}

// Ajoute un item à un menu
TZR.addMenuItem=function(mid,group,text,url,conf,newgroup,separator){
  var li='<li';
  var _class="";
  if(separator) _class+=' jd_separator';
  if(_class!="") li+=' class="'+_class.substr(1)+'"';
  li+='>';
  if(url==undefined) li+=text;
  else if(url=='#') li+='<a href="'+url+'" onclick="return false;">'+text;
  else if(url.substr(0,11)=='javascript:') li+='<a class="accessible" href="#" onclick="'+(conf?'if(!confirm(\''+conf.replace(/\'/,'\\\'').replace(/\"/g,'&quot;')+'\')) return false;':'')+url.replace("javascript:","").replace(/\"/g,'&quot;')+'return false;">'+text;
  else li+='<a class="cv8-ajaxlink accessible" href="'+url+'"'+(conf?' x-confirm="var ret=confirm(\''+conf.replace(/\'/,'\\\'').replace(/\"/g,'&quot;')+'\')"':'')+'>'+text;
  li+='</a>';
  if(newgroup) li+='<ul id="'+mid+'-'+newgroup+'"></ul>';
  li+='</li>';
  jQuery('#'+mid+'-'+group).append(li);
}

// Ajoute un item à une toolbar
TZR.addToolBarItem=function(tid,group,order,picto,url,text,target){
  if(document.getElementById(tid+'-'+group)==undefined){
    jQuery('#'+tid).append('<ul id="'+tid+'-'+group+'"><li class="separe"></li></ul>');
  }else{
    jQuery('#'+tid+'-'+group).show();
  }
  var li='<li class="icon" morder="'+order+'">';
  if(!url) li+=picto;
  else if(url.substr(0,11)=='javascript:') li+='<a href="#" onclick="'+url.replace("javascript:","").replace('"','&quot;','g')+'return false;"><img height="18" width="14" alt="'+text+'" src="'+picto+'"/></a>';
  else li+='<a class="cv8-ajaxlink" href="'+url+'"><img height="18" width="14" alt="'+text+'" src="'+picto+'"/></a>';
  li+='</li>';

  var added=false;
  var jul=jQuery('#'+tid+'-'+group);
  jul.find('li').each(function(){
    if(parseInt(jQuery(this).attr('morder'))>order){
      jQuery(this).before(li);
      added=true;
      return false;
    }
  });
  if(!added) jul.append(li);
}

// Met à jour le texte d'information
TZR.setInfoText=function(text){
  if(text!==undefined && text!==null) jQuery('#cv8-infotext>div.cv8-infotextg>div.cv8-txtseul').html(text+'&nbsp;');
}
// Recupère le texte d'information
TZR.getInfoText=function(){
  return jQuery('#cv8-infotext>div.cv8-infotextg>div.cv8-txtseul').html();
}
// Efface le chemin actuel
TZR.clearNav=function(){
  jQuery('#cv8-path>ul>li:gt(0)').remove();
}
// Ajoute une entrée au chemin
TZR.addNav=function(title,url){
  jQuery('#cv8-path>ul').append('<li><a class="cv8-ajaxlink" href="'+url+'">'+title+'</a></li>');
}
// Affiche une fenetre modale permettant de s'authentifier
TZR.authAlert=function(cb){
  var alertArgs=arguments;
  jQuery("#cv8-unauth").dialog({modal:true,resizable:false,draggable:false,width:450,height:110,close:function(event,ui){
    document.auth.login.value="";
    document.auth.password.value="";
    if(jQuery("#cv8-unauth").data('callcb') && cb){
      var args=new Array();
      for(var i=1;i<alertArgs.length;i++){
        args.push(alertArgs[i]);
      }
      cb.apply(TZR,args);
    }
    jQuery("#cv8-unauth").data('callcb',false);
  }});
}
TZR.submitLogin=function(form){
  jQuery.post(form.action,jQuery(form).serializeArray(),function(data,status){
    if(data=='ok'){
      jQuery("#cv8-unauth-error").css('visibility','hidden');
      jQuery("#cv8-unauth").data('callcb',true).dialog('close');
    }else{
      jQuery("#cv8-unauth-error").css('visibility','visible');
    }
  });
}
TZR.cancelLogin=function(form){
  jQuery("#cv8-unauth").dialog('close');
}

// Fonction de chargement via jQuery.load avec callback de gestion de l'authentification,overlay automatique
// Parametres : url, target (cible du chargement et de l'overlay), cb (callback)
//              noautocreate (par defaut, la fonction creee les div module-container si la cible est #cv8-content)
//              nocheckauth (desactive la verification de l'authentification), mode (mode de chargement : load, post)
//              noautoscroll (desactive le scroll automatique), nocache (desactivation du cache navigateur, true par defaut)
TZR.jQueryAjax=function(obj){
  if(!TZR.ajaxQueue) TZR.ajaxQueue=0;
  TZR.ajaxQueue++;
  var url=obj.url;
  var data=obj.data;
  var cb=obj.cb;
  var mode=obj.mode;
  var nocheckauth=obj.nocheckauth;
  var noautocreate=obj.noautocreate;
  var noautoscroll=obj.noautoscroll;
  var nocache=obj.nocache;
  var statetarget=obj.statetarget;
  var nowaitcursor=obj.nowaitcursor;
  if(nocache==undefined) nocache=true;
  if(!obj.target) obj.target='#cv8-content';
  var jt=jQuery(obj.target);
  if(obj.overlay) var jo=jQuery(obj.overlay);
  else var jo=jt;
  if(!nowaitcursor) jQuery('body,a').css('cursor','progress');
  // Ajoute un overlay le temps du chargement
  if(jt.attr('id')=='cv8-content'){
    if(mode=="load" && !noautocreate){
      jt.html('<div class="cv8-module" id="cv8-module-0"><div class="cv8-module-bg"><div class="cv8-module-container" id="cv8-module-container-0"></div></div></div>');
      var jt=jQuery('#cv8-module-container-0');
    }
    var overlay=TZR.setOverlay(jo);
  }else{
    var overlay=TZR.setOverlay(jo);
  }
  // Overlay de confirmation sur un objet du DOM
  if(statetarget){
    var stateoverlay=TZR.setOverlay(statetarget,{content:'<img src="/tzr/templates/ico/jtree/spinner.gif">',oclass:'overlay-confirm',css:{opacity:0.8}});
  }
  // Scroll le contenu si necessaire
  var pos=jt.position().top;
  if(jQuery(document).scrollTop()>pos) jQuery(document).scrollTop(pos);
  // Activation/desactivation du cache
  var actcachesetting=jQuery.ajaxSettings.cache;
  if(nocache) jQuery.ajaxSettings.cache=false;
  else jQuery.ajaxSettings.cache=true;
  // Complete l'url
  if(url.indexOf(' ')!=-1){
    var url2=url.substr(url.indexOf(' '));
    url=url.substr(0,url.indexOf(' '));
  }else{
    var url2='';
  }
  if(url==url.replace('_raw=','')) url+='&_raw=1';
  if(url==url.replace('_ajax=','')) url+='&_ajax=1';
  url=url+url2;
  if(typeof(data)=='function'){
    cb=data;
    data=undefined;
  }
  // Construit la callback (desactivation overlay + callback personnalisable)
  var callback=function(responseText,textStatus,XMLHttpRequest){
    TZR.ajaxQueue--;
    TZR.unsetOverlay(overlay);
    if(!nowaitcursor) jQuery('body,a').css('cursor','');
    if(!nocheckauth){
      if(XMLHttpRequest.status==401){
	TZR.authAlert(TZR.jQueryAjax,obj);
	return false;
      }
    }
    // Overlay de confirmation sur un objet du DOM
    if(statetarget){
      TZR.unsetOverlay(stateoverlay);
      stateoverlay=TZR.setOverlay(statetarget,{content:(textStatus=='success'?'OK':'ERROR'),
						 oclass:(textStatus=='success'?'overlay-confirm':'overlay-error'),css:{opacity:0.8}});
      setTimeout(function(){stateoverlay.fadeOut(800,function(){TZR.unsetOverlay(stateoverlay);})},500);;
    }
    if(cb) return cb(responseText,textStatus,XMLHttpRequest);
  };
  // Appel ajax
  if(mode=="load") jt.load(url,data,callback);
  if(mode=="post") jQuery.post(url,data,callback);
  jQuery.ajaxSettings.cache=actcachesetting;
  return overlay;
}
TZR.jQueryLoad=function(obj){
  obj.mode="load";
  TZR.jQueryAjax(obj);
}
TZR.jQueryPost=function(obj){
  obj.mode="post";
  TZR.jQueryAjax(obj);
}
// Soumet un formulaire via ajax (div : element cible pour l'overlay / loadresult : charge le resultat dans div)
TZR.ajaxSubmitForm=function(form,div,loadresult,cplt,confirmmessage){
  if(TZR.ajaxSubmitFormOngoing==form) return true;
  if(confirmmessage && !confirm(confirmmessage)) return false;
  TZR.ajaxSubmitFormOngoing=form;
  if(form.enctype=="multipart/form-data" || form.ENCTYPE=="multipart/form-data"){
    var ret=TZR.iframeSubmitForm(form,div,loadresult,cplt);
    if(ret) jQuery(form).submit();
    TZR.ajaxSubmitFormOngoing='';
    return false;
  }
  if(loadresult==undefined) loadresult=true;
  if(!TZR.isFormValidWithFocus(form,true)){
    TZR.ajaxSubmitFormOngoing='';
    return false;
  }
  if(div==undefined) div=jQuery(form).parents('div.cv8-module-container')[0];
  var param={target:div,url:form.action,data:jQuery(form).serializeArray()};
  if(cplt!=undefined) jQuery.extend(param,cplt);
  if(loadresult) TZR.jQueryLoad(param);
  else TZR.jQueryPost(param);
  TZR.ajaxSubmitFormOngoing='';
  return false;
}
// Soumet un formulaire via iframe (div : element cible pour l'overlay / loadresult : charge le resultat dans div)
TZR.iframeSubmitForm=function(form,div,loadresult,cplt){
  if(loadresult==undefined) loadresult=true;
  if(div==undefined) div=jQuery(form).parents('div.cv8-module-container')[0];
  if(cplt==undefined) cplt={};
  var jdiv=jQuery(div);
  var nowaitcursor=cplt.nowaitcursor;
  var overlay='';
  return TZR.iframeSubmitFormKernel.submit(form,{onStart:function(){
    var ret=TZR.isFormValidWithFocus(form,true);
    if(!ret) return false;
    if(!nowaitcursor) jQuery('body,a').css('cursor','progress');
    overlay=TZR.setOverlay(jdiv);
    return true;
  },onComplete:function(html){
    if(!nowaitcursor) jQuery('body,a').css('cursor','');
    if(loadresult){
      if(html=="401 Unauthorized"){
	TZR.unsetOverlay(overlay);
	cplt.force=true;
	TZR.authAlert(TZR.iframeSubmitForm,form,div,loadresult,cplt);
      }else{
	jdiv.html(html);
	TZR.unsetOverlay(overlay);
	// Scroll le contenu si necessaire
	var pos=jdiv.position().top;
	if(jQuery(document).scrollTop()>pos) jQuery(document).scrollTop(pos);
      }
    }else{
      TZR.unsetOverlay(overlay);
    }
    if(cplt){
      if(cplt.cb) cplt.cb(html);
    }
  },force:cplt.force});
}
// Ajout/suppression d'un overlay sur une div
TZR.setOverlay=function(o,opts){
  if(!opts) opts=new Object();
  if(!opts.css) opts.css=new Object();
  if(!opts.content) opts.content='<img src="/tzr/templates/ico/general/indicator-big.gif">';
  if(!opts.oclass) opts.oclass='overlay';
  // Génération du HTML de l'overlay
  var jo=jQuery(o);
  if(jo.length==0) return;
  offset=jo.offset();
  var overlay=jQuery('<div class="'+opts.oclass+'"><div class="overlay-bg"></div><span class="cv8_inlineblock"></span><span class="overlay-content" style="position:relative;">&nbsp;'+opts.content+'&nbsp;</span><span class="cv8_inlineblock"></span></div>');
  // CSS de l'overlay
  var w=jo.outerWidth();
  var h=jo.outerHeight();
  var css=jQuery.extend({position:'absolute',top:offset.top,left:offset.left,opacity:0.3,width:w,'z-index':999},opts.css);
  // CSS du fond
  var css2={opacity:css.opacity,width:'100%',height:'100%',position:'absolute',top:0,left:0};
  delete css.opacity;
  // Applique les css
  overlay.css(css);
  jQuery('div:first',overlay).css(css2);
  // Aoute l'overlay et verifie la hauteur
  jQuery('body').append(overlay);
  var ch=overlay.height();
  if(h>ch){
    overlay.css({height:h,'line-height':h+'px'});
    jQuery('span.cv8_inlineblock',overlay).css('line-height',h+'px');
  }
  // Timer pour replacement automatique
  overlay.data('_timer',setInterval(function(){
    var offset=jo.offset();
    var h=jo.outerHeight();
    var css3={top:offset.top,left:offset.left,width:jo.outerWidth()};
    if(h>ch){
      css3.height=h;
      css3['line-height']=h+'px';
    }
    overlay.css(css3);
  },100));
  // Timer pour eviter les deconnexion
  if(TZR._sessid){
    overlay.data('_timersess',setInterval(function(){
      TZR.uploadifyKeepAlive(TZR._sharescripts+'keepalive.php');
    },300000));
  }
  return overlay;
}
TZR.unsetOverlay=function(o){
  var jo=jQuery(o);
  if(jo.length==0) return;
  clearInterval(jo.data('_timer'));
  if(TZR._sessid) clearInterval(jo.data('_timersess'));
  jo.remove();
}
// Ajoute une entrée dans l'historique navigateur
TZR.addNavHistory=function(title,nowaitajax){
  // Attend la fin du traitement de la pile ajax
  if(!nowaitajax && TZR.ajaxQueue){
    setTimeout(function(){TZR.addNavHistory(title,nowaitajax);},200);
    return false;
  }
  var jh=jQuery('#cv8-history-list');
  // Prepare la liste des historique à effacer
  var htodel=new Array();
  if(TZR.historymode=='loadnav'){
    jh.find('li').each(function(i){
      if(this.id=="_"+location.hash.substring(1)) return false;
      jQuery(this).remove();
      htodel.push(this.id.substring(1));
    });
    TZR.historymode='normal';
  }
  jh.find('li').each(function(i){
    if(i>TZR.historysize-2){
      jQuery(this).remove();
      htodel.push(this.id.substring(1));
    }
  });
  // Prepare les parametres à enregistrer
  var hid='history-'+Math.floor(Math.random()*9999999);
  var container=new Array();
  jQuery('div.cv8-module-container').each(function(){
    if(typeof(this._here)=='string') container.push(this._here);
  });
  if(TZR.maintitle && TZR.maintitle!=title && title.indexOf(TZR.maintitle+" > ")!=0) title=TZR.maintitle+" > "+title;
  jQuery.post(TZR._sharescripts+'addHistory.php',{hid:hid,maintitle:TZR.maintitle,title:title,url:TZR.mainurl,comment:TZR.getInfoText(),'container':container,'todel':htodel});
  TZR.lasthid=hid;
  TZR.setDocumentTitle(title);
  jQuery(window).history('add',hid);
  jh.find('li.active').removeClass('active');
  if(title.length>35) var stitle=title.substr(0,32)+"...";
  else stitle=title;
  TZR.applyHottip(jQuery('<li class="active" id="_'+hid+'"><a href="#" onclick="TZR.loadNavHistory(\''+hid+'\');return false;">'+stitle+'</a></li>').prependTo(jh).attr('bt-xTitle',title.replace(new RegExp('>','g'), '<br>&nbsp;&nbsp;>') ));
}

// Charge une page de l'historique navigateur
TZR.loadNavHistory=function(hid,nav){
  if(nav){
    var jh=jQuery('#cv8-history-list');
    jh.find('li.active').removeClass('active');
    jQuery('#_'+hid).addClass('active');
    TZR.historymode='loadnav';
  }
  TZR.jQueryLoad({noautocreate:true,url:TZR._self+"class=XSession&function=goHistory&template=generic8-historycontent.html&skip=1&hid="+hid,cb:function(){
   if(nav) TZR.historymode='normal';
  }});
}

// Enregistre un cookie
TZR.setCookie=function(name,value,expire,path,domain,secure) {
  document.cookie=name+"="+escape(value)+((expire)?"; expires="+expire.toGMTString():"")+((path)?"; path="+path:"")+((domain)?"; domain="+domain:"")+((secure)?"; secure":"");
}
// Recupere un cookie
TZR.getCookie=function(name,isfloat,isbool){
  var deb=document.cookie.indexOf(name+"=")
  if(deb>=0) {
    deb+=name.length+1;
    var fin=document.cookie.indexOf(";",deb);
    if(fin<0) fin=document.cookie.length;
    var val=unescape(document.cookie.substring(deb,fin));
    if(isbool){
      if(!val || val=="false" || val=="0") return false;
      else return true;
    }
    if(isfloat) return parseFloat(val);
    return val;
  }
  return "";
}

// Accordeon sur des fieldset (obj=>noeud contenant les fieldset à traiter, open=index à ouvrir (0 par defaut, 'all' pour tout ouvrir))
TZR.fieldsetAccordion=function(obj,open){
  if(!open) open=0
  jQuery(obj).find('fieldset').addClass('fieldsetAccordion').each(function(i){
    var jt=jQuery(this);
    jQuery('>legend',jt).click(function(){
      jQuery(this).parents('fieldset:first').toggleClass('fieldsetAccordionClose fieldsetAccordionOpen');
      jQuery('>div,>table',this.parentNode).slideToggle(200);
    }).css('cursor','pointer');
    if(((open!='all' && i!=open) || jt.hasClass('fieldsetAccordionClose')) && !jt.hasClass('fieldsetAccordionOpen')){
      jt.addClass('fieldsetAccordionClose');
      jQuery('>div,>table',jt).hide();
    }else{
      jt.addClass('fieldsetAccordionOpen');
    }
  });
}


/* Mediatheque */
// Inverse la selection d'une fiche via un des elements du DOM
TZR.selectMedia=function(obj){
  li=jQuery(obj).parents('.cv8_inlineblock')[0];
  var cb=jQuery(':checkbox',li)[0];
  cb.checked=!cb.checked;
}
// Inverse la selection des fiches d'une ligne via un des elements du DOM
TZR.selectMediaLine=function(obj){
  jli=jQuery(obj).parents('li.cv8_inlineblock');
  var cb=jQuery(':checkbox',jli)[0];
  cb.checked=!cb.checked;
  var y=jli.offset().top;
  jli.prevAll().each(function(){
    var _y=jQuery(this).offset().top;
    if(y!=_y) return false;
    jQuery(':checkbox',this)[0].checked=cb.checked;
  });
  jli.nextAll().each(function(){
    var _y=jQuery(this).offset().top;
    if(y!=_y) return false;
    jQuery(':checkbox',this)[0].checked=cb.checked;
  });
}


/* Gestion selection */
// Met à jour la selection
TZR.SELECTION=new Object();
TZR.SELECTION.update=function(moid,geturl){
  if(!moid) moid=0;
  var jp=jQuery('#cv8-panier');
  jp.show();
  var url=TZR._self+'&moid='+TZR._sysmods_xmoduser2+'&function=browseSelection&template=generic8-panier.html&skip=1&tplentry=br&tabs='+moid;
  if(!geturl) TZR.jQueryLoad({url:url,target:'#cv8-panier',cb:function(resp,status,xml){if(resp=="") jp.hide();}});
  else return url;
}
// Met à jour le nombre de fiche cochée pour un module
TZR.SELECTION.updateChecked=function(moid){
  jQuery('#selection-nbchecked'+moid).html(jQuery('#selection-sc'+moid+' :checkbox:checked[name^="_selected"]').length);
}
// Supprime les fiches selectionnées de la selection
TZR.SELECTION.delTo=function(moid,all){
  var f=document.forms['selectionform'+moid];
  if(all) TZR.checkBoxes(f,true);
  f._function.value="delToUserSelection";
  f._next.value=TZR.SELECTION.update(moid,true);
  TZR.ajaxSubmitForm(f,'#cv8-panier');
  return false;
}
// Applique une fonction sur les elements de la selection
// use param.applyToAll=1 pour appliquer à tous les elements
TZR.SELECTION.applyTo=function(moid,func,next,param,confirm,ftarget,refresh){
  var f=document.forms['selectionform'+moid];
  if(jQuery(':checkbox:checked',f).length==0){
    if(!param || param.applyToAll!=1){
      alert(TZR._noobjectselected);
      return false;
    }else TZR.checkBoxes(f,true);
  }
  if(confirm && typeof(confirm)=='function' && !confirm.call()) return false;
  if(ftarget===undefined || ftarget===null) ftarget='#cv8-panier';
  if(next===undefined || next===null) f._next.value=TZR.SELECTION.update(moid,true);
  var jf=jQuery(f);
  jf.find('input.applyToInput').remove();
  f._function.value=func;
  if(typeof(param)=='object'){
    for(var i in param){
      jf.append('<input class="applyToInput" type="hidden" name="'+i+'" value="'+param[i]+'">');
    }
  }
  if(!ftarget) f.submit();
  else TZR.ajaxSubmitForm(f,ftarget);
  if(refresh){
    jQuery('#cv8-content div.cv8-module-container').each(function(){
      jQuery(this).data('tzrobj').refresh();
    });
  }
  return false;
}
TZR.SELECTION.exportSelection=function(moid) {
  window.open('','print','width=650,height=550,scrollbars=yes,location=no,resizable=yes');
  var form=document.forms['selectionform'+moid];
  form._next.value='';
  form._function.value='preExportBrowse';
  form.template.value='xmodtable/preexportbrowse.html';
  form.tplentry.value='br';
  form.target='print';
  form.method='post';
  form.selectedfields.value='';
  form.submit();
}
/* Soumet un formulaire (peut avoir des champs fichier) sans rechargement de la page */
/* Utilisation : TZR.iframeSubmitFormKernel.submit(form,{onStart:function,onComplete:function},true/false); */
TZR.iframeSubmitFormKernel={
  frame:function(c) {
    var n = 'iframe' + Math.floor(Math.random() * 99999);
    var d = document.createElement('DIV');
    d.innerHTML='<iframe src="about:blank" initialized="0" style="display:none" id="'+n+'" name="'+n+'" onload="TZR.iframeSubmitFormKernel.loaded(\''+n+'\');"></iframe>';
    document.body.appendChild(d);
    var i = document.getElementById(n);
    if (c && typeof(c.onComplete) == 'function') {
      i.onComplete = c.onComplete;
    }
    return n;
  },
  form : function(f, name) {
    f.setAttribute('target',name);
    return name;
  },
  submit : function(f, c) {
    var ret=false;
    if (c && typeof(c.onStart) == 'function') {
      ret=c.onStart();
    } else {
      ret=true;
    }
    if(!ret) return false;
    var id=this.form(f, TZR.iframeSubmitFormKernel.frame(c));
    jQuery(f).append('<input type="hidden" name="_iframeencode" value="1">');
    document.getElementById(id).initialized=1;
    if(c.force) f.submit();
    return true;
  },
  loaded : function(id) {
    var i = document.getElementById(id);
    if(i.initialized!=1) return false;
    if (i.contentDocument) {
      var d = i.contentDocument;
    } else if (i.contentWindow) {
      var d = i.contentWindow.document;
    } else {
      var d = window.frames[id].document;
    }
    if(d.location.href != "about:blank" && typeof(i.onComplete) == 'function') {
      if(jQuery('#_iframeencode',d.body).length==1){
	i.onComplete(jQuery('#_iframeencode',d.body).val());
      }else{
	i.onComplete(d.body.innerHTML);
      }
    }
    setTimeout(function(){jQuery(i).parent().remove()},500);
  }
}


/* Multiple files uploader */
// Lancement d'un upload de 1 ou pls fichiers
TZR.uploadifyStart=function(event, data){
  if(TZR.uploadifyInProgressFiles==undefined) TZR.uploadifyInProgressFiles=0
  TZR.uploadifyInProgressFiles+=data.filesSelected;
  setTimeout(function(){TZR.uploadifyAutoSave=confirm(TZR.uploadifyAutoSaveMessage)},500);
  if(TZR.uploadifyKeepAliveURL && !TZR.uploadifyKeepAliveTimer){
    TZR.uploadifyKeepAliveTimer=setInterval("TZR.uploadifyKeepAlive()",300000);
  }
}
// Annulation d'un fichier
TZR.uploadifyCancel=function(event, ID, fileObj, data, clearFast){
  TZR.uploadifyInProgressFiles--;
}
// Upload d'un fichier terminé
TZR.uploadifyComplete=function(event, ID, fileObj, response, data){
  jQuery("#" + event.target.id + ID + " .percentage").text(" - Completed");
  jQuery("#" + event.target.id + ID + " .cancel").remove();
  TZR.uploadifyInProgressFiles--;
  return false;
}
// Fin de traitement de file d'attente
TZR.uploadifyAllComplete=function(event, uploadObj){
  clearInterval(TZR.uploadifyKeepAliveTimer);
  TZR.uploadifyKeepAliveTimer=undefined;
  if(TZR.uploadifyAutoSave) {
    var form=jQuery(event.target).parents('form:first')[0];
    if(jQuery(form).triggerHandler('submit')!==false) form.submit();
  }
  TZR.uploadifyAutoSave=false;
}
// Garde en vie la session en cours
TZR.uploadifyKeepAlive=function(url){
  if(url) TZR.file_get_contents(url,true);
  else TZR.file_get_contents(TZR.uploadifyKeepAliveURL,true);
}
// Passe en mode standard
TZR.uploadifySwapMode=function(fieldname){
  TZR.uploadifyInProgressFiles=0;
  var std=document.getElementById(fieldname+'stdupload');
  var multi=document.getElementById(fieldname+'multiupload');
  if(std.style.display=='none'){
    document.getElementById(fieldname+'swaplink').style.display='none';
    document.getElementById(fieldname+'multiuploadUploader').style.display='none';
    document.getElementById(fieldname+'multiuploadQueue').style.display='none';
    std.style.display='block';
    multi.style.display='none';
    jQuery('input[name="'+fieldname+'_STDMODE"]',std).val('stdmode');
  }
  return false;
}

/* Gestion des champs thesaurus */
// Active le thesaurus
TZR.activeThesaurus=function(varid,moid,xtable,field,rw){
  var div=jQuery('#div'+varid);
  var table=jQuery('#table'+varid);
  var tree=jQuery("#tree"+varid);
  tree.simpleTree({
    drag:false,
    closeroot:true,
    docToFolderConvert:true,
    afterClick:function(node,updateonly){
      var span=jQuery("span:first span:first",node);
      var oid=node.attr('tzroid');
      if(span.hasClass("selected") && !updateonly){
        span.removeClass("selected").addClass("unselected");
	jQuery('input[value="'+oid+'"]',table).parents('tr:first').remove();
      }else{
	if(updateonly) var tds=jQuery('input[value="'+oid+'"]',table).parents('tr:first').find('td');
	else var tds=jQuery('tr:first',table).clone().appendTo(table).show().find('td');
	if(tds.length==0) return;
	var parents=span.parentsUntil('li.root');
	var text='';
	span.removeClass("unselected").addClass("selected");
	jQuery('input',tds[0]).val(oid);
	for(var i=parents.length-1;i>=0;i--){
	  if(parents[i].nodeName=="LI"){
	    text+=jQuery('span:first span:first',parents[i]).html()+" > ";
	  }
	}
	tds[1].innerHTML=text.substr(0,text.length-3);
      }
    },
    afterAjax:function(node){
      TZR.applySelectedValue(node,varid);
      if(rw) TZR.applyThesaurusMenu(node,varid,moid,xtable,field);
    }
  });
  TZR.applySelectedValue(tree,varid);
  if(rw) TZR.applyThesaurusMenu(tree,varid,moid,xtable,field);
}
// Selectionne les termes
TZR.applySelectedValue=function(node,varid){
  var table=jQuery('#table'+varid);
  jQuery('li',node).each(function(){
    var jt=jQuery(this);
    var oid=jt.attr('tzroid');
    if(oid && jQuery('input[value="'+oid+'"]',table).length>0){
      jt.find('>span>span').addClass('selected');
    }
  });
}
// Applique le menu contextuel à un thesaurus
TZR.applyThesaurusMenu=function(node,varid,moid,xtable,field){
  jQuery("li>span>span",node).contextMenu({menu:'xthesaurusmenu',
					   beforeShow:function(o){
                                             var m=jQuery(node);
					     if(!m.hasClass('simpleTree')) m=m.parents('ul.simpleTree:first');
					     if(jQuery(o).parents('li:first').hasClass('root')){
					       this.disableContextMenuItems('#del,#edit,#cut');
					     }else{
					       this.enableContextMenuItems('#del,#edit,#cut');
					     }
					     if(m.data('topaste')){
					       this.enableContextMenuItems('#paste');
					     }else{
					       this.disableContextMenuItems('#paste');
					     }
					   }},function(action, el, pos) {
    if(action.lastIndexOf('#')!==-1) action=action.substr(action.lastIndexOf('#')+1);
    var jtree=el.parents('ul.simpleTree:first');
    var tree=jtree[0];
    var jli=el.parents('li:first');
    var oid=jli.attr('tzroid');
    if(action=='copy'){
      jtree.data('topaste',{oid:oid,text:el.text(),mode:'copy',node:jli});
    }else if(action=='cut'){
      jtree.data('topaste',{oid:oid,text:el.text(),mode:'cut',node:jli});
      jli.addClass('tocut');
    }else if(action=="paste"){
      var param=jtree.data('topaste');
      if(param.mode=='copy'){
	jQuery.ajax({url:TZR._sharescripts+'ajax8.php?class=xthesaurusdef&function=xthesaurusdef_copyvalue&moid='+moid+'&table='+xtable+'&field='+field,async:false,data:{value:param.oid,parentoid:oid},success:function(data){
	  if(data && jli.find('ul.ajax').length==0){
	    tree.addNode('','<span>'+param.text+'</span>',function(dst,src){
	      src.attr('tzroid',data);
	      TZR.applyThesaurusMenu(dst,varid,moid,xtable,field);
	    },el.parent());
	  }
	}});
      }else{
	jQuery.ajax({url:TZR._sharescripts+'ajax8.php?class=xthesaurusdef&function=xthesaurusdef_cutvalue&moid='+moid+'&table='+xtable+'&field='+field,async:false,data:{value:param.oid,parentoid:oid},success:function(data){
	  if(data){
	    if(jli.find('ul.ajax').length==0){
	      param.node.removeClass('tocut');
	      tree.moveNodeToFolder(jli,param.node);
	    }else{
	      tree.delNode('',el.parent());
	    }
	  }
	}});
      }
      jtree.data('topaste','');
    }else if(action=="del"){
      jQuery.ajax({url:TZR._sharescripts+'ajax8.php?class=xthesaurusdef&function=xthesaurusdef_delvalue&moid='+moid+'&field='+field+'&oid='+oid+'&table='+xtable,async:false,success:function(data){
	if(data=="ok"){
	  el.parent().addClass('active');
	  tree.delNode();
	  TZR.removeThesaurusValue(varid,oid);
	}
      }});
    }else if(action=="edit"){
      var input=jQuery('<input type="text" name="value">');
      input.val(el.html());
      input.keypress(function(e){
	if(e.which==0 || e.which==27){
	  jQuery(this).parent().find('span:first').show();
	  jQuery(this).remove();
	}else if(e.which==13){
	  var _this=this;
	  jQuery.ajax({url:TZR._sharescripts+'ajax8.php?class=xthesaurusdef&function=xthesaurusdef_editvalue&moid='+moid+'&field='+field+'&oid='+oid+'&table='+xtable,async:false,data:{value:this.value},success:function(data){
	    var span=jQuery(_this).parent().find('span:first');
	    var li=span.parents('li:first');
	    if(data=="ok"){
	      span.html(_this.value);
	      tree.option.afterClick(li,true);
	    }
	    span.show();
	    jQuery(_this).remove();
	  }});
	  return false;
	}
      }).bind('click dblclick mousedown mouseup mousemove',function(e){e.stopPropagation();});
      el.hide().parent().append(input);
      input[0].focus();
    }else if(action=='add'){
      var input=jQuery('<input type="text" name="value">');
      input.keypress(function(e){
	if(e.which==0){
	  jQuery(this).parent().parent().addClass('active');
	  tree.delNode();
	}else if(e.which==13){
	  var _this=this;
	  jQuery.ajax({url:TZR._sharescripts+'ajax8.php?class=xthesaurusdef&function=xthesaurusdef_addvalue&moid='+moid+'&table='+xtable+'&field='+field,async:false,data:{value:this.value,parentoid:el.parents('li:first').attr('tzroid')},success:function(data){
	    if(data){
	      jQuery(_this).parent().html(_this.value).parents('li:first').attr('tzroid',data);
	      jQuery(_this).remove();
	    }else{
	      jQuery(_this).parent().parent().addClass('active');
	      tree.delNode();
	    }
	  }});
	  return false;
	}
      }).bind('click dblclick mousedown mouseup mousemove',function(e){e.stopPropagation();});
      tree.addNode('','<span></span>',function(dst,src){
	TZR.applyThesaurusMenu(dst,varid,moid,xtable,field);
	jQuery('>span>span',src).html(input);
	input[0].focus();
      },el.parent());
    }
  });
}
// Supprime une valeur du thesaurus de la selection
TZR.removeThesaurusValue=function(varid,oid){
  var tree=jQuery("#tree"+varid);
  var table=jQuery('#table'+varid);
  if(typeof(oid)=='object'){
    oid=jQuery(oid).parents('tr:first').find('input').val();
  }
  jQuery('input[value="'+oid+'"]',table).parents('tr:first').remove();
  jQuery('li[tzroid="'+oid+'"] span.selected',tree).removeClass("selected").addClass("unselected");
}
// Ajoute une valeur suite à une saisie via le champ en autocomplete
TZR.autocompleteThesaurus=function(varid,oid,v){
  if(oid && v){
    var table=jQuery('#table'+varid);
    if(table.find('input[value="'+oid+'"]').length>0) return;
    var tree=jQuery('#tree'+varid);
    var tds=jQuery('tr:first',table).clone().appendTo(table).show().find('td');
    if(tds.length==0) return;
    jQuery('input',tds[0]).val(oid);
    tds[1].innerHTML=v;
    tree.find('li[tzroid="'+oid+'"]>span>span').addClass('selected').removeClass('unselected');
    jQuery('#_INPUT'+varid).val('');
  }
}

// Fonctions d'ajout de ligne, de colonne et d'application de tablesorter à un champ XTableDef
TZR.XTableAddLine=function(tableid,fname){
  var jt=jQuery('#'+tableid);
  var tr=jt[0].tBodies[0].rows[jt[0].tBodies[0].rows.length-1];
  var jnewtr=jQuery(tr).clone(true);
  var reg=new RegExp(fname+"\\[(\\d+)\\]","g");
  var reg2=new RegExp("\\[_rlabels\\]\\[(\\d+)\\]","g");
  var regres=reg.exec(tr.innerHTML);
  var newnum=parseInt(regres[1])+1;
  jnewtr.html(tr.innerHTML.replace(reg,fname+"["+newnum+"]").replace(reg2,"[_rlabels]["+newnum+"]").replace('>'+newnum+'</td>','>'+(newnum+1)+'</td>'));
  jnewtr.insertAfter(tr).find('input').keyup(function(){jQuery("#"+tableid).trigger("update");}).bind('click mousedown',function(e){e.stopPropagation();}).val('');
  jt.trigger("update");
}
TZR.XTableAddColumn=function(tableid,fname){
  var jt=jQuery('#'+tableid);
  var trs=jt.find('tr')
  trs.each(function(i){
    if(this.cells.length>1){
      var reg=/(\[[^\]]+\])\[(\d+)\]/g;
      var td=this.cells[this.cells.length-2];
      var jnewtd=jQuery(td).clone(true);
      var regres=reg.exec(td.innerHTML);
      var newnum=parseInt(regres[2])+1;
      jnewtd.html(td.innerHTML.replace(reg,"$1["+newnum+"]"));
      jnewtd.insertAfter(td).find('input').keyup(function(){jQuery("#"+tableid).trigger("update");}).bind('click mousedown',function(e){e.stopPropagation();}).val('');;
    }
  });
  jt.trigger("update");
}
TZR.XTableSorter=function(tableid){
  jQuery('#'+tableid).find('input').keyup(function(){jQuery("#"+tableid).trigger("update");}).bind('click mousedown',function(e){e.stopPropagation();});
  jQuery('#'+tableid).tablesorter({textExtraction:function(node){
    var i=jQuery('input',node);
    if(i.length>0) return i[0].value;
    else return node.innerHTML;
  }});
}

/* Agenda */
TZR.Calendar=new Object();
// Ajoute/deplace/supprime un evenement/note dans le tableau des evenements/notes selon l'heure de debut/fin
TZR.Calendar.orderEvent=function(uniqid,obj,tomove,del){
  var found=false;
  var notes=obj.notes;
  var evs=obj.evs;
  var added=false;
  if(!tomove.allday || tomove.allday=='0'){
    for(var i in evs){
      var e=evs[i];
      if(e.id==tomove.id){
	evs.splice(i,1);
	break;
      }
    }
    if(del==undefined){
      for(var i in evs){
	var e=evs[i];
	if(e._isod>tomove._isod || (e._isod==tomove._isod && (e._bh>tomove._bh || (e._bh==tomove._bh && e._eh>=tomove._eh) || e._bd>tomove._bd))){
	  evs.splice(i,0,tomove);
	  added=true;
	  break;
	}
      }
      if(!added) evs.push(tomove);
    }
  }else{
    if(del){
      for(var i in notes){
	var n=notes[i];
	if(n.id==tomove.id){
	  notes.splice(i,1);
	  break;
	}
      }
    }
  }
}
// Caclule la position et la taille des evenements (les evenements doivent etre trié par heure de debut)
TZR.Calendar.calculatePosition=function(uniqid,obj){
  var dates=obj.dates;
  var evs=obj.evs;
  var max=obj.max;
  for(var num in dates){
    var date=dates[num];
    max[date]=0;
  }
  var rows=new Object();
  var cols=new Object();
  var groupinfos={max:1,rows:{},cols:{},end:-1,hour:0,date:"1000-01-01"};
  for(var i in evs){
    var e=evs[i];
    var ok=false;
    var l=TZR.Calendar.getEventLimit(e);
    var ee=l.e;
    var eb=l.b;
    var nbcase=l.d;
    var c=0;
    if(groupinfos.hour<=eb || e._isod!=groupinfos.date){
      groupinfos={max:1,rows:{},cols:{},hour:ee,date:e._isod};
      var newgroup=true;
    }else{
      var newgroup=false;
    }
    while(!ok && groupinfos.rows!=undefined && groupinfos.rows[eb]!=undefined && groupinfos.rows[eb][c]!=undefined){
      ok=true;
      for(var j=0;j<nbcase;j++){
	if(groupinfos.rows[eb+j]!=undefined && groupinfos.rows[eb+j][c]!=undefined){
	  c++;
	  ok=false;
	  break;
	}
      }
    }
    if(!newgroup){
      if(c+1>groupinfos.max) groupinfos.max=c+1;
      if(ee>groupinfos.hour) groupinfos.hour=ee;
    }
    e.groupinfos=groupinfos;
    e.col=c;
    e.row=eb;
    e.h=nbcase;
    e.w=1;
    for(j=0;j<nbcase;j++){
      if(groupinfos.rows[eb+j]==undefined) groupinfos.rows[eb+j]=new Object();
      if(groupinfos.cols[c]==undefined) groupinfos.cols[c]=new Object();
      groupinfos.rows[eb+j][c]=e;
      groupinfos.cols[c][eb+j]=e;
    }
  }
  for(var i in evs){
    e=evs[i];
    var stop=false;
    var totest=new Array();
    for(j=0;j<e.h;j++){
      totest.push(e.row+j);
    }
    for(j=e.col+1;j<e.groupinfos.max;j++){
      for(k in totest){
	k=totest[k];
	if(e.groupinfos.cols[j]!=undefined && e.groupinfos.cols[j][k]!=undefined){
	  stop=true;
	  break;
	}
      }
      if(stop) break;
      e.w++;
    }
  }
}
// Lance la mise à jour de l'agenda
TZR.Calendar.drawAgenda=function(uniqid,obj){
  for(var e in obj.notes){
    e=obj.notes[e];
    TZR.Calendar.createNoteDiv(uniqid,obj,e);
  }
  var nl=0;
  for(var i in obj.dates){
    var l=jQuery('#agad'+obj.dates[i]+'-'+uniqid+'>div.note').length+1;
    if(l>nl){
      document.getElementById('agallday'+uniqid).style.height=(l*obj.noteHeight)+"px";
      nl=l;
    }
  }
  for(var e in obj.evs){
    e=obj.evs[e];
    TZR.Calendar.createEventDiv(uniqid,obj,e);
  }
}

// Créé/met à jour la div d'une note
TZR.Calendar.createNoteDiv=function(uniqid,obj,e){
  e.id=e.id.replace(':','_');
  var ag=document.getElementById('agdaysallday-'+uniqid);
  var jdiv=jQuery('#'+e.id+"-"+uniqid);
  var div=jdiv[0];
  if(div==undefined){
    div=document.createElement("div");
    div.innerHTML='<div class="event-w"></div><div class="event-e"'+(e.cat?' style="background-color:'+e.cat+';"':'')+'></div><div class="event-s"></div><div class="event-n"></div><div class="event-content"></div>';
    div.style.backgroundColor=e.color;
    div.id=e.id+"-"+uniqid;
    div.style.height=obj.noteHeight+"px";
    div.style.position="relative";
    div.className="note";
    document.getElementById('agad'+e._isod+"-"+uniqid).appendChild(div);
    jdiv=jQuery(div);
    div.tzrevent=e;
    // Setter : met à jour le texte html de l'evenement (heure + titre)
    div.setEventText=function(){
      jQuery('.event-content',this).html(this.tzrevent.text);
    }
    // Active deplacement
    if(e.rw && e._obd==e._bd && e._oed==e._ed){
      jdiv.draggable({grid:[1,999],containment:'parent',axis:"y",start:function(event,ui){
	TZR.Calendar.startDrag(uniqid,obj,event);
	obj.actEvent="drag";
	obj.actTarget=event.target;
	jQuery('div.agadday',ag).mouseenter(function(event){
	  jdiv.mousemove(function(){return false;})
	  jQuery(obj.actTarget).appendTo(this);
	  obj.actTarget.tzrevent._isod=this.id.substr(4,10);
	  setTimeout(function(){jdiv.unbind('mousemove');},100);
	});
      },stop:function(event,ui){
	TZR.Calendar.stopDrag(uniqid,obj,event);
	jQuery('div.agadday',ag).unbind('mouseenter');
      }});
    }
    // Tooltip
    TZR.Calendar.applyHottip(uniqid,obj,jdiv);
    jdiv.mousedown(function(event){
      // Stoppe la propagation de l'evenement (sinon ie active le selected quand on veut le deplacer)
      event.stopPropagation();
    });
  }
  div.setEventText();
}

// Créé/met à jour la div d'un evenement
TZR.Calendar.createEventDiv=function(uniqid,obj,e){
  e.id=e.id.replace(':','_');
  var ag=document.getElementById('agdays-'+uniqid);
  var jdiv=jQuery('#'+e.id+"-"+uniqid);
  var div=jdiv[0];
  if(div==undefined){
    div=document.createElement("div");
    div.innerHTML='<div class="event-w"></div><div class="event-e"'+(e.cat?' style="background-color:'+e.cat+';"':'')+'></div><div class="event-s"></div><div class="event-n"></div><div class="event-content"></div>';
    div.style.backgroundColor=e.color;
    div.id=e.id+"-"+uniqid;
    div.className="event";
    document.getElementById('ag'+e._isod+"-"+uniqid).appendChild(div);
    jdiv=jQuery(div);
    div.tzrevent=e;
    // Setter : met à jour le texte html de l'evenement (heure + titre)
    div.setEventText=function(pos){
      jQuery('.event-content',this).html(TZR.Calendar.getEventText(uniqid,obj,this.tzrevent,pos));
    }
    // Active deplacement
    if(e.rw && e._obd==e._bd && e._oed==e._ed){
      jdiv.draggable({grid:[1,obj.lineHeight],containment:'parent',axis:"y",drag:function(event,ui){
	event.target.setEventText(TZR.Calendar.positionToHour(uniqid,obj,event.target));
      },start:function(event,ui){
	TZR.Calendar.startDrag(uniqid,obj,event);
	obj.actEvent="drag";
	obj.actTarget=event.target;
	event.target.style.width="100%";
	event.target.style.left="0px";
	jQuery('div.agday',ag).mouseenter(function(event){
	  jdiv.mousemove(function(){return false;});
	  jQuery(obj.actTarget).appendTo(this);
	  obj.actTarget.tzrevent._isod=this.id.substr(2,10);
	  setTimeout(function(){jdiv.unbind('mousemove');},100);
	});
      },stop:function(event,ui){
	TZR.Calendar.stopDrag(uniqid,obj,event);
	jQuery('div.agday',ag).unbind('mouseenter');
      }});
    }

    // Active redimmenssionement
    if(e.rw && (e._obd==e._bd || e._oed==e._ed)){
      if(e._obd==e._bd && e._oed==e._ed) var handles='s,n';
      else if(e._obd==e._bd) var handles='n';
      else if(e._oed==e._ed) var handles='s';
      jdiv.resizable({grid:obj.lineHeight,containment:document.getElementById('ag'+e._isod+"-"+uniqid),handles:handles,start:function(event,ui){
	obj.actEvent="resize";
	TZR.Calendar.startDrag(uniqid,obj,event);
      },stop:function(event,ui){
	TZR.Calendar.stopDrag(uniqid,obj,event);
      },resize:function(event,ui){
	if(ui.size.height!=ui.originalSize.height){
	  var pos="";
	  if(obj.actEvent=="" || obj.actEvent=="resize"){
	    if(ui.position.top!=ui.originalPosition.top) obj.actEvent="resizen";
	    else obj.actEvent="resizes";
	  }
	  if(obj.actEvent=="resizen") pos=TZR.Calendar.positionToHour(uniqid,obj,event.target,"begin");
	  else pos=TZR.Calendar.positionToHour(uniqid,obj,event.target,"end");
	  event.target.setEventText(pos);
	}
      }});
    }
    // Tooltip
    TZR.Calendar.applyHottip(uniqid,obj,jdiv);
    jdiv.click(function(event){
      var _now=new Date().getTime();
      if(this.lastclick && _now-this.lastclick<300){
	obj.vuniqid.jQueryLoad(e.url+"&display="+obj.display);
	return;
      }
      this.lastclick=_now;
    }).mousedown(function(event){
      // Stoppe la propagation de l'evenement (sinon ie active le selected quand on veut le deplacer) et supprime un eventuel hottip
      event.stopPropagation();
    });
  }
  // Position
  var l=Math.floor(100/e.groupinfos.max)*e.col;
  if(e.col+e.w==e.groupinfos.max) var w=100-Math.floor(100/e.groupinfos.max)*e.col;
  else w=Math.floor(100/e.groupinfos.max)*e.w;
  div.style.position="absolute";
  div.style.left=l+"%";
  div.style.top=(e.row*obj.lineHeight-obj.agStart*obj.lineHeight*4)+"px";
  div.style.width=w+'%';
  div.style.height=(e.h*obj.lineHeight)+'px';
  div.setEventText();
}

// Initialise un drag/resize : ecouteur touche pour annuler via ECHAP
TZR.Calendar.startDrag=function(uniqid,obj,e){
  jQuery(jQuery.bt.vars.closeWhenOpenStack).btOff();
  var o=e.target;
  var jo=jQuery(o);
  var pos=jo.position();
  jQuery(document).bind('keydown',{parent:o.parentNode,target:o,top:jo.css('top'),left:jo.css('left'),width:jo.css('width'),height:jo.css('height'),obj:obj},TZR.Calendar.cancelDrag);
}

// Termine un drag/resize : efface ecouteur touche pour annuler via ECHAP, sauvegarde des nouvelles heures/actualise agenda
TZR.Calendar.stopDrag=function(uniqid,obj,e){
  var o=e.target;
  jQuery(document).unbind('keydown',TZR.Calendar.cancelDrag);
  if(obj.actEvent!=""){
    if(!o.tzrevent.allday || o.tzrevent.allday=='0'){
      var hours=TZR.Calendar.positionToHour(uniqid,obj,o);
      if(obj.actEvent!="resizes") o.tzrevent._bh=hours.b;
      if(obj.actEvent!="resizen") o.tzrevent._eh=hours.e;
    }
    TZR.Calendar.ajaxSaveEvent(uniqid,obj,o.tzrevent,true);
  }
  obj.actEvent="";
}

// Annule un drag/resize
TZR.Calendar.cancelDrag=function(event){
  if(event.keyCode==27){
    event.data.obj.actEvent="";
    // La div a changée de colonne, on la remet
    if(event.data.target.parentNode!=event.data.parent){
      jQuery(event.data.target).appendTo(event.data.parent);
      event.data.target.tzrevent._isod=event.data.parent.id.substr(2,10);
    } 
    // Retablissement position dans la colonne
    jQuery(event.data.target).css({top:event.data.top,left:event.data.left,width:event.data.width,height:event.data.height});
    jQuery(event.data.target).mouseup();
    event.data.target.setEventText();
  }
}

// Annule une création
TZR.Calendar.cancelNew=function(event){
  if(event.keyCode==27){
    event.data.obj.actEvent="";
    jQuery(event.data.target).mouseup();
  }
}

// Rafrachi l'agenda
TZR.Calendar.refreshAgenda=function(uniqid,obj,event,del){
  if(del) jQuery(jQuery.bt.vars.closeWhenOpenStack).btOff();
  if(event) TZR.Calendar.orderEvent(uniqid,obj,event,del);
  TZR.Calendar.calculatePosition(uniqid,obj);
  TZR.Calendar.drawAgenda(uniqid,obj);
  if(!del) jQuery(jQuery.bt.vars.closeWhenOpenStack).btOn();
}

// Sauvegarde un evenement. Envoi des données au serveur et le serveur renvoie les données enregistrées que l'on met dans event afin que le traitement js porte sur les vrai données
TZR.Calendar.ajaxSaveEvent=function(uniqid,obj,event,refresh,cb){
  var reg=/<.?br.?.?>/;
  if(reg.test(event.descr)) event.descr=event.descr.replace("\n","","g").replace(/<.?br.?.?>/g,"\n");
  var param={oid:obj.oid,koid:event.oid,text:event.text,descr:event.descr,place:event.place,allday:event.allday};
  if(!event.oid || event._obd==event._bd){
    param["begin[date]"]=event._isod;
    param["begin[hour]"]=event._bh;
  }
  if(!event.oid || event._oed==event._ed){
    param["end[date]"]=event._isod;
    param["end[hour]"]=event._eh;
  }
  param['skip']=1;
  jQuery.getJSON(TZR._self+"&moid="+obj.moid+"&function=ajaxEdit",param,function(data,status){
    if(data){
      jQuery.extend(event,data);
      if(refresh) TZR.Calendar.refreshAgenda(uniqid,obj,event);
      if(cb) cb.call(TZR.Calendar,uniqid,obj,event);
    }else{
      alert('Error');
    }
  }); 
  return true;
}

// Créer un evenement
TZR.Calendar.createEvent=function(uniqid,obj,event){
  if(event.text==undefined) event.text="";
  if(event.id==undefined)  event.id="ev-"+obj.evs.length+"-"+event._isod;
  if(event.descr==undefined) event.descr='';
  if(event.place==undefined) event.place='';
  var l=TZR.Calendar.getEventLimit(event);
  event.col=0;
  event.w=1;
  event.groupinfos={max:1};
  event.row=l.b;
  event.h=l.d;
  event.rw=1;
  event.color=obj.color;
  event.dname=obj.name;
  TZR.Calendar.createEventDiv(uniqid,obj,event);
  var jdiv=jQuery('#'+event.id+"-"+uniqid);
  setTimeout(function(){
    jdiv.click();
    jQuery('#bt-edittext').triggerHandler('click');
  },100);
}

// Supprime un evenement sur le serveur
TZR.Calendar.ajaxDelEvent=function(uniqid,obj,event){
  if(event.oid==undefined) return;
  jQuery.getJSON(TZR._self+"&moid="+obj.moid+"&function=ajaxDel&oid="+obj.oid+"&koid="+event.oid,{},function(data,status){
    if(data!="ok"){
      alert('Error');
    }else{
      TZR.Calendar.delEvent(uniqid,obj,event);
    }
  });
  return true;
}

// Supprime une div evenement
TZR.Calendar.delEvent=function(uniqid,obj,event){
  jQuery(jQuery.bt.vars.closeWhenOpenStack).btOff();
  jQuery('#'+event.id+'-'+uniqid).remove();
  if(obj.display!="displayMonth") TZR.Calendar.refreshAgenda(uniqid,obj,event,true);
}

// Ecouteur clavier pour un agenda
TZR.Calendar.keyListener=function(event){
  var uniqid=event.data.uniqid;
  var obj=event.data.obj;
  var ag=document.getElementById('agenda'+uniqid);
  if(!ag){
    jQuery(document).unbind('keydown',TZR.Calendar.keyListener);
    return;
  }
  if(event.keyCode==46 && obj.actEvent==""){
    jo=jQuery('div.event-selected',ag);
    if(jo.length==1 && confirm('Supprimer?')){
      TZR.Calendar.ajaxDelEvent(uniqid,obj,jo[0].tzrevent);
    }
  }else if(event.keyCode==27 && obj.actEvent=="edit"){
    jQuery('#bt-cancel').click();
  }
}

// Retourne les limites et le durée d'un evenemtn au format decimal
TZR.Calendar.getEventLimit=function(e){
  var foo=e._bh.split(':');
  var bdec=parseFloat(foo[0])+parseFloat(foo[1])/60;
  var brounddec=Math.floor(bdec*4)/4;
  foo=e._eh.split(':');
  var edec=parseFloat(foo[0])+parseFloat(foo[1])/60;
  var erounddec=Math.ceil(edec*4)/4;
  var eb=brounddec*4;
  var ee=erounddec*4;
  return {b:eb,e:ee,d:ee-eb};
}

// Recupere l'heure a afficher d'un evenement (en prenant en compte une eventuelle position calculée par positionToHour)
TZR.Calendar.getEventText=function(uniqid,obj,event,pos){
  var ret="",b,e;
  if(!event.allday || event.allday=="0"){
    if(typeof(pos)=='object'){
      b=pos.b;
      e=pos.e;
    }else{
      b=event._bh;
      e=event._eh;
    }
    if(event._obd!=event._bd && event._oed!=event._ed) ret=".. > ..";
    else if(event._obd!=event._bd) ret=".. > "+e;
    else if(event._oed!=event._ed) ret=b+" > ..";
    else ret=b+" > "+e;
    ret='<span class="event-hour">'+ret+'</span> <span class="event-title">'+event.text+'</span>';
  }else{
    ret='<span class="event-title">'+event.text+'</span>';
  }
  return ret;
}

// Initialise la tooltip d'une div evenement 
TZR.Calendar.applyHottip=function(uniqid,obj,jo,cb){
  TZR.applyHottip(jo,{closeButton:1,trigger:"click",width:320,spikeLength:40,spikeGirth:20,padding:10,cornerRadius:10,'overlap':'jQuery(this).height()/2',positions:['top','bottom'],offsetParent:'#tooltip',hideTip:function(box,callback){if(obj.actEvent=="edit"){jQuery('#bt-cancel').click();}jQuery(box).hide();callback();},postShow:function(box){
    jQuery(this).addClass('event-selected');
    // Rend titre/descr/lieu de l'helper editable inline
    if(this.tzrevent.rw){
      jQuery('#bt-view').hide();
      TZR.Calendar.applyEditable(uniqid,obj,this,cb);
    }else{
      jQuery('#bt-del,#bt-edit').hide();
      jQuery('.ieditable2',box).removeClass("ieditable2");
    }
  },postHide:function(){jQuery('div.event-selected',document.getElementById('agdays-'+uniqid)).removeClass('event-selected');},contentSelector:TZR.Calendar.getHottipContent});
}

// Applique l'edition directe
TZR.Calendar.applyEditable=function(uniqid,obj,div,cb){
  jQuery('#bt-edittext,#bt-editplace,#bt-editdescr').click(function(){
    if(jQuery('input,textarea',this).length) return false;
    obj.actEvent="edit";
    this.oldvalue=this.innerHTML;
    if(this.innerHTML==" " || this.innerHTML=="&nbsp;") this.innerHTML="";
    if(this.id=="bt-edittext" || this.id=="bt-editplace"){
      jQuery(this).html('<input type="text" name="'+this.id.substr(7)+'" value="'+this.innerHTML+'" style="width:225px;height=17px;">');
    }else{
      jQuery(this).html('<textarea style="height:98%;width:99%;" name="'+this.id.substr(7)+'">'+this.innerHTML.replace(/<.?br.?.?>/g,"")+'</textarea>');
    }
    jQuery('input,textarea',this).focus();
    jQuery('#bt-del,#bt-edit,#bt-view').hide();
    jQuery('#bt-cancel,#bt-save').show();
  }).each(function(){
    if(this.innerHTML=="") this.innerHTML="&nbsp;";
  });
  jQuery('#bt-cancel').click(function(){
    jQuery('#bt-edittext,#bt-editplace,#bt-editdescr').each(function(){
      if(typeof(this.oldvalue)!="undefined") this.innerHTML=this.oldvalue;
    });    
    if(div.tzrevent.rw) jQuery('#bt-del,#bt-edit').show();
    else jQuery('#bt-view').show();
    jQuery('#bt-cancel,#bt-save').hide();
    obj.actEvent="";
    if(div.tzrevent.oid==undefined) return TZR.Calendar.delEvent(uniqid,obj,div.tzrevent);
  });
  jQuery('#bt-save').click(function(){
    jQuery('#bt-edittext,#bt-editplace,#bt-editdescr').each(function(){
      if(typeof(this.oldvalue)!="undefined"){
	div.tzrevent[this.id.substr(7)]=jQuery('input,textarea',this).val();
	this.innerHTML=this.oldvalue;
      }
    });
    obj.actEvent="";
    TZR.Calendar.ajaxSaveEvent(uniqid,obj,div.tzrevent,(obj.display!="displayMonth"),cb);
    jQuery('#bt-cancel,#bt-save').hide();
  });
  return ;
}

// Retourne le contenu de la tooltip d'un evenement
TZR.Calendar.getHottipContent=function(div){
  var event=this.tzrevent,d="";
  var txt=jQuery(this).parents('div.cv8-module-container:first').find('div.cv8-agendabtcontent:first').html();
  if(event.allday && event.allday!="0"){
    if(event._obd==event._oed) d=event._obd;
    else d=event._obd+" - "+event._oed;
  }else{
    if(event._obd==event._oed) d=event._obd+" "+event._bh+" - "+event._eh;
    else d=event._obd+" "+event._bh+" - "+event._oed+" "+event._eh;
  }
  txt=txt.replace('_hour_',event.dname+" : "+d);
  txt=txt.replace('_title_',event.text).replace('_place_',event.place).replace(/_descr_/g,event.descr).replace(/_url_/g,event.url).replace(/_bt/g,"bt");
  if(!event.oid){
    txt=jQuery('<div>'+txt+'</div>');
    txt.find('#bt-view,#bt-edit,#br-del').remove();
    txt=txt.html();
  }
  return txt;
}

// Recupere la decimal d'un nombre
TZR.Calendar.decimal=function(num){
  return num-Math.floor(num);
}
// Trasnforme un flaot en heur HH:mm
TZR.Calendar.floatToHour=function(num){
  var h=Math.floor(num);
  if(h<10) h="0"+h;
  var m=TZR.Calendar.decimal(num)*60;
  if(m<10) m="0"+m;
  return h+":"+m;
}
// Transforme une position en heure HH:mm
TZR.Calendar.positionToHour=function(uniqid,obj,o,what){
  var jo=jQuery(o);
  var t=parseInt(jo.css('top'));
  var h=parseInt(jo.css('height'));
  var dec=obj.agStart+(t/obj.lineHeight/4);
  if(what=='end') var b=o.tzrevent._bh;
  else var b=TZR.Calendar.floatToHour(dec);
  dec=dec+(h/obj.lineHeight/4);
  if(what=='begin') var e=o.tzrevent._eh;
  else var e=TZR.Calendar.floatToHour(dec);
  return {b:b,e:e};
}

// Création de la grille d'un agenda
TZR.Calendar.makeGrid=function(uniqid,obj){
  var agglob=document.getElementById('agglobal'+uniqid);
  var aghead=document.getElementById('agdayshead'+uniqid);
  var agdays=document.getElementById('agdays'+uniqid);
  var aghour=document.getElementById('aghour'+uniqid);
  var agdaysallday=document.getElementById('agdaysallday'+uniqid);
  var div,div2,h,ht,date,i,num,date,l,w,agw,tmp;
  // Heures
  if(obj.dates.length==1){
    tmp=document.getElementById('aghourallday'+uniqid);
    date=obj.dates[0];
    tmp.innerHTML='<a class="cv8-ajaxlink" href="'+TZR._self+'oid='+obj.oid+'&function=addEvt&moid='+obj.moid+'&tplentry=br&template=xmodcalendar/addEvt.html&day='+date.substr(8,2)+'&month='+date.substr(5,2)+'&year='+date.substr(0,4)+'&display=displayDay&allday=1">'+tmp.innerHTML+'</a>';
  }
  h=((obj.agEnd-obj.agStart)*4)*obj.lineHeight;
  agglob.style.height=(h+10)+"px";
  agdays.style.height=h+"px";
  for(i=obj.agStart;i<obj.agEnd;i=i+0.25){
    if(Math.floor(i)==i){
      ht=TZR.Calendar.floatToHour(i);
      div=document.createElement("div");
      if(Math.floor(i+1)%2) div.className="bgodd";
      else div.className="bgeven";
      if(obj.dates.length==1){
	date=obj.dates[0];
	div.innerHTML='<a class="cv8-ajaxlink" href="'+TZR._self+'oid='+obj.oid+'&function=addEvt&moid='+obj.moid+'&tplentry=br&template=xmodcalendar/addEvt.html&day='+date.substr(8,2)+'&month='+date.substr(5,2)+'&year='+date.substr(0,4)+'&display=displayDay&hour='+ht+'">'+ht+'</a>';
      }else{
	div.innerHTML=ht;
      }
      aghour.appendChild(div);
      // Fonds
      div=document.createElement("div");
      div.style.position="absolute";
      div.style.left="0px";
      div.style.top=(i*4*obj.lineHeight-obj.agStart*4*obj.lineHeight)+"px";
      if(Math.floor(i+1)%2) div.className="bgodd";
      else div.className="bgeven";
      agdays.appendChild(div);
    }
  }
  // Colonnes dates
  agw=Math.floor(100/obj.dates.length);
  for(num in obj.dates){
    num=parseInt(num);
    date=obj.dates[num];
    if(num==obj.dates.length-1) w=(100-agw*num)+"%";
    else w=agw+"%";
    l=(num*agw)+"%";
    // Div d'entete
    div=document.createElement("div");
    div.className="aghead";
    div.style.left=l;
    div.style.width=w;
    if(obj.dates.length>1){
      div.innerHTML='<a class="cv8-ajaxlink" href="'+TZR._self+'oid='+obj.oid+'&function=addEvt&moid='+obj.moid+'&function=displayDay&tplentry=br&template=xmodcalendar/displayDay.html&day='+date.substr(8,2)+'&month='+date.substr(5,2)+'&year='+date.substr(0,4)+'">'+jQuery.datepicker.formatDate("D dd/mm",jQuery.datepicker.parseDate('yy-mm-dd',date))+'</a>';
    }else{
      div.innerHTML=jQuery.datepicker.formatDate("DD dd MM yy",jQuery.datepicker.parseDate('yy-mm-dd',date));
    }
    aghead.appendChild(div);
    // Div des notes
    div=document.createElement("div");
    if(num+1==obj.dates.length) div.className="agadday agaddaylast";
    else div.className="agadday";
    div.id="agad"+date+"-"+uniqid;
    div.style.left=l;
    div.style.width=w;
    agdaysallday.appendChild(div);
    // Div des evenements
    div=document.createElement("div");
    if(num+1==obj.dates.length) div.className="agday agdaylast";
    else div.className="agday";
    div.id="ag"+date+"-"+uniqid;
    div.style.left=l;
    div.style.width=w;
    agdays.appendChild(div);
    
    // Création de la grille (div selectionnable pour creation)
    for(i=obj.agStart;i<obj.agEnd;i=i+0.25){
      div2=document.createElement("div");
      div2.className="aggrid";
      div2.id=date+"-"+TZR.Calendar.floatToHour(i)+"-"+uniqid;
      div2.setAttribute("x-dechour",i);
      div2.setAttribute("x-date",date);
      div.appendChild(div2);
    }

    // Active la selection pour creation à la volée
    if(obj.rw){
      jQuery(div).selectable({autoRefresh:true,filter:"div.aggrid",distance:2,start:function(event){
	obj.actEvent="new";
	obj.newStart=undefined;
	obj.newEnd=undefined;
      },stop:function(event,ui){
	jQuery(document).unbind('keydown',TZR.Calendar.cancelNew);
	if(obj.actEvent!=""){
	  obj.newEnd+=0.25;
	  TZR.Calendar.createEvent(uniqid,obj,{_bh:TZR.Calendar.floatToHour(obj.newStart),_eh:TZR.Calendar.floatToHour(obj.newEnd),_bd:obj.newDate,_ed:obj.newDate,_obd:obj.newDate,_oed:obj.newDate,_isod:obj.newDate});
	}
	obj.actEvent="";
      },selected:function(event,ui){
	var t=ui.selected;
	var jt=jQuery(t);
	var dechour=parseFloat(jt.attr("x-dechour"));
	if(obj.newStart==undefined) obj.newStart=dechour;
	if(obj.newEnd==undefined || obj.newEnd<dechour) obj.newEnd=dechour;
	obj.newDate=jt.attr("x-date");
      },selecting:function(event,ui){
	jQuery(document).unbind('keydown',TZR.Calendar.cancelNew);
	jQuery(document).bind('keydown',{target:event.target,obj:obj},TZR.Calendar.cancelNew);
	jQuery('.ui-selectable-helper').css({"border":"0px solid black","background-color":"transparent"});
      }
      });
    }
  }

  // Ecouteur pour supression
  if(obj.rw){
    jQuery(document).unbind('keydown',TZR.Calendar.keyListener);
    jQuery(document).bind('keydown',{uniqid:uniqid,obj:obj},TZR.Calendar.keyListener);
  }
}

// Créé une div pour l'affichage mensuel
TZR.Calendar.monthCreateDiv=function(uniqid,obj,e){
  e.id=e.id.replace(':','_');
  var div=document.getElementById(e.id+"-"+uniqid);
  if(!div){
    div=document.createElement('div');
    div.tzrevent=e;
    div.id=e.id+"-"+uniqid;
    div.className="tzr-cal-month-div";
    div.style.backgroundColor=e.color;
    jQuery('#ag'+e._isod+"-"+uniqid).append(div);
    var jdiv=jQuery(div);
    TZR.Calendar.applyHottip(uniqid,obj,jdiv,TZR.Calendar.monthCreateDiv);
    if(e.rw && e._obd==e._oed){
      jdiv.mousedown(function(event){
	event.currentTarget.tzrevent.modified=false;
	jdiv.addClass('ui-draggable-dragging');
	jQuery('.tzr-cal-display-in').mouseover(function(){
	  if(event.currentTarget.tzrevent._isod!=this.id.substr(2,10)){
	    jQuery(jQuery.bt.vars.closeWhenOpenStack).btOff();
	    jQuery(event.currentTarget).appendTo(this);
	    event.currentTarget.tzrevent._isod=this.id.substr(2,10);
	    event.currentTarget.tzrevent.modified=true;
	  }
	});
	jQuery(document).bind('mouseup',{jdiv:jdiv,uniqid:uniqid,obj:obj,event:event.currentTarget.tzrevent},TZR.Calendar.monthStopDrag).bind('keydown',{parent:div.parentNode,target:div},TZR.Calendar.monthCancelDrag);
	return false;
      });
    }
    jdiv.click(function(event){
      var _now=new Date().getTime();
      if(this.lastclick && _now-this.lastclick<300){
	obj.vuniqid.jQueryLoad(e.url+"&display="+obj.display);
	return;
      }
      this.lastclick=_now;
    });
  }
  div.innerHTML='<div class="event-w"></div><div class="event-e"'+(e.cat?' style="background-color:'+e.cat+';"':'')+'></div><div class="event-s"></div><div class="event-n"></div><div class="tzr-cal-month-paddingdiv"><div class="tzr-cal-display-event-hour">'+TZR.Calendar.getEventText(null,null,e)+'</div></div>';
}
TZR.Calendar.monthStopDrag=function(e){
  if(e.data.event.modified) TZR.Calendar.ajaxSaveEvent(e.data.uniqid,e.data.obj,e.data.event,false);
  e.data.jdiv.removeClass('ui-draggable-dragging');
  jQuery('.tzr-cal-display-in').unbind('mouseover');
  jQuery(document).unbind('mouseup',TZR.Calendar.monthStopDrag);
  return false;
}
// Annule un drag dans l'affichage mensuel
TZR.Calendar.monthCancelDrag=function(e){
  if(e.keyCode==27){
    // La div a changée de colonne, on la remet
    if(e.data.target.parentNode!=e.data.parent){
      jQuery(e.data.target).appendTo(e.data.parent);
      e.data.target.tzrevent._isod=e.data.parent.id.substr(2,10);
    } 
    e.data.target.tzrevent.modified=false;
    jQuery(document).mouseup();
    jQuery(document).unbind('keydown',TZR.Calendar.monthCancelDrag);
  }
}

