// JavaScript Document

/**

*

*	La función initAjax permite inicializar un objeto AJAX y luego devolverlo.

*   Esto sirve para encadenar dos llamadas a la función getMyHTML() sin tener

*   que utilizar AJAX asincronico.

*

*/



function initAjax(){

	

	var ajax=false;



    /*@cc_on @*/

	

    /*@if (@_jscript_version >= 5)

	

    try {

	

    ajax = new ActiveXObject("Msxml2.XMLHTTP");

	

    } catch (e) {

	

    	try {

	

    ajax = new ActiveXObject("Microsoft.XMLHTTP");

	

    } catch (E) {

	

    ajax = false;

	

    }

	

    }

	

    @end @*/

	

    if (!ajax && typeof XMLHttpRequest!='undefined') 

	{

	   	ajax = new XMLHttpRequest();

    }

    

    return ajax;

}



function getMyHTML( url , divId ) 

{

	

	var ajax = initAjax();    



	var obj = document.getElementById( divId );



	ajax.open("GET", url );



	ajax.onreadystatechange = function() 

	{



		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			//alert(ajax.responseText);

			obj.innerHTML = ajax.responseText;

        }

	}

    

    ajax.send(null);

    

}



// Verifica si el usuario se encuentra registrado

function chequearUsuario() 

{

	// si las validaciones estan correctas

	if (checkForm('form1'))

	{

		

		var usuario = document.getElementById('txtUser');

		var password = document.getElementById('txtPassword');

		var obj = document.getElementById( 'divAutentificacion' );

		var divUsuario = document.getElementById( 'divNombre' );

		var ajax = initAjax();

		

		ajax.open("GET", '../sistema/index.php?ohaction=ajaxLogin&user=' + usuario.value + '&pass=' + password.value, true);

	

		ajax.onreadystatechange = function() 

		{

			if (ajax.readyState == 4 && ajax.status == 200) 

			{

				if (ajax.responseText != 'false')

				{

					respuesta = new String(ajax.responseText);

					arrRespuesta = respuesta.split('@@');

					divUsuario.innerHTML = arrRespuesta[1];

					obj.innerHTML = "Bienvenido <b>" + arrRespuesta[0];

					sendForm('form1');

				}

				else

				{

					//document.getElementById('Submit').disabled = false;

					usuario.value = '';

					password.value = '';

					usuario.focus();

					obj.innerHTML = 'Usuario inválido, por favor intente nuevamente';

				}

				

	

			}

		}

	

		ajax.send(null);

	}

}





// Verifica si el usuario se encuentra registrado

function chequearUsuarioLive() 

{

	

	usuario = document.getElementById('txtUser').value;

	password = document.getElementById('txtPassword').value;

//	alert(usuario);

	

	if (usuario != '' && password != '')

	{

		var ajax = initAjax();

	

		var obj = document.getElementById( 'divAutentificacion' );

		var divUsuario = document.getElementById( 'divNombre' );

	

		ajax.open("GET", '../sistema/index.php?ohaction=ajaxLogin&user=' + usuario + '&pass=' + password);

	

		ajax.onreadystatechange = function() 

		{

	

			if (ajax.readyState == 4 && ajax.status == 200) 

			{

				//alert(ajax.responseText);

        if (ajax.responseText != 'false')

				{

					respuesta = new String(ajax.responseText);

					arrRespuesta = respuesta.split('@@');

					divUsuario.innerHTML = arrRespuesta[1];

					obj.innerHTML = "Bienvenido <b>" + arrRespuesta[0];

				}

			}

		}

	

		ajax.send(null);

	}

}



// Verifica si el usuario se encuentra registrado

function buscarContactos() 

{

	categoria = document.getElementById('iSubID');

	indice = categoria.selectedIndex;

	categoriavalor = categoria.options[indice].value;

	nombreapellido = document.getElementById('nombreapellido').value;

  idcontacto = document.getElementById('iConID').value;

  

	var ajax = initAjax();



	var obj = document.getElementById( 'divBuscarContactos' );



	ajax.open("GET", '../sistema/index.php?ohaction=ajaxBuscarContactos' + '&id=' + idcontacto + '&categoria=' + categoriavalor + '&nombreapellido=' + nombreapellido);



	ajax.onreadystatechange = function() 

	{



		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}



// Verifica si el usuario se encuentra registrado

function buscarContactosParaPropiedades() 

{

	categoria = document.getElementById('iSubID');

	indice = categoria.selectedIndex;

	categoriavalor = categoria.options[indice].value;

	nombreapellido = document.getElementById('nombreapellido').value;

	idpro = document.getElementById('iProID').value;



	var ajax = initAjax();



	var obj = document.getElementById( 'divBuscarContactos' );



	ajax.open("GET", '../sistema/index.php?ohaction=ajaxBuscarContactosParaPropiedades&id=' + idpro + '&categoria=' + categoriavalor + '&nombreapellido=' + nombreapellido);



	ajax.onreadystatechange = function() 

	{



		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}







// Busca una propiedad

function buscarPropiedades()

{

	referencia = document.getElementById('referencia').value;

	palabra = document.getElementById('palabra').value;

  idcon = document.getElementById('iConID').value;

	



	var ajax = initAjax();



	var obj = document.getElementById( 'divBuscar' );



	ajax.open("GET", '../sistema/index.php?ohaction=ajaxBuscarPropiedades&id=' + idcon + '&referencia=' + referencia + '&palabra=' + palabra);



	ajax.onreadystatechange = function() 

	{



		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}





// Cambia de sede

function cambiarSede(id) 

{

	var ajax = initAjax();

//	alert('../sistema/index.php?ohaction=cambiarSede&id=' + id);

	ajax.open("GET", '../sistema/index.php?ohaction=cambiarSede&idsed=' + id);



	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			window.location.reload();

		}

	}



	ajax.send(null);

}



// Busca contactos para asignar una demanda

function buscarContactosParaDemandas() 

{
	var tipo = "";
	
	
	 if(document.getElementById('tipo1').checked)
	 	tipo=document.getElementById('tipo1').value;
	else
		tipo=document.getElementById('tipo2').value;
	

	buscarpor = document.getElementById('buscarpor').value;



	var ajax = initAjax();



	var obj = document.getElementById( 'divBuscarContactos' );



	ajax.open("GET", '../sistema/index.php?ohaction=ajaxBuscarContactosParaDemandas&tipo=' + tipo + '&buscarpor=' + buscarpor);



	ajax.onreadystatechange = function() 

	{



		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			//obj.innerHTML = ajax.responseText;

			window.open('../sistema/index.php?ohaction=ajaxBuscarContactosParaDemandas&tipo=' + tipo + '&buscarpor=' + buscarpor, 'popup', 'height=400,width=650,status=no,toolbar=no,menubar=no,location=no,resizable=yes, scrollbars=yes');

		}

	}



	ajax.send(null);

}





// Muestra localizaciones
function mostrarProvincias(id)

{
	// si el id es vacio asignar 0
	if (id == '')
	{
		id = 0;
	}
	
	var ajax = initAjax();


	//var obj = document.getElementById( 'comboProvincias' );
	ajax.open("GET", '../sistema/../sistema/index.php?ohaction=mostrarProvincias&idpais=' + id);

	ajax.onreadystatechange = function() 
	{
		if (ajax.readyState == 4 && ajax.status == 200) 
		{
			//obj.innerHTML = ajax.responseText;

			var cadena = ajax.responseText;

			// Borra las opciones actuales
			var elSel = document.getElementById('iProID');

			elSel.options.length=0
			var myOption = new Option('[Seleccione]', '');

	  		elSel.options[0] = myOption;
			if (cadena != '')
			{
				// Agrega las nuevas provincias
				var opciones = cadena.split(",");
				
				for (i = 1; i <= opciones.length; i++) 
				{

					var parvalores = opciones[i-1].split("-");
					var myOption = new Option(parvalores[1], parvalores[0]);
			  		elSel.options[i] = myOption;
				}
			}
			else // sino llama a mostrar ciudad para que limpie todo
			{
				mostrarCiudades(0);
			}
		}
	}

	ajax.send(null);
}



function mostrarCiudades(id)
{

	// si el id es vacio asignar 0
	if (id == '')
	{
		id = 0;
	}
	
	var ajax = initAjax();

	//var obj = document.getElementById( 'comboCiudades' );

	ajax.open("GET", '../sistema/index.php?ohaction=mostrarCiudades&idprovincia=' + id);

	ajax.onreadystatechange = function() 
	{
		if (ajax.readyState == 4 && ajax.status == 200) 
		{
			var cadena = ajax.responseText;

			// Borra las opciones actuales
			var elSel = document.getElementById('iCiuID');
			elSel.options.length=0
			var myOption = new Option('[Seleccione]', '');
	  		elSel.options[0] = myOption;

			if (cadena != '')
			{
				// Agrega las nuevas provincias
				var opciones = cadena.split(",");
				for (i = 1; i <= opciones.length; i++) 
				{
					var parvalores = opciones[i-1].split("-");
					var myOption = new Option(parvalores[1], parvalores[0]);
			  		elSel.options[i] = myOption;
				}
			}
			else
			{
				mostrarZonas(0);
			}
		}
	}

	ajax.send(null);
}



function mostrarZonas(id)
{
	// si el id es vacio asignar 0
	if (id == '')
	{
		id = 0;
	}
	
	var ajax = initAjax();

	//var obj = document.getElementById( 'comboZonas' );

	ajax.open("GET", '../sistema/index.php?ohaction=mostrarZonas&idciudad=' + id);

	ajax.onreadystatechange = function() 
	{
		if (ajax.readyState == 4 && ajax.status == 200) 
		{
			var cadena = ajax.responseText;
			
			var elSel = document.getElementById('iZonID');

			elSel.options.length=0
			var myOption = new Option('[Seleccione]', '');
	  		elSel.options[0] = myOption;

			if (cadena != '')
			{
				// Agrega las nuevas provincias
				var opciones = cadena.split(",");
				for (i = 1; i <= opciones.length; i++) 
				{
					var parvalores = opciones[i-1].split("-");
					var myOption = new Option(parvalores[1], parvalores[0]);
			  		elSel.options[i] = myOption;
				}
			}	

	}
	}

	ajax.send(null);
}




// Trae las subcategorias para la categoria seleccionada

function cambiarSubcategoriasAJAX(id) 

{

	var ajax = initAjax();



	var obj = document.getElementById( 'comboSubcategorias' );



	ajax.open("GET", '../sistema/index.php?ohaction=mostrarSubcategorias&id=' + id);



	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			//obj.innerHTML = ajax.responseText;

			var cadena = ajax.responseText;

			

			var elSel = document.getElementById('iTinID');



			elSel.options.length=0

			var myOption = new Option('[Seleccione]', '');

	  		elSel.options[0] = myOption;



			if (cadena != '')

			{

				// Agrega las nuevas provincias

				var opciones = cadena.split(",");

				for (i = 1; i <= opciones.length; i++) 

				{

					var parvalores = opciones[i-1].split("-");

					var myOption = new Option(parvalores[1], parvalores[0]);

			  		elSel.options[i] = myOption;

				}

			}

		}

	}



	ajax.send(null);

}





// Captaciones / Demandas



function buscarContactosCaptaciones() 

{

	categoria = document.getElementById('iSubID');

	indice = categoria.selectedIndex;

	categoriavalor = categoria.options[indice].value;

	nombreapellido = document.getElementById('nombreapellido').value;



	var ajax = initAjax();



	var obj = document.getElementById( 'divBuscarContactos' );



	ajax.open("GET", '../sistema/index.php?ohaction=ajaxBuscarContactosCaptaciones&categoria=' + categoriavalor + '&nombreapellido=' + nombreapellido);



	ajax.onreadystatechange = function() 

	{



		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}



function buscarContactosCaptacionesRel() 

{

	telefono = document.getElementById('telefono').value;



	var ajax = initAjax();



	var obj = document.getElementById( 'divBuscarContactos' );



	ajax.open("GET", '../sistema/index.php?ohaction=ajaxBuscarContactosCaptacionesRel&telefono=' + telefono);



	ajax.onreadystatechange = function() 

	{



		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}





function mostrarCiudadesCapDem(idprov, idciudad, idzona)

{

	var ajax = initAjax();

	mostrarZonas(idciudad, idzona);

	document.getElementById('iCiuID2').value=idciudad;



	var obj = document.getElementById( 'comboCiudades' );



	ajax.open("GET", '../sistema/index.php?ohaction=mostrarCiudades&idprovincia=' + idprov + '&idciudad=' + idciudad);



	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}



function mostrarZonasCapDem(idciudad, idzona)

{

	var ajax = initAjax();

	document.getElementById('iZonID2').value=idzona;



	var obj = document.getElementById( 'comboZonas' );



	ajax.open("GET", '../sistema/index.php?ohaction=mostrarZonas&idciudad=' + idciudad + '&idzona=' + idzona);



	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}



function mostrarTinmuebleCapDem(idcat,id)

{

	var ajax = initAjax();

	document.getElementById('iTipInmID2').value=id;



	var obj = document.getElementById( 'comboTinmueble' );



	ajax.open("GET", '../sistema/index.php?ohaction=mostrarTinmuebles&idcat=' + idcat + '&idinm=' + id);



	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			obj.innerHTML = ajax.responseText;

		}

	}



	ajax.send(null);

}



// Cambia el estado

function cambiarEstado(id, estado) 

{

	var ajax = initAjax();

	//alert('../sistema/index.php?ohaction=modTareasAgendaestado&id=' + id + '&estado=' + estado);

	ajax.open("GET", '../sistema/index.php?ohaction=modTareasAgendaestado&id=' + id + '&estado=' + estado, true);

	

	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{



			// ESTADO = 3 Significa Tarea Completa

			// Si la tarea esta completada se debe eliminar el tachado cuando se cambia de estado

		if ( estado == '3')



			{

				

				//alert("no tachar");

				//alert(estado);

				var ele = document.getElementById(id);

				//alert(ele);

				ele.style.color = '#000000'; 

				ele.textDecoration = 'none';

			}

			// ESTADO != 3 Significa Tarea No completada  y se la cambia de estado, siempre debe tomar el estado = 3

			// Si la tarea no esta completada se debe generar el tachado cuando se cambia de estado	a Completado		

			else		

			{

				//alert(estado);

				document.getElementById(id).style.textDecoration = 'line-through';

				document.getElementById(id).style.color = '#CCCCCC';

						

			}		

			window.location.reload();

			//Para imprimir en un alert lo que devuelve el php que estoy llamando

			// Problema: Al cambiar el estado por primera vez, funciona correctamente, pero al cambiar el estado al mismo registro por segunda vez, no lo actualiza.

			//alert( ajax.responseText );

			

		}

	}



	ajax.send(null);

}





function eliminarTarea(id) 

{

	//alert (id);

	var ajax = initAjax();

	ajax.open("GET", '../sistema/index.php?ohaction=delTareasAgenda&id=' + id );

	

	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			//alert( ajax.responseText );

			window.location.reload();

		}

		

	}		

	ajax.send(null);

}



function chequearCantidadUsuarios()

{

	//alert (id);

	var ajax = initAjax();

	ajax.open("GET", '../sistema/index.php?ohaction=chequearCantidadUsuarios');

	

	ajax.onreadystatechange = function() 

	{

		if (ajax.readyState == 4 && ajax.status == 200) 

		{

			var respuesta = ajax.responseText;

			//alert("aaa" + respuesta);

			

			if (respuesta == "true")

			{

				alert("Un usuario ha iniciado sesión desde otra máquina");

				document.location.href="../sistema/index.php?ohaction=muchosUsuarios";

			}

		}

		

	}		

	ajax.send(null);

}



// Chequea estado del usuario

/*function chequearEstadoUsuario()

{

	// Cada 10 segundos

	setInterval("chequearCantidadUsuarios()", 10000);

}*/

function cambiarSubcategoriasAJAXBuscar(id) 
{

	var ajax = initAjax();

	var obj = document.getElementById( 'comboSubcategorias' );

	ajax.open("GET", 'qry_tiposinmueblesone.php?id=' + id);

	ajax.onreadystatechange = function() 
	{
		if (ajax.readyState == 4 && ajax.status == 200) 
		{
			//alert( ajax.responseText );
			obj.innerHTML = ajax.responseText;
		}
	}

	ajax.send(null);
}

