//<![CDATA[

////////// FUNCTIONS

function openWin(path,winW,winH) {
	var iMyWidth;
	var iMyHeight;
    iMyWidth = (window.screen.width/2) - ((winW/2)+ 10); 
	iMyHeight = (window.screen.height/2) - ((winH/2) + 50); 
	var win2 = window.open(path,'',"status,toolbar=0,height="+winH+",width="+winW+",resizable=yes,left=" + iMyWidth + ",top=" + iMyHeight + ",screenX=" + iMyWidth + ",screenY=" + iMyHeight + ",scrollbars=yes");
    win2.opener=window;
    win2.focus();
    return false;
}
////////// editable

function rclose(){
	document.getElementsByTagName('body')[0].className='slim';
}
function ropen(){
	document.getElementsByTagName('body')[0].className='regras';
	return false
}
function check(){
    var no=document.getElementById('nome');
    if(!no.value){
        alert ('Preencha seu nome');
        no.focus();
        return false;
    }   
    var em=document.getElementById('email');
    if(!isValidEmailAddress(em.value)){
        alert ('Verifique seu email');
        em.focus();
        return false;
    } 
    
    return true;
}
id=0;
id2=0;
dicionario='http://michaelis.uol.com.br/moderno/portugues/index.php?lingua=portugues-portugues&palavra=';
dicionario='http://www.dicio.com.br/';
//http://priberam.pt/dlpo/definir_resultados.aspx?pal=
function sendWord(w){
	id++;
	var add=addWord(w, id);
	if(add==false){
		id--;
		return;
	}
	var url='index.php?pg=checkWord&word='+w;
	globalLoad();
	var request = new Ajax(url, {
		method: 'get',
		//update: $('update'),
		onComplete: function(status) {
			globalUnLoad();
			id2++;
			if(status=='0'){
				$('p'+id2).addClass('existe');
				$('p'+id2).setProperty('title', 'Palavra verificada');	
				msg(w, 'check');	
				// add word
				if($('palavras').value=='')$('palavras').value=w;
				else $('palavras').value+=', '+w;
				atualizaPontos() ;		
			}else if(status=='2'){
				//$('p'+id2).appendText(' (?)');
				$('p'+id2).remove();
				msg('<b>'+w+'</b> não é uma palavra válida.','error');
			}else /*if(w.length>3)*/ checkOnline(w);
			//else msg('A palavra <b>'+w+'</b> não foi encontrada.','error');
		}
	}).request();
	
}
function checkOnline(w){
	//alert('check: '+w);
	var url='index.php?pg=checkOnline&word='+w;
	globalLoad();
	var request = new Ajax(url, {
		method: 'get',
		//update: $('update'),
		onComplete: function(status) {
			globalUnLoad();
			if(status=='true'){ 
				$('p'+id2).addClass('existe');
				$('p'+id2).setProperty('title', 'Palavra verificada Online');	
				msg('Palavra adicionada: <a href="'+dicionario+(w.toLowerCase())+'" onclick="return openWin(this.href,770,500)">'+w+'</a>','check');
				if($('palavras').value=='')$('palavras').value=w;
				else $('palavras').value+=', '+w;
				atualizaPontos() ;
			}else{
				msg('A palavra <b>'+w+'</b> não foi encontrada.','error');
			}	
		}
	}).request();
	
}

function addWord(w,id){
	var sv=$('palavras').value.split(', ');
	if(sv.contains(w)){
		msg('<b>'+w+'</b> já está na lista!','alert');
		return false;
	}
	var wpontos=contaPontos(w);
	var it = new Element('p',{
		'class':'pts'+wpontos,
		'id':'p'+id
	}).setHTML('<b>'+wpontos+'</b> '+w);
	
	// remove
	var x = new Element('a',{
		'title':'Remover palavra',
		'events': {
        		'click': function(){
        			removeWord(this,w);
            		}	
        	}
       		//,'onclick': "removeWord(this,'"+w+"')"
	});
	x.setText('×');
	x.injectTop(it);
	it.injectTop('words');
	$('words').scrollTop =0;
	/*$('words').toTop();
	var fx = new Fx.Styles(it, {duration:200, wait:false});
	fx.start({
		'background-color': '#ccc',
		color: '#ff8'
	});
	*/
	//atualizaPontos();
	$('msg').empty();
}
function removeWord(it,w){
	it.getParent().remove();
	var sv=$('palavras').value.split(', ');
	sv.remove(w);
	$('palavras').value=sv.join(', ');
	atualizaPontos() ;
}
function atualizaPontos() {
	n=0;
	var sv=$('palavras').value.split(', ');
	for (w=0; w<sv.length; w++) {
		word = sv[w];
		n+=contaPontos(word);
	}
	var pontos = "<b>"+n+"</b> ponto";
	if(n!=1)pontos +="s";
	$$('#sbox .pontos')[0].setHTML(pontos);	
}
function contaPontos(word) {
	var n = word.length;
	 if(n==3||n==4)return 1;
	    else if(n==5)return 2;               
	    else if(n==6)return 3;
	    else if(n==7)return 5;
	    else if(n==8)return 8;
	    else if(n>=9)return 11;
	    else return 0;
}
function salvaJogo(){
	$('words').send({
		//update: $('regras'),
		//evalScripts: 'true',
		onComplete: function(response) {
			if(response.substring(0,2)=='p/'){
				//alert(response.substring(4));
				location=response;
				msg('Jogo finalizado!', 'result');
			}else {
				msg(response, 'result');
				setTimeout(userSendWords, 2900);
			}	
		}
	});
}
function importContacts(){
	$('google-import').send({
		//update: $('regras'),
		//evalScripts: 'true',
		onComplete: function(response) {
			var spl=response.split('Auth=');
			if(spl[1]){
				var auth=spl[1];
				alert(auth);
			}else alert('Login Falhou. Tente Novamente');
		}
	});
	return false;
}
function fimdejogo(){
	var pts=$$('#sbox .pontos b')[0].getText();
	if(!pts)msg('Não jogou?','alert');
	else if(pts<10)msg('Só <b>'+pts+ "</b> pontos? você precisa praticar mais!",'result');
	else if(pts>10 && pts<20)msg('Legal! você fez <b>'+pts+ "</b> pontos... mas ainda pode melhorar.",'result');
	else if(pts>20){
		msg("Parabéns! você fez <b>"+pts+'</b> pontos.','result');
	}
	setTimeout(userSendWords, 2800);
}
function userSendWords(){

	if($('firstname')){ 
		var resp=$('firstname').getText();
		var todas=$$('#words p').length;
		var existe=$$('#words .existe').length;
		var novas=todas-existe;
		if(novas>0){
			var yesno='<span id="yesno"><a onclick="return sendNewWords(this);">Sim</a> <a onclick="return remDiv()" class="no">Não</a></span>';
			var x = new Element('p',{
				'class': 'message'
			});
			x.setHTML(resp+', você tem palavras novas na sua lista. Enviar para o dicionário?'+yesno);
			x.injectAfter($('relative'));	
			$('words').addClass('editing');				
		}
		var pts=$$('#sbox .pontos b')[0].getText();
		//if(novas<5 && pts>20)twitter_status(pts, resp);
		if(pts>25)high_scores(pts);
	}	

}	
function high_scores(pts){
	if($('id')){
		var id= $('id').value;
		//txt=pts+' pontos em '+id;
	}else return false;	
	
	var url='index.php?pg=high_scores&pts='+pts+'&id='+id;
	//window.location=url;return;
	//globalLoad();
	var request = new Ajax(url, {
		method: 'get',
		update: $('msg')
	}).request();
}
function twitter_status(pts, usr){
	if($('link')){
		var sp=$('link').value.split('id=');
		var id= sp.pop();
		//txt=pts+' pontos em '+id;
	}else return false;	
	
	var url='index.php?pg=twitter_status&pts='+pts+'&id='+id+'&usr='+usr;
	//window.location=url;return;
	//globalLoad();
	var request = new Ajax(url, {
		method: 'get'
	}).request();
}
function remDiv(){
	$('yesno').getParent().remove();
	return false;
}
function pelomenos(){
	msg("A palavra deve ter pelo menos 3 letras.",'alert');
}
function sendNewWords(a){
	var sv=new Array();	
	$$('#words p').each(function(item, index){
		if(!item.hasClass('existe')){
			var txt=item.getText().split(' ');
			sv.include(txt.getLast()); //x2 WORD
		}
	});
	if(sv.length>0){
		var url='index.php?pg=sendNewWords&words='+sv.join(', ');
		//globalLoad();
		//location=url;return false;
		var request = new Ajax(url, {
			method: 'get',
			//update: $('update'),
			//silent action		
			onComplete: function(resp) {
				remDiv();
				msg(resp,'check');
			}	
		}).request();
		$('yesno').setText('Enviando...');	
	}else msg('Não há palavras novas.','alert');
		
	return false;
}
function msg(msg,tipo){
	var p = new Element('p');
	p.setHTML(msg);
	p.addClass(tipo);
	$('msg').empty();
	$('msg').adopt(p);
}

function toggleSharer(){
	$('sharer').toggleClass('hide');
}

///////// onload 
function isValidEmailAddress(addr) {
    var re;
    re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/;
    if (re.test(addr) == true)
       return true;
    else
      return false;
}

function aMod_externalLink(){    
    var as,i,link;
    // grab all links, and loop over them
    as=document.getElementsByTagName('a');
    for(i=0;i<as.length;i++){
        var a =as[i];
        link=a.href; 
        // and check if it contains the current location 
        var host = new String(window.location.hostname);
        rExp = /www./gi;
        domain = host.replace(rExp, "");

        if(link.indexOf(domain)==-1 && link.indexOf('javascript:')==-1){
            if(!a.getAttribute('title'))a.setAttribute('title',link);
            a.setAttribute("target","_blank"); 
            
            if(a.className!='')a.className+=' ext-link';
            else a.className='ext-link';                        
        } 
        if (link.indexOf('.pdf')!=-1){ 
        	a.className = 'pdf-link';
        	a.setAttribute("target","_blank"); 
        }else if (link.indexOf('.zip')!=-1) a.className = 'zip-link';
    }
}

function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}
function postComment(){
	if($('text').value=='')return false;
	if($('name').value=='')$('name').value='Alguém';
	$('comments-box').appendText('Enviando...');
	$('comments-form').send({
		'method':'post',
		//update: $('comments-box'),
		onComplete: function(response) {
			$('text').value='';
			if(response)updateComments(response);
		}
	});
	return false;
}
function updateComments(file){
	var url='index.php?pg=getComments&file='+file;
	var request = new Ajax(url, {
		method: 'get',
		update: $('comments-box')
		
	}).request();
}
function globalLoad(){
	$('msg').addClass('loading');
}
function globalUnLoad(){
	$('msg').removeClass('loading');
}
/////// SCRIPTS

function setSel(){
	var nav=document.getElementById('nav');
	var as=nav.getElementsByTagName('a');
	for(var i=0, c=as.length; i<c;i++){
		if(as[i].href==window.location){
			as[i].parentNode.className='selected';
			break;
		}
	}
}
window.onload=setSel;

try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

//]]>
