var http_request = false;
var agregar = false;
var reporto = false;

function logout()
{
       location.href="http://passport.lanacion.com.ar/logout.aspx?pagina=" + window.location.href;
	return false;
}

function ValidateBusqueda(palabra)
{
	var palabra = trim(palabra.value);
	var length = palabra.length;

	if (length < 3) // Debe Tirar Error.
	{
		alert('Debe ingresar 3 caracteres o m�s.');
		return false;
	}
	else // Debe hacer Submit.
	{
		document.formBusqPalabra.submit();
		return true;
	}
}
function RollOver(id, src)
{
	document.getElementById(id).src = src;
}
function insertAviso()
{
	document.getElementById('dm404').value = 1;
	document.dmformaparte.submit();

}

function ValidateBusquedaDM(palabra)
{
	var palabra = trim(palabra.value);
	var length = palabra.length;

	if (length < 3) // Debe Tirar Error.
	{
		alert('Debe ingresar 3 caracteres o m�s.');
		return false;
	}
	else // Debe hacer Submit.
	{
		document.formBusqPalabraDM.submit();
		return true;
	}
}

function filtrarOptions(opt, comboZona, comboSubZona, dia, mes, anio)
{
	http_request = false;

	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// Ver nota sobre esta linea al final
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Falla :( No es posible crear una instancia XMLHTTP');
		return false;
	}

	variablesPost = "opt=" + opt;
	if(comboZona != undefined && comboSubZona != undefined)
	{
		idZona = document.getElementById(comboZona).value;
		idSubZona = document.getElementById(comboSubZona).value;

		if(idSubZona == 0)
		{
			variablesPost += "&drpZona=" + idZona;
		}
		else
		{
			variablesPost += "&drpZona=" + idZona + "&drpSubZona=" + idSubZona;
		}
	}

	http_request.onreadystatechange = filtrar;
	http_request.open("POST", "/getavisos.php?dia="+dia+"&mes="+mes+"&anio="+anio,true);
	http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http_request.send(variablesPost);
}

function filtrar()
{
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			document.getElementById('contenedor').innerHTML = http_request.responseText;
		}
		else
		{
			alert('Hubo problemas con la petici�n.');
		}
	}
}

function var_dump(objeto, vista)
{
	var res = '';
	for (i in objeto)
	{
		res += "\t["+i+"] => "+objeto[i]+" \n";
	}

	if (!vista)
	{
		myWindow = window.open('','','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=800,height=800');
		myWindow.document.write("<pre>\ndebug\n{\n"+res+'\n}\n</pre>');
		myWindow.focus();
	}
	else
	{
		eval(vista+"(res);");
	}
}

var control = 0;
function pasarMes(mesPasar, anioPasar, dia, mes, anio)
{
	http_request = false;

	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// Ver nota sobre esta linea al final
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Falla :( No es posible crear una instancia XMLHTTP');
		return false;
	}

	http_request.onreadystatechange = moverCalendario;

	http_request.open("POST", "/rshome.php?dia=" + dia + "&mes=" + mes + "&anio=" + anio, true);
	http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http_request.send("mesPasar=" + mesPasar + "&anioPasar=" + anioPasar + "&ajax=1");
}

function moverCalendario()
{
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			document.getElementById('calendario').innerHTML = http_request.responseText;
		}
		else
		{
			alert('Hubo problemas con la petici�n.');
		}
	}
}

function Buscar()
{
	document.getElementById('busquedaavanzada').action = 'buscador';
	document.busquedaavanzada.submit();
}

function BuscarDM()
{
	var DrpCatPadres = document.getElementById('DrpCategoriasPadres').selectedIndex;
	var DrpCatHijas = document.getElementById('DrpCategorias').selectedIndex;
	var TxtTitulo = document.getElementById('TxtTitulo').value;
	var DrpZona = document.getElementById('drpZona').selectedIndex;
	var DrpSubZona = document.getElementById('drpSubZona').selectedIndex;

	if ((DrpCatPadres != 0) && (DrpCatHijas == 0) && (TxtTitulo.length == 0) && (DrpZona == 0) && (DrpSubZona == 0))
	{
		document.getElementById('divErroresBusqAv').style.display = 'block';
		document.getElementById('divErroresBusqAv').innerHTML = 'Debe seleccionar una sub categor&iacute;a.';
	}
	else
	{
		if ((DrpCatPadres == 0) && (DrpCatHijas == 0) && (TxtTitulo.length == 0) && (DrpZona == 0) && (DrpSubZona == 0))
		{
			document.getElementById('divErroresBusqAv').style.display = 'block';
			document.getElementById('divErroresBusqAv').innerHTML = 'Debe seleccionar un item de b&uacute;squeda.';
		}
		else
		{
			document.getElementById('divErroresBusqAv').style.display = 'none';
			document.getElementById('dmbusquedaavanzada').action = 'dm-buscador';
			document.dmbusquedaavanzada.submit();
		}

	}
}

var _IdAviso;
var _IdFuncion;
function yoVoy(idFuncion)
{
	_IdFuncion = idFuncion;
	PedidoYoVoy.startRequest();
}

var PedidoYoVoy =
{
	handleSuccess:function(o)
	{
		if(o.responseText != '')
		{
			renderButtons(o.responseText);
		}
	},

	handleFailure:function(o){},

	startRequest:function()
	{
		var time = new Date();
		var data = 'idFuncion=' + _IdFuncion;
		YAHOO.util.Connect.asyncRequest('POST', '/ajax/yovoy.php?t=' + time.getTime(), callbackYoVoy, data);
	}
}

var callbackYoVoy =
{
	success: PedidoYoVoy.handleSuccess,
	failure: PedidoYoVoy.handleFailure,
	scope: PedidoYoVoy
}

function renderButtons(cant)
{
	createCookie('valoro_' + _IdFuncion, 1, 9999);
	document.getElementById('yovoybutton_' + _IdFuncion).innerHTML = '<img src="/images/rollingstone/btnYoVoyGris.gif">';
	document.getElementById('yovoynumber_' + _IdFuncion).innerHTML = cant;
}

function createCookie(name, value, days)
{
	if(days)
	{
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else
	{
		var expires = "";
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

/*
* Funciones para el manejo de Pedidos por Ajax
*/
var ajaxRequest = false;

function builtAjax()
{
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari, ...
		ajaxRequest = new XMLHttpRequest();
		if (ajaxRequest.overrideMimeType)
		{
			//ajaxRequest.overrideMimeType('text/xml');
			// See note below about this line
		}
	}
	else if (window.ActiveXObject)
	{ // IE
		try {
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try {
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}
	return ajaxRequest;
}

//function de testeo
function print_r(obj,vista)
{
	var out = "";
	var txt = "";
	var nli = "\n";
	var tab = "\t";
	var ret = "\r";
	var erg = "";

	if(obj)
	{
		txt = "["+typeof(obj)+"] => "+obj.name+nli+"{"+nli;
		if(typeof(obj) == "object")
		{
			for(i in obj)
			{
				txt += nli+tab+'['+i+'] => '+((typeof(obj[i]) == "function")?"function "+obj[i].name+"()":obj[i]);
				if (obj[i])
				{
					txt += nli+tab+"{";
					if(typeof(obj[i]) == "object")
					{
						if (obj[i].length > 0)
						{
							for(n in obj[i])
							{
								if(obj[i][n]) txt += nli+tab+tab+'['+n+'] => '+((typeof(obj[i][n]) == "function")?"function "+obj[i][n].name+"()":obj[i][n]);
							}
						}
					}
					else if(typeof(obj[i]) == "string")
					{
						txt += nli+tab+tab+'['+typeof(obj[i])+'] => "'+obj[i]+'"';
					}
					txt += nli+tab+"}";
				}
			}
		}
		else
		{
			txt += tab+'['+typeof(obj)+'] => "'+obj+'"';
		}

		erg = /\{[\s]*\}[\s]*/g;
		txt = txt.replace(erg, "");
		txt += ret+"}";
	}
	else
	{
		txt += "NULL or UNDEFINED";
	}

	switch(vista)
	{
		case 2:
		out = window.open('','debug','');
		out.document.write("<pre>"+txt+"</pre>");
		break;
		default:
		alert(txt);
		break;
	}
	return false;
}

/*
* Carga de Localidades en un combobox por Ajax
* funciones para la carga de combobox de provincias y sus localidades
*/
function generarListadoLocs(idProv)
{
	if(!locs[idProv])
	{
		cargLocs(idProv);
	}
	else
	{
		cargarOpcionesLocs(false,idProv,false);
	}
}

function cargLocs(id, selectedValue)
{
	var res = false;
	_ajax = builtAjax();
	
	if(_ajax)
	{
		_ajax.onreadystatechange=function()
		{
			if (_ajax.readyState == 4)
			{
				if (_ajax.status == 200)
				{
					cargarOpcionesLocs(_ajax.responseText,id,true, selectedValue);
				}
			}
		}

		_ajax.open("POST", '/rsagendaupload.php',true);
		_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		_ajax.send('l=1&v='+parseInt(id));
	}
}

function cargarOpcionesLocs(arrLocs,idProvinc,decoJson,selectedValue)
{
	idProv = idProvinc;
	var arrIdProvinc = new Array();
	var selPostLoc = false;
	if(decoJson)
	{
		arrIdProvinc = arrLocs.parseJSON();
	}
	else
	{
		arrIdProvinc = arrLocs;
	}

	if(arrLocs)
	{
		locs[idProvinc] = arrIdProvinc;
	}

	document.getElementById('loc').disabled = true;

	document.getElementById('loc').length = 0;

	document.getElementById('loc').options[0] = new Option('-- Localidad --', '0' , (locSelecc!='' ? false : true));
	
	if(idProvinc != 0)
	{
		for(var i = 0 ; i < locs[idProvinc].length ; i++)
		{
			selPostLoc = ((locSelecc == locs[idProvinc][i]['IDLOCALIDAD']) ? true : false);
	
			if(selectedValue && selectedValue == locs[idProvinc][i]['IDLOCALIDAD'])
			{
				document.getElementById('loc').options[i+1] = new Option(locs[idProvinc][i]['DENOMINACION'], locs[idProvinc][i]['IDLOCALIDAD'], selPostLoc , true);
			}
			else
			{
				document.getElementById('loc').options[i+1] = new Option(locs[idProvinc][i]['DENOMINACION'], locs[idProvinc][i]['IDLOCALIDAD'], selPostLoc);
			}
		}
	}
	
	document.getElementById('loc').disabled = false;
}

function vaciarComboLocalidades()
{
	var combo = document.getElementById('loc')
	
	for (k = 0; k < combo.options.length; k++)
	{
		combo.options[k] = null;
		
	}
	document.getElementById('loc').options[0] = new Option('-- Localidad --', '0' , true);
	
 	combo.options.length = 1;
}

function cargCombBoxFecha()
{
	var aniosMost = 10;
	var mesXsel = parseInt(mesSelecc);
	var selPostMes = false;
	var selPostAni = false;

	var nombreMes = new Array();
	nombreMes[1] = "Enero";
	nombreMes[2] = "Febrero";
	nombreMes[3] = "Marzo";
	nombreMes[4] = "Abril";
	nombreMes[5] = "Mayo";
	nombreMes[6] = "Junio";
	nombreMes[7] = "Julio";
	nombreMes[8] = "Agosto";
	nombreMes[9] = "Septiembre";
	nombreMes[10] = "Octubre";
	nombreMes[11] = "Noviembre";
	nombreMes[12] = "Diciembre";

	var date = new Array();

	for(i = 0 ; i <= aniosMost ; i++)
	{
		date[i] = new Date();
		selPostAni = (aniSelecc == parseInt(date[i].getFullYear()+i)) ? true : false;
		date[i].setFullYear(parseInt(date[i].getFullYear()+i));
		document.getElementById('anio').options[i] = new Option(date[i].getFullYear(),date[i].getFullYear(),selPostAni,selPostAni);
	}

	for(n = 0 ; n < 12 ; n++)
	{
		selPostMes = (parseInt(n+1) == mesXsel) ? true : false;
		document.getElementById('mes').options[n] = new Option(nombreMes[parseInt(n+1)],parseInt(n+1),selPostMes,selPostMes);
	}
	cargDias(false);
}

function cargDias(ctrlDia)
{
	var mesSel = document.getElementById('mes').value;
	var anioSel = document.getElementById('anio').value;
	var diaSel = document.getElementById('dia').value;
	if (ctrlDia) diaSelecc = diaSel;
	var selPostDia = false;
	var xFecha = new Date();
	xFecha.setFullYear(anioSel);
	xFecha.setMonth(parseInt(mesSel - 1));

	var numDias = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30,31, 30, 31);
	var diasMes = new Array();

	if (xFecha.getMonth()  == 1)
	{
		var year = xFecha.getYear();
		if (year % 4 == 0 && (year % 400 == 0 || year % 100 != 0))
		{
			numDias[1] = 29;
		}
		else
		{
			numDias[1] = 28;
		}
	}

	var i;
	if(pltMes.length < 28)
	{
		for (i = 1 ; i <= 31 ; i++)
		{
			selPostDia = false;
			pltMes[i] = document.getElementById('dia').options[parseInt(i - 1)] = new Option(i,i,selPostDia);
		}
	}

	if (numDias[parseInt(xFecha.getMonth())] < document.getElementById('dia').length)
	{
		document.getElementById('dia').length = numDias[parseInt(xFecha.getMonth())];
	}
	if(document.getElementById('dia').length < numDias[parseInt(xFecha.getMonth())])
	{
		for (i = document.getElementById('dia').length ; i <= numDias[parseInt(xFecha.getMonth())] ; i++)
		{
			document.getElementById('dia').options[i] = new Option(i,i,selPostDia);
		}
	}

	if(document.getElementById('dia').options[parseInt(diaSelecc - 1)])
	{
		document.getElementById('dia').options[parseInt(diaSelecc - 1)].selected = true;
	}
}

function comentariosVerTodosRS(url, idAviso)
{
	http_request = false;

	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// Ver nota sobre esta linea al final
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Falla :( No es posible crear una instancia XMLHTTP');
		return false;
	}

	http_request.onreadystatechange = cargarComentariosRS;

	http_request.open('GET', url+'?comentario=1&'+'idAviso='+idAviso, true);

	http_request.send(null);

}

function cargarComentariosRS()
{
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			console.log(http_request.responseText);
			document.getElementById('contenido').innerHTML = http_request.responseText;
		}
		else
		{
			alert('Hubo problemas con la petici�n.');
		}
	}
}
function verAviso(url)
{
	window.location = url;
}

function RedirectToFeed(dia, mes, anio, idDropZona/*, idDropSubZona*/)
{
	/*
	if(isNaN(idDropZona))
	{
		zona = document.getElementById(idDropZona);
		if(zona)
		{
			idZona = zona.value;
		}
		else
		{
			idZona = 0;
		}
	}
	else
	{
		idZona = idDropZona;
	}
	idSubZona = 0;//document.getElementById(idDropSubZona).value;

	//queryString = 'rsfeedeventos.php?dia=' + dia + '&mes=' + mes + '&anio=' + anio + '&prov=' + idZona + '&loc=' + idSubZona;
	*/
	queryString = '/xml/rsfeedeventosxml.xml';
	window.location = queryString;

}

function ltrim(s)
{
    return s.replace(/^\s+/, "");
}

function rtrim(s)
{
    return s.replace(/\s+$/, "");
}

function trim(s)
{
    return rtrim(ltrim(s));
}

function showHide(idDiv)
{
	if (document.getElementById(idDiv).style.display == 'none')
	{
		document.getElementById(idDiv).style.display = 'block';
	}
	else
	{
		document.getElementById(idDiv).style.display = 'none';
	}
}
function ScreenOpacity(idMostrar)
{
	element = document.getElementById('layerDiv');
	element.style.display = "block";
	document.getElementById('layerDiv').style.height = document.body.clientHeight + 'px';
	document.getElementById('layerDiv').style.width = document.body.clientWidth + 'px';
	element = document.getElementById(idMostrar);
	element.style.display = "";

	var x = parseInt((window.screen.width / 2) - (element.offsetWidth / 2), 10);
	var y = parseInt((window.screen.height / 2) - (element.offsetHeight), 10);

	if (y < 0)
	{
		y = 10;

	}
	element.style.top = y + 'px';
	element.style.left = x + 'px';
	element.style.position = 'fixed';
	if (navigator.userAgent.indexOf('MSIE 6') >= 0)
	{
		element.style.position = 'absolute';
	}
}
function clearText(id)
{
	document.getElementById(id).value = '';
}

function isEmail(s)
{
	if(s.match(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/))
	{
		return true;
	}
	return false;
}

function enviarRecomendacion(TxtEmailDestinatario, TxtNombreRemitente, TxtEmailRemitente, ChkCopia, OptEnviar, TxtComentarios, idAviso)
{
	var EmailDestinatario = document.getElementById(TxtEmailDestinatario).value;
	var NombreRemitente = document.getElementById(TxtNombreRemitente).value;
	var EmailRemitente = document.getElementById(TxtEmailRemitente).value;
	var ChkCopy = document.getElementById(ChkCopia).value;
	var OptEnviarCompl = document.getElementById(OptEnviar).checked;
	var Comentarios = document.getElementById(TxtComentarios).value;
	var arrErrores = new Array('', '', '');
	var valid = true;

	if (!isEmail(EmailDestinatario))
	{
		valid = false;
		arrErrores[0] = 'Verifique el e-mail de destinatario.<br>';
	}
	if (NombreRemitente == '')
	{
		valid = false;
		arrErrores[1] = 'Verifique el nombre de remitente.<br>';
	}
	if (!isEmail(EmailRemitente))
	{
		valid = false;
		arrErrores[2] = 'Verifique el e-mail de remitente.<br>';
	}

	if (valid)
	{
		enviarMailNota(EmailDestinatario, NombreRemitente, EmailRemitente, ChkCopy, OptEnviarCompl, Comentarios, idAviso);
		ScreenOpacity('divEnviarExito');
		document.getElementById('divCerrar').style.display = 'none';
		setTimeout("showHide('divEnviarExito');showHide('divEnviar');showHide('layerDiv');",2000);
	}
	else
	{
		showHide('divErrorEnvio');
		document.getElementById('divErrorEnvio').innerHTML = arrErrores[0] + arrErrores[1] + arrErrores[2];
	}
}

function showHideClose(idDiv)
{
	document.getElementById(idDiv).style.display = 'block';
}

function enviarMailNota(EmailDestinatario, NombreRemitente, EmailRemitente, ChkCopy, OptEnviar, Comentarios, idAviso)
{
	http_request = false;

	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// Ver nota sobre esta linea al final
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Falla :( No es posible crear una instancia XMLHTTP');
		return false;
	}

	http_request.onreadystatechange = envMailNota;

	var variablesPost = "nomRem=" + NombreRemitente + "&comentarios=" + Comentarios + "&emailRem=" + EmailRemitente + "&emailDest=" + EmailDestinatario +  "&enviar=" + OptEnviar + "&copy=" + ChkCopy;

	http_request.open("POST", "/dmfichaaviso.php?idAviso=" + idAviso, true);
	http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http_request.send(variablesPost);
}

function envMailNota()
{
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			document.getElementById('cantRecomendaciones').innerHTML = http_request.responseText;
		}
		else
		{
			alert('Hubo problemas con la petici�n.');
		}
	}
}

function selectAll(id)
{
	document.getElementById(id).select();
}
http_request_comentarios = false;

function verTodos(url, idAviso)
{
	http_request_comentarios = false;

	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		http_request_comentarios = new XMLHttpRequest();
		if (http_request_comentarios.overrideMimeType) {
			http_request_comentarios.overrideMimeType('text/xml');
			// Ver nota sobre esta linea al final
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request_comentarios = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request_comentarios = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request_comentarios) {
		alert('Falla :( No es posible crear una instancia XMLHTTP');
		return false;
	}

	http_request_comentarios.onreadystatechange = cargarComentarios;

	http_request_comentarios.open('GET', url+'?comentario=1&'+'idAviso='+idAviso, true);

	http_request_comentarios.send(null);

}

function cargarComentarios()
{
	if (http_request_comentarios.readyState == 4)
	{
		if (http_request_comentarios.status == 200)
		{
			document.getElementById('contenido').innerHTML = http_request_comentarios.responseText;
		}
		else
		{
			alert('Hubo problemas con la petici�n.');
		}
	}
}

function reportarCierreMudanza(idAviso, tipoReporte, texto)
{
	http_request = false;

	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// Ver nota sobre esta linea al final
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Falla :( No es posible crear una instancia XMLHTTP');
		return false;
	}

	var variablesPost = "tipoReporte=" + tipoReporte + "&texto=" + texto;

	http_request.onreadystatechange = reportarAbuso;

	http_request.open("POST", "/dmfichaaviso.php?idAviso=" + idAviso, true);
	http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http_request.send(variablesPost);
}

function reportarAbuso()
{
	if (http_request.readyState == 4)
	{
		if (http_request.status == 200)
		{
			ScreenOpacity('divReportarExito');
			document.getElementById('divCerrarReportar').style.display = 'none';
			setTimeout("showHide('divReportarExito');showHide('divReportar');showHide('layerDiv');", 2000);
			document.getElementById('linkReportar').href = 'javascript: ScreenOpacity(\'divReportado\');autoCierre();';
		}
		else
		{
			alert('Hubo problemas con la petici�n.');
		}
	}
}

function autoCierre(idDiv)
{
	setTimeout("showHide('divReportado');showHide('layerDiv');", 2000);
}

function openPopup(idAviso)
{
	popup = window.open('dmimprimir.php?idAviso=' + idAviso,'650x300','toolbar=no,status=no,scrolling=no,scrollbars=no,location=no,menubar=no,directories=no,resizable=yes,width=650,height=400');
}

function addImage()
{
	document.getElementById('file_controls').innerHTML += '<div class="filecontrol_container"><input type="file" name="txt_file[]"></div>';
}

var _IdImage;
var _IdAviso;
function deleteImage(id, idaviso)
{
	var conf = confirm("�Quer�s eliminar esta imagen?");
	if(conf)
	{
		_IdImage = id;
		_IdAviso = idaviso;
		PedidoDeleteImage.startRequest();
	}
}

var PedidoDeleteImage =
{
	handleSuccess:function(o)
	{
		if(o.responseText == 'true')
		{
			deleteImageDiv();
		}
	},

	handleFailure:function(o){},

	startRequest:function()
	{
		var time = new Date();
		var data = 'idimage=' + _IdImage + '&idaviso=' + _IdAviso;
		YAHOO.util.Connect.asyncRequest('POST', '/ajax/deleteimage.php?t=' + time.getTime(), callbackDeleteImage, data);
	}
}

var callbackDeleteImage =
{
	success: PedidoDeleteImage.handleSuccess,
	failure: PedidoDeleteImage.handleFailure,
	scope: PedidoDeleteImage
}

function deleteImageDiv()
{
	document.getElementById('image' + _IdImage).innerHTML = '&nbsp;';
}

var _IdAvisoBorrarImages;
function deleteAllImages(id)
{
	var conf = confirm("�Quer�s eliminar todas las imagenes?");
	if(conf)
	{
		_IdAvisoBorrarImages = id;
		PedidoDeleteAllImages.startRequest();
	}
}

var PedidoDeleteAllImages =
{
	handleSuccess:function(o)
	{
		if(o.responseText == 'true')
		{
			deleteAllImagesDiv();
		}
	},

	handleFailure:function(o){},

	startRequest:function()
	{
		var time = new Date();
		var data = 'idAviso=' + _IdAvisoBorrarImages;
		YAHOO.util.Connect.asyncRequest('POST', '/ajax/deleteallimages.php?t=' + time.getTime(), callbackDeleteAllImages, data);
	}
}

var callbackDeleteAllImages =
{
	success: PedidoDeleteAllImages.handleSuccess,
	failure: PedidoDeleteAllImages.handleFailure,
	scope: PedidoDeleteAllImages
}

function deleteAllImagesDiv()
{
	document.getElementById('imagesBorrarTodas').innerHTML = '&nbsp;';
}

function openPrint(idAviso)
{
	window.open('/rsfichaprint.php?idAviso='+idAviso, 'FichaPrint', 'width=700,height=830');
}

var _compartirToggled = 0;
function toogleCompartir()
{
	if(_compartirToggled)
	{
		_compartirToggled = 0;
		document.getElementById('compartirDiv').style.display = 'none';
		document.getElementById('utilities').style.borderBottom = '1px dashed #CCCCCC';
		document.getElementById('utilities').style.borderLeft = '0px';
		document.getElementById('compartirBtn').style.borderRight = '0px';
		document.getElementById('compartirBtn').childNodes[0].src = '/images/rollingstone/ico_compartir.gif';
	}
	else
	{
		_compartirToggled = 1;
		document.getElementById('compartirDiv').style.display = 'block';
		document.getElementById('utilities').style.borderBottom = '0px';
		document.getElementById('utilities').style.borderLeft = '1px dashed #CCCCCC';
		document.getElementById('compartirBtn').style.borderRight = '1px dashed #CCCCCC';
		document.getElementById('compartirBtn').childNodes[0].src = '/images/rollingstone/ico_compartir_over.gif';
	}
}

/* MODALES */
function Panel(_id, _titulo, _mensaje, _opciones, cargar)
{
    this.id = _id;
    this.titulo = _titulo;
    this.mensaje = _mensaje;
    this.opciones = _opciones;
    this.destino = document.body;
    this._header = "";
    this._body = "";
    this._footer = "";
    
    this.ajax = null;
    
    if(window.paneles == null)
    {
        window.paneles = Array();
    }

    this.cargar = function()
    {
        this.cargarOpciones();

   	    this.panel = new YAHOO.widget.Panel(this.id,this.opciones);
        var kl = new YAHOO.util.KeyListener(document, { keys:27}, { fn:this.panel.hide, scope:this.panel, correctScope:true } );
        this.panel.cfg.queueProperty("keylisteners", kl);
        
   	    window.paneles[this.id] = this.panel;
    };
    
    this.cargarOpciones = function()
    {
        var opDef = {fixedcenter:true, constraintoviewport:true, underlay:'shadow', close:true, visible:false, draggable:true};
    	for (a in this.opciones)
	    {
		    opDef[a]=this.opciones[a]
	    }
        this.opciones = opDef;
    }; 
    
    this.procesar = function(){};
    
	// Modificado para aceptar un cabezal customizado para las galerías de fotos.
    this._armarHeader = function(header)
    {
		if (header == "custom_header")
		{
			return "<iframe width='910' scrolling='no' height='40' frameborder='0' src='/_common/includes/banner_galeria_modal_custom.asp' target='ImgIframe' name='bannerIrm'/>";
		}
		else
		{
			return "<span class='color'>"+this.titulo+"</span>";
		}
    };

    this._armarBody = function()
    {
        this._body = "";
        switch(typeof this.mensaje)
        {
	        case "function":
	        {
		        this._body = this.mensaje();
			    this.panel.setBody(this._body);
	        }
	        break;
	        case "object":
	        {
			    var idLoading = 'pnl'+this.id+'_loading';
			    this._body = '<div id="'+idLoading+'" class="loading" style="display:block;"></div>';
			    this.panel.setBody(this._body);

	            this.ajax = new Ajax(this.mensaje.url);
	            this.ajax.datos["panel"] = this.panel;
	            
	            this.ajax.ocultar(this.panel.footer);

	            this.ajax.setLoading(idLoading);

                this.ajax.setForm(this.opciones.form);

	            this.ajax.handlerOk = function(o)
	            {
	            	o.argument.datos.panel.setBody(o.responseText);
	            	
	            	var matches = o.responseText.match(/(<[\s\/]*script\b[^>]*>([^>]*)<\/script>)/i);
	            	if(matches != null && matches[2] != undefined)
	            	{
	            		eval(matches[2]);
	            	}
                }
	            this.ajax.postHandlerOk = function(o)
	            {
	                o.argument.mostrar(o.argument.datos.panel.footer);
                }
                
                return this.ajax;
	        }
	        break;
	        default:
	        {
		        this._body = this.mensaje;
			    this.panel.setBody(this._body);
	        }
        }
        
        return null;
        
    };

    this._armarFooter = function()
    {
        if (this.opciones.mostrarFooter != false)
        {
	        var botones;
	        botones="<center>";
	        for (bot in this.opciones.botonera)
	        {
		        botones = botones + '<a href="javascript:'+this.opciones.botonera[bot].click+';" class="'+this.opciones.botonera[bot].clase+'" id="'+this.opciones.botonera[bot].id+'"'+(this.opciones.botonera[bot].style!=null?'style="'+this.opciones.botonera[bot].style+'"':'')+'></a>&nbsp;&nbsp;';
	        }
	        botones = botones + "</center>";
		    if (this.opciones["leyendaPie"]!=null && this.opciones["leyendaPie"]!="" )
		    {
			    botones = botones + this.opciones["leyendaPie"];
		    }
	    
    	    return botones;
        }
        else
        {
            return "";
        }
    };
    
    this.mostrar = function(header)
    {
	    this.panel.setHeader(this._armarHeader(header));
	    this.panel.setFooter(this._armarFooter());
	    this._armarBody();
		
        this.panel.render(this.destino);
		this.panel.show();
		if(this.opciones.accionJavaScript != null && this.opciones.accionJavaScript != "")
		{
			eval(this.opciones.accionJavaScript);
		}

	    if(this.ajax != null && typeof this.ajax == 'object')
	    {
	    	this.ajax.enviar();
	    }
		
    };
    
    if (cargar == null || cargar != false)
    {
    	this.cargar();
    }
}

function showPanel(id,titulo,mensaje,opciones,header) 
{
    new Panel(id,titulo,mensaje,opciones).mostrar(header);    
}

function showModalPanel(id,titulo,mensaje,opciones,header) 
{
	var opDef ={modal:true}
	
	for (a in opDef)
	{
		opciones[a]=opDef[a];
	}
	
	return showPanel(id,titulo,mensaje,opciones,header);
}

function panelLinkPermanente(linkCorto)
{
    showModalPanel(
		"panelLinkPermanente",
        "Link Permanente",
        getBodyLinkPermanente(linkCorto),
        {
            modal:true,
            width:"320px",
            zindex:"1000",
			accionJavaScript:"document.getElementById('areaLink').select();"
         },
		""
    );
}

function getBodyLinkPermanente(linkCorto)
{
	var str = "Copi&aacute; (Ctrl+C) y guard&aacute; esta direcci&oacute;n para poder ingresar directamente a esta nota: ";
	str = str + "<textarea name='areaLink' id='areaLink' style='width:270px;height:50px;font:11px/14px tahoma;margin:8px 0;'>"+ linkCorto+"</textarea>";
	return str;
}

function panelEmail(idaviso, titulo)
{
	showModalPanel
    (
        "panelEmail",
        "Enviar por email",
        {url:"/ajax/modalmailrecomendacion.php?idaviso=" + idaviso + "&titulo=" + escape(titulo)},
        {
            form:"_formEmail",
            method:"Post",
            modal:true,
            width:"450px",
            height:"550px",
            zindex:"1500"
        },
		""
    );
}

function panelGaleriaNota(idaviso, titulo)
{
	showModalPanel
	(
		"panelGaleria",
		titulo,
		{url:"/ajax/modalgaleriaimagenes.php?to=0&idaviso=" + idaviso},
		{
			modal:true,
			draggable:false,
			width:"830px",
			height:"450px",
			zindex:"1500"
		},
		""
	);
}

function limpiarFocus(obj, defaultValue)
{
	if(obj.value == defaultValue)
	{
		obj.value = "";
	}
}

function validateEmail(mail)
{
	if(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test(mail))
	{
		return true;
	}
	return false;
}

function validateAndSend()
{
	var idaviso = document.getElementById('nota_id').value;
	var titulo = document.getElementById('nota_titulo').value;
	var mailsDestino = document.getElementById('mailDestino').value;
	var nombre = document.getElementById('nombreFrom').value;
	var mailOrigen = document.getElementById('mailOrigen').value;
	var copia = document.getElementById('Copia').checked;
	var comentario = document.getElementById('comentario').value;
	var radio1 = document.getElementById('radio1').checked;
	var radio2 = document.getElementById('radio2').checked;
	
	var valid = true;
	var errors = "";
	if(mailsDestino == "")
	{
		valid = false;
		errors += "Debe ingresar al menos un destinatario<br>";
	}
	else
	{
		mails = new Array();
		mails = mailsDestino.split(';');
		var validMail = true;
		if(mails.length > 5)
		{
			valid = false;
			errors += "Los destinatarios deben ser 5 como m&aacute;ximo<br>";
		}
		else
		{
			for(var i = 0; i < mails.length; i++)
			{
				if(!validateEmail(mails[i]))
				{
					validMail = false;
				}
			}
			if(!validMail)
			{
				valid = false;
				errors += "Alguna de las direcciones de E-mail de destino es inv&aacute;lida<br>";
			}
		}
	}
	
	if(nombre == "" || nombre == "Nombre/s")
	{
		valid = false;
		errors += "Debe ingresar su nombre<br>";
	}
	
	if(mailOrigen == "")
	{
		valid = false;
		errors += "Debe ingresar al menos un destinatario<br>";
	}
	else if(!validateEmail(mailOrigen))
	{
		valid = false;
		errors += "Su direcci&oacute;n de E-mail es inv&aacute;lida<br>";
	}

	var queenviar;
	if(radio1)
	{
		queenviar = 1;
	}
	else if(radio2)
	{
		queenviar = 2;
	}
	
	if(copia)
	{
		copia = 1;
	}
	else
	{
		copia = 0;
	}
	
	if(valid)
	{
		sendMail.startRequest(idaviso, titulo, mailsDestino, nombre, mailOrigen, copia, comentario, queenviar);
	}
	else
	{
		document.getElementById('emailMensajeEnviado').style.display = 'none';
		document.getElementById('emailMensajeError').style.display = 'none';
		document.getElementById('emailMensajeError').innerHTML = errors;
		document.getElementById('emailMensajeError').style.display = 'block';
	}
}

var sendMail =
{
	handleSuccess:function(o)
	{
		sendMailResponse(o.responseText);
	},

	handleFailure:function(o){},

	startRequest:function(idaviso, titulo, mailsDestino, nombre, mailOrigen, copia, comentario, queenviar)
	{
		var time = new Date();
		var data = 'idaviso=' + idaviso + '&titulo=' + titulo + '&mailsDestino=' + mailsDestino + '&nombreFrom=' + nombre + '&mailOrigen=' + mailOrigen + '&copia=' + copia + '&comentario=' + comentario + '&queenviar=' + queenviar;
		YAHOO.util.Connect.asyncRequest('POST', '/ajax/sendmailrecomendacion.php?t=' + time.getTime(), callbackSendMail, data);
	}
}

var callbackSendMail =
{
	success: sendMail.handleSuccess,
	failure: sendMail.handleFailure,
	scope: sendMail
}

function sendMailResponse(htmlResponse)
{
	document.getElementById('emailMensajeError').style.display = 'none';
	document.getElementById('emailMensajeEnviado').style.display = 'none';
	document.getElementById('emailMensajeEnviado').innerHTML = htmlResponse;
	document.getElementById('emailMensajeEnviado').style.display = 'block';
}

function galeriaMove(idaviso, to)
{
	MoveGaleria.startRequest(idaviso, to);
}

var MoveGaleria =
{
	handleSuccess:function(o)
	{
		MoveGaleriaResponse(o.responseText);
	},

	handleFailure:function(o){},

	startRequest:function(idaviso, to)
	{
		var time = new Date();
		YAHOO.util.Connect.asyncRequest('GET', '/ajax/modalgaleriaimagenes.php?t=' + time.getTime() + '&idaviso=' + idaviso + '&to=' + to, callbackMoveGaleria, null);
	}
}

var callbackMoveGaleria =
{
	success: MoveGaleria.handleSuccess,
	failure: MoveGaleria.handleFailure,
	scope: MoveGaleria
}

function MoveGaleriaResponse(htmlResponse)
{
	galDiv 		= document.getElementById('panelGaleria');
	divsGalDiv 	= galDiv.getElementsByTagName('div');
	
	for (i = 0; i < divsGalDiv.length; i++)
	{
		if(divsGalDiv[i].className == 'bd')
		{
			divsGalDiv[i].innerHTML = htmlResponse;
		}
	}
}

function panelUploadEventMap()
{
	var calle = document.getElementById('txtCalle').value;
	var numero = document.getElementById('txtNumero').value;
	var lugar = document.getElementById('txtLugar').value;
	var zone = document.getElementById('drpZona').value;
	var loc = document.getElementById('drpLocalidades').value;

	var titulo = "";
	if(lugar != "")
	{
		titulo += lugar;
	}
	if(calle != "")
	{
		titulo +=  " - " + calle;
	}
	if(numero != "")
	{
		titulo += " " + numero;
	}
	
	showModalPanel
	(
		"panelUploadEventMap",
		titulo,
		{url:"/ajax/modalmapuploadeventos.php?zon=" + zone + "&loc=" + loc + "&lug=" + lugar + "&cal=" + calle + "&num=" + numero},
		{
			modal:true,
			draggable:false,
			width:"716px",
			height:"584px",
			zindex:"1500"
		},
		""
	);
}

function reloadLocalidadesModal(zonaSelected)
{
	ReloadComboLocalidadesModal.startRequest(zonaSelected);
}

var ReloadComboLocalidadesModal =
{
	handleSuccess:function(o)
	{
		renderComboLocalidadesModal(eval('(' + o.responseText + ')'));
	},

	handleFailure:function(o){},

	startRequest:function(zonaSelected)
	{
		var time = new Date();
		var data = 'idZona=' + zonaSelected;
		YAHOO.util.Connect.asyncRequest('POST', '/ajax/reloadlocalidadesmodal.php?t=' + time.getTime(), callbackReloadComboLocalidadesModal, data);
	}
}

var callbackReloadComboLocalidadesModal =
{
	success: ReloadComboLocalidadesModal.handleSuccess,
	failure: ReloadComboLocalidadesModal.handleFailure,
	scope: ReloadComboLocalidadesModal
}

function renderComboLocalidadesModal(html)
{
	document.getElementById('locals').innerHTML = html;
}

function changeLocation()
{
	var prov = document.getElementById('drpZonaModal');
	var loc = document.getElementById('drpLocalidadModal');
	var call = document.getElementById('txtCalleModal').value;
	var num = document.getElementById('txtNumeroModal').value;
	
	var txtProv = prov.options[prov.selectedIndex].text;
	if(txtProv == 'Buenos Aires - GBA')
	{
		if(loc.selectedIndex != 0)
		{
			txtProv = loc.options[loc.selectedIndex].text + ', Buenos Aires';
		}
		else
		{
			txtProv = 'Buenos Aires';
		}
	}
	
	var dirGoogle = num + ' ' + call + ', ' + txtProv + ', Argentina';
	
	RS.Maps.map(dirGoogle, "gm");
}

function changeCampos()
{
	document.getElementById('drpZona').value = document.getElementById('drpZonaModal').value;
	document.getElementById('drpLocalidades').value = document.getElementById('drpLocalidadModal').value;
	document.getElementById('txtLugar').value = document.getElementById('txtLugarModal').value;
	document.getElementById('txtCalle').value = document.getElementById('txtCalleModal').value;
	document.getElementById('txtNumero').value = document.getElementById('txtNumeroModal').value;
}

function confirmLocation()
{
	changeCampos();
	document.getElementById('hidSaveGoogle').value = 1;
	
	window.paneles['panelUploadEventMap'].destroy();
}

function deleteLocation()
{
	changeCampos();
	document.getElementById('hidSaveGoogle').value = 0;
	
	window.paneles['panelUploadEventMap'].destroy();
}
/* MODALES */
