var ChosenFiles = function(tabs) {
	
  var that = this;
	
	this.tabs = tabs;
	
	this.previousPostId = false;
	this.currentPostId = false;
	this.previousPostType = 'comment';
	this.currentPostType=  'comment';
	
	this.setPostType = function(postType) {
		
		that.previousPostType = that.currentPostType;
		that.currentPostType = postType;
	};	
	
	this.setPostId = function(postId) {
		
		that.previousPostId = that.currentPostId;
		that.currentPostId = postId;
	};
	
	this.init = function() {
		
		that.files = [];
		
		that.table = that.tabs.root.find('.chosenFiles');
		that.table.find('tbody').empty();
		that.zebraTable();
		
		$('#attach').hide();
	};
	
	this.zebraTable = function() {
		that.table.find('tbody tr').removeClass('oddRow');
	  that.table.find('tbody tr:odd').addClass('oddRow')	
	};
	
	this.getTotal = function() {
		return that.files.length;		
	};
	
	this.isMaxFiles = function() {
		return (that.files.length >= 5);
	};
	
	this.addFile = function(fileInfo) {
	
	 that.files.push(fileInfo);
	 
	 if (that.files.length >= 5) {
		 that.tabs.root.find('.addFile_link, .addFile_webcam').unbind('click.send');
		 that.tabs.root.find('.addFile_upload, .addFile_link, .addFile_webcam').bind('click.maxfiles', function(e){
			e.preventDefault();
			cqlook.showMessageModal('Você só pode anexar 5 arquivos para cada pergunta!', 'error');
		 });
	 };
	 
	 that.addRow(fileInfo); 
	 
	};
	
	this.addRow = function(fileInfo) {
		
	 if (fileInfo.size) {
		 fileInfo.size = parseInt(fileInfo.size / 1024, 10) + ' Kb';
	 }
	 else {
	 	 fileInfo.size = '---';
	 }
	 
	 var snippet =  
		 '<tr><td class="' + that.tabs.currentArea +'"></td>' + 
		 '<td class="fileNameTable"><span>' + fileInfo.name + '</span></td>' +
		 '<td>' + fileInfo.size + '</td>' + 
		 '<td class="trash"><a href="javascript:;" title="Apagar"></a></td></tr>';
	 
	 that.table.append(snippet);
	 that.onRemove();
	 that.zebraTable();
	 
	 $('#attach').show();
	};
	
	this.onRemove = function() {
		
		var lastTd = that.table.find('a:last');
		  
		lastTd.click(function(e){
		  
			e.preventDefault();
			
			var index = $(this).parent().parent().index('.chosenFiles tbody tr');
			that.removeFile(index);
		});
	};
	
	this.removeFile = function(index) {
		
		var fileId = that.files.splice(index, 1)[0].id;
		
		$.getJSON('/services/media/remove_post_media', {media_id: fileId}, function(json){
      
      if (json.success === false) {
        cqlook.showMessageModal('Erro, tente novamente!', 'error');
				return;
      }
		
		that.removeRow(index);
		that.tabs.root.find('.addFile_upload, .addFile_link, .addFile_webcam').unbind('click.maxfiles');
		that.tabs.events.link();
		that.tabs.events.webcam();
		
    });
	};
	
	this.removeRow = function(index) {
		
		if (that.files.length === 0) {
			$('#attach').hide();	
		}
		
		var tr = $( that.table.find('tbody tr').get(index) );
		
		tr.remove();
		that.zebraTable();
	};
	
};

