pib.Uploader = function(options) {
	this.options = {container: document, button_name: null, button_id: 'upload_button', validator: null, file_types: "*.gif;*.jpg;*.JPG;*.jpeg;*.png;*TIFF;*tiff;*tif;", file_size_limit: null};
	$.extend(this.options, options);
	this.validator = new pib.Media_Validator(this.options.container, {prefix: this.options.prefix});
	return this.initialize();
};

pib.Uploader.prototype = {
  SwfUploadRef: null,
	inProcess: false,
	UIInProcess: false,
	
	initialize: function(){
    if(this.options.button_name){
			this.resetUI();  
			this.embedSwfUpload(this.options.button_id, this.options.url, this.options.button_name);
		}	  
    
		if(this.options.container.is('form')){
			var that = this;
			this.options.container.bind('submit', function(e){
				pib.tools.stopEvent(e);
				that.sendRequest();
				return false;
			});
		}	
		
		var that = this;
		$(this.SwfUploadRef).bind('before_file_queued_handler', function(e){
			var file = arguments[1] || null;
			if(file){
				that.resetSwfUpload();
			}		
		});
    return this;
  }, 
  
  embedSwfUpload : function(button_id, upload_url, button_name) {
    var that = this;
		var button_name = button_name;
    this.SwfUploadRef = new SWFUpload({
      
      assume_success_timeout : 60,
			upload_url : upload_url, 
      flash_url : "/heap/static/swfupload/Flash/swfupload.swf", 
      file_size_limit : this.options.file_size_limit || "5MB", 
      file_types : this.options.file_types, 
      file_queue_limit : 0,
      file_upload_limit : 0,
			file_post_name: this.options.prefix + '_upload',
            
      button_placeholder_id : button_id,
      button_image_url : (pib.lang == 'en')? '/static/images/en/' + button_name : '/static/images/fr/' + button_name, 
      button_window_mode : SWFUpload.WINDOW_MODE.OPAQUE,
     	button_width : 84, 
      button_height : 24,
      
      file_queued_handler : function(a) { that.on_file_queued(a); }, 
      file_queue_error_handler : function(a, b, c) { that.on_file_queue_error(a, b, c); }, 
      file_dialog_start_handler : function() { that.on_file_dialog_start(); }, 
      file_dialog_complete_handler : function(a, b) { that.on_file_dialog_complete(a, b); }, 
      upload_progress_handler : function(a, b, c) { that.on_upload_progress(a, b, c); }, 
      upload_success_handler : function(a, b) { that.on_upload_success(a, b); }, 
      upload_error_handler : function(a, b) { that.on_upload_error(a, b); }, 
      upload_complete_handler : function(a) { that.on_upload_complete(a); }
    });
  },
	
	sendRequest: function(){
		if(!this.UIInProcess) this.UIInProcess = true;
		if(this.inProcess && this.UIInProcess) return;
		if(!this.validator.checkUploadFile()) return;		
		
		if(this.SwfUploadRef){
			var stats = this.SwfUploadRef.getStats();
			if (stats.files_queued <= 0 || stats.files_queued > 1) return;	
		}
		
		if(this.options.postParams.length){
    	var postParams = {};
			for(var i = 0; i < this.options.postParams.length; i++){
				var key = this.options.prefix + '_' + this.options.postParams[i];
				var $field = $('#' + key);
				try {
					if(key == this.options.prefix + '_prefix') key = 'prefix';
					if(key == this.options.prefix + '_session_id') key = 'session_id';
					postParams[key] = this.getFieldValue($field);					
					if(this.SwfUploadRef) this.SwfUploadRef.addPostParam(key, this.getFieldValue($field));
				} catch(e) { console.log(e.message);}
			}
		}
		
		//call API pour validation
		var that = this;
		pib.api.share.validate_reaction(function(response){
			$('.error', that.options.container).removeClass('error');
			if(response.type == heap.SUCCESS){
				if(that.SwfUploadRef){
					that.SwfUploadRef.startUpload();	
				}
				else {
					$.post(that.options.url, postParams, function(response){
						that.validator.callback(response.data);
					});	
				}
			}
			else that.validator.callback(response);
		}, postParams);
		return this;		
	},
	
	getFieldValue: function(field){
		var value = $.trim(field.val());
		if(field.hasClass('clean')){			
			var ref = field.attr('rel');
			if(ref == value) value = '';
		}
		return value;
	},
  
  resetSwfUpload : function() { /* Supprime les elements de la liste de fichiers */
    if (this.SwfUploadRef) {
  		var stats = this.SwfUploadRef.getStats();
  		var limit = arguments[0] || 0;
			while (stats.files_queued > limit) {
  			this.SwfUploadRef.cancelUpload(null, false);
  			stats = this.SwfUploadRef.getStats();
			}			
    }
		return this;
  }, 
  
  resetUI : function() { /* Initialise l'interface */
  	this.resetSwfUpload();
		this.UIInProcess = false;
		return this;
  },
	
	error: function(code){
		var token = '';
		switch(code){
			case 100:
				token = 'no_file_selected';
			break;
			case -100: 
				token = 'exceed_queue_limit_file_selected';
			break;
			case -110: 
				token = 'exceed_size_file_selected';
			break;
		 	default: 
				token = 'invalid_type_file_selected';
			break;
		}
		
		var $input = $('.upload .input input', this.options.container);
		var html = "<li>" + pib.tools.translate('upload_file_error_' + token) + "</li>";
		(arguments.length < 2)? this.validator.showStaticError(html) : this.validator.showStaticError(html).reset();
		return this;
	},
	
	on_file_queued : function(file) { /* Ajout d'1 fichier dans la liste */  	
		if(!file) return;
		var $parent = $('.upload', this.options.container);
		var $input = $('.input input', $parent);
		if($input.is('input') && $input.val() != file.name) $input.val(file.name);
	 	var stats = this.SwfUploadRef.getStats();
		return this;
  }, 
	
	on_file_queue_error : function(file, error_code) { /* Erreur de fichier - Client */
   	this.error(error_code);
		return this;		
  },
	
	on_upload_progress : function(file, bytes_loaded, bytes_total) { /* Pendant l'upload */
  	if(this.inProcess) return;
		this.inProcess = true;
		var $loader = $('.loading', this.options.container);
		pib.Loading.show($loader);
		return this;
  }, 
  
  cancel : function() {}, /* Cancel Upload */
  on_file_dialog_start : function() {}, /* Ouverture fenetre de dialogue */
	
  on_file_dialog_complete : function(num_files_sel, num_files_queued) {
		this.resetSwfUpload(1);
	}, /* Choix d'un fichier dans la fenetre de dialogue */
	
	on_upload_error : function(file, error_code) { /* Erreur fichier - Serveur */
		var that = this;
		pib.Loading.hide($('.loading', this.validator.container), function(){
				that.error(error_code, true);
		});		
		this.resetUI();
		return this;
	},
	
	on_upload_complete : function(file) { /* Fin upload */
		this.inProcess = false;
		return this;
	}, 
  
  on_upload_success : function(file, server_data) { /* Fin upload - Success */
  	var response = {}
		response.data = {};
		if(server_data) var response = eval('(' + server_data + ')');
		this.validator.callback(response.data);
		this.resetUI();
		return this;
  }
	
	//this.SwfUploadRef.stopUpload(); 
	//this.resetSwfUpload();
	//this.SwfUploadRef.startUpload();
};