var CONTEUDO_ANIMATION_DELAY = 20;
var CONTEUDO_ANIMATION_STEPS = 10;

function animateTogglePanel(panelContent, expanding)
{
	// get the height of the content
	panelContent.style.display = "";
	var contentHeight = panelContent.offsetHeight;
	
	// if panel is collapsed and expanding, we must start with 0 height
	if (expanding) { panelContent.style.height = "0px"; changeOpacity(panelContent, 0); }
	
	var stepHeight = contentHeight / CONTEUDO_ANIMATION_STEPS;
	var direction = (!expanding ? -1 : 1);
	
	setTimeout(function(){animateStep(panelContent,1,stepHeight,direction)}, CONTEUDO_ANIMATION_DELAY);
}

/**
 * Change the height of the target
 * @param panelContent	reference to the panel content to change height
 * @param iteration		current iteration; animation will be stopped when iteration reaches PANEL_ANIMATION_STEPS
 * @param stepHeight	height increment to be added/substracted in one step
 * @param direction		1 for expanding, -1 for collapsing
 */
function animateStep(panelContent, iteration, stepHeight, direction)
{
	if (iteration<CONTEUDO_ANIMATION_STEPS)
	{
		panelContent.style.height = Math.round(((direction>0) ? iteration : 10 - iteration) * stepHeight) +"px";
		if(direction >0) changeOpacity(panelContent,  (iteration/CONTEUDO_ANIMATION_STEPS));
		else changeOpacity(panelContent,  1 - (iteration/CONTEUDO_ANIMATION_STEPS));
		
		iteration++;
		setTimeout(function(){animateStep(panelContent,iteration,stepHeight,direction)}, CONTEUDO_ANIMATION_DELAY);
	}
	else
	{	
		if(direction<0)	panelContent.style.display = "none";
		panelContent.style.height = "";
		changeOpacity(panelContent, 100);
	}
}

function changeOpacity(imageobject, opacity){
	try {
		imageobject.style.opacity = opacity;
  		imageobject.style.filter = 'alpha(opacity = ' + (opacity*100) + ')'	
	} 
	catch (exception) { }
}





function toolsNoticias(name)
{
	this.varName = name;
	this.urlPagina = 'modules/ajax/noticias.tools.php';
	this.showControle = showControle;
	this.writeFormConteudo = writeFormConteudo;
	this.showEnviarEmail = showEnviarEmail;
	this.hideConteudo = hideConteudo;
	this.enviarEmail = enviarEmail;
	this.adicionarFavoritos = adicionarFavoritos;
	
	function showControle(id)
	{
		var html = '<table class="toolsNoticias"><tr><td>'+
             	'<div class="addFavoritos"><a href="javascript:;" onclick="javascript:'+this.varName+'.adicionarFavoritos('+"'"+id+"'"+');">Adicionar aos favoritos</a></div>'+
              '</td><td>'+
                '<div class="enviarEmail"><a href="javascript:;" onclick="javascript:'+this.varName+'.showEnviarEmail('+"'"+id+"'"+');">Enviar por Email</a></div>'+
              '</td><td>'+
                '<div class="imprimir"><a href="javascript:NewWindow('+"'print.php?id_noticia="+id+"'"+', '+"'CarvalhoNews_Print'"+', 600, 450, false);">Imprimir</a></div>'+
              '</td></tr>'+
            '</table>';
			
			//                '<div class="comentarios"><a href="#">2 Comentários</a> (<a href="#">Comentar</a>)</div>'+
//              '</td><td>'+
		document.write(html);
	}
	
	function writeFormConteudo(id)
	{
		var html = '<form class="opcaoNoticia" id="'+this.varName+'_Controle_'+id+'" style="display:none;"></form>';
		document.write(html);
	}	
	
	function showEnviarEmail(id)
	{
		var html = '<div class="descricao">Informe abaixo os dados do destinatário para enviar a notícia por email.</div>'+
				'<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td width="40%" valign="top">'+
					'<div>Nome:</div>'+
					'<input type="text" name="nomeEnviarEmail" id="nomeEnviarEmail" style="width:90%; padding:2px;" maxlength="255" />'+
					'<div>Email:</div>'+
					'<input type="text" name="emailEnviarEmail" id="emailEnviarEmail" style="width:90%; padding:2px;" maxlength="255" />'+
				'</td><td width="60%" valign="top">'+
					'<div>Comentário:</div>'+
					'<textarea name="comentarioEnviarEmail" id="comentarioEnviarEmail" style="width:95%;" rows="3"></textarea>'+
				'</td></tr></table>'+
				'<div class="notificacao" id="notificacaoEnviarEmail" style="display:none;"></div>'+
				'<div class="barraBotao">'+
					'<input name="BtnEnviar" type="button" value="Enviar" class="newButton" onclick="javascript:'+this.varName+'.enviarEmail('+ id +');" /> &nbsp;&nbsp;'+
					'<input name="BtnCancelar" type="button" value="Cancelar" class="newButton" onclick="javascript:'+this.varName+'.hideConteudo('+ id +');" />'+
				'</div>';
		var formObj = MM_findObj(this.varName+'_Controle_'+id);
		if(formObj) {
			formObj.innerHTML = html;
			animateTogglePanel(formObj, true);
		}
		
	}
	
	function hideConteudo(id)
	{
		var formObj = MM_findObj(this.varName+'_Controle_'+id);
		if(formObj) {
			animateTogglePanel(formObj, false);
		}
	}

	function enviarEmail(id)
	{
		var ajax = AjaxStart();
		if(!ajax) { showMessage('error','Não foi possível enviar a notícia por email. O seu navegador não tem suporte para esta operação.'); return false; }
	
		ajax.open("POST", this.urlPagina, true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		var formObj = MM_findObj(this.varName+'_Controle_'+id);
		var notificacao = "";
		
		if(formObj)
		{
			if(!MM_findObj('nomeEnviarEmail', formObj).value) notificacao += 'Nome; ';
			if(!MM_findObj('emailEnviarEmail', formObj).value) notificacao += 'Email; ';
		}
		
		ajax.onreadystatechange = function() {
			//CARREGANDO CONTEÚDO DO ARQUIVO
			if(ajax.readyState == 1) {
				showMessage('notice','Enviando a notícia selecionada para o email informado...');
			}
			if(ajax.readyState == 4 ) {
				if (ajax.status == 401) {
					showMessage('privileges','Não foi possível enviar a notícia por email! O usuário foi desconectado.');
				} else if (ajax.status == 404) {
					showMessage('notice','A notícia selecionada não foi encontrada!');
				} else if (ajax.status == 200) {
					showMessage('ok','Notícia enviada para o email com sucesso!');
				} else {
					showMessage('error','Não foi possível enviar a notícia por email! [Erro '+ajax.status+': '+ajax.responseText+'] Contate o administrador do sistema.');
				}
			}
		}
		
		if(notificacao != '') {
			var notificacaoObj = MM_findObj('notificacaoEnviarEmail', formObj);	
			notificacao = "Os seguintes campos estão incompletos: "+ notificacao;
			if(notificacaoObj) {
				notificacaoObj.innerHTML = notificacao;
				notificacaoObj.style.display = '';
			} else alert(notificacao);
			
		} else {
			var args = formToArgs(this.varName+'_Controle_'+id);
			params = 'doAction=enviarEmail&id='+id+'&'+args;
			ajax.send(params);
			this.hideConteudo(id);
		}
		return true;
	}
	
	function adicionarFavoritos(id) {
		var ajax = AjaxStart();
		if(!ajax) { showMessage('error','Não foi possível adicionar a notícia aos favoritos. O seu navegador não tem suporte para esta operação.'); return false; }
	
		ajax.open("POST", 'modules/ajax/noticias.tools.php', true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		ajax.onreadystatechange = function() {
			//CARREGANDO CONTEÚDO DO ARQUIVO
			if(ajax.readyState == 1) {
				showMessage('notice','Adicionando notícia aos favoritos...');
			}
	
			if(ajax.readyState == 4 ) {
				if (ajax.status == 401) {
					showMessage('privileges','Não foi possível adicionar a notícia aos favoritos! O usuário foi desconectado.');
				} else if (ajax.status == 404) {
					showMessage('privileges','A notícia não foi encontrada.');
				} else if (ajax.status == 500) {
					showMessage('notice','A notícia já está adicionada aos favoritos.');
				} else if (ajax.status == 200) {
					showMessage('ok','Notícia adicionada aos favoritos com sucesso.');
				} else {
					showMessage('error','Não foi possível definir a notícia como favorita! [Erro '+ajax.status+': '+ajax.responseText+'] Contate o administrador do sistema.');
				}
			}
		}
		
		params = 'doAction=adicionarFavoritos&id='+id;
		ajax.send(params);
		return true;
	}
}
