// ProBase callback functions for SWFUpload

var swfuploadQueued = PbLib.g('Queued');
var swfuploadUploading = PbLib.g('Uploading');
var swfuploadCancelled = PbLib.g('Cancelled');
var swfuploadUploadingFinished = PbLib.g('Done');

// Javascript component has loaded: hide the "no javascript" file upload html element
function swfuploadLoaded()
{
	$('degradedUI' + this.id).hide();
	$('flashUI' + this.id).show();

	$(this.id + '_use_js').value = '1';

	this.showEmptyRow(true);

	// flag using Flash
	window.uploadUsingFlash = true;

	// enable single / multiple file picking
	this.setButtonAction(this.multiple ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE);

	// add move handler
	if (this.ordered) {
		var me = this;
		$("uploadlist" + this.id).onselectstart = function(){ return false; }
		$("uploadlist" + this.id).observe('mousedown', function(e){ me.startDrag(e); })
	}
}

SWFUpload.prototype.startDrag = function(event)
{
	var me = this;

	// find the active row
	var sourceTR = getActiveRow(event);
	if (!sourceTR) return;

	var moving = function(event)
	{
		// find current row
		var targetTR = getActiveRow(event);
		if (!targetTR) {
			// moving outside the container
			done();
			return;
		}
		// if source == target, skip
		if (sourceTR != targetTR) {
			// if target is located _before_ source, move source up
			if (targetTR.offsetTop < sourceTR.offsetTop) {
				targetTR.insert({before: sourceTR});
			} else {
				targetTR.insert({after: sourceTR});
			}
			// update the order hidden input
			me.updateOrderInput();
		}
	}

	var up = function(event)
	{
		done();
	}

	var done = function()
	{
		document.stopObserving('mousemove', moving);
		document.stopObserving('mouseup', up);
	}

	document.observe('mousemove', moving);
	document.observe('mouseup', up);

	Event.stop(event);
}

// Places the ids of all TRs in the hidden input used to store these
SWFUpload.prototype.updateOrderInput = function ()
{
	var input = $("uploadlist" + this.id + '_order');
	var ids = [];
	var uploadList = $("uploadlist" + this.id);
	var trs = uploadList.select('tr');
	for (var i = 2; i < trs.length; i++) {
		ids.push(trs[i].id);
	}

	input.value = ids.join(',');
}

function getActiveRow(event)
{
	var tr = Event.findElement(event, 'tr');
	if ((typeof tr == 'undefined') || tr == document || !tr.id) {
		return null;
	}
	return tr;
}

// File selection dialog is closed; start uploading immediately
function fileDialogComplete(filesSelected, filesQueued)
{
	this.startUpload();
	return true;
}

// If no file is present in the upload table, show an empty row
// It also affects the "disabled" status of the upload button
SWFUpload.prototype.showEmptyRow = function(hideIfEmpty)
{
	var uploadListTBody = $($("uploadlist" + this.id).tBodies[0]);
	var itemCount = uploadListTBody.select('tr').length;
	if (itemCount > 1 || !hideIfEmpty) {
		$("uploadlist" + this.id).show();
	}
	var show = (itemCount == 1);
	uploadListTBody.childNodes[0].style.display = show ? '' : 'none';
}

// Returns all submit buttons (FormElementButton) in the current form
// Presumes that the buttons have class 'submit'
function getSubmitButtons(swfupload)
{
	var form = $(swfupload.id + '_use_js').form;
	return $(form).select('button.submit');
}

// Deactivates all submit buttons. This is done while files are uploading
// to assure that the form is not submitted
function deactivateSubmitButtons(swfupload)
{
	var submits = getSubmitButtons(swfupload);
	swfupload.oldSubmitButtonTexts = [];
	for (var i = 0; i < submits.length; i++) {
		var submit = submits[i];
		var title = submit.innerHTML;
		swfupload.oldSubmitButtonTexts[i] = title;
		submit.innerHTML = "<img src='" + PbLib.getNewURI('/ui/uibase/img/loader.gif') + "' width='16' height='16' /> " +
			title + ' (' + PbLib.g('Please wait for uploads ...') + ')';
		submit.disabled = true;
	}
}

// Activates all submit buttons (again)
function activateSubmitButtons(swfupload)
{
	var submits = getSubmitButtons(swfupload);
	for (var i = 0; i < submits.length; i++) {
		var submit = submits[i];
		submit.innerHTML = swfupload.oldSubmitButtonTexts[i];
		submit.disabled = false;
	}
}

// Removes a file that has been uploaded this session, before the form was last submitted unsuccessfully,
// but has not yet been stored in Library
SWFUpload.prototype.removeUploadMeta = function(formelementId, tempMetaFile)
{
	new Ajax.Request(PbLib.getNewURI('l/' + this.module + '/removeupload/meta/' + formelementId + '/' + tempMetaFile));
	$('row_' + tempMetaFile).remove();

	this.showEmptyRow(false);
}

// Removes a file that has been uploaded this session, since the form was last submitted
SWFUpload.prototype.removeUploadFilename = function(formelementId, fileId, filename)
{
	new Ajax.Request(PbLib.getNewURI('l/' + this.module + '/removeupload/filename/' + formelementId + '/' + filename));
	$('row_' + fileId).remove();

	this.showEmptyRow(false);
}

// Removes a document, a value of this formelement, that is stored in Library
SWFUpload.prototype.removeDocument = function(formelementId, docId)
{
	$(this.id + '_keep_' + docId).checked = false;
	$(this.id + '_doc_' + docId).remove();

	this.showEmptyRow(false);
}

SWFUpload.prototype.removeAllFiles = function()
{
	var uploadListTBody = $("uploadlist" + this.id).tBodies[0];
	uploadListTBody.select('a.cancelbtn').each(function(a) {
		a.onclick();
	});
}

fileQueued =  function(file, queuelength)
{
	if (!this.multiple) {
		this.removeAllFiles();
	}

	var uploadlistTable = document.getElementById("uploadlist" + this.id);
	uploadlistTable.style.display = '';

	if (file.size > 1024 * 1024 * 1024) {
		var readable = file.size / (1024 * 1024 * 1024);
		var scale = 'GB';
	} else if (file.size > 1024 * 1024) {
		var readable = file.size / (1024 * 1024);
		var scale = 'MB';
	} else if (file.size > 1024) {
		var readable = file.size / 1024;
		var scale = 'kB';
	} else {
		var readable = file.size;
		var scale = 'B';
	}

	readable = Math.round(readable) + ' ' + scale;

	if (uploadlistTable && document.createElement) {
		var oRow = new Element('tr');
		oRow.id = 'row_' + file.id;

		var oCell = new Element('td');
		var inner = '';
		if (this.previewWidth) {
			inner +=
				"<div class='img-spacer' style='width:" + this.previewWidth + "px; height:" + this.previewHeight + "px'>" +
						"<img src='" + PbLib.getNewURI('ui/uibase/icon/24/rectangle.png') + "' />" +
				"</div>";
		}
		inner += file.name;
		oCell.innerHTML = inner;
		oCell.style.height = '2em';
		oRow.appendChild(oCell);

		var oCell = new Element('td').addClassName('upload-size');
		oCell.innerHTML = readable;
		oRow.appendChild(oCell);

		var oCell = new Element('td').addClassName('upload-status');
		oCell.innerHTML = swfuploadQueued + "<span style='padding-left: 5px; display: none;' id='progress_" + file.id + "'></span>";
		oCell.id = 'status_' + file.id;
		oRow.appendChild(oCell);

		var oCell = new Element('td');
		var removeImg = PbLib.getNewURI('ui/uibase/icons/16/remove.png');
		oCell.innerHTML = "<a id='deletebtn_" + file.id + "' class='cancelbtn' href='#' onclick='swfu" + this.id + ".cancelUpload(\"" + file.id + "\");return false'><img src='" + removeImg + "'></a>";
		oRow.appendChild(oCell);

		uploadlistTable.tBodies[0].appendChild(oRow);
	}

	this.showEmptyRow(false);
}

SWFUpload.prototype.uploadFileCancelled = function(file, queuelength)
{
	if (file) {
		$('row_' + file.id).remove();
	}
	this.showEmptyRow(false);
}

function uploadFileStart(file, position, queuelength)
{
	var cell = document.getElementById('status_' + file.id);
	cell.childNodes[0].nodeValue = swfuploadUploading;

	var progress = document.getElementById('progress_' + file.id);
	progress.style.display = '';

	deactivateSubmitButtons(this);
}

function uploadFileComplete(file) {
	if (file.filestatus == -4) {

		var cell = document.getElementById('status_' + file.id);
		cell.childNodes[0].nodeValue = swfuploadUploadingFinished;
		var elem = document.getElementById('status_' + file.id);
		elem.style.background = "";

		var elem = document.getElementById('progress_' + file.id);
		elem.style.display = 'none';

		var elem = document.getElementById('deletebtn_' + file.id);
		elem.onclick = function() { window['swfu' + this.id].removeUploadFilename(this.id, file.id, file.name); }.bind(this);

		this.updateOrderInput();
	}

	activateSubmitButtons(this);

	this.startUpload();
}

function uploadProgress(file, bytesLoaded) {
	var progress = document.getElementById('status_' + file.id);
	var percent = Math.ceil((bytesLoaded / file.size) * 100);
	var imgProgress = PbLib.getNewURI('/ui/uibase/img/progressbar.png');
	var parentWidth = progress.offsetWidth;
	var offset = -400 + (percent / 100) * parentWidth;
	progress.style.background = "url(" + imgProgress + ") no-repeat " + offset + "px 0";
	progress.style.width = '100px';
	progress.removeClassName('upload-status');

	var progress = document.getElementById('progress_' + file.id);
	progress.innerHTML = '(' + percent + '%)';
}

function uploadError(file, errorCode, message) {
	this.uploadFileCancelled(file);

	activateSubmitButtons(this);
}

function fileQueueError(file, errorCode, message) {

	if (errorCode == -110) {
		alert(PbLib.g('The file exceeds the allowed size.'));
	} else {
		alert(message);
	}

}
