var vCadena = 0;
var vNumero = 1;
var vEmail = 2;
var sColorOrgnl = '#000000';
var sColorInvld = '#ff5c00';
var aArchivos;

function fnListaArchivos() {
	aArchivos = $("input[name=archivos]:checked");
	var aObjetos = new Array();
	$.each(aArchivos, function(i, v) {
		aObjetos.push(v.value);
	});
	return aObjetos; 
}

function fnTodosNinguno(opcion) {
	var chkd = $(opcion).attr("checked");
	aArchivos = $("input[name=archivos]");
	$.each(aArchivos, function(i, v) {
		v.checked = chkd;
	});			
}

function fnMenuOpcion(lnk) {
	var id; var href; var w = 450; var h = 150; var grp = 'iframe';
	var bSigue = true;
	var bArchivos = false;
	var sError = '';
	var nAltoPorArchivo = 5;
	var oMenu = $('#' + lnk);
	id = oMenu.attr('id');
	href = oMenu.attr('href') + '?';
	switch(id) {
		case 'Usuarios':
			w = 700; h = 500;
			break;
		case 'Crear':
		case 'Subir':
			h = 220;
			break;
		case 'Borrar':
			bSigue = confirm("Esta seguro de querer borrar la lista de archivo?");
		case 'Mover':
		case 'Descargar':
			nAltoPorArchivo = 0;
			h = 170;
		case 'Renombrar':
			bArchivos = true;
			break;
	}
	if (bArchivos) {
		var aLista = fnListaArchivos();
		h = h + aLista.length * nAltoPorArchivo; 
		if (aLista.length) {
			var sFilesQS = aLista.join(',');
			href += 'file=' + sFilesQS + '&';
		} else {
			bSigue = false;
			sError = "Seleccione uno o mas archivos.";
		}
	}
	if (bSigue) {
		href += 'width=' + w + '&height=' + h + ';&keepThis=true&TB_iframe=false';
		if ($.browser.msie) {
			w += 25;
			h += 20;
			fnNuevaVentana(href, id, {'width':w, 'height':h, 'scrollbars': 'no', 'resizable':'no', 'toolbar':'no'}, false);
		} else {
			tb_show(id, href, grp);
		}
	} else {
		if (sError != '') { alert(sError); }			
	}
	$("#TB_window").css("width", h + 29);
	return false;
}

function fnValidaAutenticacion() {
	$("label").css("color", sColorOrgnl);
	if (!fnCampoValido('Email', vEmail)) { return false; }
	if (!fnCampoValido('Clave', vCadena)) { return false; }
	return true;
}

function fnValidaUsuario() {
	$("label").css("color", sColorOrgnl);
	if (!fnCampoValido('email', vEmail)) { return false; }
	if ($('#id').val() == 0 || ($('#id').val() != 0 && $('#clave').val() != '')) {
		if (!fnCampoValido('clave', vCadena, 8)) { return false; }
		if ($('#clave').val() != $('#confirma').val()) {
			return fnAvisoCampoInvalido('confirma', 0, 'Las claves deben ser identicas');
		}
	}
	if (!fnCampoValido('perfil', vNumero, 0)) { return false; }
	if (!fnCampoValido('espacio', vNumero, 0)) { return false; }
	return true;
}

function fnDescargarArchivos() {
	if (!fnCampoValido('nombre', vCadena, 0)) { return false; } 
	if ($('#borrar').attr("checked")) { 
		var sMensaje = "Si marca la casilla de 'Borrar los archivos', estos seran borrados permanentemente del servidor.\n Desea borrarlos?";
		return confirm(sMensaje); 
	}
	return true;
}

function fnSubirArchivo(filefield, URL, Element) {
	if  (fnCadenaValida($('#archivo').val())) {
		$("#Usuario").hide();
		$("h2#mensaje, p#load").css("text-align", "center");
		$("h2#mensaje").css("padding-top", "30px");
		$("h2#mensaje").text("Subiendo el archivo. No cierre la ventana.");	
		$("p#load").show();
		$.ajaxFileUpload({
			url:URL, 
			secureuri:false,
			fileElementId:filefield,
			dataType: 'json',
			success: function (data, status) {
				if(typeof(data.error) != 'undefined') {
					if(data.error != '') {
						$(Element).html(data.error);
					} else {
						$(Element).html(data.msg);
					}
				}
				$("p#load").hide();
				$("h2#mensaje").css("padding-top", "0px");
				$("#Usuario").show();
			},
			error: function (data, status, e) {
				$(Element).html('Error: ' + data.responseText);
				$("p#load").hide();
				$("h2#mensaje").css("padding-top", "0px");
				$("#Usuario").show();
			}
		});
	}	
	return false;
}

function fnSeleccionaAchivo() {
	$('#fake').val($('#archivo').val());
	/*
	if (/\.zip$/i.test($('#fake').val())) {
		$('#zip').show("slow");
	} else {
		$("#descomprime").removeAttr('checked');
		$('#zip').hide("slow");	
	}
	*/
}

function fnCampoValido(id, tipo, len) {
	var bValido = false;
	var dCampo = $('#' + id);
	dCampo.val($.trim(dCampo.val()));
	switch (tipo) {
		case vCadena:
			bValido = fnCadenaValida(dCampo.val(), len);
			break;
		case vNumero:
			bValido = fnNumeroValido(dCampo.val(), len);
			break;
		case vEmail:
			bValido = fnEmailValido(dCampo.val());
			break;
	}
	if (!bValido) { fnAvisoCampoInvalido(id, len, ''); }
	return bValido;
}

function fnAvisoCampoInvalido(id, len, mensaje) {
	var sMensaje = mensaje;
	if (!sMensaje) {
		sMensaje = "Campo Invalido: " + id + ".";
		if (len) { sMensaje += " Minimo " + len + " caracteres"; }
	}
	alert(sMensaje);
	$("label[for='" + id + "']").css("color", sColorInvld);
	$('#' + id).focus();
	return false;		
}

function fnCadenaValida() {
	if (arguments[1]) { return ( arguments[0].length >= arguments[1] ); }
	return (typeof arguments[0] == 'string' && arguments[0] != '' && isNaN(arguments[0])); 
}
function fnNumeroValido() { 
	return (!isNaN(arguments[0]) && arguments[0] != '' && arguments[0] != arguments[1]); 
}
function fnEmailValido() {
	var RegExPattern = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
	if (arguments[0] != '' && RegExPattern.test(arguments[0])) { return true; }
	return false;
}
function fnNuevaVentana(url, win, cnf, mdl) {
	var win = null;
	cnf['left'] = 0;
	cnf['top'] = 0;
	if (cnf['width'] > screen.width) cnf['width'] = screen.width - 20;
	if (cnf['height'] > screen.height) cnf['height'] = screen.height - 20;		
	var winl = (screen.width - cnf['width']) / 2;
	var wint = (screen.height - cnf['height']) / 2;
	if (winl > 0) cnf['left'] = winl;
	if (wint > 0) cnf['top'] = wint;	
	var settings = '';
	for(var key in cnf) {
		settings += ' ' + key + '=' + cnf[key] + ',';
	}
	
	abierto = false;
	if (mdl) {
		if (window.showModalDialog) {
			window.showModalDialog(url, win, "dialogWidth:" + cnf['width'] + "px;dialogHeight:" + cnf['height'] + "px;unadorned:0");	
			abierto = true;
		}
	}
	
	if (!abierto) {
		win = window.open(url, win, settings);
		win.window.focus();
	}
	return false;
}

function fnCloseAndReload() {
	opener.location.reload(true);
	self.close();	
}

