
//INICIO DE LA FUNCION QUE CREA EL OBJETO AJAX
function objetoAjax()
{
  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;
} 
// FIN DE LA FUNCION QUE CREA EL OBJETO AJAX

//INICIO DE LA FUNCION QUE COMPRUEBA SI EXISTE EN LA BASE DE DATOS EL USUARIO QUE SE ESTA LOGEANDO
function comprobar()
{
usuario=document.formulario.usuario.value;
password=document.formulario.password.value;

	ajax=objetoAjax();
 	ajax.open("POST", '../admin/proceso.php', true);
	ajax.onreadystatechange=function () {
	if (ajax.readyState==4) {
			resultado=ajax.responseText;
            //alert(resultado);
			if(resultado=="si")
                document.location.href="../admin/panel.php";
else
    alert("                El usuario no existe en el sistema \n por favor revise el nombre de usuario y password ingresados");
		}
	}
	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    ajax.send("usuario="+usuario+"&password="+password+"&funcion=comprobar");


}
//FIN DE LA FUNCION QUE COMPRUEBA SI EXISTE EN LA BASE DE DATOS EL USUARIO QUE SE ESTA LOGEANDO

// INICIO DE LA FUNCION PARA AGREGAR USUARIOS AL SISTEMA
function Agregar_Usuario()
{


	resultado=Validar_Ingreso(); // SE ENCUENTRA EN FUNCIONES.JS


	if(resultado==true)
	{
			usuario=$('usuario');
			clave=$('clave');
			nivel=$('nivel');
			indice=nivel.selectedIndex;
			nivel=nivel.options[indice];


			ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones.php', true);
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{
						resp=ajax.responseText;
						alert(resp);
						usuario.value="";
						clave.value="";
						$('clave_repetida').value="";
						$('nivel').selectedIndex=0;
                        refresca_div();
                        activada(0,"insertar");
                        
                       
				}
			}
			ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			ajax.send("usuario="+usuario.value+"&clave="+clave.value+"&nivel="+nivel.value+"&funcion=insertar");
    }

}
// FIN DE LA FUNCION PARA AGREGAR USUARIOS AL SISTEMA


//INICIO DE LA FUNCION PARA ACTUALIZAR EL DIV DONDE SE MUESTRAN LOS USUARIOS
function refresca_div()
{
        ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones.php', true);
            
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{
						resp=ajax.responseText;
						//alert(resp);
                        $('resultado').innerHTML = resp;
						

				}
			}
			ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			ajax.send("funcion=refrescar");
}
//FIN DE LA FUNCION PARA ACTUALIZAR EL DIV DONDE SE MUESTRAN LOS USUARIOS

//INICIO DE LA FUNCION PARA MODIFICAR DATOS DE LOS USUARIOS (PASSWORD Y NIVEL)
 function Modificar_Usuario()
{


	resultado=Validar_Para_Modificar("nueva_clave","nuevo_nivel"); // SE ENCUENTRA EN FUNCIONES.JS


	if(resultado==true)
	{
        //alert("puedo modificar")
			usuario=$('usuario_m');
            id_usuario=$('id_usuario_m');
			nueva_clave=$('nueva_clave');
			nuevo_nivel=$('nuevo_nivel');
			indice=nuevo_nivel.selectedIndex;
			nuevo_nivel=nuevo_nivel.options[indice];


			ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones.php', true);
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{
						resp=ajax.responseText;
						alert(resp);
                        refresca_div();
                        activada(0,"modificar");

						//usuario.value="";
						//nueva_clave.value="";

				}
			}
			ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send("id_usuario="+id_usuario.value+"&usuario="+usuario.value+"&nueva_clave="+nueva_clave.value+"&nuevo_nivel="+nuevo_nivel.value+"&funcion=modificar");
            
    }

}
//FIN DE LA FUNCION PARA MODIFICAR DATOS DE LOS USUARIOS (PASSWORD Y NIVEL)



//INICIO FUNCION QUE ME PERMITE BUSCAR UN USUARIO PARA LUEGO MODIFICAR LOS DATOS DEL MISMO (solo el password)
function modificar_mis_datos()
{

resultado=Validar_Para_Modificar("nueva_clave_m_p","nivel_m_p"); // SE ENCUENTRA EN FUNCIONES.JS


	if(resultado==true)
	{
        id_usuario=$('id_usuario_m_p').value; //
        nivel_m_p=$('nivel_m_p').value;  //
        nueva_clave=$('nueva_clave_m_p').value; //
        

       // alert(id_usuario+"***"+nivel_m_p+"***"+nueva_clave)

	//instanciamos el objetoAjax
	ajax=objetoAjax();
	//uso del medotod GET
	ajax.open("POST", "../php_ajax/operaciones.php");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
            respuesta=ajax.responseText;
            cadena="\n. Debe logearse nuevamente con la clave que acaba de crear\n";
            alert("              "+respuesta+cadena);
            location.href="../admin/";

		}
	}

	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//enviando los valores
	ajax.send("id_usuario="+id_usuario+"&nueva_clave="+nueva_clave+"&nuevo_nivel="+nivel_m_p+"&funcion=modificar");
    } 
}
//FIN DE FUNCION QUE ME PERMITE BUSCAR UN USUARIO PARA LUEGO MODIFICAR LOS DATOS DEL MISMO  (solo el password)


//INICIO FUNCION QUE ME PERMITE BUSCAR UN USUARIO Y
// MODIFICAR LOS DATOS DEL MISMO EN SU PANEL DE CONTROL ( SOLO PERMITE CAMBIAR EL PASSWORD)
function busca_modificar_password(id_usuario)
{
    

	//donde se mostrará el formulario con los datos
	//divFormulario = $('formulario');

	//instanciamos el objetoAjax
	ajax=objetoAjax();
	//uso del medotod POST
	ajax.open("POST", "../php_ajax/operaciones.php");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {

           respuesta=ajax.responseText;
            
            var arreglo=respuesta.split("*");
			$("id_usuario_m_p").value=arreglo[0];
            $("usuario_m_p").value=arreglo[1];
            $("nivel_m_p").selectedIndex =arreglo[2];
            $("nueva_clave_m_p").value="";
			


		}
	}

	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//enviando los valores
	ajax.send("id_usuario="+id_usuario+"&funcion=busca_modificar_password");
}
//FIN DE FUNCION QUE ME PERMITE BUSCAR UN USUARIO Y
// MODIFICAR LOS DATOS DEL MISMO EN SU PANEL DE CONTROL ( SOLO PERMITE CAMBIAR EL PASSWORD)




//INICIO FUNCION QUE ME PERMITE BUSCAR UN USUARIO Y
// MODIFICAR LOS DATOS DEL MISMO
function busca_modificar(id_usuario)
{


	//donde se mostrará el formulario con los datos
	//divFormulario = $('formulario');

	//instanciamos el objetoAjax
	ajax=objetoAjax();
	//uso del medotod POST
	ajax.open("POST", "../php_ajax/operaciones.php");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
            respuesta=ajax.responseText;

            var arreglo=respuesta.split("*");
			$("id_usuario_m").value=arreglo[0];
             $("usuario_m").value=arreglo[1];
            $("nuevo_nivel").selectedIndex =arreglo[2];
           $("clave_original").value =arreglo[3];


		}
	}

	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//enviando los valores
	ajax.send("id_usuario="+id_usuario+"&funcion=busca_modificar_password");
}
//FIN DE FUNCION QUE ME PERMITE BUSCAR UN USUARIO Y  MODIFICAR LOS DATOS DEL MISMO


//INICIO DE LA FUNCION PARA ELIMINAR UN USUARIO
function Eliminar_Usuario(id_usuario)
{
if(confirm("Desea eliminar permanentemente a este usuario?"))
 {
	/*if(resultado==true)
	{
        //alert("puedo modificar")
			usuario=$('usuario_m');
            id_usuario=$('id_usuario_m');
			nueva_clave=$('nueva_clave');
			nuevo_nivel=$('nuevo_nivel');
			indice=nuevo_nivel.selectedIndex;
			nuevo_nivel=nuevo_nivel.options[indice];
    */        


			ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones.php', true);
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{
						resp=ajax.responseText;
						
                        refresca_div();
                        alert(resp);
                        cerrar_ventana_modal('modificar');
						//usuario.value="";
						//nueva_clave.value="";

				}
			}
}
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send("id_usuario="+id_usuario+"&funcion=eliminar");

}
//FIN DE LA FUNCION PARA MODIFICAR DATOS DE LOS USUARIOS (PASSWORD Y NIVEL)
////////////////////// FIN DE CONTROLES AJAX PARA LOS USUARIO /////////////////////////
/************************************************************************************/

///////////////////////INICIO DE CONTROLES PARA LAS NOTICIAS//////////////////////////


// INICIO DE LA FUNCION PARA AGREGAR NOTICIAS
function Agregar_Noticia()//
{


			ante_titulo=$('ante_titulo');
			titulo=$('titulo');
                        sumario=$('sumario');

			id_tipo_noticia=$('id_tipo_noticia');
			indice=id_tipo_noticia.selectedIndex;
			id_tipo_noticia=id_tipo_noticia.options[indice];

            myf = $('Contenido_Noticia___Frame');
            myf = myf.contentWindow.document || myf.contentDocument;
            myf2=myf.getElementById('xEditingArea').getElementsByTagName('iframe')[0].contentWindow.document || myf.getElementById('xEditingArea').getElementsByTagName('iframe')[0].contentDocument;
            //alert(myf2.body.innerHTML);
            //alert('dsfsdsdf');
            //myf2.body.innerHTML='sdsdsdsdsd'
            Contenido_Noticia=myf2.body.innerHTML;


			ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones_noticias.php', true);
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{
				    resp=ajax.responseText;

                                    if(resp=="Existe")
                                    alert("Ya existe una noticia con el titulo ingresado");

                                    else
                                        {

                                    refresca_div_noticias();
                                    alert(resp); // DATOS CARGADOS CORRECTAMENTE
                                    //alert(Contenido_Noticia)
                                    myf = $('Contenido_Noticia___Frame');
            
                                   // alert("A limpiar : "+Contenido_Noticia);
                                    ante_titulo.value="";
                                    titulo.value="";
                                    sumario.value="";
                                
                                    

                                    $('id_tipo_noticia').selectedIndex=0;
                                    activada(0,"insertar_noticia");

                                    }
                                    /*
                                    return false;
				    ante_titulo.value="";
				    titulo.value="";
                                    sumario.value="";
				    $('id_tipo_noticia').selectedIndex=0;
                                    Contenido_Noticia="";*/
                        
                        //activada(0,"insertar");
                        
                       
				}
			}
			ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			ajax.send("ante_titulo="+ante_titulo.value+"&titulo="+titulo.value+"&sumario="+sumario.value+"&id_tipo_noticia="+id_tipo_noticia.value+"&Contenido="+Contenido_Noticia+"&funcion=insertar_noticia");
//return false;
//alert("Datos guardados exitosamente");
   //  } //llave del if(resultado==true)

    /*else
       {
         return false;
    }*/



} // llave de la funcion Agregar_Noticia()
// FIN DE LA FUNCION PARA AGREGAR NOTICIAS

// INICIO DE LA FUNCION PARA MODIFICAR NOTICIAS
function Modificar_Noticia()
{

//alert("estoy en Modificar_Noticia(), el valor de id_noticia = "+$('id_noticia').value);
        /*do{
	resultado=Validar_Campos_Noticia(); // SE ENCUENTRA EN FUNCIONES.JS
        }while(resultado!=true);*/

//if(resultado==true && $('activada').value==1)
	//{


			id_noticia=$('id_noticia2').value;
                       // alert(id_noticia);
                        ante_titulo=$('ante_titulo2').value;
			titulo=$('titulo2').value;
                        sumario=$('sumario2').value;

                        //Contenido_Noticia2=$('Contenido_Noticia2');

			id_tipo_noticia=$('id_tipo_noticia2');
			indice=id_tipo_noticia.selectedIndex;
			id_tipo_noticia=id_tipo_noticia.options[indice];
                       

                        myf = $('Contenido_Noticia2___Frame');
                        myf = myf.contentWindow.document || myf.contentDocument;
                        myf2=myf.getElementById('xEditingArea').getElementsByTagName('iframe')[0].contentWindow.document || myf.getElementById('xEditingArea').getElementsByTagName('iframe')[0].contentDocument;
                        //alert(myf2.body.innerHTML);
                        //alert('dsfsdsdf');
                        //myf2.body.innerHTML='sdsdsdsdsd'
                        Contenido_Noticia=myf2.body.innerHTML;

                    /*    alert(
                        "id_noticia = " +id_noticia+"\n "+
                        "id_tipo_noticia = "+indice+"\n "+
                                "ante titulo = "+ante_titulo+"\n "+
                               "titulo = "+titulo+"\n "+
                               "sumario = "+sumario+"\n "+
                               "Contenido_Noticia2 = "+Contenido_Noticia+"\n "
                            );*/

			ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones_noticias.php', true);
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{

                                   
                                   resp=ajax.responseText;
                                  // alert(resp);


                            	    if(resp=="ok")
                                        {
                                    alert("Datos actualizados exitosamente");
                                    Pagina($('numero_de_pagina').value);
                                    //refresca_div_noticias();
                                    

                                    ante_titulo.value="";
                                    titulo.value="";
                                    sumario.value="";
                                    Contenido_Noticia="";

                                    $('id_tipo_noticia2').selectedIndex=0;
                                    activada(0,"modificar_noticia");
                                        }
                                    else
                                        {

                                    alert("Error actualizando datos\n intente nuevamente");

                                    }
                                    /*
                                    return false;
				    ante_titulo.value="";
				    titulo.value="";
                                    sumario.value="";
				    $('id_tipo_noticia').selectedIndex=0;
                                    Contenido_Noticia="";*/

                        //activada(0,"insertar");


				}
			}
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send("id_noticia="+id_noticia+"&ante_titulo="+ante_titulo+"&titulo="+titulo+"&sumario="+sumario+"&id_tipo_noticia="+indice+"&Contenido_Noticia="+Contenido_Noticia+"&funcion=modificar_noticia");

///return false;
//alert("Datos guardados exitosamente");
   //  } //llave del if(resultado==true)

    /*else
       {
         return false;
    }*/

} // llave de la funcion Agregar_Noticia()
// FIN DE LA FUNCION PARA MODIFICAR NOTICIAS





// MODIFICAR LOS DATOS DEL MISMO
function busca_modificar_noticias(id_detalle_noticia,numero_de_pagina)
{
   $('id_noticia2').value=id_detalle_noticia;
   $('numero_de_pagina').value=numero_de_pagina;
   /*
            //Contenido_Noticia="";

	//donde se mostrará el formulario con los datos
	//divFormulario = $('formulario');
*/
	//instanciamos el objetoAjax
	ajax=objetoAjax();
	//uso del medotod POST
	ajax.open("POST", "../php_ajax/operaciones_noticias.php");
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
            respuesta=ajax.responseText;
            //alert(respuesta);
//$('ante_titulo').value=respuesta;
           oFCKeditor = new FCKeditor('Contenido_Noticia2') ;
           oFCKeditor.BasePath	=  'fckeditor/' ;
           oFCKeditor.Width = "800";
           oFCKeditor.Height = "450";
           oFCKeditor.ReplaceTextarea() ;
            myf = $('Contenido_Noticia2___Frame');
            myf = myf.contentWindow.document || myf.contentDocument;
            myf2=myf.getElementById('xEditingArea').getElementsByTagName('iframe')[0].contentWindow.document || myf.getElementById('xEditingArea').getElementsByTagName('iframe')[0].contentDocument;

//$cadena=$campo[id_detalle_noticia]."*".$campo[id_tipo_noticia]."*".$campo[antetitulo].
//"*".$campo[titulo]."*".$campo[sumario]."*".$campo[texto_noticia]."*".$campo[fecha_publicacion];
            var arreglo=respuesta.split("*");
           /* for(i=0;i<=6;i++)
                    alert(arreglo[i]);*/
           $("id_tipo_noticia2").selectedIndex=arreglo[1];
           $("ante_titulo2").value=arreglo[2];
           $("titulo2").value=arreglo[3];
           $("sumario2").value=arreglo[4];
           myf2.body.innerHTML=arreglo[5];
            


		}
	}

	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//enviando los valores
	ajax.send("id_detalle_noticia="+id_detalle_noticia+"&funcion=busca_datos_noticia");
}
//FIN DE FUNCION QUE ME PERMITE BUSCAR UN USUARIO Y  MODIFICAR LOS DATOS DEL MISMO

//INICIO DE LA FUNCION PARA ACTUALIZAR EL DIV DONDE SE MUESTRAN LOS USUARIOS
function refresca_div_noticias()
{
        ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones_noticias.php', true);
            
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{
						resp=ajax.responseText;
						//alert(resp);
                        $('resultado').innerHTML = resp;
						

				}
			}
			ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			ajax.send("funcion=refrescar_noticia");
}
//FIN DE LA FUNCION PARA ACTUALIZAR EL DIV DONDE SE MUESTRAN LOS USUARIOS


//INICIO DE LA FUNCION PARA ELIMINAR UN USUARIO
function Eliminar_Noticia(id_detalle_noticia)
{
if(confirm("Desea eliminar esta noticia?"))
 {
	/*if(resultado==true)
	{
        //alert("puedo modificar")
			usuario=$('usuario_m');
            id_usuario=$('id_usuario_m');
			nueva_clave=$('nueva_clave');
			nuevo_nivel=$('nuevo_nivel');
			indice=nuevo_nivel.selectedIndex;
			nuevo_nivel=nuevo_nivel.options[indice];
    */


			ajax=objetoAjax();
			ajax.open("POST", '../php_ajax/operaciones_noticias.php', true);
			ajax.onreadystatechange=function ()
			{
				if (ajax.readyState==4)
				{
						resp=ajax.responseText;

                        refresca_div_noticias();
                        alert(resp);
                        //cerrar_ventana_modal('insertar_modificar');
						//usuario.value="";
						//nueva_clave.value="";

				}
			}
}
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send("id_detalle_noticia="+id_detalle_noticia+"&funcion=eliminar_noticia");

}

function Pagina(nropagina)
{
    //alert(nropagina);
 //donde se mostrará los registros
 divContenido = document.getElementById('resultado');

 ajax=objetoAjax();
 //uso del medoto GET
 //indicamos el archivo que realizará el proceso de paginar
 //junto con un valor que representa el nro de pagina
 ajax.open("GET", "paginador.php?pag="+nropagina);
 divContenido.innerHTML= '<div align="center"><br><br><br><img src="../imagenes_fundacite/ajax-loader.gif"></div>';
 ajax.onreadystatechange=function() {
  if (ajax.readyState==4) {
   //mostrar resultados en esta capa
   divContenido.innerHTML = ajax.responseText
  }
 }
 //como hacemos uso del metodo GET colocamos null ya que enviamos
 //el valor por la url ?pag=nropagina
 ajax.send(null)
}

function Pagina_Noticias(nropagina)
{
    //alert(nropagina);
 //donde se mostrará los registros
 divContenido = document.getElementById('noticias');

 ajax=objetoAjax();
 //uso del medoto GET
 //indicamos el archivo que realizará el proceso de paginar
 //junto con un valor que representa el nro de pagina
 ajax.open("GET", "paginador_principal.php?pag="+nropagina);
 divContenido.innerHTML= '<div align="center"><br><br><br><img src="../imagenes_fundacite/ajax-loader.gif"></div>';
 ajax.onreadystatechange=function() {
  if (ajax.readyState==4) {
   //mostrar resultados en esta capa
   divContenido.innerHTML = ajax.responseText;
  }
 }
 //como hacemos uso del metodo GET colocamos null ya que enviamos
 //el valor por la url ?pag=nropagina
 ajax.send(null)
}
