//Conexión a archivos remotos
function conexionajax(){
	if(typeof XMLHttpRequest != "undefined"){
		return new XMLHttpRequest();
	}else if(window.ActiveXObject){
		var versionnavegador=["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
		for (var i=0; i < versionnavegador.length; i++){
			try{
				var objXmlHttp= new ActiveXObject
				(versionnavegador[i]);
				return objXmlHttp;
			}catch (objError){
			}
		}
	}throw new Error("No fué posible conectar el objeto XMLHttp, ya que no pudo crearse o no existe");
}

function salir(){
	setCookie("user",'', getExpDate(0,0,0));
	setCookie("asignada",'', getExpDate(0,0,0));
	setCookie("in",'', getExpDate(0,0,0));
	window.location.href ='index.php';
	botones('');
}

function validarusuario_inicio(){
	
	if(getCookie("user")){
		var conexion = conexionajax();
		conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
		conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		conexion.onreadystatechange = function() {
			if (conexion.readyState==4) {
				//datos de usuario
				var texto = conexion.responseXML;
				if(texto.getElementsByTagName("resultado")[0].firstChild.nodeValue > '0'){
					/*Seteando la cookie del usuario para que dure una hora (dias, horas, minutos)*/
					setCookie("user",getCookie("user"), getExpDate(1,0,0));
					/*eliminando el formulario de logueo*/
					document.getElementById("login_home").style.display="none";
					/*mostrar botones de sesion*/
					document.getElementById("botones_cuenta").style.display="block";
					document.getElementById("miboton").style.display="block";
					document.getElementById("nombre_usuario").innerHTML="<b>Usuario:</b> "+texto.getElementsByTagName("nombre")[0].firstChild.nodeValue+" "+texto.getElementsByTagName("apellido")[0].firstChild.nodeValue;
				}else{
					alert('Error de registro!!!\nEl usuario proporcionado no es válido\n Rectifique los datos e intente de nuevo');
					document.getElementById("txt_login").value="";
					document.getElementById("txt_password").value="";
				}
			}
		}
		//generando y creando cookie
		conexion.send("acciones=registra_usuario&idusuario="+getCookie("user"));
	}
}

function validarusuario(){
	if(document.getElementById("txt_login").value!="" && document.getElementById("txt_password").value!=""){
		var conexion = conexionajax();
		conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
		conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		conexion.onreadystatechange = function() {
			if (conexion.readyState==4) {
				//datos de usuario
				var texto = conexion.responseXML;
				if(texto.getElementsByTagName("resultado")[0].firstChild.nodeValue > '0'){
					/*Seteando la cookie del usuario para que dure una hora (dias, horas, minutos)*/
					setCookie("user",texto.getElementsByTagName("resultado")[0].firstChild.nodeValue, getExpDate(0,0,30));
					setCookie("asignada",texto.getElementsByTagName("asignada")[0].firstChild.nodeValue, getExpDate(0,0,30));
//					/*eliminando el formulario de logueo*/
//					document.getElementById("login_home").style.display="none";
//					/*mostrar botones de sesion*/
//					document.getElementById("botones_cuenta").style.display="block";
					//window.location.href ='inicio.php';
					if(texto.getElementsByTagName("asignada")[0].firstChild.nodeValue=='S'){
						alert("Su clave ha sido asignada por el sistema.\nPor favor proceda a cambiarla para poder ingresar a su cuenta de forma segura");
						document.getElementById("miboton").style.display="none";
						document.getElementById("cuerpo").innerHTML=document.getElementById("cambio_clave").innerHTML;
					}else{
						//document.getElementById("miboton").style.display="block";
						window.location.href ='inicio.php';
					}
					document.getElementById("nombre_usuario").innerHTML="<b>Usuario:</b> "+texto.getElementsByTagName("nombre")[0].firstChild.nodeValue+" "+texto.getElementsByTagName("apellido")[0].firstChild.nodeValue;
				}else{
					alert('Error de registro!!!\nEl usuario proporcionado no es válido\n Rectifique los datos e intente de nuevo');
					document.getElementById("txt_login").value="";
					document.getElementById("txt_password").value="";
				}
			}
		}
		//generando y creando cookie
		conexion.send("acciones=valida_usuario&txt_login="+document.getElementById('txt_login').value.toLowerCase()+"&txt_password="+document.getElementById('txt_password').value.toLowerCase());
	}else{
		alert ("Debe ingresar nombre de usuario\ny contraseña para ingresar al sistema");
	}
}

function botones(nombre){
	switch (nombre){
		case '':
		destacadas_home('0');
		break;
		case 'home':
		quienes_somos('4');
		break;
		case 'enlaces':
		otros_contenidos('9');
		break;
		case 'aliados':
		otros_contenidos('14');
		break;
		case 'horoscopo':
		document.getElementById("cuerpo").innerHTML=document.getElementById("horoscopo").innerHTML;
		break;
		case 'ayuda':
		otros_contenidos('15');
		break;
		case 'registro':
		document.getElementById("cuerpo").innerHTML=document.getElementById("registro").innerHTML;
		break;
		case 'olvido_clave':
		document.getElementById("cuerpo").innerHTML=document.getElementById("recupera_clave").innerHTML;
		break;
		case 'boletin':
		document.getElementById("cuerpo").innerHTML="Boletin";
		break;
	}
}

/****************************************MACROZONAS DESTACADOS Y LISTADOS********************************************************/

function destacados_macrozona(macrozona,pais){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/destacadas_macrozona.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {	
			var texto = conexion.responseText;
			document.getElementById("cuerpo").innerHTML="";
			document.getElementById("cuerpo").innerHTML+=texto;
		}else{
			document.getElementById("cuerpo").innerHTML=document.getElementById("cargando").innerHTML;	
		}
	}
	data='';
	data+="acciones=listar_publicaciones";
	data+="&macrozona="+macrozona;
	data+="&pais="+pais;
	conexion.send(data);
}

function vertodas(macrozona, pais, pagina){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/destacadas_macrozona.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {	
			var texto = conexion.responseText;
			document.getElementById("cuerpo").innerHTML="";
			document.getElementById("cuerpo").innerHTML+=texto;
			paginas_macrozonas(macrozona, pais, pagina);
		}else{
			document.getElementById("cuerpo").innerHTML=document.getElementById("cargando").innerHTML;	
		}
	}
	data='';
	data+="acciones=listar_todaspublicaciones";
	data+="&macrozona="+macrozona;
	data+="&pais="+pais;
	data+="&pagina="+pagina;
	conexion.send(data);
}

function paginas_macrozonas(macrozona, pais, pagina){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/destacadas_macrozona.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {	
			var texto = conexion.responseText;
			document.getElementById("paginador_publicaciones").innerHTML="";
			document.getElementById("paginador_publicaciones").innerHTML+=texto;
		}
	}
	data='';
	data+="acciones=paginacion";
	data+="&macrozona="+macrozona;
	data+="&pais="+pais;
	data+="&pagina="+pagina;
	conexion.send(data);
}

/*********************************************HOROSCOPO DETALLES************************************************************************/

function mostrar_signo(id){
	var ancho=900;
	var alto=330;
	var izq= parseInt((screen.availWidth/2) - (ancho/2));
	var top= parseInt((screen.availHeight/2) - (alto/2));
	var ventana_detalle=window.open("includes/detallehoroscopo.php?id="+id, "", "status=no,menubar=no,height="+alto+",width="+ancho+",left="+izq+",top="+top+",screenX="+izq+",screenY="+top+" ");	
	ventana_detalle.focus();
}

/*************************************DESTACADAS Y LISTADOS DE HOME***********************************************************/

function destacadas_home(pagina){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/destacadas_home.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {	
			var texto = conexion.responseText;
			document.getElementById("cuerpo").innerHTML="";
			document.getElementById("cuerpo").innerHTML+=texto;
		}else{
			document.getElementById("cuerpo").innerHTML=document.getElementById("cargando").innerHTML;	
		}
	}
	data='';
	data+="acciones=listar_publicaciones";
	data+="&idusuario="+getCookie("user");
	data+="&pagina="+pagina;
	conexion.send(data);
}

function vertodashome(pagina){
	/*Se vacía el centro de la página*/
	document.getElementById("cuerpo").innerHTML="";
	cuerpo=document.getElementById("cuerpo");
	/*encabezado de la pagina*/
	head=document.createElement("div");
	head.setAttribute("style",'width:95%;margin-top:5px;margin-left:15px;');
	head.setAttribute("id",'encabezado');
	cuerpo.appendChild(head);
	
	/*Imagen del encabezado*/
	headimagen=document.createElement("img");
	headimagen.setAttribute("src","img/img_publicaciones.jpg");
	head.appendChild(headimagen);
	
	/*Se crea el div que contendrá el listado de publicaciones*/
	listado=document.createElement("div");
	listado.setAttribute("style",'width:95%;margin-top:5px;margin-left:15px;height:275px');
	listado.setAttribute("id",'lista_publicaciones');
//	listado.innerHTML="este es el lugar de los listados";
	cuerpo.appendChild(listado);
	/*Paginador de publicaciones*/
	paginador=document.createElement("div");
	paginador.setAttribute("style",'width:95%;margin-top:5px;margin-left:15px;');
	paginador.setAttribute("id",'paginador_publicaciones');
	//paginador.innerHTML="este es el lugar de los numeritos";
	cuerpo.appendChild(paginador);
	/*****conexion al archivo remoto para listar todas las publicaciones activas****/
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/destacadas_home.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {	
			var texto = conexion.responseText;
			document.getElementById("lista_publicaciones").innerHTML="";
			document.getElementById("lista_publicaciones").innerHTML+=texto;
			paginas_listado(pagina);
		}else{
			document.getElementById("lista_publicaciones").innerHTML=document.getElementById("cargando").innerHTML;	
		}
	}
	data='';
	data+="acciones=listar_todaspublicaciones";
	data+="&pagina="+pagina;
	conexion.send(data);
}

function paginas_listado(pagina){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/destacadas_home.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {	
			var texto = conexion.responseText;
			document.getElementById("paginador_publicaciones").innerHTML="";
			document.getElementById("paginador_publicaciones").innerHTML+=texto;
		}
	}
	data='';
	data+="acciones=paginacion";
	data+="&pagina="+pagina;
	conexion.send(data);
}

/******************************************************************************************************************************/

function detalle_publicacion_home(id){
	
	var ancho=650;
	var alto=500;
	var izq= parseInt((screen.availWidth/2) - (ancho/2));
	var top= parseInt((screen.availHeight/2) - (alto/2));
	var ventana_detalle=window.open("includes/detallepub.php?id="+id, "", "status=no,menubar=no,height="+alto+",width="+ancho+",left="+izq+",top="+top+",screenX="+izq+",screenY="+top+" ");	
	ventana_detalle.focus();
}

function quienes_somos(link){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {
			var texto = conexion.responseText;
			document.getElementById("cuerpo").innerHTML=texto;
		}else{
			document.getElementById("cuerpo").innerHTML=document.getElementById("cargando").innerHTML;	
		}
	}
	data="";
	data+="acciones=mostrar_contenido";
	data+="&idcontenido="+link;
	conexion.send(data);
}

function otros_contenidos(id){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {
			var texto = conexion.responseText;
			document.getElementById("cuerpo").innerHTML=texto;
		}else{
			document.getElementById("cuerpo").innerHTML=document.getElementById("cargando").innerHTML;	
		}
	}
	data="";
	data+="acciones=mostrar_otroscontenido";
	data+="&idcontenido="+id;
	conexion.send(data);
}

function listar_pais(id){
	/*objeto pais*/
	combopais=document.getElementById(id);
	combopais.className="inputs";
	combopais.style.width="135px";
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {
			document.getElementById("cargando"+id).style.display="none";
			var texto = conexion.responseXML;
			/*Numero total de paises*/
			paises=texto.getElementsByTagName("numero")[0].firstChild.nodeValue;
			//alert(paises);	
			option=document.createElement("option");
			option.setAttribute("value",'0');
			option.innerHTML="Seleccione un pa&iacute;s";
			combopais.appendChild(option);
			for( var i=0; i<paises;i++){
				option=document.createElement("option");
				option.setAttribute("value",texto.getElementsByTagName("value")[i].firstChild.nodeValue);
				option.innerHTML=texto.getElementsByTagName("nombre")[i].firstChild.nodeValue;
				combopais.appendChild(option);
			}
		}else{
			document.getElementById("cargando"+id).style.display="block";
			document.getElementById("cargando"+id).innerHTML="Cargando lista de pa&iacute;ses";
		}
	}
	//generando y creando cookie
	conexion.send("acciones=listar_paises");	
}

function listar_estado(id,select){
	var pais = select.options[select.selectedIndex].value;
	if(pais>0){
		var conexion = conexionajax();
		conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
		conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		conexion.onreadystatechange = function() {
			if (conexion.readyState==4) {
				document.getElementById(id).innerHTML="";
				/*Creando objeto select de estados*/
				comboestado=document.createElement("select");
				comboestado.style.width="135px";
				comboestado.setAttribute("id",id+"_select");
				comboestado.setAttribute("class","inputs");
				comboestado.className="inputs";
				document.getElementById(id).appendChild(comboestado);				
				/*Creando option vacía*/
				option.setAttribute("value",'0');
				option.innerHTML="Seleccione un estado";
				comboestado.appendChild(option);
				/*Creando listado de opciones*/
				var texto = conexion.responseXML;
				/*Numero total de estados*/
				estados=texto.getElementsByTagName("numero")[0].firstChild.nodeValue;
				for( var i=0; i<estados;i++){
					option=document.createElement("option");
					option.setAttribute("value",texto.getElementsByTagName("value")[i].firstChild.nodeValue);
					option.innerHTML=texto.getElementsByTagName("nombre")[i].firstChild.nodeValue;
					comboestado.appendChild(option);
				}
			}else {
				document.getElementById(id).innerHTML="Cargando lista de estados";
			}
		}
		//generando y creando cookie
		conexion.send("acciones=listar_estados&pais="+pais);
	}else{
		document.getElementById(id).innerHTML="";
	}
}

function listar_cuentas(idbanco,contcuentas){
	/*Cuentas*/
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {
				document.getElementById(contcuentas).innerHTML="";
				/*Creando objeto select de estados*/
				combocuentas=document.createElement("select");
				combocuentas.setAttribute("id",contcuentas+"_select");
				combocuentas.setAttribute("class","inputs");
				document.getElementById(contcuentas).appendChild(combocuentas);				
				/*Creando option vacía*/
				option=document.createElement("option");
				option.setAttribute("value",'0');
				option.setAttribute("selected",'true');
				option.innerHTML="Seleccione una cuenta";
				combocuentas.appendChild(option);
				/*Creando listado de opciones*/
				var texto = conexion.responseXML;
				/*Numero total de estados*/
				cuentas=texto.getElementsByTagName("numero")[0].firstChild.nodeValue;
				for( var i=0; i<cuentas;i++){
					option=document.createElement("option");
					option.setAttribute("value",texto.getElementsByTagName("value")[i].firstChild.nodeValue);
					option.innerHTML=texto.getElementsByTagName("nombre")[i].firstChild.nodeValue;
					combocuentas.appendChild(option);
				}
			}else {
				document.getElementById(contcuentas).innerHTML="Cargando lista de cuentas";
			}
	}
	data='';
	data+="acciones=listar_cuentas";
	data+="&idbanco="+idbanco;
	conexion.send(data);
}

function listado_bancos(contenedor,contcuentas){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/principal.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {
				document.getElementById(contenedor).innerHTML="";
				/*Creando objeto select de estados*/
				combobanco=document.createElement("select");
				combobanco.setAttribute("id",contenedor+"_select");
				combobanco.setAttribute("class","inputs");
				document.getElementById(contenedor).appendChild(combobanco);				
				document.getElementById(contenedor+"_select")["onchange"]=new Function("listar_cuentas(this.value,'"+contcuentas+"')");
				/*Creando option vacía*/
				option=document.createElement("option");
				option.setAttribute("value",'0');
				option.setAttribute("selected",'true');
				option.innerHTML="Seleccione un banco";
				combobanco.appendChild(option);
				/*Creando listado de opciones*/
				var texto = conexion.responseXML;
				/*Numero total de estados*/
				bancos=texto.getElementsByTagName("numero")[0].firstChild.nodeValue;
				for( var i=0; i<bancos;i++){
					option=document.createElement("option");
					option.setAttribute("value",texto.getElementsByTagName("value")[i].firstChild.nodeValue);
					option.innerHTML=texto.getElementsByTagName("nombre")[i].firstChild.nodeValue;
					combobanco.appendChild(option);
				}
			}else {
				document.getElementById(contenedor).innerHTML="Cargando lista de bancos";
			}
	}
	data='';
	data+="acciones=listar_bancos";
	conexion.send(data);
}

function form_planificador(){
	var conexion = conexionajax();
	conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/planificador.php');
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {
			var texto = conexion.responseText;
			document.getElementById("cuerpo").innerHTML=texto;
			setTimeout("listando_macrozona('listarzonas')",500);
		}else{
			document.getElementById("cuerpo").innerHTML=document.getElementById("cargando").innerHTML;	
		}
	}
	data='';
	conexion.send(data);
}



function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
		countfield.value = maxlimit - field.value.length;
}
/*Validar campos enteramente numéricos*/
function onlyNumbersDano(evt){
	var keyPressed = (evt.which) ? evt.which : event.keyCode
	return !(keyPressed > 31 && (keyPressed < 48 || keyPressed > 57));
}

/*******************************pago_virtual***************************************************************/
function pago_virtual(monto,producto,idpago){
	/*Nombre de las variables
	ref==>Referencia de la transaccion
	producto==>Nombre del producto
	monto==>Monto a cancelar
	*/
	/*Se determinara el numero de transaccion*/
//	alert("monto-->"+monto);
//	alert("producto-->"+producto);
//	alert("idpago-->"+idpago);
	var conexion = conexionajax();
	if(idpago!=0){
		conexion.open('POST', '..'+document.getElementById("carpeta_raiz").innerHTML+'includes/balance.php');		
	}else{
		conexion.open('POST', '../includes/balance.php');
	}
	
	conexion.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	conexion.onreadystatechange = function() {
		if (conexion.readyState==4) {	
			var texto = conexion.responseXML;
			if(texto.getElementsByTagName("data")[0].firstChild.nodeValue=='1' && texto.getElementsByTagName("data1")[0].firstChild.nodeValue=='1'){
				document.getElementById("formulario_pago").style.display='none';
				document.getElementById("espacio_punto").style.display='block';
				document.getElementById("punto_virtual").src='http://174.133.200.100:8080/bpagoubicala/index_merc.jsp?monto='+monto+'&ref='+texto.getElementsByTagName("numero")[0].firstChild.nodeValue+'&producto='+producto;
			}
			
			if(texto.getElementsByTagName("data1")[0].firstChild.nodeValue=='0'){
				alert("Se ha detectado un error al registrar su solicitud (50005)");
			}
		}else{
			document.getElementById("formulario_pago").innerHTML=document.getElementById("cargando").innerHTML;
		}
	}
	data='';
	data+="acciones=numero_trans";
	data+="&idpago="+idpago;
	conexion.send(data);
}