var MooImageUploader = new Class({
	version:3.2,
	Implements: [Events, Options],
	options: {
		uploadUrl:'uploadScript.php',
		titleText:'Uploader une image',
		jsonFormat:true,
		cropUrl:'crop.php',
		cropInitCoords:{x:0,y:0,w:81,h:81},
		cropMinimumSize:{w:80,h:80},
		cropProportionnel : false,
		scrollWithPage:false,
		previewWindow:false,	
		backgroundQuit:false,
		closeText:'Annuler'
	},
	initialize: function(el, options) {
		this.setOptions(options);
		el.addEvent('click',this.show.bind(this));
	},
	show:function(){
		this.iuWidth = 700;
		this.iuHeight = 550;
		if (!$("IUoverlay")) {
			new Element('div',{'id':'IUoverlay','styles':{'opacity':0.6}}).inject(document.body);
			this.IUOverlaySize();
			$('IUoverlay').set('tween', {duration: 400});
		}
		if (!$("IUwindow")) {
			this.IUWindow = new Element('div',{
				'id':'IUwindow',
				'styles':{
					'opacity':0
				}
			}).inject(document.body).store(':curIU',this).adopt(
				new Element('div',{'id':'IUHeaderContainer'}).adopt(
					new Element('div',{'id':'IUtitle'}).set('text',this.options.titleText),
					new Element('div',{'id':'IUcloseWindow'}).adopt(new Element('a',{'id':'IUcloseWindowButton'}).set('text',this.options.closeText))
				),
				new Element('iframe',{'id':'hiddenIframe','name':'hiddenIframe'}),
				new Element('div',{'id':'IUFormContainer'}).adopt(
					new Element('form',{'method':'post','enctype':'multipart/form-data','action':this.options.uploadUrl,'target':'hiddenIframe','events':{
						submit:function(){
							$('IUFormContainer').setStyle('display','none');
							$('IUFormContainer').adopt(new Element('div',{'id':'IULoader'}).set('text','Upload en cours'));
							
						}
					}}).adopt(
						new Element('input',{'type':'file','name':'uploadFile'}),
						new Element('button',{'type':'submit'}).set('text','Envoyer').setStyle('margin-left',50)
					)
				)
			);
		}
		
		if(this.options.backgroundQuit)	$("IUoverlay").addEvent('click',this.IUremove.bind(this));
		$("IUcloseWindowButton").addEvent('click',this.IUremove.bind(this));
		this.IUposition();
		this.IUshowWindow();
		if(this.options.scrollWithPage)
		{
			window.addEvent('scroll',this.IUposition.bind(this));
			window.addEvent('resize',function(){
				this.IUposition();
				this.IUOverlaySize.delay(200);
			}.bind(this));
		}
		else
			window.document.body.setStyle('overflow','hidden');
		document.addEvent('keyup',function(event){if (event.code == 27) {this.IUremove();}}.bind(this));
	},
	IUshowWindow: function (){
		$('IUwindow').set('tween', {duration: 1000});
		$('IUwindow').tween('opacity', 0, 1);
	},
	IUOverlaySize: function(){
		$("IUoverlay").setStyles({height: window.getScrollHeight() + 'px',width: window.getScrollWidth() + 'px'});
	},
	IUJobDone:function(jsonResponse){
		if(this.options.jsonFormat){jsonResponse = JSON.decode(jsonResponse);}
		if(jsonResponse.error == 1){
			alert(jsonResponse.errorText);
			$('IULoader').destroy();
			$('IUFormContainer').setStyle('display','');
			return;
		}
		if(this.options.previewWindow)
			var previewContainer = new Element('div',{'id':'previewContainer'});
		var textContainer = new Element('div',{'id':'textContainer'});
		var buttonContainer = new Element('div',{'id':'buttonsContainer'});
		if(this.options.previewWindow)
			textContainer.adopt(new Element('p').set('text','A gauche, ce a quoi votre photo ressemblera.'));
		textContainer.adopt(
			new Element('p').set('text','Pour faire des ajustements, vous pouvez glisser et redimentionner le recrangle ci-dessous. Quand vous avez fini, cliquez sur le bouton "Sauvegarder"').setStyle('color','#666666')
		);
		var lassoContainer = new Element('div',{'id':'lassoContainer'});
		$('IUFormContainer').empty().setStyles({
			borderBottom:'1px solid black',
			display:'block',
			height:'90px'
		});
		if(this.options.previewWindow)
			$('IUFormContainer').adopt(previewContainer);
		$('IUFormContainer').adopt(textContainer,buttonContainer)
		var cropContainer = new Element('div').inject(lassoContainer);
		$('IUwindow').adopt(lassoContainer);
		var previewImage;
		var myCrop = new CropCrop(cropContainer,jsonResponse.imageUrl,{
			coords : this.options.cropInitCoords,
			minimum : this.options.cropMinimumSize,
			prop : this.options.cropProportionnel,
			onImageLoaded : function(image){
				previewImage = image.clone();
				if(this.options.previewWindow)
					previewContainer.adopt(previewImage)
			}.bind(this),
			onMove:function(coords, image){
				if(this.options.previewWindow)
				{
					var width = image.width-coords.w+80;
					var height = width*image.height/image.width;
					previewImage.setStyles({
						width:width,
						height:height,
						left:-coords.x*width/image.width,
						top:-coords.y*height/image.height
					});
				}
			}.bind(this)
		});
		buttonContainer.adopt(new Element('button',{'events':{'click':function(){
			new Request.JSON({
				url:this.options.cropUrl,
				method:'post',
				data:$H({
					x:myCrop.getCoords().x,
					y:myCrop.getCoords().y,
					w:myCrop.getCoords().w,
					h:myCrop.getCoords().h,
					url:jsonResponse.imageUrl
				}).toQueryString(),
				onSuccess:function(jsonReponse){
					this.IUremove(jsonReponse);
				}.bind(this)
			}).send();
		}.bind(this)}}).set('text','Sauvegarder'));
	},
	IUremove:function (jsonResponse){
		if(this.options.scrollWithPage)
		{
			window.removeEvents('scroll');
			window.removeEvents('resize');
		}
		else
			window.document.body.setStyle('overflow','auto');
		if(this.options.backgroundQuit)	$("IUoverlay").removeEvents('click');
		if ($('IUcloseWindowButton')) 	$("IUcloseWindowButton").removeEvents('click');
		$('IUwindow').set('tween', {
			duration: 250,
			onComplete: function(){$('IUwindow').dispose();}
		});
		$('IUwindow').tween('opacity', 1, 0);
		$('IUoverlay').set('tween', {
			duration: 400,
			onComplete: function(){$('IUoverlay').dispose();}
		});
		$('IUoverlay').tween('opacity', 0.6, 0);
		if($type(jsonResponse) != "event") 	this.fireEvent('onReady',jsonResponse);
		else 					this.fireEvent('onClose');
	},
	IUposition: function (){
		$('IUwindow').setStyles({
			width: this.iuWidth + 'px',
			height: this.iuHeight + 'px',
			left: (window.getScrollLeft() + (window.getWidth() - this.iuWidth) / 2) + 'px',
			top: (window.getScrollTop() + (window.getHeight() - this.iuHeight) / 2) + 'px'
		});
	}
});

function wakeUp(jsonResponse){
	$('IUwindow').retrieve(':curIU').IUJobDone(jsonResponse);
}
