/* directory of zeitgeist files */
var pathToData = '/xml/'

/* guarda variáveis carregadas de XML */
var tags = {};

/* lista de buscas ativas e respectivos códigos identificadores */
var buscasPossiveis = [], buscasIds = [], searchPath = [];
buscasPossiveis.push('Web no mundo');
buscasIds.push(1);
searchPath.push('http://busca.uol.com.br/www/index.html?q=')

buscasPossiveis.push('Web no Brasil');
buscasIds.push(2);
searchPath.push('http://busca.uol.com.br/br/index.html?q=')

buscasPossiveis.push('Web no UOL');
buscasIds.push(3);
searchPath.push('http://busca.uol.com.br/uol/index.html?q=')

buscasPossiveis.push('Imagens');
buscasIds.push(4);
searchPath.push('http://busca.uol.com.br/imagem/index.html?q=')

buscasPossiveis.push('Shopping UOL');
buscasIds.push(5);
searchPath.push('http://shopping.busca.uol.com.br/busca.html?q=')

buscasPossiveis.push('Vídeos');
buscasIds.push(6);
searchPath.push('http://busca.uol.com.br/video/index.html?q=')

buscasPossiveis.push('Notícias');
buscasIds.push(7);
searchPath.push('http://noticias.busca.uol.com.br/uol/index.html?q=')

buscasPossiveis.push('Rádio UOL');
buscasIds.push(8);
searchPath.push('http://musica.busca.uol.com.br/radio/index.php?check=musica&param1=homebusca&busca=')

buscasPossiveis.push('Blog');
buscasIds.push(9);
searchPath.push('http://blog.busca.uol.com.br/www/index.html?q=')

var maxTagsToShow = 25;

/* setup do calendário */
var yesterday = new Date(); 
var MAXATTEMPTS = 5;
ub.cal = {}
ub.cal.minDate = new Date('07/25/2007'); // mm/dd/aaaa
ub.cal.meses = ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"];
ub.cal.dias = ["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"];


function createTagCloud(){
	if( !ub.DOM.$('outer') ) return;
	if( !ub.DOM.$('home-destaque') ) return;
	if( typeof currentDate == "undefined") return;
	var outer = ub.DOM.$('outer')
	var homeDestaque = ub.DOM.$('home-destaque')
	currentDate = new Date(currentDate - (1000*24*3600)); // yesterday
	yesterday = currentDate;

	/* creates tagCloudHeader and Calendar */
	var tagCloudOuter = document.createElement( 'div' )
	var tagCloud = document.createElement( 'div' )
	tagCloudOuter.id = "tag-cloud-outer";
	tagCloud.id = "tag-cloud";

	outer.insertBefore( tagCloudOuter, homeDestaque)
	tagCloudOuter.appendChild( tagCloud )
	
	var title = document.createElement('h2');
	title.appendChild( document.createTextNode('Palavras mais buscadas:') );
	tagCloud.appendChild(title);
/*	
	var arquivo = document.createElement('p');
	arquivo.id = 'tag-cloud-arquivo';
	tagCloud.appendChild(arquivo)
	
	var linkArquivo = document.createElement('a');
	linkArquivo.href = '#';
	linkArquivo.id = 'arquivo-link';
	arquivo.appendChild(linkArquivo)
	addEvent(linkArquivo,"click", toogleCalendar);
	linkArquivo.appendChild( document.createTextNode('ver arquivo') )
*/
	var selectBusca = document.createElement('select');
	selectBusca.id = 'tag-cloud-select';
	//tagCloud.appendChild(selectBusca); //k
	addEvent( selectBusca,"change", handleSelectChange )
	
	var tagCloundContainer = document.createElement('div');
	tagCloundContainer.id = 'tag-cloud-container';
	tagCloud.appendChild(tagCloundContainer);
	
	for( var i=0, tipodebusca; tipodebusca = buscasPossiveis[i]; i++){
		var option = document.createElement('option');
		option.value = tipodebusca;
		option.appendChild( document.createTextNode(tipodebusca) )
		selectBusca.appendChild(option)
	}
	/* tagCloudHeader and Calendar ends */
	
	// generates and append tagCloud for a specific search
	var indexSearch = 0;
	var sHash = document.location.hash.toString();
	if(sHash.length>0){
		switch( sHash ){
			case '#oppre':
				indexSearch = 4;
				break;
			case '#opimg':
				indexSearch = 3;
				break;
			case '#opvid':
				indexSearch = 5;
				break;
			case '#opnot':
				indexSearch = 6;
				break;
			case '#oprad':
				indexSearch = 7;
				break;
		}
	} else {
		var webOptions = ub.DOM.$('weboptions');
		if( webOptions ){
			var radios = webOptions.elements['tipo'];
			if( radios ){
				var indice = 2;
				for(var i=0; i<radios.length; i++){
					if(radios[i].checked){
						var indice = i;
					}
				}
				if(indice==1){
					indexSearch = 2;
				} else if(indice==0){
					indexSearch = 1;
				}
			}
		}
	}
	indexSearch = 0; //just one option
	generatesTagsForSearchAndDate(indexSearch, currentDate, true, 1);
}

function dateToString( dateObj ){
	var sMonth, sDate, sYear, aYYYYMMDD;
	sMonth = (dateObj.getMonth()+1).toString(); 
	if(sMonth.length==1){sMonth = '0'+sMonth}
	sDate = dateObj.getDate().toString(); 
	if(sDate.length==1){sDate = '0'+sDate}
	aYYYYMMDD = [dateObj.getFullYear(), sMonth, sDate];
	return aYYYYMMDD.join('');
}

function generatesTagsForSearchAndDate( searchTypeIndex, dDate, ordered, tryNewDate ){
	if( !searchTypeIndex ){ searchTypeIndex = 0 }
	if( !dDate ) {
		return false;
	}
	if(!(dDate.constructor === Date)) {
		ub.DOM.removeClass( ub.DOM.$('outer'), 'tagcloud');
		return false;
	}
/*
	var sMonth = (dDate.getMonth()+1).toString(); 
	if(sMonth.length==1){sMonth = '0'+sMonth}
	var sDate = dDate.getDate().toString(); 
	if(sDate.length==1){sDate = '0'+sDate}
	var aYYYYMMDD = [dDate.getFullYear(), sMonth, sDate];
*/	var sYYYYMMDD = dateToString(dDate)

	var container = document.getElementById('tag-cloud-container');
	var tagClouds = container.getElementsByTagName('p');
	var testId = 'tagcloud-' + buscasIds[searchTypeIndex] + '-' + sYYYYMMDD;

	for(var i=0, oP; oP = tagClouds[i]; i++){
		ub.DOM.removeClass(oP, 'active');
	}
	if( typeof tags[testId] != "undefined" ) {
		ub.DOM.setClass( ub.DOM.$( testId ), 'active');
		return false;
	}
	var xhr = iniciaAJAX();
	if ( !xhr ) return;
	
	var urlToLoad = [pathToData, buscasIds[searchTypeIndex],'-',sYYYYMMDD,'-', (ordered)?'a':'w','.xml']
	
	xhr.open ( "GET", urlToLoad.join(''), true );
	xhr.onreadystatechange = function() {
		if ( xhr.readyState == 4 ) {
			if ( !xhr.responseText )
				return;
			if( xhr.status && /200|304/.test(xhr.status) ){
				parseResults( xhr, searchTypeIndex );
				currentDate = new Date(dDate)
			} else if( tryNewDate && tryNewDate < MAXATTEMPTS ){
				if( xhr.status && /302|404/.test(xhr.status) ){
					tryNewDate++;
					var tempDate = new Date(dDate - (1000*24*3600))
					generatesTagsForSearchAndDate( searchTypeIndex, tempDate, ordered, tryNewDate )
				}
			} else if( tryNewDate && tryNewDate == MAXATTEMPTS ){
				// FALTA: dizer que 'arquivo não foi encontrado'?
			}
		}
	}
	xhr.send ( null );
}

function parseResults(requestMade, searchIndex){
	xmlData = requestMade.responseXML;
	var i, itemCollection, item, link, name, weight, sDate;
	sDate = xmlData.getElementsByTagName('date')[0].firstChild.nodeValue;
	var oP = document.createElement('p');
	ub.DOM.setClass( oP, 'tagcloud');
	oP.id = 'tagcloud-' + buscasIds[searchIndex] + '-' + sDate;
	itemCollection = xmlData.getElementsByTagName('item_collection');
	if( itemCollection ){
		itemCollection = itemCollection[0];
	}
	var itemCol = itemCollection.getElementsByTagName('item');
	var iItens = (itemCol.length>maxTagsToShow)? maxTagsToShow : itemCol.length;
	aItensAux = new Array()
	for(i=0; i < itemCol.length; i++){
		aItensAux.push(itemCol[i]);
	}
	function sortByWeight(a, b){
		var aVal = parseFloat( a.getElementsByTagName('weight')[0].firstChild.nodeValue );
		var bVal = parseFloat( b.getElementsByTagName('weight')[0].firstChild.nodeValue );
		return bVal-aVal;
	}
	function sortByName(a, b){
		var aVal = a.getElementsByTagName('name')[0].firstChild.nodeValue.replace("+"," ");
		var bVal = b.getElementsByTagName('name')[0].firstChild.nodeValue.replace("+"," ");
		if(aVal<bVal) return -1;
		if(aVal>bVal) return 1;
		return 0;
	}
	aItensAux.sort(sortByWeight);
	aItensAlpha = [];
	oWeights = {};
	for(i=0; i < aItensAux.length; i++){
		// var weight = /*1 +*/ Math.ceil((iItens-i)/Math.floor(iItens/5));
		var weight = aItensAux[i].getElementsByTagName('weight')[0].firstChild.nodeValue;
		var name = aItensAux[i].getElementsByTagName('name')[0].firstChild.nodeValue.replace("+"," ");
		oWeights[name] = weight;
		aItensAlpha.push(aItensAux[i])
	}
	aItensAlpha.length = iItens;
	aItensAlpha.sort(sortByName);
	var minWeight, maxWeight, minIndex, interval, faixa2, faixa3, faixa4, faixa5, sWeight;
	maxWeight = aItensAux[0].getElementsByTagName('weight')[0].firstChild.nodeValue;
	minIndex = (aItensAux.length>maxTagsToShow)? maxTagsToShow : aItensAux.length;
	minWeight = aItensAux[minIndex].getElementsByTagName('weight')[0].firstChild.nodeValue;
	interval = (parseFloat(maxWeight)- parseFloat(minWeight))/6;
	faixa2 = parseFloat(minWeight)+ interval;
	faixa3 = parseFloat(minWeight)+ 2*interval;
	faixa4 = parseFloat(minWeight)+ 3*interval;
	faixa5 = parseFloat(minWeight)+ 4*interval;
	for(i=0; i < iItens; i++){
		link = document.createElement('a');
		name = aItensAlpha[i].getElementsByTagName('name')[0].firstChild.nodeValue.replace("+"," ");
		// weight = oWeights[name];
		weight = parseFloat( oWeights[name] );
		if(weight < faixa2) {
			sWeight = 's1';
		} else if (weight < faixa2){
			sWeight = 's2';	
		} else if (weight < faixa3){
			sWeight = 's3';	
		} else if (weight < faixa4){
			sWeight = 's4';	
		} else if (weight < faixa5){
			sWeight = 's5';	
		} else {
			sWeight = 's6';	
		}
		link.href = searchPath[searchIndex] + escape(name) + '&ad=off';
		//link.target = "_blank";
		link.appendChild( document.createTextNode( unescape(name) ) );
		// ub.DOM.setClass( link, 's'+ parseInt(weight) )
		ub.DOM.setClass( link, sWeight+" float"+weight );
		oP.appendChild(link);
		oP.appendChild( document.createTextNode(' ') );
	}
	document.getElementById('tag-cloud-container').appendChild(oP);
	tags[oP.id]=oP.id;
	ub.DOM.setClass( oP, 'active');
	ub.DOM.setClass( ub.DOM.$('outer'), 'tagcloud');

}

function iniciaAJAX() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	@else
		xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
}

function handleSelectChange(e){
	var oSelect = ub.DOM.$('tag-cloud-select');
	var indice = (oSelect)?oSelect.selectedIndex: 0; //just one option
	generatesTagsForSearchAndDate(indice, currentDate, true, 1);
}

function toogleCalendar(e){
	if( !ub.DOM.$('tag-cloud-outer') ) return;
	if( !ub.DOM.$('arquivo-link') ) return;
	ub.DOM.$('arquivo-link').blur();
	e.preventDefault();
	
	if( ub.DOM.$('arquivo-link').firstChild && ub.DOM.$('arquivo-link').firstChild.nodeValue == 'ver arquivo' ) {
		ub.DOM.$('arquivo-link').firstChild.nodeValue = 'fechar arquivo';
		ub.DOM.setClass( ub.DOM.$('tag-cloud-outer'), 'calendar');
		if( !ub.DOM.$('tag-cloud-calendar') ) {
			createCalendar();
		}
	}
	else {
		ub.DOM.$('arquivo-link').firstChild.nodeValue = 'ver arquivo';
		ub.DOM.removeClass( ub.DOM.$('tag-cloud-outer'), 'calendar');
	}
}


function createCalendar(){
	/* some code here */
	// based on currentDay
	var calDiv, calH4, calTable, calThead, calTbody, calTr, calTh, calNav, calOk, prevLink, nextLink;
	calDiv = document.createElement('div');
	calDiv.id = "tag-cloud-calendar";
	calH4 = document.createElement('h4');
	ub.DOM.$('tag-cloud-outer').appendChild(calDiv);
	calDiv.appendChild( calH4 );
	calH4.appendChild( document.createTextNode('\u00a0') );

	calNav = document.createElement('p');
	calNav.id = "calendar-nav";
	prevLink = document.createElement('a');
	prevLink.href = "#prevMonth"
	prevLink.id = "calendar-prev";
	calNav.appendChild( prevLink );
	prevLink.appendChild( document.createTextNode('anterior'));
	nextLink = document.createElement('a');
	nextLink.href = "#nextMonth";
	nextLink.id = "calendar-next";
	calNav.appendChild( nextLink );
	nextLink.appendChild( document.createTextNode('próximo'));

	calDiv.appendChild( calNav );
	calTable = document.createElement('table');
	calThead = document.createElement('thead');
	calTbody = document.createElement('tbody');
	calTr = document.createElement('tr');
	calDiv.appendChild(calTable)
	calTable.appendChild(calThead);
	calThead.appendChild(calTr);
	for(var i=0; i<7; i++){
		calTh = document.createElement('th');
		calTr.appendChild(calTh)
		calTh.appendChild( document.createTextNode( ub.cal.dias[i] ) );
	}
	calTable.appendChild(calTbody);
	calTbody.id = 'calendar-tbody';
	calOk = atualizaCalendario( currentDate )
	if( calOk ){
		addEvent( calTbody, "click", pickDate );
		addEvent( calNav, "click", navMonth );
	}
}

function ajustaDia( data ){
	if(!(data.constructor === Date)) {
		return new Date(currentDate);
	}
	if( data > yesterday ){
		return new Date(yesterday);
	}
	if( data < ub.cal.minDate ){
		return new Date(ub.cal.minDate);
	}
	return data;
}

function atualizaCalendario( diaAtual ){
	var i, cal, colh4, h4, tbody, tr, td, week, day, dayStr, firstDayOfMonth, lastDay, pPrevNext, prevLink, nextLink, firstMonth, finalMonth, firstDate, finalDate, linkDay, bActualMonth;
	diaAtual = ajustaDia( diaAtual );
	
	/* atualiza mês */
	cal = ub.DOM.$('tag-cloud-calendar');
	colh4 = cal.getElementsByTagName('h4');
	if( colh4.length > 0 ){
		h4 = colh4[0];
		while(h4.firstChild){
			h4.removeChild( h4.firstChild );
		}
		h4.appendChild( document.createTextNode( ub.cal.meses[diaAtual.getMonth()] + ' ' + diaAtual.getFullYear() ) )
		h4.id = "data" + dateToString( diaAtual );
	}
/*
	for(i=0; i<h4.length; i++){
		while(h4[i].firstChild){
			h4[i].removeChild( h4[i].firstChild );
		}
		h4[i].appendChild( document.createTextNode( ub.cal.meses[diaAtual.getMonth()] + ' ' + diaAtual.getFullYear() ) )
		h4[i].id = "data" + dateToString( diaAtual );
	}
*/
	/* atualiza navegação */
	firstMonth=true;
	firstDate = ub.cal.minDate.getDate();
	finalMonth=true;
	finalDate = yesterday.getDate();
	pPrevNext = ub.DOM.$('calendar-nav');
	bActualMonth = false;
	if(! (diaAtual.getMonth() == ub.cal.minDate.getMonth() && diaAtual.getFullYear() == ub.cal.minDate.getFullYear()) ) {
		firstMonth = false;
		ub.DOM.removeClass(ub.DOM.$('calendar-nav'), 'firstMonth');
	} else {
		ub.DOM.setClass(ub.DOM.$('calendar-nav'), 'firstMonth');
	}
	if(! (diaAtual.getMonth() == yesterday.getMonth() && diaAtual.getFullYear() == yesterday.getFullYear()) ) {
		finalMonth = false;
		ub.DOM.removeClass(ub.DOM.$('calendar-nav'), 'finalMonth');
	} else {
		ub.DOM.setClass(ub.DOM.$('calendar-nav'), 'finalMonth');
	}
	if( currentDate.getMonth() == diaAtual.getMonth() && currentDate.getFullYear() == diaAtual.getFullYear() ){
		bActualMonth = true;
	}
	/* atualiza calendário */
	tbody = ub.DOM.$('calendar-tbody');
	while(tbody.firstChild){
		tbody.removeChild( tbody.firstChild );
	}
	firstDayOfMonth = new Date(diaAtual);
	firstDayOfMonth.setDate(1);
	day = -firstDayOfMonth.getDay();
	lastDay = (new Date(diaAtual.getFullYear(), diaAtual.getMonth()+1, 0)).getDate();
	for(week=1; week<7; week++){
		tr = document.createElement('tr');
		tbody.appendChild(tr);
		for(i=0; i<7; i++){
			td = document.createElement('td');
			tr.appendChild(td);

/*
				if (curDay < 0 || curDay >= lastDay) {
					dayStr = ' ';
				} else if (firstMonth && curDay < firstDate-1) {
					dayStr = curDay+1;
					atts['class'] += 'inactive';
				} else if (finalMonth && curDay > lastDate-1) {
					dayStr = curDay+1;
					atts['class'] += 'inactive';
				} else {
					d.setDate(curDay+1);
					var dStr = _dateToStr(d);
					dayStr = jQuery("<a></a>").attr({'href':'javascript:;', 'rel':dStr}).html(curDay+1).click(function(e)
					{
						jQuery.datePicker.selectDate(jQuery.attr(this, 'rel'), this);
						return false;
					})[0];
					if (_selectedDate && _selectedDate==dStr) {
						jQuery(dayStr).attr('class','selected');
					}
				}
*/


			if(day<0 || day>=lastDay){
				dayStr = '\u00a0';
				td.appendChild( document.createTextNode( dayStr ) );
			} else if (firstMonth && day < firstDate-1) {
				dayStr = day+1;
				td.appendChild( document.createTextNode( dayStr ) );
			} else if (finalMonth && day > finalDate-1) {
				dayStr = day+1;
				td.appendChild( document.createTextNode( dayStr ) );
			} else {
				dayStr = day+1;	
				linkDay = document.createElement('a');
				linkDay.href = "#day"+dayStr;
				linkDay.rel = "day" + dateToString( diaAtual ).substring(0, 6) + (dayStr.toString().length < 2? '0':'') + dayStr;
				linkDay.appendChild( document.createTextNode( dayStr ) );
				td.appendChild( linkDay );
				if( bActualMonth && currentDate.getDate() == dayStr ){
					var parentTd = ub.DOM.ascend( linkDay, 'td' );
					if( parentTd ){
						ub.DOM.setClass(parentTd, 'current');
					}
				}
			}
			day++;
		}
	}
	// faz o highlight do dia corrente, se ele existir
	
	return true;
}

function pickDate(e){
	e.preventDefault();
	e.stopPropagation();
	var target = addEvent.getTarget(e);
	if (!target) return;
	target = ub.DOM.ascend(target, 'a');
	if (!target) return;
	var dDate = target.rel.toString().replace('day','');
	if( ! dDate.toString().match(/^\d{8}$/) ) return;
	currentDate = new Date( dDate.substring(0,4), parseInt(dDate.substring(4,6).replace(/^0/,''))-1, dDate.substring(6,8) )
	atualizaCalendario( currentDate );
	var oSelect = ub.DOM.$('tag-cloud-select');
	var indice = oSelect? oSelect.selectedIndex: 0; //just one option
	generatesTagsForSearchAndDate(indice, currentDate, true, 1);
}

function navMonth(e){
	e.preventDefault();
	e.stopPropagation();
	if(!ub.DOM.$('calendar-tbody')) return;
	var target = addEvent.getTarget(e);
	if (!target) return;
	target = ub.DOM.ascend(target, 'a');
	if (!target) return;
	var cal = ub.DOM.$('tag-cloud-calendar');
	if (!cal) return;
	var colh4 = cal.getElementsByTagName('h4');
	if( colh4.length == 0) return;
	var h4 = colh4[0];
	var sYYYYMMDD = h4.id.replace(/^data/,"");
	var sYYYY = sYYYYMMDD.substring(0,4)
	var sMM = sYYYYMMDD.substring(4,6).replace(/^0/,'');
	var sDD = sYYYYMMDD.substring(6,8);
	if( target.id == "calendar-prev" ){
		var novaData = (sMM=='1')? new Date( sYYYY-1, 11, 1) : new Date( sYYYY, parseInt(sMM)-2, 1);
	} else {
		var novaData = new Date(sYYYY, parseInt(sMM), 1);
	}
	atualizaCalendario( novaData );
}
