/* Demo Note:  This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete.
The FileProgress class is not part of SWFUpload.
*/

//lazy ugly hack
var byteTracker = {};
var timeTracker = {};

var SWFUexternal = {};

SWFUexternal.macko = function(swfu)
{
	var totFileSize = 0;
	var loopCnt = swfu.getStats().files_queued + swfu.getStats().upload_cancelled + swfu.getStats().queue_errors;

	timeTracker = {};
	byteTracker = {};
	for (var i = 0; i < loopCnt; i++)
	{
		tmpFile = swfu.getFile(i);

		alert(tmpFile.filestatus);
		if (tmpFile.filestatus == -1)
		{
			//Set sizeRemaining
			byteTracker[tmpFile.id] = 0
			totFileSize = totFileSize + tmpFile.size;
		} //if
	} //for

}

SWFUexternal.calculateMovingAverage = function (history) 
{
	var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0;
	var i;
	var mSum = 0, mCount = 0;
	
	size = history.length;
	
	// Check for sufficient data
	if (size >= 8) {
		// Clone the array and Calculate sum of the values 
		for (i = 0; i < size; i++) {
			vals[i] = history[i];
			sum += vals[i];
		}

		mean = sum / size;

		// Calculate variance for the set
		for (i = 0; i < size; i++) {
			varianceTemp += Math.pow((vals[i] - mean), 2);
		}

		variance = varianceTemp / size;
		standardDev = Math.sqrt(variance);
		
		//Standardize the Data
		for (i = 0; i < size; i++) {
			vals[i] = (vals[i] - mean) / standardDev;
		}

		// Calculate the average excluding outliers
		var deviationRange = 2.0;
		for (i = 0; i < size; i++) {
			
			if (vals[i] <= deviationRange && vals[i] >= -deviationRange) {
				mCount++;
				mSum += history[i];
			}
		}
		
	} else {
		// Calculate the average (not enough data points to remove outliers)
		mCount = size;
		for (i = 0; i < size; i++) {
			mSum += history[i];
		}
	}

	return mSum / mCount;
};

SWFUexternal.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) 
{
	var i, unit, unitDivisor, unitLabel;

	if (baseNumber === 0) {
		return "0 " + unitLabels[unitLabels.length - 1];
	}
	
	if (singleFractional) {
		unit = baseNumber;
		unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : "";
		for (i = 0; i < unitDivisors.length; i++) {
			if (baseNumber >= unitDivisors[i]) {
				//unit = (baseNumber / unitDivisors[i]).toFixed(2);
				unit = (baseNumber / unitDivisors[i]).toFixed(0);
				unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : "";
				break;
			}
		}
		
		return unit + unitLabel;
	} else {
		var formattedStrings = [];
		var remainder = baseNumber;
		
		for (i = 0; i < unitDivisors.length; i++) {
			unitDivisor = unitDivisors[i];
			unitLabel = unitLabels.length > i ? " " + unitLabels[i] : "";
			
			unit = remainder / unitDivisor;
			if (i < unitDivisors.length -1) {
				unit = Math.floor(unit);
			} else {
				//unit = unit.toFixed(2);
				unit = unit.toFixed(0);
			}
			if (unit > 0) {
				remainder = remainder % unitDivisor;
				
				formattedStrings.push(unit + unitLabel);
			}
		}
		
		return formattedStrings.join(" ");
	}
};


/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
function fileQueued(file) 
{
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Feltöltésre várakozik. Kérjük, nyomja meg a Feltöltés gombot.");
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}
}

function fileQueueError(file, errorCode, message) 
{
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) 
{
	try {
		if (numFilesSelected > 0) 
		{
			document.getElementById(this.customSettings.progressTarget).style.display = 'block';
			document.getElementById(this.customSettings.cancelButtonId).style.visibility = 'visible';
			//xxx
			document.getElementById(this.customSettings.cancelButtonId).style.display= '';

			var totFileSize = 0;
			this.customSettings.totalBytesRemaining = 0;

			//jquery alternative
			//var flist = $("#fsUploadProgress > div[id^='SWFUpload_']");
			var flist = $$("#fsUploadProgress > div[id^='SWFUpload_']");

			timeTracker = {};
			byteTracker = {};
			for (var i = 0; i < flist.length; i++)
			{
				var fileid = flist[i].id;
				var filedata = this.getFile(fileid);
				//These are files that are in the queue!

				if ( $(fileid).readAttribute('status') == 'waiting' )
				{
					byteTracker[fileid] = 0;
					totFileSize = totFileSize + filedata.size;
				} //if

				//alert(this.getFile( flist[i].id ).filestatus );
				//alert( this.getFile(flist[i].id).val('className') );
			} //for

			this.customSettings.totalBytesQueued = totFileSize;
			this.customSettings.totalBytesRemaining = this.customSettings.totalBytesQueued;

//XXXHERE
//			alert(totFileSize);
			
			//alert(this.customSettings.totalBytesRemaining);
			
/*
mi kell:
ossz bytemeret
eddig feltoltott byteok szama vagy hatralevo, feltoltendo byteok szama
*/

			//var listx = $("div[id^='SWFUpload_0_']").css('float','left');
			//alert(listx.length);

			//document.getElementById('submit_browse').style.visibility = 'visible';

			document.getElementById('uploadbutton_enabled').style.display = '';
			document.getElementById('uploadbutton_disabled').style.display = 'none';

			document.getElementById('uploadSuccess').style.display = 'none';
			
			df.gid('status_err').innerHTML = '-';
			df.gid('status_ok').innerHTML = '-';

//			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		} //if

		/* I want auto start the upload and I can do that here */
		//XXX
		//this.startUpload();
	} 
	catch (ex)
	{
        this.debug(ex);
	}
}

function uploadStart(file) {
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and
		return true to indicate that the upload should start.
		It's important to update the UI here because in Linux no uploadProgress events are called. The best
		we can do is say we are uploading.
		*/

		document.getElementById('uploadbutton_enabled').style.display = 'none';
		document.getElementById('uploadbutton_disabled').style.display = '';

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Feltöltés...");
		progress.toggleCancel(true, this);
	}
	catch (ex) {}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) 
{
	try 
	{
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("Feltöltés...");
		var bytesDelta = 0;

		bytesDelta = bytesLoaded - byteTracker[file.id];
		byteTracker[file.id] = bytesLoaded;

		this.customSettings.totalBytesRemaining -= bytesDelta;
		//this.customSettings.htmlobjProgressTotalPercentage.innerHTML = ((this.customSettings.totalBytesQueued-this.customSettings.totalBytesRemaining) / this.customSettings.totalBytesQueued) *100;
		
		// Get time and deltas
		var now = (new Date()).getTime();
		var lastTime = timeTracker.lastTime;
		var deltaTime = now - lastTime;
		//var deltaBytes = bytesUploaded - tracking.bytesUploaded;
		var deltaBytes = bytesDelta;
		
		if (!timeTracker.startTime)
			timeTracker.startTime = now;
		
		if (deltaBytes === 0 || deltaTime === 0) {
			return tracking;
		}

		// Update tracking object
		timeTracker.lastTime = now;
		timeTracker.bytesUploaded = this.customSettings.totalBytesQueued - this.customSettings.totalBytesRemaining;

		this.customSettings.htmlobjProgressTotalPercentage.innerHTML = this.customSettings.totalBytesRemaining;
		
		// Calculate speeds
		timeTracker.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000);
		timeTracker.averageSpeed = (timeTracker.bytesUploaded * 8) / ((now - timeTracker.startTime) / 1000);
		
		// Calculate moving average
		if (!timeTracker.movingAverageHistory)
			timeTracker.movingAverageHistory = [];

		timeTracker.movingAverageHistory.push(timeTracker.currentSpeed);

		if (timeTracker.movingAverageHistory.length > 10) {
			timeTracker.movingAverageHistory.shift();
		}
		
		timeTracker.movingAverageSpeed = SWFUexternal.calculateMovingAverage(timeTracker.movingAverageHistory);
		
		// Update times
		timeTracker.timeRemaining = (this.customSettings.totalBytesQueued - timeTracker.bytesUploaded) * 8 / timeTracker.movingAverageSpeed;
		timeTracker.timeElapsed = (now - timeTracker.startTime) / 1000;
		
		var bps = timeTracker.bytesUploaded / timeTracker.timeElapsed;
		//bytesUploaded hianycikk
		
		//this.customSettings.htmlobjProgressTotalPercentage.innerHTML = this.customSettings.totalBytesRemaining / bps;

		
		//this.customSettings.htmlobjProgressTotalPercentage.innerHTML = this.customSettings.totalBytesQueued +':'+ timeTracker.bytesUploaded;

		//var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"];
		//this.customSettings.htmlobjProgressTotalPercentage.innerHTML = SWFUexternal.formatUnits(timeTracker.averageSpeed, bpsUnits, bpsUnitLabels, true);
		

		var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["nap", "óra", "perc", "mp"];
		//this.customSettings.htmlobjProgressTotalPercentage.innerHTML = SWFUexternal.formatUnits(timeTracker.timeElapsed, timeUnits, timeUnitLabels, false);
		this.customSettings.htmlobjProgressTotalPercentage.innerHTML = SWFUexternal.formatUnits(this.customSettings.totalBytesRemaining / bps, timeUnits, timeUnitLabels, false);
		


		// Update percent
		timeTracker.percentUploaded = (timeTracker.bytesUploaded / file.size * 100);
		
	
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) 
{
	try 
	{
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Kész.");
		progress.toggleCancel(false);

		statusok = df.gid('status_ok');
		statuserr = df.gid('status_err');
		
		//-*-* Update successcnt
		if (statusok.innerHTML == '-')
		{
			statusok.innerHTML = 0;
		} //if
		
		statusok.innerHTML = parseInt(statusok.innerHTML)+1;
		
	} catch (ex) {
		this.debug(ex);
	}
} //function

function uploadError(file, errorCode, message) 
{
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		//-*-* Update errorcnt
		statuserr = df.gid('status_err');
		if (statuserr.innerHTML == '-')
			statuserr.innerHTML = 0;

		statuserr.innerHTML = parseInt(statuserr.innerHTML)+1;
		
		//-*-* Add erroneous files
		df.gid('status_errfiles_header').style.display = 'table-row';
		df.gid('status_err_header').style.display = 'table-row';
		
		df.gid('status_errfiles').innerHTML += file.name+"<BR>";
//xxxxxxxxxxxx
		switch (errorCode) 
		{
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:

			//message holds the HTTP error code, so based on that we do some checking 
			//upload_url gives back the following codes
			switch(message)
			{
				case '495':
					message = 'A fájl nem - vagy hibásan - érkezett meg a szerverre. <BR>Kérjük értesítse az üzemeltetőt és levélben mellékelje a hibás fájt. Köszönjük!';
					progress.setStatus("Feltöltési hiba: " + message);
				break;

				case '496':
					message = 'Hibás fájlformátum';
					progress.setStatus("Feltöltési hiba: " + message);
				break;

				default:
					progress.setStatus("Feltöltési hiba: " + message);
					this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
				break;
			} //switch

		break;

		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Feltöltés sikertelen.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Szerver (IO) hiba");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Biztonsági hiba");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Túllépte a feltöltési méretlimitet.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			// If there aren't any files left (they were all cancelled) disable the cancel button
			if (this.getStats().files_queued === 0) 
			{
				//document.getElementById(this.customSettings.cancelButtonId).disabled = true;
				document.getElementById(this.customSettings.cancelButtonId).style.visibility = 'hidden';
				//xxx
				document.getElementById(this.customSettings.cancelButtonId).style.display = 'none';
			}
			progress.setStatus("Megszakítva.");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Leállítva.");
			break;
		default:
			progress.setStatus("Egyéb hiba: " + errorCode);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function uploadComplete(file) {
	if (this.getStats().files_queued === 0) 
	{
		document.getElementById(this.customSettings.cancelButtonId).style.visibility = 'hidden';
		document.getElementById(this.customSettings.cancelButtonId).style.display = 'none';
		
		photoupload.gotupdated = true;
		
		if (df.gid('status_err').innerHTML != '-')
		{
			//df.gid('status_refreshme').style.display = 'table-row';
			//df.gid('refreshme').style.visibility = 'visible';
			//errorbaby
		}
		else
		{
			//df.enableArea('albumhide','Albums'); 
			//location.href = '/fotofeltoltes/'+album_id+'/';
		} //if

		//Reload albums
		photoupload.albumList(photoupload.album_id);
		df.enableArea('albumhide','Albums'); 

		//Show infopanel
		alert('Sikeres feltöltés, a rendelés folytatásához kérem zárja be a képfeltöltő ablakot!');
		
	} //if
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) 
{
	var status = document.getElementById("UploadStatus");
	
		if (statuserr.innerHTML == '-')
			document.getElementById('uploadSuccess').style.display = '';

	//status.innerHTML = numFilesUploaded + '/' + numFilesQueued + " kép" + (numFilesUploaded === 1 ? "" : "") + " feltöltve.";
}

