function listFilesCategory(){
	listFiles(true);
}

function viewFile(){
	if ($(".videoContainer").length > 0)
		videosThumbnails();
	else
		imagesThumbnails();
	var mainImg = $('#mainFile').find('img');
	if (mainImg.width() > 1000)
		mainImg.width(1000);
	return false;
}

function listFiles(category){
	if (category == null || category == undefined)
		category = false;
	
	category = true;
	
	$("#switchViewList1, #uploadLinkImg").tipTip({
		delay: 0,
		edgeOffset: 7,
		defaultPosition: "top"
	});
	
	// thumbnails tooltip
	$('.file').toolTip({
		ElementClassId: 'file'
	});
	
	// Click on checkbox
	$('#selectAll').click(function(){
		var allSelected = true;
		$('.select').each(function(){
			if (!$(this).attr('checked'))
				allSelected = false;
		});
		$('.select').each(function(){
			if (allSelected){
				$(this).attr('checked', '');
				$('#selectAll').attr('checked', '');
				$('#files tr').removeClass('row_selected');
				$('#actionsButton').removeClass('actionsButtonColorActivated');
				$('#actionsButton').addClass('actionsButtonColor');
			}
			else {
				$(this).attr('checked', 'selected');
				$('#selectAll').attr('checked', 'selected');
				$('#files tr').addClass('row_selected');
				$('#actionsButton').removeClass('actionsButtonColor');
				$('#actionsButton').addClass('actionsButtonColorActivated');
			}
		});
	});
	
	// Click on row
	$('#files tr').click( function() {
		var oneIsSelected = false;
		if ($(this).hasClass('row_selected')){
			$(this).removeClass('row_selected');
			$(this).find('td:last-child > input').attr('checked', '');
		}
		else {
			$(this).addClass('row_selected');
			$(this).find('td:last-child > input').attr('checked', 'checked');
		}
		$('.select').each(function(){
			if ($(this).attr('checked'))
				oneIsSelected = true;
		});
		if (oneIsSelected == true){
			$('#actionsButton').removeClass('actionsButtonColor');
			$('#actionsButton').addClass('actionsButtonColorActivated');
		}
		else {
			$('#actionsButton').removeClass('actionsButtonColorActivated');
			$('#actionsButton').addClass('actionsButtonColor');
		}
	});
	
	$('#multiDeleteFiles').click(function(){
		actionMultiDelete();
		return false;
	}).confirm({
	  msg: ' ? ',
	  timeout: 5000,
	  buttons: {
	    ok: getText('Yes'),
	    cancel: getText('No'),
	    separator: ' '
	  }
	});
	
	$('.multiDownload').click(function(){
		var values = 'ids=';
		var compt = 0;
		var href = '';
		$('.select').each(function(){
			if ($(this).attr('checked')){
				compt++;
				values = values + $(this).val() + ';';
			}
		});
		if (compt > 0)
			window.location.href = this.href + '?' + values;
		else
			alert(getText('MultiDownloadAlert'));
		return false;
	});
	
	var callback = function() {
		dataTableUpdate();
	};
	
	if ($("#head").children().length == 10){
		dataTableParam = {"aoColumns": [ 
		    { "sType": 'html'}, // Name
  			{ "sType": 'num-html', "sClass": "center" }, // Size
  			{ "sType": 'html', "sClass": "center" }, // Aspect
  			{ "sType": 'dimensions', "sClass": "center" }, // Dimensions
  			{ "sType": 'numeric', "sClass": "center" }, // Hits
  			{ "sType": 'html', "sClass": "center" } , // Category
  			{ "sType": 'html', "sClass": "center" }, //  Owner
  			{ "sType": 'html', "sClass": "center" }, //  Status
  			{ "sType": 'html', "sClass": "center", "bSortable": false }, //  Edit
  			{ "sType": 'html', "sClass": "center", "bSortable": false } // Select
	  		], "bSortClasses": false,
	  		"iDisplayLength": config.tableDisplayResults,
	  		"oLanguage": getDatatableLanguage(),
	  		"sDom": '<lftip<"multiActions">>',
	  		"fnDrawCallback": dataTableUpdate
		};
	} else if ($("#head").children().length == 9){
		dataTableParam = {"aoColumns": [ 
		    { "sType": 'html'}, // Name
  			{ "sType": 'num-html', "sClass": "center" }, // Size
  			{ "sType": 'html', "sClass": "center" }, // Aspect
  			{ "sType": 'dimensions', "sClass": "center" }, // Dimensions
  			{ "sType": 'numeric', "sClass": "center" }, // Hits
  			{ "sType": 'html', "sClass": "center" } , // Category
  			{ "sType": 'html', "sClass": "center" }, //  Owner
  			{ "sType": 'html', "sClass": "center", "bSortable": false }, //  Edit
  			{ "sType": 'html', "sClass": "center", "bSortable": false } // Select
	  		], "bSortClasses": false,
	  		"iDisplayLength": config.tableDisplayResults,
	  		"oLanguage": getDatatableLanguage(),
	  		"sDom": '<lftip<"multiActions">>',
	  		"fnDrawCallback": dataTableUpdate
		};	
	} else {
		dataTableParam = 
		{"aoColumns": [
  			{ "sType": 'html' }, // Name
  			{ "sType": 'num-html', "sClass": "center" }, // Size
  			{ "sType": 'html', "sClass": "center" }, // Aspect
  			{ "sType": 'dimensions', "sClass": "center" }, // Dimensions
  			{ "sType": 'numeric', "sClass": "center"}, // Hits
  			{ "sType": 'html', "sClass": "center" }, // Category
  			{ "sType": 'html', "sClass": "center" }, // Owner
  			{ "sType": 'html', "sClass": "center", "bSortable": false } // Select
  			], "bSortClasses": false,
  			"oLanguage": getDatatableLanguage(),
  			"iDisplayLength": config.tableDisplayResults,
	  		"sDom": '<lftip<"multiActions">>',
	  		"fnDrawCallback": dataTableUpdate
  		};
	}
	dTable = $('#files').dataTable(dataTableParam);
	
	$('div.multiActions').append($('#multiActions'));
	$('div.multiActions').append($('#multiActionsTool'));
	
	/*****************
	 * MULTI ACTIONS *
	 ****************/
	
	$("#actionsButton").button();
	$("#multiActions").tooltip({
		offset: [-265,-18],
		effect: 'toggle',
		tipClass: 'tool',
		delay: 30
	});
	
	removeAjaxEvents = function(){
		if (dTable != undefined && dTable.length)
			dTable.fnDestroy();
		$("#tiptip_holder").remove();
		$('.file,.switchCategory,#selectAll,.deleteMultiFile,.multiDownload,.deleteFile,.editFile').unbind();
	};
};

function updateImageThumbnail(currentFileId, position){
	var updatedSrcPath = $('#file' + currentFileId).find('img').attr('src');
	if (!updatedSrcPath)
		return;
	
	var posQ = updatedSrcPath.indexOf('q=');
	var motifX = new RegExp('.*x[0-9]\.jpg');
	var posX = updatedSrcPath.match(motifX);
	if (posQ != -1){
	    var qVal = parseInt(updatedSrcPath.substring(posQ + 2, updatedSrcPath.length)) + 1;
	    if (position && position > 0){
	    	if (posX)
	    		updatedSrcPath = updatedSrcPath.substring(0, posQ - 6) + position + '.jpg?q=' + qVal;
	    	else
	    		updatedSrcPath = updatedSrcPath.substring(0, posQ - 5) + "x" + position + '.jpg?q=' + qVal;
	    }
	    else {
	    	if (posX)
	    		updatedSrcPath = updatedSrcPath.substring(0, posQ - 7) + '.jpg?q=' + qVal;
	    	else
	    		updatedSrcPath = updatedSrcPath.substring(0, posQ - 1) + '?q=' + qVal;
	    }
	    
	} else {
		if (position && position > 0){
			if (posX)
	    		updatedSrcPath = updatedSrcPath.substring(0, posQ - 6) + "x" + position + '.jpg?q=' + qVal;
	    	else
	    		updatedSrcPath = updatedSrcPath.substring(0, updatedSrcPath.length - 4) + "x" + position + '.jpg?q=0';
		}
		else {
			if (posX)
				updatedSrcPath = updatedSrcPath.substring(0, updatedSrcPath.length - 6) + '.jpg?q=0';
			else
				updatedSrcPath = updatedSrcPath + '?q=0';
		}
	}
	$('#file' + currentFileId).find('img').attr('src', updatedSrcPath);
}

function updateImagePositionThumbnail(currentFileId, position){
	var updatedSrcPath;
	var positionElement = null;
	
	$(containerId + ' .multiThumb').each(function(){
		if ($(containerId + ' .multiThumb').index($(this)) == position){
			positionElement = $(this);
		}
	});
	
	if (positionElement == null)
		return;
	
	updatedSrcPath = positionElement.attr('src');
	
	if (!updatedSrcPath)
		return;
	
	var posQ = updatedSrcPath.indexOf('q=');
	if (posQ != -1){
	    var qVal = parseInt(updatedSrcPath.substring(posQ + 2, updatedSrcPath.length)) + 1;
	    if (position && position > 0)
	    	updatedSrcPath = updatedSrcPath.substring(0, posQ - 6) + position + '.jpg?q=' + qVal;
	    else
	    	updatedSrcPath = updatedSrcPath.substring(0, posQ - 1) + '?q=' + qVal;
	} else {
		if (position && position > 0)
			updatedSrcPath = updatedSrcPath.substring(0, updatedSrcPath.length - 5) + position + '.jpg?q=0';
		else
			updatedSrcPath = updatedSrcPath + '?q=0';
	}
	
	positionElement.attr('src', updatedSrcPath);
}

function dataTableUpdate(){
	var containerId = null;
	$('.deleteFile').unbind();
	$('.editFile').unbind();
	
	$('.editFile').click(function (){
		var aPos = dTable.fnGetPosition(($(this).parent())[0]);
		var href = $(this).attr('href');
		var currentFileId = searchIdFromHref(href);
		containerId = createMbContainer('#editFileMain', "editContainer", currentFileId);
		
		$(containerId).mb_open(href, function(){
			$(".makeMeAbutton").button();
			$('#uploadContent').change(function(){
				$('#uploadContentValue').val($('#uploadContent').val());
			});
			$('#uploadThumbnail').change(function(){
				$('#uploadThumbnailValue').val($('#uploadThumbnail').val());
			});
			
			var uploaderThumbnail = null;
			var allowedExt = [];
			var allowedSize = [];
			var allowedImgExt = ["jpg", "gif", "png"];
			
			var currentThumbPath = $('#thumbnailPath' + currentFileId).val();
			var initialThumbPosition = 0;
			var thumbPosition = 0;
			var cpt = 0;
			$(containerId + ' .multiThumb').each(function(){
				if (currentThumbPath.indexOf($(this).attr("src")) != -1){
					$(this).addClass("thumbSelected");
					$(this).css("border", "2px solid red");
					thumbPosition = cpt;
					initialThumbPosition = cpt;
				}
				cpt++;
			});
			
			$(containerId + ' .multiThumb').click(function(){
				cpt = 0;
				$(containerId + ' .multiThumb').css("border", "2px solid transparent");
				$(containerId + ' .multiThumb').removeClass("thumbSelected");
				$(this).css("border", "2px solid red");
				$(this).addClass("thumbSelected");
				$('#thumbnailPath' + currentFileId).val($(this).attr("src"));
				$(containerId + ' .multiThumb').each(function(){
					if ($(this).hasClass("thumbSelected")){
						thumbPosition = cpt;
						uploaderThumbnail = initFileUploaderThumbnail(currentFileId, thumbPosition, allowedImgExt, allowedSize);
					}
					cpt++;
				});
			});
			
			// Uploads
			
			$.ajax({
			   type: "POST",
			   url: 'uploadUpdateInfoJson' + extension,
			   dataType: 'json',
			   data: {fileId: currentFileId},
			   success: function(json) {
				  if (json.code == 1 || json.list == null || json.list.length < 3){
					  $.jGrowl('',{
							theme: 	'error',
							header: json.message,
							life:	5000,
							sticky: false
					  }); 
				  } else { 
					  var allowedExtension = json.list[0];
					  allowedSize = json.list[1];
					  
					  allowedExtension = allowedExtension.split(','); //*.jpg;*.gif;*.png
					  
					  for (pos = 0; pos < allowedExtension.length; pos++){
						  allowedExt[pos] = allowedExtension[pos];
					  }
					  
					  // Thumbnail
					  uploaderThumbnail = initFileUploaderThumbnail(currentFileId, thumbPosition, allowedImgExt, allowedSize);
					  
					  // Content
					  var uploaderContent = new qq.FileUploader({
						  	message: getText('uploadFile'),
						    element: document.getElementById('uploadContent' + currentFileId),
						    action: "servletUpload",
							params: {fileId: currentFileId, mode: 'updateContent'},
							allowedExtensions: allowedExt,
							sizeLimit: allowedSize,
							debug: false,
							multiple: false,
							onSubmit: function(id, fileName){},
							onProgress: function(id, fileName, loaded, total){},
							onComplete: function(id, fileName, responseJSON){
								$.jGrowl('',{
									theme: 	'success',
									header: $('#fileName').val() + " : " + getText('ContentUpdated'),
									life:	7000,
									sticky: false
								});
								updateImageThumbnail(currentFileId, 0);
							},
							onCancel: function(id, fileName){},
							messages: {
								typeError: getText("typeError"),
					            sizeError: getText("sizeError"),
					            minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
					            emptyError: "{file} is empty, please select files again without it.",
					            onLeave: getText("onLeave")
							},
							showMessage: function(message){ 
								$.jGrowl('',{
									theme: 	'error',
									header: $('#fileName').val() + " : " + getText('ContentUpdated') + " " + getText('updated') + 
									" " + getText("failed") + " : <br /> " + message,
									life:	15000,
									sticky: false
								});
							}
					  });
				  }
			   },
			   error : function(res){
				   $.jGrowl('',{
						theme: 	'error',
						header: getText('Error'),
						life:	5000,
						sticky: false
					});
			   }
			});
			
			$('#submitFile' + currentFileId).click( function (){
				$('#updateFileAjax' + currentFileId).ajaxSubmit({
					dataType: 'json',
					success: function(json) {
						if (json.code != 0){
						  $.jGrowl('',{
								theme: 	'error',
								header: json.message,
								life:	5000,
								sticky: false
						  }); 
						} else {
							 $.jGrowl('',{
									theme: 	'success',
									header: json.message,
									life:	5000,
									sticky: false
							  }); 
				            $(containerId).mb_close();
				            $('#link' + currentFileId).text(json.map['name']);
				            dTable.fnUpdate(json.map['size'], aPos[0], 1);
				            dTable.fnUpdate(json.map['aspect'], aPos[0], 2);
				            dTable.fnUpdate(json.map['dimensions'], aPos[0], 3);
				            dTable.fnUpdate(json.map['category'], aPos[0], 5);
				            dTable.fnUpdate(json.map['status'], aPos[0], 7);
				            if (initialThumbPosition != thumbPosition)
				            	updateImageThumbnail(currentFileId, thumbPosition);
						}
				    },
				    error: function(res) {
			            $(containerId).mb_close();
			            $.jGrowl('',{
							theme: 	'error',
							header: getText('Error'),
							life:	5000,
							sticky: false
						});
				    }
				});
				return false;
			});
			$('#cancelFile' + currentFileId).click( function (){
				$(containerId).mb_close();
				return false;
			});
		});
		$(containerId).css('top', (getScrollPosition()[1] + 100) + 'px');
		return false;
	});
	
	$('.deleteFile').click(function(){
		// Single Delete
		var id = searchIdFromHref($(this).attr('href'));
		$.ajax({
			   type: "POST",
			   url: 'deleteFileJson' + extension,
			   data: "id=" + id,
			   success: function(json){
				  if (json.code == 0){
					  $('#' + id).html(json.message).css('color', 'red');
					  $('.' + id).each(function(){
						  $(this).html('');
					  });
					  if (actionsJson.actions[actions.deleteFile] == undefined || actionsJson.actions[actions.deleteFile] == null)
						  actionsJson.actions[actions.deleteFile] = [];
					  actionsJson.actions[actions.deleteFile].push([new Date().getTime(), id, 1]);
				  }
				  else {
					  $('#' + id).html(json.message).css('color', 'orange').css('text-decoration', 'blink');
				  }
			   },
			   error : function(msg){
				 alert(getText('Error'));
			   }
			 });
		return false;
	}).confirm({
		  msg: getText('Delete') + ' ? ',
		  timeout: 5000,
		  buttons: {
		    ok: getText('Yes'),
		    cancel: getText('No'),
		    separator: ' '
		  }
	});
}

function initFileUploaderThumbnail(currentFileId, position, allowedImgExt, allowedSize){
	return new qq.FileUploader({
	  	message: getText('UploadImage'),
	    element: document.getElementById('uploadThumbnail' + currentFileId),
	    action: "servletUpload",
		params: {fileId: currentFileId, mode: 'updateThumbnail', position: position},
		allowedExtensions: allowedImgExt,
		sizeLimit: allowedSize,
		debug: false,
		multiple: false,
		onSubmit: function(id, fileName){},
		onProgress: function(id, fileName, loaded, total){},
		onComplete: function(id, fileName, responseJSON){
			$.jGrowl('',{
				theme: 	'success',
				header: $('#fileName').val() + " : " + getText('ThumbnailUpdated'),
				life:	7000,
				sticky: false
			});
			updateImageThumbnail(currentFileId, position); // For tooltip div
			updateImagePositionThumbnail(currentFileId, position); // Inside the edit box
		},
		onCancel: function(id, fileName){},
		messages: {
			typeError: getText("typeError"),
            sizeError: getText("sizeError"),
            minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
            emptyError: "{file} is empty, please select files again without it.",
            onLeave: getText("onLeave")  
		},
		showMessage: function(message){ 
			$.jGrowl('',{
				theme: 	'error',
				header: $('#fileName').val() + " : " + getText('ContentUpdated') + " " + getText("failed") + 
				" : <br />" + message,
				life:	15000,
				sticky: false
			});
		}
  });   
}
