/*
Contiene:
- nuevoAjax: Para realizar procedimientos de Ajax, de consultas simples, actualizaciones, inserciones y eliminaciones...
- siempre_centre: Centra una capa en la ventana..
- Bloquear teclas (F5, Ctrl).
- abrir popup, llamar ventanas emergentes...
- cargaXML, para traer consultas de Ajax en formato Xml
- MM_preloadImages, Realiza una precarga de las Imagenes... 
Desarrollado por: Jorge Rubiano, ostricajh@gmail.com
*/
var nomdivajax; //Guarda el nombre del div en que se pasará el Ajax...
function nuevoAjax()
{
	var xmlhttp = false;
	try
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E)
		{
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest != "undefined")
	{
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}
//Ajusta la capa oscura...
function ajuscapa_bloquea(capbloquea)
{
	document.getElementById(capbloquea).style.top="0px"; 
	document.getElementById(capbloquea).style.left="0px";
	document.getElementById(capbloquea).style.width=(screen.width - 250)+"px";
	document.getElementById(capbloquea).style.height = screen.height+200+"px";
}
//Centra en la pantalla independiente el movimiento del Scroll...
function siempre_centre(capsiecentrada)
{
	ancho = document.getElementById(capsiecentrada).style.width;
	alto = document.getElementById(capsiecentrada).style.height;
	//alert(ancho+"--"+alto);
	cenmovx = document.getElementById(capsiecentrada).style.left = ((parseInt(document.getElementById('capaoscura').style.width) - parseInt(ancho)) / 2);
	cenmovy = document.getElementById(capsiecentrada).style.top = (((parseInt(document.getElementById('capaoscura').style.height) - parseInt(alto)) / 2));
	xMoveTo(capsiecentrada, cenmovx, xScrollTop() + cenmovy - 200);
	capacentrada = capsiecentrada;
}
//Bloquear botón Derecho y además bloquea el botçon F5 y F11...
document.oncontextmenu = function(){return false;}
document.onkeydown=keyPressed;
function keyPressed(evt)
{
	var f11 = 122; // Para F11
	var ctrla = 65; // Para CTRL+A
	var f5 = 116;
	if(document.all )
	{
    	// Guardamos pulsaciones del teclado y comparamos a las de restringir
    	if (event.keyCode == f11 || event.keyCode == f5)
    	{
        	 // Con event.keyCode anulamos la accion
         	event.keyCode = 0;
         	window.event.returnValue = false;
     	}
		else if(event.ctrlKey)
		{
    		if(event.keyCode == ctrla)
    		{
         		// Con event.keyCode anulamos la accion
         		event.keyCode = 0; 
         		window.event.returnValue = false;
    		}
		}
	}
}
//Abrir una ventana Popup...
function abrirpopup(nombre, ancho, alto, nventana, adaleatorio)
{
	var blnBloqueado = true; //Si es true quiere decir que tiene un bloqueaor de Popup's...
	var aleatorio = Math.floor(Math.random() * 1000000);
	if(adaleatorio == 1) nombre += "&random="+aleatorio;
	dat = 'width='+ancho+',height='+(alto)+',left=0,top=0,scrollbars=yes,resize=no';
	var ventana = window.open(nombre, nventana, dat);
    if(ventana) blnBloqueado = false;
	if(blnBloqueado == true) alert("Upps! - Usted tiene un bloqueador de Popup's Activado.");
	return blnBloqueado;
}
//Carga Ajax por Ajax trayendo los datos en formato xml...
function cargaXML(url) {
	if(url==''){
		return;
	}
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
	} else if (window.ActiveXObject) {
		isIE = true;
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("GET", url, true);
			req.send();
		}
	}
}
//Revisa si el correo esta Sintácticamente bien escrito...
function correo_bien(email)
{
	var s = email, ent = false;
	var filter=/^[A-Za-z_\.\\\-\][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;	
	if (filter.test(s)==true) ent = true;
	return ent;
}
//Centra una ventana Popup en la pantalla...
function window_onload() 
{
    iz=(screen.width-document.body.clientWidth) / 2; 
    de=(screen.height-document.body.clientHeight) / 2; 
    moveTo(iz,de); 	
}
//Redondea una cantidad, al decimal dado...
function redondear(cantidad, decimales) 
{
	var cantidad = parseFloat(cantidad);
	var decimales = parseFloat(decimales);
	decimales = (!decimales ? 2 : decimales);
	return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
}

//Dimensionar una imagen...
/*function dimensionar_img(anchoimg, altoimg, ancho, alto)
{	
	alert(anchoimg+" -- "+altoimg+" -- "+ancho+" -- "+alto);
	nuedimensiones = "";
	if(anchoimg == altoimg)	//La imagen es Cuadrada...
	{
		nuedimensiones = ancho+"--"+ancho;
		alert("Es cuadrada");
	}
	else
	{
		alert("Primer Else");
		if(anchoimg > altoimg)
		{			
			if(anchoimg >= ancho)
			{
				tmpancho = anchoimg - abs(anchoimg - ancho);
				altoimg = altoimg - abs(anchoimg - ancho);
				nuedimensiones = tmpancho+"--"+altoimg;
			}
			else
			{
				tmpancho = Number(anchoimg) + Number(abs(anchoimg - ancho));
				altoimg = Number(altoimg) + Number(abs(anchoimg - ancho));
				nuedimensiones = tmpancho+"--"+altoimg;
			}
		}
		else
		{
			alert("Segundo Else");
			if(altoimg >= alto)
			{								
				nuedimensiones = ancho+"---"+alto;
			}
			else
			{
				alert("Tercer Else");
				tmpalto = Number(altoimg) + Number(abs(alto - altoimg));
				anchoimg = Number(anchoimg) + Number(abs(alto - altoimg));
				nuedimensiones = tmpalto+"--"+anchoimg;
			}
		}
	}
	//alert(nuedimensiones);
	return nuedimensiones;
}*/
//Realiza una precarga de las Imagnes...
function MM_preloadImages() 
{
	var d=document; 
	if(d.images)
	{ 
		if(!d.MM_p) d.MM_p=new Array();
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
		for(i=0; i<a.length; i++)
		{
			if (a[i].indexOf("#")!=0)
			{ 
				d.MM_p[j]=new Image; 
				d.MM_p[j++].src=a[i];
			}
		}
	}
}
//Para realizar la busqueda en los textos...
var NS4 = (document.layers); 
var IE4 = (document.all);
var win = window;    // Con frames usar top.nombre.window;
var nsearch = 0;
function findInPage(str) 
{
	var txt, i, found;
	if (navigator.appName != "Netscape") 
	{
		if (str != "")
		{				
			if (IE4) 
			{
				txt = win.document.body.createTextRange();
				for (i = 0; i <= nsearch && (found = txt.findText(str)) != false; i++) 
				{
					txt.moveStart("character", 1);
					txt.moveEnd("textedit");
				}
				if (found) 
				{
					try
					{
						txt.moveStart("character", -1);
						txt.findText(str);
						txt.select();
						txt.scrollIntoView();
						nsearch++;
					}
					catch (e)
					{
						nsearch++;
						//alert("No encontrado ninguna coincidencia con la busqueda "+str);
						//alert(e.name + " - " + e.message);
					}					
				}
				else 
				{
					if (nsearch > 0) 
					{
						nsearch = 0;
						findInPage(str);
					}
					else
					{
						alert("No encontrado ninguna coincidencia con la busqueda "+str);
					}
				}
			}
		}
		else
		{
			alert("Por favor digite el dato que desea buscar.");
		}
	}
	else
		window.find(str);
}

function cargador_grilla()
{
	var txt = "<table width='100%' border='0' cellpadding='2' cellspacing='0' class='Estilo1'><tr>";
	txt += "<td width='60%'>&nbsp;</td>";
	txt += "<td width='40%' bgcolor='#F3F3F3' class='borexterior'><div align='center'>";
	txt += "<span style='padding:5px'><img src='loading3.gif' width='16' height='16' align='absmiddle'>";
	txt += "<strong>&nbsp;&nbsp;Cargando datos</strong>... </span></div></td></tr></table>";
	return txt;	
}

function solo_numeros(hField)
{
	strIn=hField.value.replace(/[^0-9]/g, "");
	hField.value=(strIn.split ("")).join("");
}

function tipo_texto(hField, tipo)
{
	if(tipo == 1) //Mayúsculas a Minúsculas...
	{
		hField.value = hField.value.toLowerCase();
	}
	else
	{
		//Minúsculas a Mayúsculas...
		hField.value = hField.value.toUpperCase(); 
	}
}

function dice_fecha_letras(fecha, carsepara)
{
	var meses = new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", 
						  "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
	var partefecha = fecha.split(carsepara);
	return creafecha = partefecha[0]+" de "+meses[partefecha[1]-1]+" de "+partefecha[2];	
}

//Esta debería ser global, es decir en el archivo ajax, hay que moverla...
function comprueba_nota_texto(hField)
{
	var strIn;	
	strIn = hField.value.replace(/[^0-9.,]/g, ""); 	
	hField.value = (strIn.split ("")).join("");	
	hField.value = hField.value.replace(",", ".");
	//Nuevo
	escinco = false;
	for(i=0,cupuntos=0, cresulta="";i<hField.value.length;i++)
	{		
		if(hField.value.substr(i,1) == ".") 
		{
			if(cupuntos < 1) 
			{			
				if(i!=0)
				{
					if(escinco == false)
						cresulta += hField.value.substr(i,1);
				}
				else
				{
					hField.value = "";	
					break;
				}
			}
			cupuntos++;
		}
		else
		{
			if(i == 0)
			{
				if(hField.value.substr(i,1) <= 5)
				{
					cresulta += hField.value.substr(i,1);
					if(cresulta >= 5) escinco = true;
				}
				else
				{
					hField.value = "";	
					break;
				}
			}
			else
				cresulta += hField.value.substr(i,1);
		}
	}
	if(cresulta <= 5)
	{
		if(hField.value.length >= 4)
		{
			hField.value = Math.round(cresulta * Math.pow(10, 1)) / Math.pow(10, 1);
		}
		else
		{
			hField.value = cresulta;	
		}
	}
	else
	{
		hField.value = cresulta.substr(0,1);
	}
	hField.value = hField.value.replace(".", ",");
	//Fin de nuevo...
}

//Saber si el archivo es válido...
function formato_archivo(direccion, tipoarchivos)
{
	var bien = false;
	var partdir = direccion.split("\\");
	for(i in partdir)
	{
		noarchivo = partdir[i];
	}
	pararchivo = noarchivo.split("."); 
	ent = false;
	for(i in pararchivo)
	{
		extension = pararchivo[i];
		ent = true;
	}
	if(ent == true)
	{
		extension = extension.toLowerCase();
		for(i in tipoarchivos)
		{
			if(extension == tipoarchivos[i])
			{
				bien = true;
				break;
			}	
		}
	}	
	return bien;
}

function saber_bisiesto(year) 
{ 
	return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;
	//1 Bisiesto
	//0 No es bisiesto
}

function calcula_dias_semana(dia, mes, year) 
{	
	var dia = parseInt(dia, 10);
	var mesx = parseInt(mes, 10);
	var year = parseInt(year, 10);
	if (mes == 1) 
	{
	  mesx = 13;
	  year = year - 1;
	}
	if (mes == 2) 
	{
	  mesx = 14;
	  year = year - 1
	}
	var val4 = parseInt(((mesx + 1)*3)/5, 10);
	var val5 = parseInt(year/4, 10);
	var val6 = parseInt(year/100, 10);
	var val7 = parseInt(year/400, 10);
	var val8 = dia+(mesx*2)+val4+year+val5-val6+val7+2;
	var val9 = parseInt(val8/7, 10);
	var val0 = val8-(val9*7);
	if(val0 == 0) val0 = 7;
	return val0;
}

//Formato de fecha dd/mm/aaaa
function fechaMayorOIgualQue(fec0, fec1)
{ 
    var bRes = false; 
    var sDia0 = fec0.substr(0, 2); 
    var sMes0 = fec0.substr(3, 2); 
    var sAno0 = fec0.substr(6, 4); 
    var sDia1 = fec1.substr(0, 2); 
    var sMes1 = fec1.substr(3, 2); 
    var sAno1 = fec1.substr(6, 4); 
	if (sAno0 > sAno1)	
	{
		bRes = true;
	}
	else 
	{ 
		if (sAno0 == sAno1)
		{ 
			if (sMes0 > sMes1)
			{
				bRes = true; 
			}
			else
			{ 
				if (sMes0 == sMes1)
				{
					if (sDia0 >= sDia1)
					{
						bRes = true; 
					}
				}
			} 
		} 
	} 
	return bRes; 
}

function caracteres_especiales_archivos(nomarchivo)
{
	//alert("El archivo que llega es: "+nomarchivo);
	try
	{
		var carcmal = new Array(new Array("á", "a"), new Array("é", "e"), 
								new Array("í", "i"), new Array("ó", "o"), 
								new Array("ú", "u"), new Array("Á", "A"), 
								new Array("É", "E"), new Array("Í", "I"),
								new Array("Ó", "O"), new Array("Ú", "U"), 
								new Array("ñ", "n"), new Array("Ñ", "N"));
		for(i in carcmal)
		{
			//alert(carcmal[i][0]+" - "+carcmal[i][1]);
			nomarchivo = nomarchivo.replace(carcmal[i][0], carcmal[i][1]);
		}
		//alert(nomarchivo);
	}
	catch(e)
	{
		alert("Error: "+e);
	}
	return nomarchivo;
}

//Ordenar los datos de la Tabla...
function ordenar_array(objArray, orden) 
{
    objArray.sort( new Function("x","y","return ( x < y ) ? " + orden + " : ( x > y ) ? " + ( 0 - orden ) + " : 0;") );
}
//Funcione spara quitar espcios en blanco..
function lTrim(sStr)
{
	while (sStr.charAt(0) == " ")
		sStr = sStr.substr(1, sStr.length - 1);
	return sStr;
}
function rTrim(sStr)
{
	while (sStr.charAt(sStr.length - 1) == " ")
		sStr = sStr.substr(0, sStr.length - 1);
	return sStr;
}

function allTrim(sStr)
{
	return rTrim(lTrim(sStr));
}

function pantalla_completa(url, nombre)
{
	dat = 'width='+screen.width+',height='+(screen.height-85)+',left=0,top=0,scrollbars=no,resize=no,status=no';
	window.open(url, nombre, dat);
}

function acepta_txt_valor(texto, tipo)
{	
	switch(Number(tipo))
	{
		case 1: //texto...
				strIn = texto.value.replace(/[^A-Za-zñÑáéíóúÁÉÍÓÚ\ \@\%\$\?\¿\¡\!\_]/g, ""); 
				break;
		case 2: //Numeros...
				strIn = texto.value.replace(/[^0-9.,\-\+\*\/\$\%\']/g, ""); 	
				break;
		case 3: //Numeros y letras...
				strIn = texto.value.replace(/[^A-Za-zñÑ0-9.,\-\+\*\/\$\%\'\ \?\¿\¡\!]/g, "");
				break;				
	}	
	texto.value = (strIn.split ("")).join("");
}

function leer_texto(id, idioma)
{
	var txt = texto = "";
	texto = document.getElementById(id).innerHTML;	
	txt = "<iframe src='http://vozme.com/text2voice.php?text="+texto+"&lang="+idioma+"&gn=mlfm&interface=full' frameborder='0' height='0px' style='width:0%'></iframe>";	
	document.getElementById("lectura").innerHTML = txt;
}

//Para saber si una hora es:
/*
	1 - Igual
	2 - Hora uno mayor que Hora dos...
	3 - Hora uno MENO que Hora dos...
*/
function hora_mayor_menor_igual_que(fecha_uno, fecha_dos)
{
	//alert(fecha_uno+" - "+fecha_dos);	
	//Partir los valores de las horas...
	parte_fecha_uno = fecha_uno.split(":");
	parte_fecha_dos = fecha_dos.split(":");
	//Primero pasar los valores a hora militar...	
	if(Number(parte_fecha_uno[0]) == 12 && parte_fecha_uno[2] == "am")
	{
		parte_fecha_uno[0] = 0;
	}
	if(Number(parte_fecha_dos[0]) == 12 && parte_fecha_dos[2] == "am")
	{
		parte_fecha_dos[0] = 0;
	}
	if(parte_fecha_uno[2] == "pm")
	{
		if(Number(parte_fecha_uno[0]) != 12)
		{
			parte_fecha_uno[0] = Number(parte_fecha_uno[0]) + 12;
		}
	}
	if(parte_fecha_dos[2] == "pm")
	{
		if(Number(parte_fecha_dos[0]) != 12)
		{
			parte_fecha_dos[0] = Number(parte_fecha_dos[0]) + 12;
		}
	}
	//alert(parte_fecha_uno[0]+" == "+parte_fecha_dos[0]);
	if(parte_fecha_uno[0] == parte_fecha_dos[0])
	{
		//Saber los minutos...
		if(parte_fecha_uno[1] == parte_fecha_dos[1])
		{
			devuelve = 1; //Son iguales...
		}
		else
		{
			if(parte_fecha_uno[1] > parte_fecha_dos[1])
			{
				devuelve = 2; //La hora uno es mayor que la hora dos...
			}
			else
			{
				devuelve = 3; //La hora uno es MENOR que la hora dos...
			}
		}
	}
	else
	{
		if(parte_fecha_uno[0] > parte_fecha_dos[0])
		{
			devuelve = 2; //La hora uno es mayor que la hora dos...
		}
		else
		{
			devuelve = 3; //La hora uno es MENOR que la hora dos...
		}
	}		
	return devuelve;
}