
/* This is an example of how to cancel all the files queued up.  It's made somewhat generic.  Just pass your SWFUpload
object in to this method and it loops through cancelling the uploads. */
function cancelQueue(instance) {
//	document.getElementById(instance.customSettings.cancelButtonId).disabled = true;
	$('#' + instance.customSettings.cancelButtonId).addClass('disabled');	
	instance.stopUpload();
	var stats;
	
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} while (stats.files_queued !== 0);
	
}

/* **********************
   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 fileDialogStart() {
	/* I don't need to do anything here */
}
function fileQueued(file) {
	try {
		// You might include code here that prevents the form from being submitted while the upload is in
		// progress.  Then you'll want to put code in the Queue Complete handler to "unblock" the form
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Подготовка...");
		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("Файл слишком большой.");
			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("Нельзя загружать пустые файлы.");
			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("Неверный тип файла.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			alert("Вы выбрали слишком много файлов.  " +  (message > 1 ? "You may only add " +  message + " more files" : "You cannot add any more files."));
			break;
		default:
			if (file !== null) {
				progress.setStatus("Неизвестная ошибка");
			}
			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 (numFilesQueued > 0) {
			$('#' + this.customSettings.cancelButtonId).removeClass('disabled');
		}
		
		/* I want auto start and I can do that here */
		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 */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Загрузка...");
		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("Загрузка...");
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Загрузка завершена.");		
		progress.getID3Tags(file);		//получаем и выводим инфу из ID3 тэгов
		progress.setComplete();
		progress.toggleCancel(false);
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued === 0) {
//			document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			$('#' + this.customSettings.cancelButtonId).addClass('disabled');
		} else {	
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}

}

function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Ошибка при загрузке: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			progress.setStatus("Ошибка конфигурации.");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Загрузка не удалась.");
			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("Ошибка на сервере");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Ошибка доступа");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Достигнут предел загрузок.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
			progress.setStatus("Файл не найден.");
			this.debug("Error Code: The file was not found, 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 (this.getStats().files_queued === 0) {
	//			document.getElementById(this.customSettings.cancelButtonId).disabled = true;
				$('#' + this.customSettings.cancelButtonId).addClass('disabled');				
			}
			progress.setStatus("Отменено");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Остановлено");
			break;
		default:
			progress.setStatus("Неизвестная ошибка: " + error_code);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}
function addslashes(str) {
	str=str.replace(/\"/g,"'");
	return str;
}
/********************************************/
	function confirmUploads() {
		$('#uploadedFilesConfirm .profileButton').replaceWith("<img src='/media/images/beta-pics/loaders/universal_loader_01.gif'/>");
		var info = new Array;
		var forms = $(".uploadedFileName");
		var jSonTracks = new Array;
		jSonTracks = '{"tracks":[';
		for (var i = 0; i < forms.length-1; i++) {
			var tds = forms[i].getElementsByTagName("span");
			info[0] = tds[0].innerHTML;
			info[1] = tds[1].innerHTML;			
			info[2] = tds[2].innerHTML;			
			var inputs = forms[i].getElementsByTagName("input");
			for (j = 0; j < inputs.length; j++) {
				info[j+3] = $(inputs[j]).val();
			}
			jSonTracks += '{';
			jSonTracks += '"fileName":"' + addslashes(info[0]) + '", ';						
			jSonTracks += '"title":"' + addslashes(info[4]) + '", ';			
			jSonTracks += '"performer":"' + addslashes(info[3]) + '", ';						
			jSonTracks += '"album":"' + addslashes(info[5]) + '", ';						
			jSonTracks += '"tags":"' + addslashes(info[6]) + '", ';						
			jSonTracks += '"year":"' + addslashes(info[7]) + '", ';									
			jSonTracks += '"trackLength":"' + addslashes(info[1]) + '", ';						
			jSonTracks += '"bitrate":"' + addslashes(info[2]) + '" ';						
			jSonTracks += '}';
			if(i!=forms.length-2)
				jSonTracks += ', ';			

		}
		jSonTracks += ']}';		
    	$.post('/track/create/', {
    	   tracks: jSonTracks
	 	   }, function(data){
				var tracks = '';
				var plists = $('#uploaderWnd .fromList');
		   		jQuery.each(plists, function(){
					tracks = '[';
					jQuery.each(data, function(){
						tracks += '{"id":"' + this.id + '", ';
						tracks += '"performer":"' + this.performer + '", ';
						tracks += '"title":"' + this.title + '", ';
						tracks += '"trackLength":"' + this.trackLength + '"}';					
						if(this != data[data.length-1])
							tracks += ', ';						
					});
					tracks += ']';
					if(!tracklists[this.id])
						tracklists[this.id] = new trackList;
					tracklists[this.id].addSong(tracks, this.id, $(this).html());
					if(this==plists[plists.length-1]){
						$('#uploadedFilesInfo').remove();
						$('#uploadedFilesConfirm').replaceWith('<div class="uploadeHello"><img style="margin-left:48px;margin-top:18px;margin-right:20px;" src="/media/images/lips.jpg"/>Спасибо</div>');
						setTimeout(function(){
							$('a.uploaderButton').css('background', 'url("/media/images/uploader_off.gif") no-repeat top left');							
							$('#uploaderBottomBanner').css('background-position', '0px 0px');							
							uploaderState = 0;							
							Uploader_Object('hideWnd');			
							$('#uploaderWnd').remove();
						}, 2000);						
					}
				});
			});	
	}