﻿		var blacklist = new Array('1','2','3','4','5','–','usa','comece','daqueles','nova','vão','chamou','quase','estamos','momento','voltar','disse','estava','deve','chegou','outra','6','7','8','9','0','e','','algo','cerca','deu','vamos','hoje','bom','coisa','nada','né','têm','interessante','minha','quero','recentemente','ter','é','bem','si','pra','ainda','quanto','desta','cada','do','estou','tenho','dá','porque','ir','qual','só','estará','vou','tão','coisas','me','nem','estão','faz','quais','irá','sejam','sempre','lá','somente','então','fazer','pois','grande','algumas','fizesse','das','acham','considero','podem','acha','todas','será','além','traz','pode','já','você','tem','serem','seja','estas','vocês','de','ele','eles','a','acho','estes','achar','ou','atualmente','quer','ok','estar','nenhum','querer','lhe','daqui','te','sobre','isso','isto','essa','essas','está','vai','à','as','mas','uma','sua','fez','qualquer','nós','são','há','suas','mais','era','num','não','dos','por','entre','aos','ao','o','os','para','um','no','nos','que','nas','foi','se','na','em','da','como','com','seu','seus','meu','nosso','eu','desse','esse','dar','dará','aquele','este','aqui','ali','pouco','poucos','bastante','muito','fosse','esta','último','últimos','última','últimas','até','deles','alguns','toda','todos','todo','às','ela','elas','pela','pelas','teve','tinha','dentro','ativo','nesse','nesses','quem','quando','onde','ser','vez','outros','outro','também','sido','após','pelo','novo','tendo','mesmo','apenas','houve','nunca','dois','meses','sendo','tanto');
		var punctuation = new Array(',',';','.','?','!',')','|','-','(','[',']',':','%','+','"','”','“','…','1','2','3','4','5','6','7','8','9','0');
		var tinc = 2;
		var maxtags = 5;
	
		jQuery = jQuery.noConflict();
		jQuery(document).ready(function() {
  
			//var corpus = jQuery("p,span,h1,h2,h3,li,b,a").text();
			var corpus = jQuery('title').text() + jQuery("#post-content").text();
			corpus = cleanCorpus(corpus);
			showTags(corpus);			
		});	


		function showTags(corpus){
			counter = getScores(corpus.toLowerCase());
			var result = "";		
			//counter = sumtitle(title,counter,tinc);
			cont = 0;
			for(i in counter){
				result += counter[i] +",";
				cont++;
				if(cont == maxtags){
					break;
				}
				if(cont == 1){
					var list = counter.slice(0,5).join(',');
					//getTextAd(list);
				}
			}			
			
			
			jQuery("meta").each(function() {if(this.name == 'keywords') getTextAd(this.content);})
			
			jQuery("#ignit-tags").html(result);			
		}
		
		function getTextAd(tag){
			//alert(tag);
			jQuery.getJSON("http://servidor-sites.appspot.com/api?tag="+tag+"&callback=?",
			   function(result){
					//alert(result.text);
					if(result != ""){
						jQuery("#ignit-tag").html(result.tag);	
						jQuery("#ignit-site").html(result.name);
						jQuery("#ignit-logo").html('<img src="http://ignitweb.com/wp-content/uploads/2009/09/ignitlogo-01-tiny4.png"/>');						
						jQuery("#ignit-msg").html("Para mais informa&#231;&#245;es sobre ");	
						jQuery("#ignit-msg2").html("visite");							
						jQuery("#ignit-url").attr("href",result.url);
						jQuery("#ignit-ads").show();
					}else{
						//alert('NOT FOUND'); 
					}	
			   }
			);		
		}	
		
		function sumtitle(title,counter,inc){
			title = cleanCorpus(title.toLowerCase());
			title = getScores(title);
			title = removeall(blacklist,title);
			for(i in title){
				if(typeof counter[i] == "undefined"){
					counter[i] = inc;
				}else{			
					counter[i] += inc;
				}
			}
			return sortAssoc(counter);
		}		
		
		function removeall(blacklist,counter){
			for(i in blacklist){
				if(blacklist[i] in counter)
					delete counter[blacklist[i]];			
			}
			return counter;
		}	

		function cleanCorpus(corpus){		
			for(i in punctuation){
				corpus = replaceAll(corpus,punctuation[i], "");			
			}							
			return corpus;
		}
		
		function getScores(corpus){		

			var vector = corpus.split(" ");
			var counter = new Array();
			var positions = new Array();
			
			//Cria arrays de frequência e posição de palavras	
			jQuery.each(vector,function(i, val){	
				if(typeof counter[val] == "undefined"){
					positions[val.trim()] = (vector.length - i)/vector.length;
					counter[val.trim()] = 1;
				}else{
					counter[val.trim()]++;
				}
			});		

			//Remove palavras marcadas na blacklist
			counter = removeall(blacklist,counter);
			positions = removeall(blacklist,positions);
			
			//Cria lista de palavras por ordem de maior frequência
			var keys = getKeys(counter);
			var result = sortByValue(keys,counter);			
			
			//Calcula scores com base na média entre o score de posição e de frequência.	
			var maxCount = counter[result[0]];			
			for(k in positions){
				positions[k] = (positions[k] + counter[k]/maxCount)/2;
			}
			
			//Cria lista de palavras final ordenadas pelo novo score
			keys = getKeys(positions);
			result = sortByValue(keys,positions);			
			return result;	
		}	
		
		function sortAssoc(aInput){
			var aTemp = [];
			for (var sKey in aInput)
				aTemp.push([sKey, aInput[sKey]]);
			aTemp.sort(function () {return arguments[0][1] > arguments[1][1]});
			var aOutput = [];
			for (var nIndex = aTemp.length-1; nIndex >=0; nIndex--)
				aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
			return aOutput;
		}
		
		String.prototype.trim = function()
		{
			return this.replace(/^\s*/, "").replace(/\s*$/, "");
		}

		function replaceAll(str, de, para){
			var pos = str.indexOf(de);
			while (pos > -1){
				str = str.replace(de, para);
				pos = str.indexOf(de);
			}
			return (str);
		}	
		
		function sortByValue(keyArray, valueMap) {
			return keyArray.sort(function(a,b){return valueMap[b]-valueMap[a];});
		}	
		
		function getKeys(arr){
			var arrT = new Array();
			for(i in arr)
				arrT.push(i);
			return arrT;	
		}		