// Seteo general
function getSettings(obj){
	return {
        flash_url : obj.url_final+'js/swfupload/swfupload.swf',
        upload_url: obj.url_final+'inc/ajax/upload_swf.php',
        post_params: obj.post,
        file_size_limit : obj.peso,
        file_types : obj.tipos,
        file_types_description : 'Archivos permitidos',
        file_upload_limit : obj.upload_limit,
        file_queue_limit : 0,
        custom_settings : {
            nombre : obj.nombre,
            div_aviso: obj.nombre+'_aviso',
            progressTarget : obj.upload_progress,
            cancelButtonId : 'cancelar_archivos',
            peso_permitido : obj.peso,
            uploaded : false
        },
    
        // Button settings
        button_image_url: obj.url_final+'images/XPButtonUploadText.png',
        button_width: '90',
        button_height: '22',
        button_placeholder_id: 'boton_'+obj.nombre+'_swfu',
        button_text: '<span class="theFont">Examinar...</span>',
        button_text_style: '.theFont { font-size: 14; text-align: center; width: 90px; font-family: arial, helvetica; }',
        button_action : obj.accion,
    
        debug: false,
    
        file_dialog_start_handler: fileDialogStart,
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : obj.file_dialog_complete_handler,
    
        upload_start_handler : uploadStart,
    
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : obj.upload_complete_handler
    
        //queue_complete_handler : queueComplete
	};
}

// acción al inicio de selección de archivo
function fileDialogStart() {

	$('#'+this.customSettings.div_aviso).html('');
    $('#preview_'+this.customSettings.nombre).html('');	
	$('#'+this.customSettings.div_aviso).removeClass('aviso');
	this.cancelUpload();

}

// archivo en espera
function fileQueued(file) {
	try {
		if(!ValidaCampo(file.name, '.-')) {
            var progress = new FileProgress(file, this.customSettings.progressTarget, this.customSettings.nombre);
            progress.setStatus('Pendiente...');
            progress.toggleCancel(true, this);
            $('#'+this.customSettings.nombre).val(file.name);
            // marco el reemplazo si el archivo tiene el mismo nombre que el original
            if(file.name==$('#'+this.customSettings.nombre+'_original').val()){
                $('#'+this.customSettings.nombre+'_reemplaza').val(1);
            }
            $('#'+this.customSettings.div_aviso).html(file.name);
            $('#'+this.customSettings.div_aviso).addClass('aviso');
        }

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

}

// acción al finalizar la selección de archivos diferido
function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			$('#'+this.customSettings.cancelButtonId).removeAttr('disabled');
		}
		
	} catch (ex)  {
        this.debug(ex);
	}
}

// acción al iniciar la subida
function uploadStart(file) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget, this.customSettings.nombre);
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
        var kb_subidos = Math.ceil(bytesLoaded / 1024)+' KB';
        var kb_totales = Math.ceil(bytesTotal / 1024)+' KB';
        var texto_status = 'Subiendo Archivo... Total: {total} Subidos: {subidos} ({porcentaje} %)';
        texto_status = texto_status.replace('{total}', 0);
        texto_status = texto_status.replace('{subidos}', 0);
        texto_status = texto_status.replace('{porcentaje}', 0);
		
        progress.setStatus(texto_status);
		progress.toggleCancel(true, this);
	}
	catch (ex) {}
	
	return true;
}

// acción de progreso de carga
function uploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
        var kb_subidos = Math.ceil(bytesLoaded / 1024)+' KB';
        var kb_totales = Math.ceil(bytesTotal / 1024)+' KB';
        var texto_status = 'Subiendo Archivo... Total: {total} Subidos: {subidos} ({porcentaje} %)';
        texto_status = texto_status.replace('{total}', kb_totales);
        texto_status = texto_status.replace('{subidos}', kb_subidos);
        texto_status = texto_status.replace('{porcentaje}', percent);

		var progress = new FileProgress(file, this.customSettings.progressTarget, this.customSettings.nombre);
		progress.setProgress(percent);
		progress.setStatus(texto_status);
	} catch (ex) {
		this.debug(ex);
	}
}

// exito en la subida
function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget, this.customSettings.nombre);
		progress.setComplete();
        msg = serverData.split('||');
        mensaje_servidor = 'Completo: '+msg[0];
		progress.setStatus(mensaje_servidor);
        $('#'+this.customSettings.div_aviso).html(mensaje_servidor);
		progress.toggleCancel(false);
		$('#'+this.customSettings.nombre).val(msg[1]);
        this.customSettings.previo = msg[2];

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

// una vez que terminó la subida diferida
function uploadComplete(file) {
	if (this.getStats().files_queued > 0) {
        this.startUpload();
    } else {
        this.customSettings.uploaded = true;
        $('#' + this.customSettings.cancelButtonId).attr('disabled','disabled');
        
        var cadena_if = '';
        
        for(i=1;i<=total_archivos;i++){
        	cadena_if = cadena_if + 'swfu_' + archivos[i] + '.customSettings.uploaded === true';
            if(i<total_archivos) {
            	cadena_if = cadena_if + ' && ';
            }
        } // fin del bucle
        if (eval(cadena_if)) {
            formulario.submit();
    	}
        
	}
}

// acción al finalizar la selección de archivos directo
function fileDialogComplete_directo(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			$('#'+this.customSettings.cancelButtonId).removeAttr('disabled');
		}
	
    	this.startUpload();
    
	} catch (ex)  {
        this.debug(ex);
	}
}

// una vez que terminó la subida diferida
function uploadComplete_directo(file) {
    $('#preview_'+this.customSettings.nombre).html(this.customSettings.previo);	
}

function cancelar_archivos() {
    // recorro los archivos
    for(i=1;i<=total_archivos;i++){
        cadena_archivo = 'swfu_' + archivos[i] + '.cancelQueue()';
        eval(cadena_archivo);
    } // fin del bucle
}

function queueComplete(numFilesUploaded) {
	texto_status = '{numero} archivo/s subido/s';
    $('#'+this.customSettings.div_aviso).html(texto_status.replace('{numero}', numFilesUploaded));
}

