// JavaScript Document
// Date : 2010/09/01
// document.writeln('<scr'+'ipt type="text/javascript" src="http://arezus.fr/lib/core/js/prototype.js"></scr'+'ipt>');
function msApplication(){
	this.getBrowser=function(){
		var sBrowser = 'undef';
		if ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1)) sBrowser = 'ie6';
        application.browser = sBrowser
		return application.browser;
	}
	this.loadScript=function(scripts){
		new Ajax.Request('/lib/core/ajax/loadScripts.php',{
			parameters:scripts.toJSON(),
			onSuccess: function(r){
				alert(r.responseText);
				r.responseText.evalScripts();
			},
			onFailure: function(r){
				alert('failure');
			}
		})
	}
	this.loadConfig=function(){
		new Ajax.Request('/lib/core/ajax/loadConfig.php',{
			asynchronous:false,
			onSuccess: function(r,json){
				application.config=r.responseJSON;
			}
		})
	}
	this.loadLangues=function(){
        asynchronous:false,
		new Ajax.Request('/lib/core/ajax/loadLangues.php',{
			onSuccess: function(r){// alert(r.responseText)
				application.langue=r.responseJSON
                // if (debug) debug.print (Object.inspect(r.responseJSON));
				//alert(Object.inspect(r.responseJSON))
			}
		})
	}
	this.createBodyMask=function(fadeDelay){
        if (typeof fadeDelay=='undefined') fadeDelay=0
		if ($$('div.applicationBodyMask').length>0) return;
		var docSize = this.getDocumentSize();
		var mskWidth = Math.max(docSize[0], document.viewport.getWidth());
		var mskHeight = Math.max(docSize[1],screen.availHeight-50 );
        // alert(screen.availHeight);
		var bodyMask = new Element('div', {"class" : "applicationBodyMask", "style" : "position:absolute;top:0px;left:0px;z-index:999990;width:"+mskWidth+"px; height:"+mskHeight+"px;"});
		bodyMask.setOpacity(0);
		$$('body')[0].insert(bodyMask);
		if (fadeDelay!=0){
			new Effect.Appear(bodyMask, {duration:fadeDelay, from:0.0, to:0.5});
		} else {
			bodyMask.setOpacity(1);
		}
	}
	this.updateBodyMask=function(fadeDelay){
		var docSize = this.getDocumentSize();
		var mskHeight = Math.max(docSize[1], document.viewport.getHeight());
		if ($$('div.applicationBodyMask')[0]) $$('div.applicationBodyMask')[0].style.height= mskHeight+'px';
	}
	this.destroyBodyMask=function(fadeDelay){
		if (typeof fadeDelay=='undefined') fadeDelay=0
		if ($$('div.applicationBodyMask').length == 0) return
		var bodyMask=$$('div.applicationBodyMask')[0];
		if (bodyMask) {
			if (fadeDelay!=0){
				new Effect.Appear(bodyMask, {
					duration:fadeDelay,
					from:0.5, to:0.0,
					afterFinish:function(){
						bodyMask.remove();
						this.bodyMask=null;
					}
				});
			} else {
				bodyMask.remove();
				this.bodyMask=null;
			}
		}
	}
	this.enableZoom=function(){
		// par la classe
		$$('img.zoomable','img.zoom').each(function(_img){
			$(_img).onclick=function(){applicationZoom(this);}
			$(_img).style.cursor='pointer';
		});
		// par le lien
		var _domain=window.location.protocol + "//" + window.location.hostname;
		$$('a[href="zoom"]').each(function(_a){
			if(_img=_a.getElementsByTagName('img')[0]) {
				$(_img).onclick=function(){applicationZoom(this);}
				$(_img).style.cursor='pointer';
				$(_a).onclick=function(){return false;}
			}
		})
	}
	this.zoom=function(media,aslike){
        media=$(media);
        //alert(1)
		if (media.hasClassName('msAblbumDiapo')) return false;
		if (typeof(aslike)=='undefined') aslike=false;
		var src=media.src;
		var viewportHeight=document.viewport.getHeight();
		if (src.indexOf('/tools/images/')>1) src = src.split('/tools/images/')[1]
		var regexp = new RegExp("http:\/\/");
		if((regexp.test(src)) && (aslike==false)){
			src = src.replace(regexp, "");
			q=src.indexOf('/')
			src=src.substring(q+1);
		}
		if (src.indexOf('?')>0) src=src.substr(0,src.indexOf('?'));
		this.createBodyMask();
		$$("body")[0].style.cursor='wait';
		style='position:absolute;left:50%;top:50%;width:auto;height:auto;z-index:999999;';
		var d = new Element('div', {'class':'applicationZoom', 'style':style});d.hide();
		var i = new Element('img');
		d.appendChild(i);
		$$("body")[0].appendChild(d);
		d.insert(new Element('p',{'class':'zoomImgAlt'}).update(media.alt));
		$$("body")[0].style.cursor='wait';
		$(i).onload=function(){ //alert('onload');
			window.clearTimeout(zoomWto);
			var d=$$("div.applicationZoom")[0];
			var s = d.getDimensions();
			d.style.marginLeft = -(parseInt(s.width)  / 2) + "px";
			d.style.marginTop = -(parseInt(s.height)  /2) + document.documentElement.scrollTop +"px";
			// alert(media.alt)
			d.show();
			$$("body")[0].style.cursor='default';
		}
		$(i).onerror=function(){//alert("erreur");
			e=i.ancestors()[0];
			if (e) e.remove();
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
		}
		$$('div.applicationBodyMask')[0].onclick=function(){
			e=i.ancestors()[0];
			if (e) e.remove();
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
		}
		$(i).onclick=function(){
			i.ancestors()[0].remove();
			destroyBodyMask();
		}
		var re=new RegExp('^http')
		if (! re.match(src)) src='/tools/images/'+src +'?maxh='+Math.max(viewportHeight-50,250);
		$(i).setAttribute('src',src);
		zoomWto=window.setTimeout(function(){
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
		},5000);
	}
	this.createUserPromptBox=function(sBoxContentUrl, hBoxCustomParam){
        if (($('applicationUserPromptBox')) || (typeof(sBoxContentUrl)!='string') || (sBoxContentUrl=='')) return;
        var isSmartBox=(new Array('xml','tpl').indexOf(sBoxContentUrl.substr(-3,3)) >-1); 
        parameters='pboxContentFile=' + sBoxContentUrl;
        if (isSmartBox===true) parameters=parameters+"&hBoxCustomParam=" + Object.toJSON(hBoxCustomParam);
        this.createBodyMask();
		hBoxParameters = $H({'title':this.nom,'width':'450px','height':'350px','classname':''}); // parametres par default
		hBoxParameters.definedValues=$H();
		var keys = Object.keys(hBoxCustomParam);var values = Object.values(hBoxCustomParam);for (i=0; i<keys.length; i++){hBoxParameters.set(keys[i],values[i]);}
		var url = "/lib/core/ajax/userPromptBox_LoadContent.php";
		var myAjax = new Ajax.Request(url,{
			method: 'get',
			asynchronous : false,
			parameters: parameters,
			onSuccess: function(response){
                    hBoxParameters.set('htmlContent',unescape(response.responseText));
					hBoxParameters.set('width',parseInt(hBoxParameters.get('width')));
					hBoxParameters.set('height',parseInt(hBoxParameters.get('height')));
					pbStyle='position:absolute;left:50%;top:50%;z-index:999999; display:block; overflow:hidden;';
					pbStyle = pbStyle + ';width:'+hBoxParameters.get('width')+'px;height:'+hBoxParameters.get('height')+'px;'
					var promptBox = new Element('div',{'id':'applicationUserPromptBox', 'class':hBoxParameters.get('classname'), 'style':pbStyle});
					promptBox.insert(new Element('div',{'id':'applicationUserPromptBoxTitle','style':'position: absolute;top:0px; left:0px; width: 100%; height:15px; padding-top:4px; padding-left:5px;'}).update(hBoxParameters.get('title')));
					var pbCloseBtn= new Element('a',{'id' :'applicationUserPromptBoxCloseButton', 'href':'javascript:destroyUserPromptBox();','style':'position: absolute;top:2px; right:3px; width: 16px; height:16px; padding-bottom:1px; background-position:center center;background-image:url(/app/img/applicationUserPromptBoxCloseButton.png)'});
					pbCloseBtn.onmouseover=function(){$('applicationUserPromptBoxCloseButton').style.backgroundImage ='url(/app/img/applicationUserPromptBoxCloseButton-hover.png)';}
					pbCloseBtn.onmouseout=function(){$('applicationUserPromptBoxCloseButton').style.backgroundImage ='url(/app/img/applicationUserPromptBoxCloseButton.png)';}
					promptBox.insert(pbCloseBtn)
					promptBox.insert(new Element('div',{'id':'applicationUserPromptBoxContent','style':'position:absolute; top:35px; padding-left:10px; width:inherit; height:auto;'}).update(hBoxParameters.get('htmlContent')));
					promptBox.hide();
                    
 					$$("body")[0].insert(promptBox)
					var s = promptBox.getDimensions();
                    var vpsize=document.viewport.getDimensions();
                    var vpscroll=document.viewport.getScrollOffsets()
					promptBox.style.marginLeft = -(parseInt(s.width)  / 2) + "px";
                    promptBox.style.marginTop = ((-parseInt(s.height)  / 2) + vpscroll.top) + "px";
                    //  alert((-parseInt(s.height)  / 2) + vpscroll.top)
                    /*
                    if (debug) {
                        debug.print("s : " + s.height);
                        debug.add('vp : ' + vpsize.height);
                        debug.add((vpsize.height-s.height)/2);
                        debug.add(promptBox.offsetTop)
                        debug.add(parseInt(((vpsize.height-s.height)/2)+vpscroll.top) +"px");
                        debug.add(promptBox.style.marginTop)
                        
                    }        
                    */           
					var pbDefinedValues=hBoxParameters.get('definedValues');
                    if (isSmartBox===false){
                        if (typeof(pbDefinedValues)!='undefined'){
                            var pbdvkeys = pbDefinedValues.keys();
                            var pbdvValues = pbDefinedValues.values();
                            var elements  = $('applicationUserPromptBoxContent').descendants();
                            for (i=0; i<pbdvkeys.length; i++){
                                if (new RegExp('[.]').match(pbdvkeys[i])) var obj_att=(pbdvkeys[i]).split("."); else var obj_att=new Array(pbdvkeys[i],'innerHTML');
                                elem = elements.find(function(e){return (e.id == obj_att[0]) ;});
                                
                                if (typeof(elem) != 'undefined') {
                                    switch(obj_att[1]){
                                        case "checked":$(elem).checked = parseInt(pbdvValues[i]);break;
                                        case "innerHTML":$(elem).innerHTML = unescape(pbdvValues[i]);break;
                                        case "itemSelected":var selectThis = 'non terminée';$$('select#'+elem.id+' option').each(function(o){if(o.value.toLowerCase()==unescape(pbdvValues[i].toLowerCase())){o.selected = true;}});break;
                                        default:$(elem).setAttribute(obj_att[1],unescape(pbdvValues[i]));
                                    }
                                }
                            }

                        }
                    }
					scripts = $('applicationUserPromptBoxContent').getElementsByTagName('script');
					for (i=0; i<scripts.length; i++) eval(scripts[i].innerHTML)
					(typeof promptboxOnCreate == "function")?promptboxOnCreate():null ; // v2
					promptBox.show();
                    $('applicationUserPromptBoxTitle').onmousedown=function(){
                        promptBox.drag= new Draggable(promptBox, {
                            zindex:999999,
                            ghosting:false,
                            starteffect:function(){},
                            endeffect:function(){}
                        });
                    }
                    $('applicationUserPromptBoxTitle').onmouseup=function(){
                        promptBox.drag.destroy()
                    }
				},
			onFailure: function(){
					alert('echec lors du chargement de la boite utilisateur ' + sBoxContentUrl);
				}
			})
	}
	this.destroyUserPromptBox=function(delai){
	   if (typeof this.onDestroyUserPromptBox=='function') this.onDestroyUserPromptBox();
		if (typeof(delai)=='number'){
			pbWto=window.setTimeout(function(){window.clearTimeout(pbWto);destroyUserPromptBox()},parseInt(delai));
			return
		}
		if ($$('div#applicationUserPromptBox').length == 0) return
		(typeof promptboxOnDestroy == "function")?promptboxOnDestroy():null ; // v2
		this.destroyBodyMask();
		var e=$$('div#applicationUserPromptBox')[0];
		if ($(e)) $$("body")[0].removeChild($(e));
	}
	this.updateUserPromptBox=function(){ // TODO
		return(1);
	}
	this.flatUserPromptBox=function(){
		$$('#applicationUserPromptBox input,#applicationUserPromptBox textarea,#applicationUserPromptBox select').each(function(e1){
			e2=new Element('span',{'class':'pbFlattenElement'});
			inserer=true;
			switch(e1.tagName.toLowerCase()){
				case 'select':
					e2.innerHTML=e1.options(e1.selectedIndex).text;
					break;
				case 'input':
					switch(e1.getAttribute('type').toLowerCase()){
						case 'text':
							e2.innerHTML=e1.value;
							break;
						case 'text':
							e2.innerHTML=e1.value;
							break;
						default:
							inserer=false;
					}
					break;
				default:
					inserer=false;
			}
			p=e1.ancestors()[0];
			if (inserer) p.insertBefore(e2,e1);
			e1.remove();
		})
	}
	this.getQuerystring=function(){
        this.querystring=new Array();
		var qs=location.search.substring(1, location.search.length);
		//alert(qs);
		if (qs.length == 0) return qs;
		qs = qs.replace(/\+/g, ' ');
		var args = qs.split('&');
		this.querystring=$H({});
		for (var i = 0; i < args.length; i++) {
			var pair = args[i].split('=');
			var name = decodeURIComponent(pair[0]);
			var value = (pair.length==2)? decodeURIComponent(pair[1]): name;
			this.querystring[name] = value; // alert(name + ':' + value);
		}
		return this.querystring;
	}
	this.setcookie=function(name,value,expires,path,domain,secure){
     document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
	}

	this.getcookie=function(name){
       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
            return unescape(document.cookie.substring(deb,fin))
            }
        return null;
	}
	this.deletecookie=function(name, path, domain) {
      if (this.getcookie(name)) {
        document.cookie = name + "=" +
          ((path) ? "; path=" + path : "") +
          ((domain) ? "; domain=" + domain : "") +
          "; expires=Thu, 22-Dec-97 22:00:01 GMT";
      }
	}
	this.getDocumentSize=function(){ // retourne un array avec les dimensions du doc
		return new Array((document.documentElement && document.documentElement.scrollWidth) ? document.documentElement.scrollWidth : (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth,(document.documentElement && document.documentElement.scrollHeight) ? document.documentElement.scrollHeight : (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight);
	}
	this.getWindowHeight=function() {
   		var windowHeight = 0;
   	 	if (typeof(window.innerHeight) == 'number') {
        	windowHeight = window.innerHeight;
    	} else {
        	if (document.documentElement && document.documentElement.clientHeight) {
				windowHeight = document.documentElement.clientHeight;
        	} else {
            	if (document.body && document.body.clientHeight) {
                	windowHeight = document.body.clientHeight;
            	}
        	}
    	}
    	return windowHeight;
	}
	this.addEvent=function(obj, evType, fn){

		if (obj.addEventListener){
   			obj.addEventListener(evType, fn, false);
   			return true;
		}
		if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		}
		return false;
	}
	this.isValidEmail=function(email, callback){
		this.createBodyMask();
		application.createBodyMask();
		var thisApp=this;
		var url = '/lib/core/ajax/isValidEmail.php';
		new Ajax.Request(url, {
            method: 'post',
            asynchronous: true,
            parameters: 'email='+email,
            onSuccess: function(r) { // alert(!!r.responseText)
                var datas=r.responseText.split("\n")
                if (typeof callback == 'function') callback(datas[0]==='true')
                thisApp.destroyBodyMask();
            },
            onFailure: function() {
                alert('La requête Ajax a echouée');
                thisApp.destroyBodyMask();
            }
        });
	}
}
//********************************* CLASSIC UPLOAD ***************************
function msClassicUpload(hDefinedValues){// alert(hDefinedValues.extensions);
    if (typeof(hDefinedValues)=='undefined') hDefinedValues=$H();
    var boxTpl='/lib/msclassicupload/boxes/upload.tpl';
    application.createUserPromptBox(boxTpl,({'title':'Envoyer un fichier','width':'400px', 'height':'280px', 'definedValues':hDefinedValues}))
}


//************************************ FORMULAIRES ********************************
function msForm(formulaire){
	if (! $(formulaire)) return false;
    this.formulaire=$(formulaire);
    this.datas=this.formulaire.serialize(true);
	if ($(this.formulaire)) this.inputs=this.formulaire.getInputs();
	// Validation selon la règle edictée par le champ hidden "!rules" du formulaire si il existe
         this.valider=function(callback){ // alert($(this.formulaire).serialize());
        if (! $(this.formulaire)) return;
		parameters=$(this.formulaire).serialize(true);
		$(this.formulaire).disable();
		$$('#'+this.formulaire.id +' .missing').each(function(e){e.removeClassName('missing')})
		var msFormFormulaireId=$(formulaire).id;
		if (msFormFormulaireId=='') {alert('Erreur fatale : le fomulaire n\'a pas d\'id');return};
		var url = '/lib/core/ajax/formValider.php';
        thatForm=this;
		new Ajax.Request(url, {
		method: 'post',
			asynchronous: true,
			parameters: parameters,
			onSuccess: function(r) { // alert(r.responseText)
				$(msFormFormulaireId).enable();
				datas=r.responseText.split("\n")
				if (datas[0]=='ok'){
					if (typeof(callback)=='function'){callback();}
					return;
				} else {
					fields=datas[1].split(';');
					for (i=0; i<fields.length; i++){
						if (fields[i] != ''){
							if ($$('#'+msFormFormulaireId+' *[name="'+fields[i]+'"]')[0]){
								$$('#'+msFormFormulaireId+' *[name="'+fields[i]+'"]')[0].addClassName('missing');
							}
						}
					}
                    if (typeof(thatForm.validationFailure=='function')) thatForm.validationFailure(r);
				}
			},
			onFailure: function() {
				alert('La requête a echouée');
				$(msFormFormulaireId).enable();
			}
		});
	}
	// Envoi du formulaire par mail
	this.envoyer=function(callback){
		parameters=$(this.formulaire).serialize(true); // alert($(this.formulaire).serialize());// return;
		$(this.formulaire).disable();
		var url = '/lib/core/ajax/formEnvoyer.php';
		new Ajax.Request(url, {
			method: 'post',
			asynchronous: true,
			parameters: parameters,
			onSuccess: function(r) {   // alert("RETOUR " + r.responseText + ' cb : ' + typeof(callback));
				if (typeof(callback)=='function'){callback(r);}
			}
		});
	}
	this.setExpediteur=function(fromNom,fromEmail){
		var fe=this.formulaire.getInputs('hidden','!fromNom');
		(fe.length>0)?fe[0].value=fromNom:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!fromNom','value':fromNom}));
		fe=this.formulaire.getInputs('hidden','!fromEmail');
		(fe.length>0)?fe[0].value=fromEmail:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!fromEmail','value':fromEmail}));
	}
    this.setFrom=function(fromNom,fromEmail){
		var fe=this.formulaire.getInputs('hidden','!fromNom');
		(fe.length>0)?fe[0].value=fromNom:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!fromNom','value':fromNom}));
		fe=this.formulaire.getInputs('hidden','!fromEmail');
		(fe.length>0)?fe[0].value=fromEmail:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!fromEmail','value':fromEmail}));
	}
	this.setDestinataire=function(destinataire){
		var fe=this.formulaire.getInputs('hidden','!to');
		(fe.length>0)?fe[0].value=destinataire:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!to','value':destinataire}));
	}
	this.setTo=function(destinataire){
		var fe=this.formulaire.getInputs('hidden','!to');
		(fe.length>0)?fe[0].value=destinataire:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!to','value':destinataire}));
	}
    this.setSujet=function(subject){
		var fe=this.formulaire.getInputs('hidden','!subject');
		(fe.length>0)?fe[0].value=subject:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!subject','value':subject}));
	}
    this.setSubject=function(subject){
		var fe=this.formulaire.getInputs('hidden','!subject');
		(fe.length>0)?fe[0].value=subject:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!subject','value':subject}));
	}
	this.setTemplate=function(template){
		var fe=this.formulaire.getInputs('hidden','!mailTemplate');
		(fe.length>0)?fe[0].value=template:this.formulaire.insert(new Element('input',{'type':'hidden','name':'!mailTemplate','value':template}));
	}

    this.setChamp=function(_name,_value){
		this.setField(_name,_value)
	}
	this.setField=function(_name,_value){
		var fe=this.formulaire.getInputs('hidden',_name);
		(fe.length>0)?fe[0].value=_value:this.formulaire.insert(new Element('input',{'type':'hidden','name':_name,'value':_value}));
	}

}

function msAlbum(container, nodesDiapos, zoomDiapos){
	if (typeof(container) != 'undefined') this.container=container;
	this.title='';
	this.diapos=new Array();
	this.maxHeight=parseInt(document.viewport.getHeight()*.70);
	this.zoomCurrentIdx=0;
	this.slideshowPause=false;
	var containerW=container.offsetWidth;
	var containerH=container.offsetHeight;
    //if (debug) alert((typeof zoomDiapo) )
	if (typeof zoomDiapos == 'undefined') zoomDiapos=true
	if (typeof nodesDiapos != 'undefined') {
            var thisAlbum=this;
            thisAlbum.diapos= this.container.select(nodesDiapos);
            // if (debug) alert(nodesDiapos +  ' ' +thisAlbum.diapos.length)
            thisAlbum.diapos.each(function(diapo){
                // alert(diapo.offsetWidth);
                // diapo.style.left=parseInt((containerW-diapo.offsetWidth)/2)+'px';
                // diapo.style.top=parseInt((containerH-diapo.offsetHeight)/2)+'px';
                diapo.select('img').invoke('addClassName','msAblbumDiapo');
                diapo.onclick=function(){
                    thisAlbum.zoom(thisAlbum.diapos.indexOf(this));
                    return false;
		}
       });
	}
	this.slideshow=function(timeout){
        // if (debug()) alert(debug)
		// alert(this.slideshowPause); 
		if (this.slideshowPause==true) return
		if (this.diapos.length < 2) return;
		if (typeof timeout == 'undefined') timeout=3000
		var thisAlbum=this;
		var oCurrent=null;
		this.diapos.each(function(_e){
			if (_e.hasClassName('current'))	oCurrent=_e
		});
		if (oCurrent==null) {
			this.diapos[0].addClassName('current');
			window.setTimeout(function(){thisAlbum.slideshow()},timeout)
			return
		}
		var idxCrnt=this.diapos.indexOf(oCurrent)
		var idxNext=idxCrnt+1;
		if (idxNext > (this.diapos.length-1)) idxNext=0;
		var oNext=this.diapos[idxNext];
		oNext.setOpacity(0);
		oNext.addClassName('next');
		new Effect.Opacity(oNext, {
			from: 0,
			to: 1,
			duration: 1,
			afterFinish:function(){
				oNext.addClassName('current');
				oNext.removeClassName('next');
				oCurrent.removeClassName('current');
				window.setTimeout(function(){thisAlbum.slideshow()},timeout)
			}
		});
	}
	this.zoom=function(firstDispo){
		if (typeof (firstDispo)== 'undefined') firstDispo=0;
		this.slideshowPause=true;
		var oBody=$$("body")[0]
		oBody.style.cursor='wait';
		application.createBodyMask(2);
		var thisAlbum=this
		style='position:absolute;left:50%;top:50%;width:auto;height:auto;z-index:999999;';
		this.div= new Element('div', {'class':'applicationAlbumZoom', 'style':style});this.div.hide();
		var _center= new Element('div',{'class':'applicationAlbumZoomCenter'});
		_center.setStyle({'float':'left'})
		this.zoomImg = new Element('img');
		this.zoomTags=new Element('div',{'class':'tags'})
		this.zoomTitre=new Element('span',{'class':'titre'})
		this.zoomTexte=new Element('span',{'class':'texte'})
		this.zoomTags.appendChild(this.zoomTitre);
		this.zoomTags.appendChild(this.zoomTexte);
		_center.appendChild(this.zoomImg);
		_center.appendChild(this.zoomTags);
		var aLeft=new Element('a', {'class':'applicationAlbumZoomMvLeft'})
		var aRight=new Element('a', {'class':'applicationAlbumZoomMvRight'})
		aLeft.onclick=function(){thisAlbum.zoomDiapo('left')}
		aRight.onclick=function(){thisAlbum.zoomDiapo('right')}
		if (this.title != '') this.div.appendChild(new Element('p',{'class':'albumTitle'}).update(this.title));
		this.div.appendChild(aLeft);
		this.div.appendChild(_center);
		this.div.appendChild(aRight);
		//this.div.appendChild(_tags)
		oBody.appendChild(this.div);
		this.zoomImg.onload=function(){ //alert('onload');
			window.clearTimeout(zoomWto);
			var d=$$("div.applicationAlbum")[0];
			var s = thisAlbum.div.getDimensions();
			thisAlbum.div.style.marginLeft = -(parseInt(s.width)  / 2) + "px";
			thisAlbum.div.style.marginTop = -(parseInt(s.height)  /2) + document.documentElement.scrollTop +"px";
			thisAlbum.div.show();
			$$("body")[0].style.cursor='default';
			var height=thisAlbum.zoomImg.offsetHeight
			$$("div.applicationAlbumZoom a").each(function(_a){_a.setStyle({'marginTop':parseInt(height/2)+'px'})})
			thisAlbum.zoomTags.show();
			thisAlbum.zoomImg.setOpacity(1);
		}
		this.zoomImg.onerror=function(){// alert("erreur");
			var e=this.img.ancestors()[0];
			if (e) e.remove();
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
		}
        this.closeZoom=function(){
            var e=$$('div.applicationAlbumZoom')[0];
			if (e) e.remove();
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
			thisAlbum.slideshowPause=false;
        }
		$$('div.applicationBodyMask')[0].onclick=function(){
			var e=$$('div.applicationAlbumZoom')[0];
			if (e) e.remove();
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
			thisAlbum.slideshowPause=false;
		}
		if (typeof this.zoomImg_onclick=='function') {
            this.zoomImg.onclick=this.zoomImg_onclick;
        }else {
            this.zoomImg.onclick=function(){
                thisAlbum.zoomDiapo('right');
            }
		}

		this.zoomDiapo(firstDispo);
	}
	this.zoomDiapo=function(mvTo){
		$$("body")[0].style.cursor='wait';
		this.zoomTags.hide();
		this.zoomImg.setOpacity(0.3);
		switch(mvTo){
			case 'right':
				this.zoomCurrentIdx++;
				break;
			case 'left':
				this.zoomCurrentIdx--;
				break;
			default:
				this.zoomCurrentIdx=mvTo;
		}
		if (this.zoomCurrentIdx >= this.diapos.length) this.zoomCurrentIdx=0;
		if (this.zoomCurrentIdx < 0) this.zoomCurrentIdx = this.diapos.length-1;
		var diapo=this.diapos[this.zoomCurrentIdx];
		var diapoImg=(diapo.tagName!='IMG')?diapo.select('img')[0]:diapo;
		var src=diapoImg.src;
		var alt=diapoImg.alt;
		if(diapo.select('.titre')[0]) this.zoomTitre.innerHTML=diapo.select('.titre')[0].innerHTML;
		if(diapo.select('.texte')[0]) this.zoomTexte.innerHTML=diapo.select('.texte')[0].innerHTML;

		if (src.indexOf('/tools/images/')>1) src = src.split('/tools/images/')[1]
		var regexp = new RegExp("http:\/\/");
		// if((regexp.test(src)) && (aslike==false)){
		if(regexp.test(src)) {
			src = src.replace(regexp, "");
			q=src.indexOf('/')
			src=src.substring(q+1);
		}
		if (src.indexOf('?')>0) src=src.substr(0,src.indexOf('?'));
		var re=new RegExp('^http')
		if (! re.match(src)) src='/tools/images/'+src +'?maxh='+Math.max(this.maxHeight,250);;
		this.zoomImg.setAttribute('src',src);
		this.zoomImg.setAttribute('alt',alt);
		zoomWto=window.setTimeout(function(){
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
		},7000);
	}
}



// ************************************ POST IT DE DEBOGAGE ******************************
function Debug(){
    if ($('debug')) return;
	var _div=new Element('div',{'id':'debug'});
	_div.setStyle({'position':'absolute', 'top':'10px', 'left':'10px', 'width':'300px', 'textAlign':'left', 'backgroundColor':'#f0ffff', 'padding':'10px'}); // , 'height:auto','border':'#800 solid 1px', 'color':'#800' });
	this._div=_div;
	$$('body')[0].insert(_div);
	this.add=function(text){
	this._div.innerHTML=this._div.innerHTML+text+'<br>';
	}
	this.clear=function(){
		this._div.innerHTML='';
	}
	this.print=function(text){
		this._div.innerHTML=text+'<br>';
	}
	this.move=function(){
		$('debug').style.top=(document.viewport.getScrollOffsets().top+10)+'px'
	}
}

function msNewsletter(){
   this.envoiId='';
   this.isClick=false;
   this.tracker=function(){   if (debug) debug.add('this.isClick : ' +this.isClick)
       if(this.isClick){
            var _now=new Date();
            var nowTime=_now.getTime();
            var expireTime=new Date();
            expireTime.setTime(_now.getTime()+(365*24*60*60*1000));
            application.setcookie('nl11ev', nowTime, expireTime);
        }
        var url = '/lib/newsletters2011/ajax/tracker.php';
        new Ajax.Request(url, {
            method: 'get',
            asynchronous: true,
            parameters: 'envoiId='+this.envoiId+'&isClick='+this.isClick,
            onSuccess: function(r) {
               // alert(r.responseText);
            },
            onfailure: function(r) {
                alert("ECHEC ");
            }
        });
    }
}

// ****************************************** MISC ******************************
destroyUserPromptBox=function(delai){
	application.destroyUserPromptBox(delai);
}
destroyBodyMask=function(){
	application.destroyBodyMask();
}
applicationZoom=function(media){
	application.zoom(media);
}
getWindowHeight=function(){
	return application.getWindowHeight()
}

// ******************************** INITIALISATION ****************************
var application = new msApplication();
application.browser = application.getBrowser();
application.getQuerystring();
application.loadConfig();
var hBoxParameters =$H();
var windowOnloadFunctions = new Array;
var debug=false


// ******************************** NEWSLETTER ****************************
if ((typeof application.querystring._nlck != 'undefined') || (application.getcookie('nl11ev')!=null)){
    var newsletter=new msNewsletter();
    if (typeof application.querystring._nlck != 'undefined'){
        newsletter.envoiId=application.querystring._nlck;
        newsletter.isClick=true;
    } else {
        newsletter.envoiId=application.getcookie('nl11ev')
    }
    newsletter.tracker();
}
