var resultado_ajax;
var procesando;
var logueando;
var deslogueando;
function Ajax(){ 
/*
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; 
*/
	var A;
	
	var msxmlhttp = new Array(
		'Msxml2.XMLHTTP.5.0',
		'Msxml2.XMLHTTP.4.0',
		'Msxml2.XMLHTTP.3.0',
		'Msxml2.XMLHTTP',
		'Microsoft.XMLHTTP');
	for (var i = 0; i < msxmlhttp.length; i++) {
		try {
			A = new ActiveXObject(msxmlhttp[i]);
		} catch (e) {
			A = null;
		}
	}
	
	if(!A && typeof XMLHttpRequest != "undefined")
		A = new XMLHttpRequest();
	if (!A)
		alert("Could not create connection object.");
	return A;
} 

function ajax_query(pagina,capa,parametros,cargando,capa_resultado) {
	var ajax = Ajax(); 

	if(!ajax){
		alert("No se puede ejecutar este proceso: Error de navegador");
		return false;
	}
	
	procesamiento(1);
	document.getElementById(capa).innerHTML = cargando; 
	
	ajax.open("POST",pagina,true);
	
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4) { 
			resultado_ajax = ajax.responseText;
			document.getElementById(capa_resultado).innerHTML=ajax.responseText;
			if (logueando == 1) {
				respuesta_login();
			} else if (deslogueando == 1) {
				window.location = '../index.php';
			}
			if (resultado_ajax == "noticia_deshabilitada") {
				administrar_noticias();
			} else if (resultado_ajax == "noticia_habilitada") {
				administrar_noticias();
			} else if (resultado_ajax == "cambiar_orden_noticia") {
				cambiaubicacion();
			} else if (resultado_ajax == "clima_actualizado") {
				window.location = 'index.php';
			}
			procesamiento(0);
		}
	}
	
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(parametros);

}

function procesamiento (valor) {
	var A;
	procesando = valor;
	if (valor == 1) {
		A = document.getElementById("cuerpo");
		A.style.filter = 'alpha(opacity=25)';	
		A.style.opacity = 0.25;
		document.getElementById("cargando").style.visibility = 'visible';
	} else {
		A = document.getElementById("cuerpo");
		A.style.filter = 'alpha(opacity=100)';	
		A.style.opacity = 1;
		document.getElementById("cargando").style.visibility = 'hidden';
	}

}

function alert_confirm(alerta,accion,link) {
	confirmar = confirm(alerta); 
	if (confirmar) {
			if (accion == "ir") {
				window.location.href = link;
			} else if (accion == "ajax_query") {
					var cadena;
					cadena = link.split(",");
					ajax_query(cadena[0],cadena[1],cadena[2],cadena[3],cadena[4]);
			}
	}
}

function borrar(link) {
	confirmar = confirm("¿Esta seguro que desea deshabilitar la noticia seleccionada?\nRecuerde que las noticias no se eliminan definitivamente de\nla Base de Datos, solo se deshabilitan a mostrarse publicamente."); 
	if (confirmar) {
		window.location.href = link;
	}
}

function borrar_foto(id,foto) {
	confirmar = confirm("¿Esta seguro que desea quitar la fotografia?"); 
	if (confirmar) {
		window.location.href = 'index.php?accion=modificarnoticia&noticia='+id+'&borrar_foto='+foto;
	}
}

var clockID = 0;
function UpdateClock() {
   if(clockID) {
      clearTimeout(clockID);
      clockID  = 0;
   }

   var tDate = new Date();

	hora = tDate.getHours();
   if(hora < 10) {
		hora = "0" + hora;
	}

	minutos = tDate.getMinutes();
   if(minutos < 10) {
		minutos = "0" + minutos;
	}

	segundos = tDate.getSeconds();
   if(segundos < 10) {
		segundos = "0" + segundos;
	}
   
   document.theClock.theTime.value = "" 
                                   + hora + ":" 
                                   + minutos + " hs";
   
   clockID = setTimeout("UpdateClock()", 1000);
}
function StartClock() {
   clockID = setTimeout("UpdateClock()", 500);
}

function KillClock() {
   if(clockID) {
      clearTimeout(clockID);
      clockID  = 0;
   }
}

function modnot() {
	if (modificarnoticia.volanta.value.length < 1) {
		alert("No has escrito la Volanta!");
		modificarnoticia.volanta.focus();
		return (false);
		exit;
	}
	if (modificarnoticia.producto.value.length < 1) {
		alert("No has escrito el Titulo!");
		modificarnoticia.titulo.focus();
		return (false);
		exit;
	}
	if (modificarnoticia.copete.value.length < 1) {
		alert("No has escrito el Copete!");
		modificarnoticia.copete.focus();
		return (false);
		exit;
	}
return (true);
}

function agrnot() {
	if (agregarnoticia.seccion.value < 1) {
		alert("Debes seleccionar la Seccion!");
		agregarnoticia.seccion.focus();
		return (false);
		exit;
	}
	if (agregarnoticia.volanta.value.length < 1) {
		alert("No has escrito la Volanta!");
		agregarnoticia.volanta.focus();
		return (false);
		exit;
	}
	if (agregarnoticia.titulo.value.length < 1) {
		alert("No has escrito el Titulo!");
		agregarnoticia.titulo.focus();
		return (false);
		exit;
	}
	if (agregarnoticia.copete.value.length < 1) {
		alert("No has escrito el Copete!");
		agregarnoticia.copete.focus();
		return (false);
		exit;
	}
return (true);
}

function ChangeItemVideo(idSeccion,maximo,accion){
	if(accion == "siguiente"){
		if( parseInt(posVideo[idSeccion]) + Number(1) <= parseInt(maximo) ){
			posVideo[idSeccion] = posVideo[idSeccion] + 1;
		}else{
			posVideo[idSeccion] = 0 ;
		}
	}else{
		//num = parseInt(posVideo[idSeccion]) - Number(1);
		//alert(num);
		if( parseInt(posVideo[idSeccion]) - Number(1) >= parseInt(0) ){
			posVideo[idSeccion] = posVideo[idSeccion] - 1;
		}else{
			posVideo[idSeccion] = maximo ;
		}
	}
	//alert(posVideo[idSeccion]);
	
	for( var i = 0 ; i <= maximo ; i++  ){
		if( i == posVideo[idSeccion] ){
			document.getElementById("Item_"+idSeccion+"_"+i).style.display = "block";
			document.getElementById("Count_Item_"+idSeccion).innerHTML = Number(i) + Number(1);
		}else{
			document.getElementById("Item_"+idSeccion+"_"+i).style.display = "none";
		}
	}	
}

function cambia_img_clima (objeto) {
	var valornuevo = objeto.options[objeto.selectedIndex].value;
	if (valornuevo == 0) {
		var img = 'soleado.gif';
	} else if (valornuevo == 1) {
		var img = 'nublado.gif';
	} else if (valornuevo == 2) {
		var img = 'lluvioso.gif';
	} else if (valornuevo == 3) {
		var img = 'tormenta.gif';
	}
	document.getElementById('img_tiempo').innerHTML = '<img src="../imagenes/'+img+'">';
}

function cargar_clima() {
	var temperatura;
	var humedad;
	var sensaciontermica;
	var parametros;
	var imagen;
	indice = document.clima.img.selectedIndex;
	imagen = document.clima.img[indice].value;
	temperatura = document.clima.temperatura.value;
	humedad = document.clima.humedad.value;
	sensaciontermica = document.clima.sensaciontermica.value;
	parametros = 'accion=cargar_clima&temperatura='+temperatura+'&humedad='+humedad+'&sensaciontermica='+sensaciontermica+'&img='+imagen;
	ajax_query('../ajax.php','cargando',parametros,'<strong>Guardando datos del Clima</strong>...<br /><img src="../imagenes/ajax_loading3.gif" />','tiempo')
	//window.location = 'index.php';
}

function loguear() {
	logueando = 1;
	usuario = document.login.usuario.value;
	password = document.login.clave.value;
	parametros = 'accion=loguear&usuario='+usuario+'&clave='+password;
	ajax_query('../ajax.php','cargando',parametros,'<strong>Cargando datos del usuario</strong>...<br /><img src="../imagenes/ajax_loading3.gif" />','capa_resultado');
}

function desloguear() {
	deslogueando = 1;
	alert_confirm('Desea terminar la sesion?','ajax_query','../ajax.php,cargando,accion=terminar_sesion,<strong>Cerrando la sesion del usuario</strong>...<br /><img src=../imagenes/ajax_loading3.gif />,cargando');
}

function respuesta_login () {
	logueando = 0;
	if (resultado_ajax==1) {
		window.location = 'index.php';
	} else {
		alert ("El nombre o contraseña es incorrecta");
	}
}

function administrar_noticias() {
	var lista_tipo;
	var ubicacion;
	var habilitado;
	var lista_usuario;
	var indice;
	var valor;
	indice = document.administrar_noticia.lista_tipo.selectedIndex;
	lista_tipo = document.administrar_noticia.lista_tipo[indice].value;
	indice = document.administrar_noticia.ubicacion.selectedIndex;
	ubicacion = document.administrar_noticia.ubicacion[indice].value;
	indice = document.administrar_noticia.habilitado.selectedIndex;
	habilitado = document.administrar_noticia.habilitado[indice].value;
	indice = document.administrar_noticia.lista_usuario.selectedIndex;
	lista_usuario = document.administrar_noticia.lista_usuario[indice].value;
	ajax_query('../ajax.php','cargando','accion=administrar_noticias&lista_tipo='+lista_tipo+'&ubicacion='+ubicacion+'&habilitado='+habilitado+'&lista_usuario='+lista_usuario,'<strong>Listando noticias</strong>...<br /><img src=../imagenes/ajax_loading3.gif />','administrar_noticias_resultado')
}

function cambiaubicacion() {
	var indice = document.ordenarnoticia.ubicacion.selectedIndex;
	var ubicacion = document.ordenarnoticia.ubicacion[indice].value;
	ajax_query('../ajax.php','cargando','accion=ordenarnoticias&ubicacion='+ubicacion,'<strong>Listando noticias</strong>...<br /><img src=../imagenes/ajax_loading3.gif />','noticias_ordenadas');
}

function cambiaorden(objeto,valoractual,ubicacion) {
	var valornuevo = objeto.options[objeto.selectedIndex].value;
	ajax_query('../ajax.php','cargando','accion=update_orden_noticias&ubicacion='+ubicacion+'&update='+valoractual+'-'+valornuevo,'<strong>Cambiando el orden de las noticias</strong>...<br /><img src=../imagenes/ajax_loading3.gif />','noticias_ordenadas_temp');
}

function email_contacto() {
	var nombre;
	var email;
	var texto;
	nombre = document.contacto.nombre.value;
	texto = document.contacto.texto.value;
	ajax_query('../ajax.php','cargando','accion=email_contacto&nombre='+nombre+'&texto='+texto,'<strong>Enviando e-mail</strong>...<br /><img src=../imagenes/ajax_loading3.gif />','email_contacto_resultado');
}

function actualizar_clima() {
		var div1=document.getElementById('div_clima');
		//div1.innerHTML='<div align="center">Cargando....</div><div align="center"><img src="imgs/loading.gif" width="32" height="32" /></div>';
		var url = 'clima.php';
        var pars = 'clima=1';
        var myAjax = new Ajax.Updater( div1, url, { method: 'get', parameters: pars });
}


var winName="ver" 
	function A_V(theURL,w,h) { 
	l = (screen.width - w)/2; 
	t = (screen.height - h)/2; 
	var windowprops ="top=15,left=200,toolbar=no,location=no,status=no, menubar=no,scrollbars=yes, resizable=no,width=" + w + ",height=" + h +", left="+l+", top="+t; 
	var ver=window.open(theURL,winName,windowprops); 
	return ver;
	}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  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];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
