var cancel = false;
var FileUploaderMoo = new Class({
	Implements: [Events],
	ID_KEY : 'APC_UPLOAD_PROGRESS',
	uploadServerUrl : serverUrl + 'ajax/upload-action.php',
	pollDelay : 0.5,
	form : null,
	idElement : null,
	iframe : null,
	myRequest : null,
	progressWrapper: null,
	progressBar: null,
	/*fileList: null,*/
	tagFile: null,
	/*moduleFile : null,*/

	initialize: function(form, progressBar) { //, fileList) {
		this.form = $(form);
		/*this.tagFile = $(form).getProperty('tag');*/
		this.idElement = $(this.ID_KEY); // + '_' + this.tagFile);
		this.progressWrapper = $(progressBar);
		//this.fileList = $(fileList);
		//this.moduleFile = $(form).getProperty('module');

		this.iframe = new Element('iframe', { name : '_upload_frame' }).setStyle('display', 'none');
		this.form.appendChild(this.iframe);
		this.form.target = this.iframe.name;

		this.form.addEvent('submit', function (e){

				if(($('mediafile').value.lastIndexOf(".jpg")!=-1)||
				   ($('mediafile').value.lastIndexOf(".JPG")!=-1)||
				   ($('mediafile').value.lastIndexOf(".jpeg")!=-1)||
				   ($('mediafile').value.lastIndexOf(".JPEG")!=-1)||
				   ($('mediafile').value.lastIndexOf(".mpg")!=-1)||
				   ($('mediafile').value.lastIndexOf(".MPG")!=-1)||
				   ($('mediafile').value.lastIndexOf(".wmv")!=-1)||
				   ($('mediafile').value.lastIndexOf(".WMV")!=-1)||
				   ($('mediafile').value.lastIndexOf(".avi")!=-1)||
				   ($('mediafile').value.lastIndexOf(".AVI")!=-1)||
				   ($('mediafile').value.lastIndexOf(".mov")!=-1)||
				   ($('mediafile').value.lastIndexOf(".MOV")!=-1)){
					var id = this.generateId();
					this.idElement.value = id;
					this._monitorUpload(id);
				} else {
					$('mediafile').value='';
					alert(supportedFiles + ' (JPG, MPG, WMV, AVI and MOV)');
                                        e.stop();
				}

		}.bind(this));

		this.progressBar=new ProgressBar(0,{
			'width':250,
			'height':15,
			'darkbg':'#C10C0D',
			'darkfg':'#fff',
			'lightbg':'#fff',
			'lightfg':'#C10C0D'
		});
		this.progressWrapper.appendChild(this.progressBar);
	},

	generateId : function() {
		var now = new Date();
		return now.getTime();
	},

	delay : function(seconds) {
		var ms = seconds * 1000;
		var then = new Date().getTime();
		var now = then;
		while ((now - then) < ms)
			now = new Date().getTime();
	},

	_monitorUpload : function(myId) {
		this.myRequest = new Request.JSON({
                    url: this.uploadServerUrl,
                    method: 'post',
                    onComplete: function(response) {
                        this._onMonitorSuccess(response);
                    }.bind(this)
                }).send({
                    data: {
                        action : 'status',
                        id : myId
                    }
		});
	},

	/*_listUploadedFile: function() {
		this.myRequest = new Request.JSON({
  		url: this.uploadServerUrl,
                async: false,
  		onComplete: function(file) {
				this.fileList.empty();
				if(file){
					var container = new Element('div', {
						'class':'imageViewer'
					});
					var image = new Element('img', {
						'src': serverUrl + '/tmp/'+file,
						'alt':file,
						'height':'80px',

						'id':'image_'+file
					});
					image.inject(container);
					container.inject(this.fileList);

					//this.fireEvent('elementUpdated', this);
				}
      }.bind(this)
   	}).send({
			data: {
				action : 'filelist',
				tag : this.tagFile,
				module : this.moduleFile
			}
	  });
	},*/

	_onMonitorSuccess : function(response) {
		var json = response;



		if(json) {
			this.progressWrapper.setStyle('display', 'inline');
			this.progressBar.setValue(Math.round(json.percent*Math.pow(10,2))/Math.pow(10,2));
			//this.fireEvent('elementUpdated', this);

			if (!json.finished) {
					this.delay(this.pollDelay);
					this.compteur++;
					this._monitorUpload(json.id);
			} else {
				//this.fireEvent('uploadCompleted', this);
				//this.fireEvent('elementUpdated', this);
			}
		}
	}
});

var ProgressBars=0;
var ProgressBar=new Class({
	initialize:function(value,parameters){
		var vals={
			'id':'progressbar_'+(ProgressBars++),
			'value':$pick(value,0),
			'width':0,
			'height':0,
			'darkbg':'#006',
			'darkfg':'#fff',
			'lightbg':'#fff',
			'lightfg':'#000'
		};
		if(parameters && $type(parameters)=='object')$extend(vals,parameters);
		if(vals.height<12)vals.height=12;
		var obj=new Element('div',{
			'id':vals.id,
			'class':'progressbar_wrapper',
			'styles':{
				'border':'1px solid #000',
				'width':vals.width,
				'height':vals.height,
				'position':'relative'
			}
		});
		obj.vals=vals;
		obj.vals.dark=new Element('div',{
			'id':vals.id+'_dark',
			'class':'progressbar_dark',
			'styles':{
				'width':vals.width,
				'height':vals.height,
				'background':vals.darkbg,
				'color':vals.darkfg,
				'position':'absolute',
				'text-align':'center',
				'left':0,
				'top':0,
				'line-height':vals.height-2
			}
		});
		obj.vals.light=new Element('div',{
			'id':vals.id+'_light',
			'class':'progressbar_light',
			'styles':{
				'width':vals.width,
				'height':vals.height,
				'background':vals.lightbg,
				'color':vals.lightfg,
				'position':'absolute',
				'text-align':'center',
				'left':0,
				'top':0,
				'line-height':vals.height-2
			}
		});
		obj.appendChild(obj.vals.dark);
		obj.appendChild(obj.vals.light);
		obj.setValue=ProgressBar_setValue;
		if(vals.width)obj.setValue(vals.value);
		else setTimeout('ProgressBar_checkForParent("'+obj.id+'")',1);
		return obj;
	}
});
function ProgressBar_setValue(value){
	value=parseFloat(value);
	if(isNaN(value))value=0;
	if(value>100)value=100;
	if(value<0)value=0;
	this.vals.value=value;
	this.vals.dark.empty();
	this.vals.light.empty();
	this.vals.dark.appendText(value+'%');
	this.vals.light.appendText(value+'%');
	var r=parseInt(this.vals.width*(value/100));
	this.vals.dark.setStyle('clip','rect(0,'+r+'px,'+this.vals.height+'px,0)');
	this.vals.light.setStyle('clip','rect(0,'+this.vals.width+'px,'+this.vals.height+'px,'+r+'px)');
}
function ProgressBar_checkForParent(id){
	var obj=$(id);
	if(!obj)return;
	if(!obj.parentNode)return setTimeout('ProgressBar_checkForParent("'+id+'")',1);
	obj.setStyle('width','100%');
	var w=obj.offsetWidth;
	obj.vals.dark.setStyle('width',w);
	obj.vals.light.setStyle('width',w);
	obj.vals.width=w;
	obj.setValue(obj.vals.value);
}
