/* 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. */
var width_flash = 102;

function cancelQueue(instance) 
{
	$(instance.customSettings.cancelButtonId).disabled = true;
	$(instance.customSettings.cancelButtonId).className = "btn_small_small btn_disabled";
	$(instance.customSettings.cancelButtonId).style.display = "none";
	
	/* show button */
	upload1.getMovieElement().style.width = width_flash + "px";
	
	
	if( $('libros').value != "" || $('fsUploadProgress1').innerHTML != "" )
	{
		$('libros').value = "";
				
		/* show button */
		upload1.getMovieElement().style.width = width_flash + "px";
		
		$('progressBar1').empty();
		$('progressWrapper1').style.display = "none";
		
		paginas_total = 0;
		$('paginas_total').value = 0;
	}
	
	instance.stopUpload();
	var stats;
	
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} 
	while (stats.files_queued !== 0);
	
	$('fsUploadProgress1').empty();
}

/* **********************
   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 */
	$('progressBar1').empty();
	$('fsUploadProgress1').empty();
}

function fileQueued(fileObj) {
	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(fileObj, this.customSettings.progressTarget);
		//progress.SetStatus("pendiente...");
		progress.ToggleCancel(true, this);
		
	} catch (ex) { this.debug(ex); }
}

function fileQueueError(fileObj, error_code, message) {
	try {
		if (error_code === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			Dialog("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(fileObj, this.customSettings.progressTarget);
		progress.SetError();
		progress.ToggleCancel(false);

		switch(error_code) {
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				progress.SetStatus("File is too big.");
				this.debug("Error Code: File too big, File name: " + fileObj.name + ", File size: " + fileObj.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: " + fileObj.name + ", File size: " + fileObj.size + ", Message: " + message);
				break;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				progress.SetStatus("Invalid File Type.");
				this.debug("Error Code: Invalid File Type, File name: " + fileObj.name + ", File size: " + fileObj.size + ", Message: " + message);
				break;
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				Dialog("You have selected too many files.  " +  (message > 1 ? "You may only add " +  message + " more files" : "You cannot add any more files."));
				break;
			default:
				if (fileObj !== null) {
					progress.SetStatus("Unhandled Error");
				}
				this.debug("Error Code: " + error_code + ", File name: " + fileObj.name + ", File size: " + fileObj.size + ", Message: " + message);
				break;
		}
		
		/* show button */
		upload1.getMovieElement().style.width = width_flash + "px";
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(num_files_queued) {
	try {
		if (this.getStats().files_queued > 0) {
			/* hide button */
			upload1.getMovieElement().style.width = "0px";
	
			$(this.customSettings.cancelButtonId).disabled = false;
			$(this.customSettings.cancelButtonId).className = "btn_small_small";
			$(this.customSettings.cancelButtonId).style.display = "";
			
			$('continuar_1').disabled = false;
			$('continuar_1').className = "btn_green_cuadcirc";
			
			
			document.getElementById('paso_col_1').style.display = "";
			if( $defined(mySlide1) )
			{
				mySlide1.slideIn();
			}
		}
		
		/* I want auto start and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function uploadStart(fileObj) {
	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(fileObj, this.customSettings.progressTarget);
		//progress.SetStatus("subiendo...");
		progress.ToggleCancel(true, this);
	}
	catch (ex) {}
	


	return true;
}

function uploadProgress(fileObj, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(fileObj, this.customSettings.progressTarget);
		progress.SetProgress(percent);
		//progress.SetStatus("subiendo...");
	} catch (ex) { 
		this.debug(ex); 
	}
}

function uploadSuccess(fileObj, server_data) {
	var prts = [];
	prts = server_data.split("|");

	if( prts[1] == undefined || prts[2] == undefined || prts[3] == undefined )
	{
		try {
			var progress = new FileProgress(fileObj, this.customSettings.progressTarget);
			progress.SetError();
			progress.SetStatus("cancelado.");
			progress.ToggleCancel(false);
		}
		catch(e) {
		}
		
		
		if( prts[0].match(/encrypted/i) )
		{
			Dialog('El archivo esta encriptado');
		}
		else if( prts[0] == "error1" )
		{
			Dialog('No ha sido posible leer el n&uacute;mero de p&aacute;ginas del documento ' + fileObj.name);
		}
		else if( prts[0] == "error2" )
		{
			Dialog('El archivo debe tener un m&iacute;nimo de ' + minnumpag +  ' p&aacute;ginas (' + fileObj.name + ')');
		}
		else if( prts[0] == "error3" )
		{
			Dialog('El archivo debe tener un maximo de ' + maxnumpag +  ' p&aacute;ginas (' + fileObj.name + ')');
		}
		else if( prts[0].match(/encrypted/i) )
		{
			Dialog('pdf error');
		}
		else
		{
			Dialog('error desconocido ');
		}
		
		try {
			$(this.customSettings.cancelButtonId).disabled = true;
			$(this.customSettings.cancelButtonId).className = "btn_small_small btn_disabled";
			$(this.customSettings.cancelButtonId).style.display = "none";

			/* show button */
			upload1.getMovieElement().style.width = width_flash + "px";
		}
		catch(ex) {
		}
		
		return false
	}
	
	try {
		
		addLibro(prts[0], prts[1]);
		
		var ico;
		if( fileObj.name.match(/\.ppt$/i) ) {
			ico = "<img src=img/powerpoint.png />";
		}
		else if( fileObj.name.match(/\.doc$/i) ) {
			ico = "<img src=img/doc-document.png />";
		}
		else {
			ico = "<img src=img/pdf-document.png />";
		}
		
		var cname = fileObj.name.length > 11 ? fileObj.name.substr(0, 11) + "..." : fileObj.name;
		
		name = "<input type=\"hidden\" name=\"tamanos[]\" value=\"" + prts[3] + "\" /><!-- <a href=\"javascript:void(0)\" onclick=\"javascript:borrarLibroUp('" + fileObj.id + "', '" + prts[0] + "', '" + prts[1] + "')\" class=\"progressCancel\"><img src=img/delete.png /></a> -->" + ico + cname + "<br /><b>P&aacute;ginas:</b> <span style=\"font-weight:normal\">" + prts[1] + "</span><br /><b>Tama&ntilde;o:</b> <span style=\"font-weight:normal\">" + ( (prts[2] < 1024) ? prts[2] + "b" : parseInt(prts[2]/1024) + "kb") + "</span><br /><b>Medida:</b> <span style=\"font-weight:normal\">" + prts[3] + "</span>";
		
		if( !prts[3].match(/(210x297|216x279|170x235|150x210|190x190|229x178|108x175)/) )
		{
			Dialog("<span>El libro que usted ha subido no coincide con ninguno de nuestros formatos<br />elija uno de los formatos para convertir<br /></span>"+
				   	"<span><select onchange=\"javascript:justifyLibro(this.value); Effect.fade('ventanaalert');\">"+
						"<option value=\"\"> -- Seleccionar -- </option>"+
						"<option value=\"210x297\">210x29.7 A4</option>"+
						"<option value=\"216x279\">216x27.9</option>"+
						"<option value=\"170x235\">170x23.5</option>"+
						"<option value=\"150x210\">15x21</option>"+
						"<option value=\"190x190\">19x19</option>"+
						"<option value=\"229x178\">22.9x17.8</option>"+
						"<option value=\"108x175\">10.8x17.5</option>"+ 
					"</select></span>");
		}
		
		if( $("up_" + fileObj.id) )
		{
			$("up_" + fileObj.id).innerHTML = name;

			var progress = new FileProgress(fileObj, this.customSettings.progressTarget);
			progress.SetComplete();
			progress.SetStatus("");
			progress.ToggleCancel(false);
			
			if( previewPags && $type(previewPags) == "function" )
			{
				previewPags(prts[1], 0, 0);
			}
		}
		else
		{
			Dialog('Archivo enviado con exito.');
			closeBox();
			$("flashUI1").innerHTML = name;
			$("paso_col_1").style.display = "";
			mySlide1.slideIn();
		}

	} catch (ex) { this.debug(ex); }
}

function uploadComplete(fileObj) {
	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;
			////document.getElementById(this.customSettings.cancelButtonId).className = "btn_small_small btn_disabled";
		} else {	
			this.startUpload();
		}
	} catch (ex) { this.debug(ex); }

}

function uploadError(fileObj, error_code, message) {
	try {
		var progress = new FileProgress(fileObj, this.customSettings.progressTarget);
		progress.SetError();
		progress.ToggleCancel(false);

		$(this.customSettings.cancelButtonId).disabled = true;
		$(this.customSettings.cancelButtonId).className = "btn_small_small btn_disabled";
		$(this.customSettings.cancelButtonId).style.display = "none";

		/* show button */
		upload1.getMovieElement().style.width = width_flash + "px";


		switch(error_code) {
			case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
				progress.SetStatus("Upload Error: " + message);
				this.debug("Error Code: HTTP Error, File name: " + fileObj.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
				progress.SetStatus("Configuration Error");
				this.debug("Error Code: No backend file, File name: " + fileObj.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
				progress.SetStatus("Upload Failed.");
				this.debug("Error Code: Upload Failed, File name: " + fileObj.name + ", File size: " + fileObj.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.IO_ERROR:
				progress.SetStatus("Server (IO) Error");
				this.debug("Error Code: IO Error, File name: " + fileObj.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
				progress.SetStatus("Security Error");

				this.debug("Error Code: Security Error, File name: " + fileObj.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				progress.SetStatus("Upload limit exceeded.");
				this.debug("Error Code: Upload Limit Exceeded, File name: " + fileObj.name + ", File size: " + fileObj.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
				progress.SetStatus("File not found.");
				this.debug("Error Code: The file was not found, File name: " + fileObj.name + ", File size: " + fileObj.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: " + fileObj.name + ", File size: " + fileObj.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				if (this.getStats().files_queued === 0) {
					document.getElementById(this.customSettings.cancelButtonId).disabled = true;
				}
				progress.SetStatus("cancelado.");
				progress.SetCancelled();
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				progress.SetStatus("detenido.");
				break;
			default:
				progress.SetStatus("Unhandled Error: " + error_code);
				this.debug("Error Code: " + error_code + ", File name: " + fileObj.name + ", File size: " + fileObj.size + ", Message: " + message);
				break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}
