/************************************************************************************************************
 *	Copyright (c) 2006, Instituto CTS (www.cts.org.br).
 *	Todos os Direitos Reservados.
 *
 *	rybena.js: Arquivo responsável pela chamada do Player Rybená
 *	Versão: 1.0 - 07/12/2006
 *	Autor: Francisco Abrantes - francisco@cts.org.br
 *	Contato: rybena@cts.org.br
 *	website: www.rybena.org.br
 *
 *	As informações neste arquivo são confidenciais e não devem ser divulgadas.
 *
 *	Rybená é marca registrada, protegida contra a utilização não autorizada, 
 *	conforme preceitua a Lei nº 9.609, de 19 de fevereiro de 1998, regulamentada 
 *	pelo Decreto nº 2.556, de 20 de abril de 1998, combinada com a Lei nº 9.610, 
 *	de 19 de fevereiro de 1998, estando devidamente registrado no Instituto 
 *	Nacional  da Propriedade Industrial - INPI (Decreto nº 2.556/98, art. 1º) 
 *	sob o nº 00064074, ficando os infratores sujeitos às sanções cíveis e penais 
 *	previstas nos respectivos diplomas legais.
	
	OBSERVAÇÕES: 
	Este arquivo foi criado para o sítio web do TJRJ (www.tj.rj.gov.br) porque o mesmo continha 
	muitas camadas de frames (<iframe></iframe>).

	SOLUÇÃO:
	A cada 5 segundos, é chamada uma função que verifica se há algum texto selecionado na página (CADA FRAME).  
	É verificado se a menssagem que está selecionada já foi ou está sendo sinalizada pelo Player Rybená. 
	Se ouver algum texto selecionado, a janela do Player Rybená abrirá altomáticamente.

	PRÉ-CONDIÇÕES:
	Deverá ser colocado um link referenciando este arquivo em todas as páginas (dentro do código HTML) 
	que contenham algum conteúdo que deva ser traduzido pelo Player Rybená.
	Exemplo:
	<script type="text/javascript" src="http://www.rybenamobile.com.br/player/tjrj/js/Rybena.js"></script>

	CRITÉRIO: ESTE ARQUIVO NÃO PODE SER ALTERADO.
	
	EXTRAS: 
	No fim deste arquivo estão as definições de estilo (CSS) usadas pelo Player Rybená.
	.selo-player 	-> seta a posição da imagem
	.image-selo  	-> relativo à imagem: (seloRybena.gif)
	.image-mao	 	-> relativo à imagem: (ico_mao.gif)
	.ajuda*		 	-> formatação da janela de ajuda
	div			 	-> formatação da (div) flutuante
************************************************************************************************************/

//CAMPO TEMPORÁRIO QUE GUARDA A ÚLTIMA SELEÇÃO
document.write('<input type="hidden" id="selecao" value=""/>');

//CONTA O TEMPO PARA A CHAMADA DA FUNÇÃO: buscaSelecao()
setInterval("buscaSelecao()", 5000); // Intervalo de 5 segundos

//BUSCA A SELEÇÃO DO TEXTO EM TODOS OS FRAMES
function buscaSelecao() {

	var message = "";
	var lastMessage = document.getElementById("selecao").value;
	var tipBrowser = 0; // 1 == "Firefox"; 2 == "Internet Explorer"; 3 == "" ;

	//VERIFICA BROWSER - PEGA SELEÇÃO FORA DOS FRAMES
	if (window.getSelection) {
		message		= new String(window.getSelection());
		tipBrowser	= 1;
	} else if (document.selection) {
		message		= new String(document.selection.createRange().text);
		tipBrowser	= 2;
	} else if (document.getSelection) {
		message		= new String(document.getSelection());
		tipBrowser	= 3;
	}
	
/*
	//PEGA SELEÇÃO DENTRO DOS FRAMES
	if ( message == '' || message == null ) {	
		for(i=0; i < parent.frames.length; i++) {
			switch (tipBrowser)
			{
				case 1:
					evento	= top.frames[i].getSelection();
					message = new String(top.frames[i].getSelection());
					break;
				case 2:
					evento	= top.frames[i].document.selection.createRange().text;
					message = new String(top.frames[i].document.selection.createRange().text);
					break;
				case 3:
					evento	= top.frames[i].getSelection();
					message = new String(top.frames[i].getSelection());
					break;
			}		
			if ( message != '' && message != null ) break;
		}
	}
*/	
	//CHAMA A FUNÇÃO getPlayerRybena()
	//SOMENTE SE message FOR MAIOR QUE 1 E DIFERENTE DA ÚLTIMA MENSSAGEM TRADUZIDA PARA NÃO ENTRAR EM LOOP
	if(message != '' && message != null && message.length > 1 && message != lastMessage) {
		document.getElementById("selecao").value = null;
		getPlayerRybena(message);
	}
	//CAMPO TEMPORÁRIO - GUARDA A ÚLTIMA SELEÇÃO
	document.getElementById("selecao").value = message;
}

//EXECUTA - FUNÇÃO PRINCIPAL
function getPlayerRybena( message )
{
	var action	= "http://www.rybenamobile.com.br/player/tjrj/php/player_rybena.php";
//	var action	= "http://www.rybenamobile.com.br/player/mpts/php/player_rybena.php";

	var janela	= "webPlayerRybena";
	
	//MENSAGEM
	var msg = trataMenssagem( message );
	
	//FORMULARIO		
	var newForm = criaFormulario(action, janela);

	//JANELA
	var winprops = criaJanela();

	//ENVIO
	try{
		var myWin = window.open("about:blank", janela, winprops);
		newForm.elements[0].value = msg;		
		newForm.elements[1].value = "www.tj.rj.gov.br";
//		newForm.elements[1].value = "";
		newForm.submit();
		myWin.focus(); 
	}catch(err){
		alert("Um bloqueador de popups impediu a janela do Rybena.");
	}
	
}

//MENSAGEM - Retorna menssagem formatada para o Rybená 
function trataMenssagem( message ) {
	var msg	= "";
	message = message.replace(/\n/g, ' ');
	for(i = 0; i < message.length; i++) 
	{			
		if (message.charAt(i) == '\n' || message.charCodeAt(i) == 10)
		{
			msg += " ";
		} else {
			msg += message.charAt(i);
		}
	}
	msg = escape(msg); 
	msg = msg.replace(new RegExp('\\+','g'),'%2B');
	msg = msg.replace(new RegExp('%20','g'),'+');

	return msg;
}

//FORMULARIO - Retorna o formulário de envio
function criaFormulario(action, janela) {
	var newForm = document.getElementById("sendform");
	if (newForm == null)
	{
		newForm = document.createElement("form");
		newForm.id = "sendform";
		newForm.target = janela;
		newForm.action = action;
		newForm.method = "POST";
		document.body.appendChild(newForm);
		
		var newField1 = document.createElement("input");
		newField1.name = "msg";
		newField1.type = "hidden";
		newForm.appendChild(newField1);			
		
		var newField2 = document.createElement("input");
		newField2.name = "Dominio";
		newField2.type = "hidden";
		newForm.appendChild(newField2);			
	}		
	return newForm;
}

//JANELA - Retorna as propriedades da janela
function criaJanela() {
	var w = 255, h = 385;
	var winl = (screen.width - w) / 2, wint = (screen.height - h) / 2;
	var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',resizable=0,status=no';
	return winprops;
}

//ABRE A JANELA DE AJUDA
function MM_findObj(n, d) { //v4.0
	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 && document.getElementById) x=document.getElementById(n); return x;
}
//FECHA A JANELA DE AJUDA
function MM_showHideLayers() { //v3.0
	var i,p,v,obj,args=MM_showHideLayers.arguments;
	for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) 
	{ 
		v=args[i+2];
		if (obj.style) { 
			obj=obj.style; 
			v=(v=='show')?'visible':(v='hide')?'hidden':v; 
		}
		obj.visibility = v; 
	}
}

//FORMATAÇÃO - CSS
document.write('<style type="text/css">');
document.write('div{font-size: 10px; color: #636363; font-family: Verdana, Arial, Helvetica, sans-serif; text-decoration: none;}');
document.write('.selo-player{position: relative; top: -56px; left: 3px; z-index: 1;}');
document.write('.image-selo{width: 87px; height: 22px; border: 0px solid;}');
document.write('.image-mao{width: 23px; height: 18px; border: 0px solid;}');
document.write('.ajuda{position: absolute; visibility: hidden; top: 290px; left: 4px; width:190px; height:95px; border: #000000 1px solid; background-color: #FFFFE1; z-index:1;}');
document.write('.ajuda-titulo{font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; font-weight: bold;}');
document.write('.ajuda-texto{font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px;}');
document.write('</style>'); 