/**
* WEBAPP PFZONE v3.00
* Nécessite mootools.js v1.2
* --- Note sur mootools:ligne 3673: ajax mod , virer la gestion xml "<root>" pour request.HTML vu que mon code est pas forcément compliant XHTML.
*
* Element addon :
* 	- recenter/show/hide/toggle (fading)
*   - tobox (place en boite)
* 	- zoomTo(to) / zoomRelativeTo(to)
* 	- deactivate((string)waiting) : desactive un lien. Waiting on donne la class waiting et on remplace le corps avec waiting.
*   - setWaiting(txt) : rend un div en mode waiting
*
* Liste des variables à instancier avant d'appeler ce script:
*
* SID = sessionid courante;
* appversion = Numero de version de l'application en cours;
* app_main = window;
* myUrl = l'url de la page courant;
* cookieset = Si les cookies sont acceptés ou non
* lenom= Le nickname en cours
* force= Bool de forcage pour l'opération de checkmail
* last_id = Dernier userid connu dans cette page
* nbrmess = Nombre de messages en attente d'etre délivrés
* modif = Une modification a eu lieu et nécessite un enregistrement
* currentpage = page courante
* myZone = zone particulière à laquelle appartient l'utilisateur;
* _mailinterval = en seconde, temps entre deux appels à checkmail
*
* --------------------------- PFZAPP Fonction étendues pour la gestion de contenu:
* - pace(id,min,force):bool = sorte de sémaphore pour tester ou non si un id est dispo. Empeche l'execution d'une fonction plus d'1 fois toutes les MIN secondes.
* - script(url,opt) = lance un script
* - loadContent(url,destination_layer/predefined_type,options)
*
*/

var _DEFAULT_CHARSET = 'windows-1252';
//var _DEFAULT_CHARSET = 'utf-8';


var myTips,myInfoBox,winsize=Window.getSize(),winscroll=document.getScroll();
function coreInit() {
	if (Browser.Engine.trident3 || Browser.Engine.webkit && Browser.Engine.version<420)
		enable_effects=false;
	myTips = new Tips('.infotool',{className:'infotool',fixed:false,showDelay:50,hideDelay:50});
	myInfoBox = new Roar({position:'lowerRight',duration:5000});
}

function makeUrl(url,opt) {
	var ret;
	if(!$chk(opt)) opt="";
	else if($type(opt)!="string") opt=$H(opt).toQueryString();
	var base = url.split("?");
	if (base.length>1) {
		url=base[0];
		if (opt!="") opt+="&"+base[1];
		else opt=base[1];
	}
	ret = url;
	if (!cookieset) ret+="?sid="+SID;
	if (opt!="") {if (cookieset) ret+="?"; else ret+="&";ret+=opt;}
	return ret;
}
/**
* Retourne un objet url,options
*/
function extractUrl(url) {
	if ($type(url)!="string") url="";
	var ret={url:"",options:{}}, base = url.split("?");
	if (base.length>1) {
		url=base[0];
		var k,v;
		base[1].split("&").each(function(v){
			if (v!="") {k=v.split("=",2);if(k.length==1)k[1]="";ret.options[k[0]]=k[1];}
		});
	}
	ret.url = url;
	return ret;
}
function extractForm(formid) {
	var opt = {},i=0;
	myForm=$(formid);
	if(myForm) { $each(myForm.getElements("input,textarea,select"),function(e){
		if (e.type=="select-multiple") {
			i=0;
			$each(e.getChildren(),function(d){
				opt[e.name+'['+d.value+']']=d.selected?1:0;
			})
		}
		else {
			opt[e.name]=e.value;
		}
	});}
	return opt;
}
var preloadImages=new Array();var preloadImagesi=0;
function preloadImage(img) {preloadImagesi++;preloadImages[preloadImagesi]=new Image();preloadImages[preloadImagesi].src=img;}
function changeImage(imgid, url, onload) {
	var thisimg = $(imgid);
	if (!$chk(thisimg)) return null;
	if (!$chk(url)) return null;
	if (Browser.Engine.trident && thisimg.isFixed) {
		var currentAlphaImg = thisimg.filters(0).src
		if (currentAlphaImg != url) {
			thisimg.filters(0).src = url;
		}
	} else {
		if (thisimg.src != url) {
			thisimg.src = url;
		}
	}
	if ($type(onload)=="function") thisimg.addEvent('load',onload);
	return thisimg;
}

/***
* flipLayer(id_layer)
* retourne
**/
var this_disp = new Array();
function flipLayer(thislayer) {
	var thisdiv=document.getElementById('obj_'+thislayer+'_div');
	var thisimg=document.getElementById('obj_'+thislayer+'_img');
	if (thisdiv.style.display == 'none') { // ouvert
		thisdiv.style.display = 'block';
		if (thisimg && thisimg.picon) changeImage('obj_'+thislayer+'_img', thisimg.picon);
		else if (thisimg) thisimg.src = '/images/picto_down.gif';
		this_disp[thislayer] = 1;
		return true;
	} else {                               // fermé
		thisdiv.style.display = 'none';
		if (thisimg && thisimg.picoff) changeImage('obj_'+thislayer+'_img', thisimg.picoff);
		else if (thisimg) thisimg.src = '/images/arrow_right.png';
		this_disp[thislayer] = 0;
		return false;
	}
}
var this_disp_family = new Array();
function swapLayer(layer_family, layerb) {
	flipLayer(layer_family.toString()+this_disp_family[layer_family].toString());
	flipLayer(layer_family.toString()+layerb.toString());
	this_disp_family[layer_family] = layerb;
}


/** Popup
* PFZONE@2008 / rev1.0
*
* info(title,content)   : affiche une bulle info
* main((str)url,(obj)opt,(obj)options)
*                           : ouvre un popup interne
* openwin(url,opt,title,scrollable,resizable,width,height,options)
*                           : ouvre un popup window
* message(content,timeout,onclose)
*                           : ouvre un popup purement informatif
*
* ---- Fonction de base
* open(id,options)          : ouvre un popup
* close(id)                 : ferme le popup
* reload(id,url,opt,options): reload le popup(id)
* seed(id)                  : récupère le numero de seed pour un popupid,
* getid(id)					: recupère la référence de l'element du popup / null si non
* last()					: récupère la ref du dernier élément ouvert / null si non
*
* OPTIONS:
*   type: 0:place options.content dans inner, 1:winpopup, 2:inner
* 	url:
* 	urlparam:
*   setFocus: objid to focus on
*   onLoad: fnct
*   onClose:
*/
var popup={
	current: '',					// Current id ouvert (pour les popup, c'est vide, le popup inner, main...)
	options: {
		type:1,                     // Window Type
		width:500,
		height:240,
		title:'',                   // Title
		sc:true,                    // SCrollable
		rs:true,                    // ReSize
		url:'main.php',             // url à appeler
		urlparam:{},                // parametres à transmettre avec l'url
		content:'Contenu par défaut',
		events:{},
		timeout:0,
		setFocus:false,             // Element sur lequel placer le focus au chargement du popup
		onLoad: false,
		onClose: false,
		onCloseCheck: function(){return true;}	// Permet de faire un test avant fermeture. Doit retourner true ou false.
	},
	/**
	* Initialise la page avec le winid
	**/
	init:function(id){
		this.opened.set(id,{ seed:0, type:false, timer:false, el:false });
	},
	opened: new Hash(),      // chaque id a 'el' à false si fermé, sinon l'élement correspondant
	info:function(title,text,onclick) {
		// UTILISE ROAR
		myInfoBox.alert(title,text);
		if ($type(onclick)=="function") { myInfoBox.items.getLast().addEvent('click', onclick); }
	},
	reload: function(id,opt) {
		if (!$defined(opt)) opt={};
		var myPopup = this.getid(id);
		if (myPopup==null) return false;
		myPopup.urlparam = $merge(myPopup.urlparam,opt);
		this.open(id,myPopup);
	},
	main: function(url,opt,options) {
		this.inner('main',url,opt,options);
	},
	inner: function(id,url,opt,options) {
		if (!$defined(options)) options={}; options=$merge({'type':2,'url':url,'urlparam':opt},options);
		this.open(id,options);
	},
	openwin: function(url,opt,title,sc,rs,w,h,options) {
		if (!$defined(options)) options={}; options=$merge({'type':1,'url':url,'urlparam':opt,'width':w,'height':h,'title':title,'sc':sc,'rs':rs},options);
		this.open(title, options);
	},
	message: function(content,timeout,options) {
		if(!$defined(options)) options={};
		if(!$chk(timeout)) timeout=0;
		options=$merge({'type':0,'content':'<div class="popmessage">'+content+'</div>','timeout':timeout},options);
		this.open('main',options);
	},
	seed:function(id) {
		if(this.opened.has(id)) return this.opened.get(id).seed; else return 0;
	},
	/**
	* @param string id de la fenetre
	* @param array options
	*   type: 0:place options.content dans inner, 1:winpopup, 2:inner
	* 	url:
	* 	urlparam:
	*   setFocus: objid to focus on
	*   onLoad: fnct
	*   onClose:
	*/
	open: function(id,options) {
		if (!$defined(options)) options={};
		if (!$defined(options.type)) { alert('PFZAPP:POPUP:OPEN:NO_TYPE');return false;}
		if (!this.opened.has(id)) this.opened.set(id,{
			seed:0,
			type:-1,
			url:'',urlparam:'',
			timer:false,
			el:false
		});
		var myPopup = this.opened.get(id);
		// Clear les onLoad, timers et incrémente le seed si réouverture depuis ancien timeout
		myPopup.onLoad="";
		$clear(myPopup.timer); myPopup.timer = false; myPopup.seed++;
		// Retabli les options
		options=$merge(this.options,options);
		// Retabli le type
		var isAlreadyOpen = (myPopup.type>=0);
		myPopup.type=Number(options.type);

		if (options.setFocus!="") this.setOnLoad(id,"if ($('"+options.setFocus+"')) $('"+options.setFocus+"').focus();");

		// Retabli les url et urlparam si besoin
		var simple_url,urlparam = options.urlparam; if ($defined(options.url)) { var extracted_url = extractUrl(options.url); simple_url = extracted_url.url; urlparam = $merge(extracted_url.options,urlparam,{'winid':id}); }

		// Options à setter pour la squeezebox
		if (myPopup.type==0 || myPopup.type==2) {
			options.events.onShow = function(){popup.onComplete(id);};
			if (options.onLoad!==false) {
				this.setOnLoad(id,options.onLoad);
			} else {;}
			if (options.onClose!==false) {
				options.events.onClose = options.onClose;
			} else {;}
			if (options.onCloseCheck!==false) {
				options.events.closable = options.onCloseCheck;
			} else {;}
		}
		switch(myPopup.type) {
			case 0: // UTILISE SQUEEZEBOX
				var newTxtContent = new Element('div',{'html':options.content});
				newTxtContent.setStyles({width:options.width, height:options.height});
				myPopup.el = SqueezeBox.open(newTxtContent, $merge({'handler':'adopt'},options.events));
				break;
			case 1:
				myPopup.el = window.open(makeUrl(simple_url,urlparam), options.title, 'location=no,toolbar=no,menubar=no,scrollbars='+(options.sc?"yes":"no")+',status=no,resizable='+(options.rs?"yes":"no")+',width='+options.w+',height='+options.h);
				if (myPopup.el == null ) alert(_ANTIPOPUP);
				break;
			case -2: // Reload le squeezebox
			case 2: // UTILISE SQUEEZEBOX
				var sq_options = $merge({
					size:{x:options.width,y:options.height},
					handler:'ajax',
					ajaxOptions: { data:urlparam, onComplete:function(){;} },
					onOpen: function(){setTimeout(function(){
						if(Browser.Engine.trident4){ $$('img[src$=png]').each(function(img, i) {IE_fixPNG(img);});}
					},100)}
				},options.events);
				//alert(simple_url+"--"+JSON.encode(sq_options));
				myPopup.el = SqueezeBox.open(simple_url, sq_options );
				break;
			case 3:
				break;
			case -1: // Reload le popup
				document.location.href = makeUrl(simple_url,urlparam);
		}
		if (options.timeout>0) { if (options.timeout<500) options.timeout=500; myPopup.timer = popup.close.delay(options.timeout,this,id); }

		myPopup.url = simple_url;
		myPopup.urlparam = urlparam;
		this.opened.set(id,myPopup);
		this.current = id;
		return myPopup.el;
	},
	resize: function(id,x,y){
		if (!this.opened.has(id)) return false;
		var auto = (!$chk(x));
		var myPopup = this.opened.get(id); if (!myPopup.el) return false;
		var el = myPopup.el;
		switch(this.opened[id].type) {
			case 0: case 2:
				el.resize('auto'); break;
			case 1:
				if (auto) {
					maxX=screen.availWidth-50;
					maxY=screen.availHeight-50;
					var size=$(el).getScrollSize();
					var newx=size.x>maxX?size.x=maxX:size.x;
					var newy=size.y>maxY?size.y=maxY:size.y;
					el.resizeTo(newx,newy);
				} else
					el.resizeTo(x,y);
				break;
		}
		return this;
	},
	center: function(id) {
		if (!this.opened.has(id)) return false;
		if (this.opened[id].type==1) {
			el = this.opened[id].el;
			var size=$(el).getScrollSize();
			maxX=(screen.availWidth+10)/2;
			maxY=(screen.availHeight+30)/2-50;
			el.moveTo(mapX,mapY);
		}
		return this;
	},
	focus: function(id) {
		if (!this.opened.has(id)) return false; this.opened[id].el.focus(); return true;
	},
	setOnLoad : function(id,script) {
		if (!this.opened.has(id)) return false;
		if ($type(script)=="function") script="("+script.toString()+").apply(this);";
		this.opened[id].onLoad += script;
		return true;
	},
	onComplete:function(id) {
		if (this.opened.has(id)) {
			switch (this.opened[id].type) {
				case 0:case 2:
					this.setOnLoad(id,"SqueezeBox.removeEvents('show');popup.resize('"+id+"');");
					break;
			}
			try{eval(this.opened[id].onLoad)} catch(e) {alert('Erreur popup.complete('+id+'):'+this.opened[id].onLoad+'\n'+JSON.encode(e))};
		}
	},
	close: function(id,recurs) {
		if (!this.opened.has(id)) this.opened.set(id,{type:-1,timer:false,el:false});
		if (eval(this.opened[id].onCloseCheck)==false) return false;
		if (!$chk(recurs)) recurs=0; recurs++;
		var myPopup = this.opened.get(id); myPopup.timer = $clear(myPopup.timer);
		switch(myPopup.type) {
			case 1:
				myPopup.el.close(); break;
			case 0:case 2:
				if (!SqueezeBox.isOpen && recurs<100) {popup.close.delay(50,this,[id,recurs]); return false; }
				else SqueezeBox.close();
				break;
		}
		myPopup.type=-1;
		this.opened.set(id,myPopup);
		this.current = false;
		return true;
	},
	getid: function(id) {
		if (!this.opened.has(id) || !$defined(this.opened.get(id).type) || this.opened.get(id).type<0) return null;
		else return this.opened.get(id);
	},
	last: function(){
		if (this.current==false) return false;
		var myPopup = this.getid(this.current);
		if (myPopup==null) return false;
		else return myPopup;
	}
}
/** popError
* PFZone(2008)
* revision 1.0
*
*
* - default_div:string      = main div pour afficher l'erreur
* - main(message)           = afficher le message d'erreur dans le maindiv
* - open(div,txt,timeout)   = affiche sur le div. Timeout: backup le contenu et le raffiche au bout de n secondes
* - close(div)              = Si !MAIN S'il existe un backup, réaffiche le backup sinon vire l'affichage
*/
var popError = {
	default_div:'appmainerror',
	opened:{},
	timer:null,
	main: function(message) {
		this.open(default_div,message)
	},
	close: function(div) {
		if (!$defined(div)) div=this.default_div;
		if (!$defined(this.opened[div])) return false;
		var thisdiv=$(div);
		if (div==this.default_div) {thisdiv.hide();}
		else { thisdiv.update(this.opened[div].backup); }
		this.opened[div].open=false;
		return false;
	},
	open: function(div,message,timeout) {
		if ($defined(div) && div!='main') {
			var thisdiv=$(div);
			if ($type(thisdiv)!=="element") return false;
		} else {
			div=this.default_div;
			var thisdiv=$(this.default_div);
			thisdiv.show();
		}
		//alert(JSON.encode(thisdiv.getStyles('display','height','zIndex')));
		this.opened[div]={'opened':true,'backup':thisdiv.get("html")};
		thisdiv.update(message);
		if (enable_effects) new Fx.Morph(thisdiv, {duration: 400, transition: Fx.Transitions.Cubic.easeOut}).start('.poperror-error')
								.chain(function(){this.start('.poperror-normal')})
								.chain(function(){this.start('.poperror-error')})
								.chain(function(){this.start('.poperror-normal')});
		if ($chk(timeout)) this.timer=setTimeout(function(){popError.close(div);},timeout);
		return true;
	}
}

var pfzapp = {
	paces: new Hash(),      // Gere les exclus et les temps de retry
	requests: new Hash(),

	pace: function(paceid,min,force) {
		var now=(new Date()).valueOf();
		if (!this.paces.has(paceid)) this.paces.set(paceid,{ init:new Date(), last:0 })
		if (force || (now-this.paces[paceid].last)>min) {
			this.paces[paceid].last = now;
			return true;
		} else return false;
	},
	script: function(url,opt) { this.loadContent(url,'script',opt); },
	/** loadContent(String url, Object url_options, String destination_layer/fonction)
		destination_layer = "script"  pour evaluer le truc */
	loadContent: function (url,destination,opt,onComplete) {
		var myUrl = this.cleanUrl(url,opt);
		if ($type(onComplete)!="function") onComplete=$empty;
		if (destination=="script") {
			var myHTMLRequest = new Request({
				url:myUrl.url,
				method:'post',
				encode:_DEFAULT_CHARSET,
				evalResponse:true,
				data:myUrl.options.toQueryString()
				// onSuccess:function(js,xml){try{eval(js);}catch(e){alert("Call:"+myUrl.url+myUrl.options.toJSON()+"\nfile:"+e.fileName+":"+e.lineNumber+"\n"+e.message+"\n----------------\n"+js);}en comment "\n\n"+(e.stack)}
				}).post();
		} else {
			if (Browser.Engine.webkit && Browser.Engine.version<420) {
				includeContent(makeUrl(myUrl.url,myUrl.options),destination);
			}
			else {
				this.cancelContent(destination);
				this.requests.set(destination, new Request.HTML({
				update:destination,
				method:'post',
				url:myUrl.url,
				data:myUrl.options.toQueryString(),
				encode:_DEFAULT_CHARSET,
				autoCancel:true,
				evalScripts:true,
				onComplete : function(responseTree, responseElements, responseHTML, responseJavaScript) { onComplete(destination);}
				}).post());
			}
		}
	},
	cleanUrl: function(url,opt) {
		if (!$defined(opt)) opt={sid:SID}; opt=$H(opt);
		var extracted_url = extractUrl(url);var simple_url = extracted_url.url;var options = opt.combine(extracted_url.options);
		if (!cookieset) options.sid=SID;
		return {url:simple_url,options:options};
	},
	onContentLoaded: function(destination){;},
	cancelContent: function (destination) {
		if (this.requests.has(destination)) {
			this.requests[destination].cancel();
			delete this.requests[destination]
		}
	}
}

Element.implement({
	deactivate: function(waiting) {
		this.setStyles({textDecoration:'none'}); this.set("href",""); this.addEvent("onclick",null);
		if ($defined(waiting)) {
			this.removeClass("action"); this.setWaiting(waiting.toString());
		} else this.setStyle("cursor","none");
		this.blur();
		return this;
	},
	setWaiting: function(text) {
		var ctxt = this.get("html");
		this.addClass("waiting");
		this.set("oldhtml",ctxt);
		if (text) this.set("html",text);
		return this;
	},
	resetWaiting: function() {
		this.removeClass("waiting");
		this.set("html",this.get("oldhtml"));
		this.erase("oldhtml");
		return this;
	},
	recenter:function(ref) {
		if (!$defined(ref)) ref=Window;
		var size = ref.getSize(), scroll = ref.getScroll();
		this.setStyles({
			left: (scroll.x + (size.x - this.offsetWidth) / 2).toInt() + 'px',
			top: (scroll.y + (size.y - this.offsetHeight) / 2).toInt() + 'px'
		});
		return this;
	},
	hide:function(effects) {
		if ($type(effects)!="boolean") effects=true;
		this.store("isOpen",false);
		if (effects && enable_effects) {
			this.fade('out');
		} else this.setStyle('display','none');
	},
	show:function(effects) {
		if ($type(effects)!="boolean") effects=true;
		this.store("isOpen",true);
		if (effects && enable_effects) {
			this.fade('in');
			this.setStyles({'display':'block'});
		} else this.setStyle('display','block');
	},
	toggle:function(effects) {
		if ($type(effects)!="boolean") effects=true;
		if (this.retrieve("isOpen")==true) this.hide(effects); else this.show(effects);
	},
	update:function(text) {this.set('html',text);},
	tooltip:function(title,text) {
		this.store("tip:title",title);
		this.store("tip:text",text);
		myTips.attach(this);
	},
	tobox : function() {
		boxes.create(this);
	},
	zoomRelativeTo: function(to) {
		var scale = this.options.resizeLimit;
		if (!scale) {
			scale = this.container.getSize();
			scale.x *= this.options.resizeFactor;
			scale.y *= this.options.resizeFactor;
		}
		for (var i = 2; i--;) {
			if (to.x > scale.x) {
				to.y *= scale.x / to.x;
				to.x = scale.x;
			} else if (to.y > scale.y) {
				to.x *= scale.y / to.y;
				to.y = scale.y;
			}
		}
		return this.zoomTo({x: to.x.toInt(), y: to.y.toInt()});
	},
	zoomTo: function(to) {
		if (to.x > screen.availWidth  ) to.x = screen.availWidth;
		if (to.y > screen.availHeight ) to.y = screen.availHeight;
		var pos = (!this.options.centered) ? {
			x: (this.coords.left + (this.coords.width / 2) - to.x / 2).toInt()
				.limit(scroll.x + this.options.margin, scroll.x + box.x - this.options.margin - to.x),
			y: (this.coords.top + (this.coords.height / 2) - to.y / 2).toInt()
				.limit(scroll.y + this.options.margin, scroll.y + box.y - this.options.margin - to.y)
		} :  {
			x: scroll.x + ((box.x - to.x) / 2).toInt(),
			y: scroll.y + ((box.y - to.y) / 2).toInt()
		};
		if (this.options.cutOut) this.element.setStyle('visibility', 'hidden');
		var vars = {left: pos.x, top: pos.y, width: to.x, height: to.y};
		if (this.options.opacityResize != 1) vars.opacity = [this.options.opacityResize, 1];
		else this.box.set('opacity', 1);
		this.tweens.box.start(vars).chain(this.finishOpen.bind(this));
		this.fireEvent('onOpen');
	}
})

function testCookies() {
	var ret = true;
	if ((Cookie.read("sid"))==false) { Cookie.write("sid",SID); if (Cookie.read("sid")===false) ret=false; }
	return ret;
}

//************************ Forms
var currentpage = false;
var radio_toreset = new Array();

function setCheckbox(checkObj, val) {
	if (currentpage=="cv") modif=true
	var objForm = $('form'+checkObj);
	var objLabel = $('label'+checkObj);
	if (objForm.value!=val) { objForm.value = val; objLabel.addClass('checkbox_on'); }
	else { objForm.value = "0"; objLabel.removeClass('checkbox_on'); }
}
 function setRadio(thisForm, checkObj, Val, Default) {
	  if (typeof radio_toreset[checkObj] == "undefined") {
		  if (Default=='') radio_toreset[checkObj]=-99;
		  else radio_toreset[checkObj] = Default;
	  }
	  if (radio_toreset[checkObj] == Val) {
		  var obj_to_unset = Val;
		  var obj_to_set = Default;
	  } else {
		  var obj_to_unset = radio_toreset[checkObj];
		  var obj_to_set = Val;
	  }

	  radio_toreset[checkObj] = obj_to_set;
	  document.forms[thisForm][checkObj].value = obj_to_set;

	  if (typeof document.images['img_'+checkObj+"_"+obj_to_unset] != "undefined") document.images['img_'+checkObj+"_"+obj_to_unset].src = "/images/checkbox_uncheck.png";
	  if (typeof document.images['img_'+checkObj+"_"+obj_to_set]   != "undefined") document.images['img_'+checkObj+"_"+obj_to_set].src = "/images/checkbox_check.png";
  }

//*********************************************
// REDIMENSIONNER IMAGES
//*********************************************
var to_resize=new Array();
function resizePicto(step) {
	resizePic(to_resize[step].img, to_resize[step].x_max, to_resize[step].y_max);
	//delete(to_resize[step]);
	to_resize[step] = true;
}
function resizePic(img,x_max,y_max) {
	var step = to_resize.length;
	if (to_resize[step] != null && to_resize[step]===true) return false;
	img.style.display = 'block';
	if (img.height==0) {
		img.style.display = 'none';
		to_resize[step] = new Object();
		to_resize[step].img=img; to_resize[step].x_max=x_max; to_resize[step].y_max=y_max;
		setTimeout('resizePicto('+step+');',10);
	}
	var x = img.width;
	var y = img.height;
	var ratio = y / x;
	//if (deja) { deja=false; alert(img.instance + "\r\n" + ratio);}
	if (x>x_max) {
		img.width = x_max;
		y = img.height = x_max * ratio;
	}
	if (y>y_max) {
		img.height = y_max;
		x = img.width = y_max / ratio;
	}
	img.style.display = 'none';
	img.style.display = 'block';
	return true;
}

var boxid=0;
var boxes = {
	create:function(div){
		boxid++;
		var box = $(div);
		var size = box.getCoordinates();
		var content = box.get("html");
		if (Browser.Engine.trident4) {
			box.setStyles({'margin':'25px'});
		} else {
			box.addClass('box-container');
		}
		box.setStyles({'position':'relative',width:size.width,'height':'auto'});
		box.update('');
		['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
			new Element('div', {id:'box'+boxid+dir,'class': 'box-all box-' + dir}).inject(box);
		});
		new Element('div', {id:'box'+boxid+'center','class': 'box-center'}).inject(box);
		if (Browser.Engine.trident4) {
			$('box'+boxid+'center').addClass('box-all');
			box.setStyles({height:size.height});
		}
		$('box'+boxid+'center').update(content);
	}
};


this.scrolled = $empty;
this.resized = $empty;
window.addEvent("resize",function(){ winsize=Window.getSize(); this.resized();}.bind(this));
window.addEvent("scroll",function(){ winscroll=document.getScroll(); this.scrolled();}.bind(this));
window.addEvent("domready",function(){coreInit();});
