// JavaScript Document
function msApplication(){
	this.getBrowser=function(){
		var sBrowser = 'undef';
		if ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1)) sBrowser = 'ie6';
		return sBrowser;
	}
	this.loadScript=function(src){
		document.writeln('<scr'+'ipt type="text/javascript" src="'+src+'"></scr'+'ipt>');
	}
	this.loadConfig=function(){
		new Ajax.Request('/lib/core/ajax/loadConfig.php',{
			onSuccess: function(r,json){
				application.config=r.responseJSON;
			}
		})
	}
	this.loadLangues=function(){
		new Ajax.Request('/lib/core/ajax/loadLangues.php',{
			onSuccess: function(r){
				application.langue=r.responseJSON
				//alert(Object.inspect(r.responseJSON))
			}
		})
	}
	this.createBodyMask=function(){
		if ($$('div.applicationBodyMask').length>0) return;
		var docSize = this.getDocumentSize();
		var mskWidth = Math.max(docSize[0], screen.width);
		var mskHeight = Math.max(docSize[1], screen.height);
		var bodyMask = new Element('div', {"class" : "applicationBodyMask", "style" : "position:absolute;top:0px;left:0px;z-index:999990;width:"+mskWidth+"px; height:"+mskHeight+"px;"});
		$$('body')[0].insert(bodyMask);
	}
	this.destroyBodyMask=function(){
		if ($$('div.applicationBodyMask').length == 0) return
		var e=$$('div.applicationBodyMask')[0];
		if ($(e)) $$("body")[0].removeChild($(e));
		this.bodyMask=null;
	}
	this.enableZoom=function(){
		imgZoomable = $$('img.zoomable','img.zoom');
		imgZoomable.each(function(e){
			$(e).onclick=function(){applicationZoom(this);}
			$(e).style.cursor='pointer';
		});
	}
	this.zoom=function(media,aslike){
		if (typeof(aslike)=='undefined') aslike=false;
		var src=media.src;
		windowHeight=this.getWindowHeight();
		if (src.indexOf('/tools/images/')>1) {
			datas = src.split('/tools/images/');
			src=datas[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;border:#eee 20px solid;z-index:999999;';
		var d = new Element('div', {'id':'applicationZoom', 'style':style});d.hide();
		var i = new Element('img');
		d.appendChild(i);
		$$("body")[0].appendChild(d);
		$$("body")[0].style.cursor='wait';
		$(i).onload=function(){ //alert('onload');
			window.clearTimeout(zoomWto);
			var d=$("applicationZoom");
			var s = d.getDimensions();
			d.style.marginLeft = -(parseInt(s.width)  / 2) + "px";
			d.style.marginTop = -(parseInt(s.height)  /2) + document.documentElement.scrollTop +"px";  
			d.show();
			$$("body")[0].style.cursor='default';
		}
		$(i).onerror=function(){//alert("eereur");
			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 +'?max='+Math.max(windowHeight-40,250); 
		$(i).setAttribute('src',src);
		zoomWto=window.setTimeout(function(){
			destroyBodyMask();
			$$("body")[0].style.cursor='default';
		},3000);
	}
	this.createUserPromptBox=function(sBoxContentUrl, hBoxCustomParam){ 
		if (($('applicationUserPromptBox')) || (typeof(sBoxContentUrl)!='string') || (sBoxContentUrl=='')) return;
		this.createBodyMask();
		hBoxParameters = $H({'title':this.nom,'width':'450px','height':'350pw','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: 'pboxContentFile=' + sBoxContentUrl,
			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:18px; padding-top:2px; 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; left:10px; width:auto; height:auto;'}).update(hBoxParameters.get('htmlContent')));
					promptBox.hide();
					$$("body")[0].insert(promptBox)
					var s = promptBox.getDimensions();
					promptBox.style.marginLeft = -(parseInt(s.width)  / 2) + "px";
					promptBox.style.marginTop = -(parseInt(s.height)  /2) + document.documentElement.scrollTop +"px";  
					var pbDefinedValues=hBoxParameters.get('definedValues');
					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();
				},
			onFailure: function(){
					alert('echec lors du chargement de la boite utilisateur ' + sBoxContentUrl);
				}
			})
	}
	this.destroyUserPromptBox=function(delai){
		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(){
		qs=location.search.substring(1, location.search.length);
		if (qs.length == 0) return;
		qs = qs.replace(/\+/g, ' ');
		var args = qs.split('&');
		this.querystring=new Array();
		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);
		}
	}
	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
		// var w=document.documentElement.offsetWidth;
		// var h=document.documentElement.offsetHeight;
		// var size=new Array(w,h);
		// return size;
		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; 
	}
}

function msForm(formulaire){
	this.formulaire=$(formulaire);
	this.valider=function(callback){
		
		if (! $(this.formulaire)) return;
		parameters=$(this.formulaire).serialize(true);
		$(this.formulaire).disable();
		var msFormFormulaireId=$(formulaire).id;
		if (msFormFormulaireId=='') {alert('Errreur fatale : le fomulaire n\'a pas d\'id');return};
		$$('#'+msFormFormulaireId +' *').each(function(e){e.removeClassName('missing')})
		
		var url = '/lib/core/ajax/formValider.php';
		new Ajax.Request(url, {
		method: 'post',
			asynchronous: true,
			parameters: parameters,
			onSuccess: function(r) {  if (debug==true) 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'); 
							}	
						}
					}
				}
			},
			onFailure: function() {
				alert('La requête a echouée');
				$(msFormFormulaireId).enable();
			}
		});
		this.envoyer=function(callback){
			parameters=$(this.formulaire).serialize(); // ,alert(parameters);//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);
					if (typeof(callback)=='function'){callback(r);}
				}
			});
		}
	}
	this.setExpediteur=function(fromNom,fromEmail){
		this.formulaire.insert(new Element('input',{'type':'hidden','name':'!fromNom','value':fromNom}));
		this.formulaire.insert(new Element('input',{'type':'hidden','name':'!fromEmail','value':fromEmail}));
	}
	this.setDestinataire=function(destinataire){
		this.formulaire.insert(new Element('input',{'type':'hidden','name':'!to','value':destinataire}));
	}
	this.setSujet=function(subject){
		this.formulaire.insert(new Element('input',{'type':'hidden','name':'!subject','value':subject}));
	}
	this.setTemplate=function(template){
		//alert(3);
		this.formulaire.insert(new Element('input',{'type':'text','name':'!mailTemplate','value':template}));
	}
}
var application = new msApplication(); 
application.browser = application.getBrowser();
application.loadConfig();
application.loadLangues();
application.lang=application.getcookie('lang');
var hBoxParameters =$H(); 
var windowOnloadFunctions = new Array;
var debug=false; 

destroyUserPromptBox=function(delai){
	application.destroyUserPromptBox(delai);
}
destroyBodyMask=function(){
	application.destroyBodyMask();
}
applicationZoom=function(media){
	application.zoom(media);
}
getWindowHeight=function(){
	return application.getWindowHeight()
}
