// (C)opyright N-Gine Innovation 2008 - Tous droits réservés
// http://www.ngine-innovation.com
// fichier créé le 22/10/2008 par m.c.

// Ce script utilise jQuery

// la liste des annuaires. Si un annuaire venait � �tre supprimé, la taille de la liste reste
// inchang�e mais l'�l�ment devient null.
var fileBrowsers = new Array();

// ************************************************************************************************
// ************************************************************************************************
// ***      Classe FileBrowserMac2i
// ************************************************************************************************
// ************************************************************************************************
// Constructeur
// param ownerType : à qui appartiennent les fichiers ("client ou public")
//       ownerName : nom formalisé du membre ou vide
//       parentDiv : id du div dans lequel placer l'explorateur
//       width : largeur du parentDiv en px [VALEUR IGNOREE - LARGEUR FIXE 815PX]
//       height : hauteur du parentDiv en px
//       mac2i : nom de domaine de mac2i
//       readOnly : lecture seule - si vrai, impossible d'envoyer des fichiers

function FileBrowserMac2i(ownerType, ownerName, parentDiv, width, height, mac2i, readOnly)
{	
	this.mainDiv = $('#' + parentDiv);

	if (this.mainDiv.length == 0)
		return;

	this.ownerType = ownerType;
	this.ownerName = ownerName;	
	if (mac2i && (mac2i != ''))
		this.ndd = mac2i;
	else
		this.ndd = "www.mac2i.com"
	this.widgetWidth = 700; //width;
	this.colWidths = [20,25,600, 80];
	this.readOnly = readOnly;	
	this.id = fileBrowsers.length;
	fileBrowsers[this.id] = this;
	
	this.mainDiv.html(
	'<div style="width:' + this.widgetWidth + 'px;">\n\
		<div class="fileDetailsContainer" style="width:' + this.widgetWidth + 'px;height:' + (this.widgetHeight - 100) + 'px;">\n\
			<form action="" id="' +  this.ownerType + 'RemFileBrowser' + this.id + '" onsubmit="return false;">\n\
			<table id="fileDetails'+this.id+'_header" class="fileDetails sortable blue small" style="width:' + this.widgetWidth + 'px">' +
				'<thead>\n\
					<tr style="height:22px;">\n\
					<th style="width:'+this.colWidths[1]+'px"><span></span></th><th style="width:'+this.colWidths[2]+'px"><span>Titre</span></th>'+
					'<th style="width:'+this.colWidths[3]+'px"><span>Taille</span></th></tr>\n\
				</thead>\n\
			</table>\n\
			<div class="fileDetailsBodyContainer" style="height:' + (this.widgetHeight - 123) + 'px;">\n\
				<table id="fileDetails'+this.id+'_body" class="fileDetails sortable blue small" style="width:' + this.widgetWidth + 'px">' +
					'<tbody><tr >\n\
					<td style="width:'+this.colWidths[1]+'px">Aucun fichier</td><td style="width:'+this.colWidths[2]+'px">&nbsp;</td>\n\
					<td style="width:'+(this.colWidths[3]+15)+'px">&nbsp;</td></tr>' +
					'</tbody>\n\
				</table>\n\
			</div>\n\
		</div>\n\
		</form>\n\
	<div style="width:' + this.widgetWidth + 'px;text-align:center;margin-top:20px;">' +
		(readOnly?'':'<form action="http://' + this.ndd + '/scripts/php/files/upload.php" id="' +  ownerType + 'AddFileBrowser' + this.id + '" enctype="multipart/form-data" method="post" target="uploadIFrame" onsubmit="return NotifyUploadStart(' + this.id + ');">' +
		'<input name="MAX_FILE_SIZE" value="10000000" type="hidden" /><input type="hidden" name="owner" value="' + this.ownerType + '" /><input type="hidden" name="fileBrowserID" value="' + this.id + '" />' +
		'<input type="hidden" name="id" value="' + this.ownerName + '" /><table style="width:100%;"><tr><td style="width:30%;text-align:right;">Titre</td><td style="width:70%;text-align:left;">: <input type="text" size="50" name="title" value="nouveau fichier"/></td></tr><tr><td style="width:30%;text-align:right;">Fichier</td><td style="width:70%;text-align:left;">: <input name="userfile[]" type="file" />&nbsp;&nbsp;&nbsp;' +
		'<input type="submit" name="submit" value="Envoyer" /></td></tr></table></form><p style="font-size:x-small;" id="uploadNotifParag">&nbsp;</p>')+'</div></div>');



	this.mainDiv.find("#fileBrowserDeleteButton" + this.id).click(bindMethod(this, this.removeFiles));

	$("body").append('<iframe name="uploadIFrame" src="about:blank" style="width:0;height:0;border:0;"></iframe>');

	if (this.id == 0)
		$("head").append('<link type="text/css" rel="stylesheet" href="http://' + this.ndd + '/styles/filebrowser.css"/>');

	this.mainDiv.find('#fileDetails'+this.id+'_body').tablesorter({headerId:'fileDetails'+this.id+'_header',headers:{0:{sorter:false},1:{sorter:"text"},4:{sorter:"datetimeFR"},5:{sorter:"filesize"}},widgets:["zebra"]});

		this.fileCount = 0;
	this.logCount = 0;

	this.uploading = false;
	
	this.refresh();
	
}

// ------------------------------------------------------------------------------------------------
// supprime l'explorateur de la page HTML (libération de la mémoire ?)
FileBrowserMac2i.prototype.destroy = function()
{
	removeDomElement(this.mainDiv);
	fileBrowsers[this.id] = null;
}

// ------------------------------------------------------------------------------------------------
// Affiche un message d'information et place un timeout pour l'effacer 5 sec plus tard
// param msg : le message à afficher
//       forced : le message n'est pas effacé au bout de 5 sec si cette valeur est spécifiée
FileBrowserMac2i.prototype.log = function(msg, forced)
{
	this.mainDiv.find("#uploadNotifParag").html(msg);
	if (!forced)
	{
		this.logCount++;
		setTimeout("HideLog(" + this.id + ");", 5000);
	}
}

// ------------------------------------------------------------------------------------------------
// Efface le precedent message d'information
FileBrowserMac2i.prototype.hideLog = function()
{
	this.logCount--;
	if (this.logCount == 0)
		this.mainDiv.find("#uploadNotifParag").html("&nbsp;");
}

// ------------------------------------------------------------------------------------------------
// fonction appelée lorsqu'un upload commence
// retour : true si un upload n'est pas deja en cours 
FileBrowserMac2i.prototype.uploadStart = function()
{
	if (this.uploading)
		return false;
	this.uploading = (this.mainDiv.find("input:file").val() != '');
	if (this.uploading)
		this.log("envoi du fichier en cours...\n selon votre connexion l'opération peut durer plusieurs secondes", true);
	return this.uploading;
}

// ------------------------------------------------------------------------------------------------
// fonction appelée lorsqu'un upload est termin�
// param msg : le message à afficher
FileBrowserMac2i.prototype.uploadEnd = function(msg)
{
	this.mainDiv.find("input[name=title]").val('nouveau fichier');
	this.mainDiv.find("input:file").val('');
	this.log(msg);
	this.uploading = false;
}

// ------------------------------------------------------------------------------------------------
// Fait un appel cross-domain pour refraichir la liste des fichiers 
FileBrowserMac2i.prototype.refresh = function()
{	
	CrossDomainCall('http://' + this.ndd + '/scripts/php/files/fileList.php?OwnerType=' + this.ownerType +
		'&OwnerName=' + this.ownerName +
		'&FileBrowserID=' + this.id);
}

// ------------------------------------------------------------------------------------------------
// Supprime un/des fichiers sur le serveur
FileBrowserMac2i.prototype.removeFiles = function()
{
	var fileIds = '';
	this.mainDiv.find("input[@type=checkbox][@checked]").each(function() {fileIds += $(this).val() + '.';});
	
	if (fileIds != '')
		CrossDomainCall('http://' + this.ndd + '/scripts/php/files/delete.php?OwnerType=' + this.ownerType +
			'&OwnerName=' + this.OwnerName +
			'&FileIDs=' + fileIds.substr(0, fileIds.length - 1) +
			'&FileBrowserID=' + this.id);
	else
		this.log("Aucun fichier s&eacute;lectionn&eacute;");
	return false; // ne pas suivre le lien
}

// ------------------------------------------------------------------------------------------------
// modifie la liste de fichiers
// param json : la liste des fichiers en JSON
FileBrowserMac2i.prototype.replaceOrAddFilesInView = function(action, jsonData)
{
	var html = '';
	if (action == 'replace')
		this.fileCount = 0;
	if (jsonData.files)
		
		for (i = 0; i < jsonData.files.length; i++)
		{
			this.fileCount++;
			var file = jsonData.files[i];
			html += '<tr><td class="icon ' + file.typeClass + 'Icon" title="' + file.typeName + '" style="width:'+this.colWidths[1]+'px"></td>' +
				'<td style="width:'+this.colWidths[2]+'px"><a href="http://' + this.ndd + '/scripts/php/files/download.php?name=' + file.fname + '&ownerType=' + this.ownerType + '">' + file.fname + '</a></td>' +
				'<td style="width:'+this.colWidths[3]+'px">' + file.size + '</td></tr>';
		}
	if (action == 'replace')
		this.mainDiv.find("#fileDetails"+this.id+"_body tbody").html(html);
	else // 'add'
		this.mainDiv.find("#fileDetails"+this.id+"_body tbody").append(html);
	this.initTableSorter();
	this.mainDiv.find("#fileDetails"+this.id+"_body tbody tr td").hover(function(){
		$(this).parent().addClass('trhover');
	}, function() {
		$(this).parent().removeClass('trhover');
	});
	

	/*if (jsonData.MAX_FILE_SIZE)
		{
			this.mainDiv.find("input[@name = MAX_FILE_SIZE]").val(jsonData.MAX_FILE_SIZE);
		}*/
		
}

// ------------------------------------------------------------------------------------------------
// modifie la liste de fichiers
// param json : la liste des fichiers en JSON
FileBrowserMac2i.prototype.replaceFilesInView = function(jsonData)
{
	this.replaceOrAddFilesInView('replace', jsonData);
}

// ------------------------------------------------------------------------------------------------
// modifie la liste de fichiers - ajoute des fichiers
// param json : la liste des fichiers en JSON
FileBrowserMac2i.prototype.addFilesToView = function(jsonData)
{
	if (this.fileCount == 0)
		this.mainDiv.find("#fileDetails"+this.id+"_body tbody").empty();
	this.replaceOrAddFilesInView('add', jsonData);
}

// ------------------------------------------------------------------------------------------------
// modifie la liste de fichiers - supprime des fichiers
// param json : la liste des fichiers en JSON
FileBrowserMac2i.prototype.removeFilesFromView = function(jsonData)
{
	if ($.browser.msie)
		this.mainDiv.find(".fileDetailsContainer").scrollTop(0);
	if (jsonData.files)
	{
		for (i = 0; i < jsonData.files.length; i++)
		{
			this.mainDiv.find("input[@type=checkbox][@value='" + jsonData.files[i].id + "']").each(function() {
				$(this).parent().parent().remove();
			});
			this.fileCount--;
		}
		this.log(jsonData.files.length + " fichier" + ((jsonData.files.length > 1)?"s":"") + " supprim&eacute;" + ((jsonData.files.length > 1)?"s":""));
	}
	location.reload() ; 
	//this.initTableSorter();

	//if (jsonData.MAX_FILE_SIZE)
		//this.mainDiv.find("input[@name=MAX_FILE_SIZE]").val(jsonData.MAX_FILE_SIZE);
}

// ------------------------------------------------------------------------------------------------
// Initialise le tableSorter - A appeler après chaque changement dans la liste de fichiers
FileBrowserMac2i.prototype.initTableSorter = function()
{
	if (this.fileCount < 1)
		this.mainDiv.find("#fileDetails"+this.id+"_body tbody").html('<tr><td style="width:'+this.colWidths[0]+'px">&nbsp;</td><td style="width:'+this.colWidths[1]+'px"><!-- aa --></td><td style="width:'+this.colWidths[2]+'px">Aucun fichier</td><td style="width:'+this.colWidths[3]+'px">&nbsp;</td><td style="width:'+this.colWidths[4]+'px"></td></tr>');
	this.mainDiv.find("#fileDetails"+this.id+"_body").each(function() {
		$(this).trigger("update");
		$(this).trigger("sorton",[[[3]]]);
	});
}

// ************************************************************************************************
// ************************************************************************************************
// ***      M�thodes globales
// ************************************************************************************************
// ************************************************************************************************

// ------------------------------------------------------------------------------------------------
// Remplace la liste de fichiers affich�e dans un fileBrowser 
// param fileBrowserID : id du fileBrowser � mettre � jour
//       jsonData : les donn�es � afficher
//       scriptID : id du script cr�� par l'appel cross-domain
function ReplaceFilesInView(fileBrowserID, jsonData, scriptID)
{
	var fileBrowser = fileBrowsers[fileBrowserID];
	if (fileBrowser && jsonData.files)
		fileBrowser.replaceFilesInView(jsonData);

	//RemoveScript(scriptID);
}

// ------------------------------------------------------------------------------------------------
// Ajoute des fichiers � la liste affich�e dans un fileBrowser 
// param fileBrowserID : id du fileBrowser � mettre � jour
//       jsonData : les donn�es � afficher
//       scriptID : id du script cr�� par l'appel cross-domain
function AddFilesToView(fileBrowserID, jsonData, scriptID)
{
	var fileBrowser = fileBrowsers[fileBrowserID];
	if (fileBrowser && jsonData.files)
		fileBrowser.addFilesToView(jsonData);

	//RemoveScript(scriptID);
}

// ------------------------------------------------------------------------------------------------
// Supprime des fichiers de la liste affich�e dans un fileBrowser 
// param fileBrowserID : id du fileBrowser � mettre � jour
//       jsonData : les donn�es � afficher
//       scriptID : id du script cr�� par l'appel cross-domain
function RemoveFilesFromView(fileBrowserID, jsonData, scriptID)
{
	var fileBrowser = fileBrowsers[fileBrowserID];
	if (fileBrowser && jsonData.files)
		fileBrowser.removeFilesFromView(jsonData);

	//RemoveScript(scriptID);
}

// ------------------------------------------------------------------------------------------------
// Supprime des fichiers de la liste affich�e dans un fileBrowser 
// param fileBrowserID : id du fileBrowser � mettre � jour
//       jsonData : les donn�es � afficher
//       scriptID : id du script cr�� par l'appel cross-domain
function HideLog(fileBrowserID)
{
	var fileBrowser = fileBrowsers[fileBrowserID];
	if (fileBrowser)
		fileBrowser.hideLog();
}

// ------------------------------------------------------------------------------------------------
// Notifie du debut d'un upload 
// param fileBrowserID : id du fileBrowser
function NotifyUploadStart(fileBrowserID)
{
	var fileBrowser = fileBrowsers[fileBrowserID];
	if (fileBrowser)
		return fileBrowser.uploadStart();
	return false;
}

// ------------------------------------------------------------------------------------------------
// Notifie de la fin d'un upload 
// param fileBrowserID : id du fileBrowser
//       msg : le message à afficher
function NotifyUploadEnd(fileBrowserID, msg)
{
	var fileBrowser = fileBrowsers[fileBrowserID];
	if (fileBrowser)
		fileBrowser.uploadEnd(msg);
}

var iFrameCallback = {};
iFrameCallback.notifyUploadEnd = NotifyUploadEnd;
iFrameCallback.addFilesToView = AddFilesToView;


// ------------------------------------------------------------------------------------------------
// crÃ©Ã© une closure
// code magique qui permet de lier une mÃ©thode Ã  un contexte (il est ainsi possible de diffÃ©rer
// l'exÃ©cution d'une mÃ©thode d'instance pour un Ã©vÃ¨nement par ex)
// param object : le contexte d'exÃ©cution (le plus souvent this)
//       method : la mÃ©thode Ã  lier au contexte
function bindMethod(object, method) {
    return function() {
        return method.apply(object, arguments);
    }
}

// ------------------------------------------------------------------------------------------------
// Appel cross-domain
// permet de passer outre la limitation du httpRequest et de de faire des requÃªtes ajax sur d'autres
// domaines. La solution est d'ajouter une balise <script> au document, celle-ci pouvant provenir
// d'un autre domaine.
function CrossDomainCall(URL)
{
  var BaliseScript = document.createElement('script');
  BaliseScript.id = new Date().getTime(); // genere un id unique
  BaliseScript.language="JavaScript";
  BaliseScript.src = URL + '&ScriptID=' + BaliseScript.id;
  BaliseScript.type = 'text/javascript';
  document.body.appendChild(BaliseScript);
}

