// -------------------------------------------------------------------
// Virtual Pagination Script- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Last updated: May 31st, 2007
//
// PUBLIC: virtualpaginate(className, chunksize)
// Main Virtual Paginate Object function.
// -------------------------------------------------------------------

function virtualpaginate(className, chunksize, elementType){
var elementType=(typeof elementType=="undefined")? "div" : elementType //The type of element used to divide up content into pieces. Defaults to "div"
this.pieces=virtualpaginate.collectElementbyClass(className, elementType) //get total number of divs matching class name
//Set this.chunksize: 1 if "chunksize" param is undefined, "chunksize" if it's less than total pieces available, or simply total pieces avail (show all)
this.chunksize=(typeof chunksize=="undefined")? 1 : (chunksize>0 && chunksize <this.pieces.length)? chunksize : this.pieces.length
this.pagecount=Math.ceil(this.pieces.length/this.chunksize) //calculate number of "pages" needed to show the divs
this.showpage(-1) //show no pages (aka hide all)
this.currentpage=0 //Having hidden all pages, set currently visible page to 1st page
this.showpage(this.currentpage) //Show first page
this.firsttime=true //firsttime event
//Footer
this.footer_linktext="Início";
this.footer_linkurl="#topo";
this.footer_imgurl="images/icon_top.gif";
}

// -------------------------------------------------------------------
// PRIVATE: collectElementbyClass(classname)- Returns an array containing DIVs with the specified classname
// -------------------------------------------------------------------

virtualpaginate.collectElementbyClass=function(classname, element){ //Returns an array containing DIVs with specified classname
var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element
var pieces=[]
var alltags=document.getElementsByTagName(element)
for (var i=0; i<alltags.length; i++){
if (typeof alltags[i].className=="string" && alltags[i].className.search(classnameRE)!=-1)
pieces[pieces.length]=alltags[i]
}
return pieces
}

// -------------------------------------------------------------------
// PUBLIC: showpage(pagenumber)- Shows a page based on parameter passed (0=page1, 1=page2 etc)
// -------------------------------------------------------------------

virtualpaginate.prototype.showpage=function(pagenumber){
var totalitems=this.pieces.length //total number of broken up divs
var showstartindex=pagenumber*this.chunksize //array index of div to start showing per pagenumber setting
var showendindex=showstartindex+this.chunksize-1 //array index of div to stop showing after per pagenumber setting
for (var i=0; i<totalitems; i++){
if (i>=showstartindex && i<=showendindex)
this.pieces[i].style.display="block"
else
this.pieces[i].style.display="none"
}
this.currentpage=parseInt(pagenumber)
if (this.cpspan) //if <span class="paginateinfo> element is present, update it with the most current info (ie: Page 3/4)
this.cpspan.innerHTML='Página '+(this.currentpage+1)+'/'+this.pagecount

goSetDimensions()
}

// -------------------------------------------------------------------
// PRIVATE: paginate_build_() methods- Various methods to create pagination interfaces
// paginate_build_selectmenu(paginatedropdown)- Accepts an empty SELECT element and turns it into pagination menu
// paginate_build_regularlinks(paginatelinks)- Accepts a collection of links and screens out/ creates pagination out of ones with specific "rel" attr
// paginate_build_flatview(flatviewcontainer)- Accepts <span class="flatview"> element and replaces it with sequential pagination links
// paginate_build_cpinfo(cpspan)- Accepts <span class="paginateinfo"> element and displays current page info (ie: Page 1/4)
// -------------------------------------------------------------------

virtualpaginate.prototype.paginate_build_selectmenu=function(paginatedropdown, anchortext){
var instanceOfBox=this
var anchortext=anchortext || new Array()
this.selectmenupresent=1
for (var i=0; i<this.pagecount; i++){
if (typeof anchortext[i]!="undefined") //if custom anchor text for this link exists, use anchor text as each OPTION's text
paginatedropdown.options[i]=new Option(anchortext[i], i)
else //else, use auto incremented, sequential numbers
paginatedropdown.options[i]=new Option("Página "+(i+1)+" de "+this.pagecount, i)
}
paginatedropdown.selectedIndex=this.currentpage
paginatedropdown.onchange=function(){
instanceOfBox.showpage(this.selectedIndex)
}
}

virtualpaginate.prototype.paginate_build_regularlinks=function(paginatelinks){
var instanceOfBox=this
for (var i=0; i<paginatelinks.length; i++){
var currentpagerel=paginatelinks[i].getAttribute("rel")
if (currentpagerel=="previous" || currentpagerel=="next" || currentpagerel=="first" || currentpagerel=="last") //screen for these "rel" values
paginatelinks[i].onclick=function(){
instanceOfBox.navigate(this.getAttribute("rel"))
return false
}
}
}

// -------------------------------------------------------------------
//Codigo adaptado para atribuir o event handler de onclick para os botoes de navegacao 
// e hyperlink para retornar ao topo do texto com a ancora de nome "navbar" 
virtualpaginate.prototype.paginate_build_regularlinks_anchor=function(paginatelinks){
var instanceOfBox=this
for (var i=0; i<paginatelinks.length; i++){
var currentpagerel=paginatelinks[i].getAttribute("rel")
if (currentpagerel=="previous" || currentpagerel=="next" || currentpagerel=="first" || currentpagerel=="last") //screen for these "rel" values
paginatelinks[i].onclick=function(){
instanceOfBox.navigate(this.getAttribute("rel"));
//return false
}
}
}

virtualpaginate.prototype.paginate_build_indexlinks=function(paginatelinks){
var instanceOfBox=this
if (this.chunksize!=this.pieces.length){
	for (var i=0; i<paginatelinks.length; i++){
	paginatelinks[i].onclick=function(){
		instanceOfBox.navigatelinks(this.getAttribute("rel"));
		//return false
	}
}
}
}

virtualpaginate.prototype.paginate_build_normallinks=function(paginatelinks){
var instanceOfBox=this
if (this.chunksize!=this.pieces.length){
	for (var i=0; i<paginatelinks.length; i++){
	paginatelinks[i].onclick=function(){
		instanceOfBox.navigatelinks(this.getAttribute("rel"));
		//return false
	}
}
}
else {
	for (var i=0; i<paginatelinks.length; i++){
	paginatelinks[i].onclick=function(){

		//return false
	}
}
}
}



virtualpaginate.prototype.paginate_build_flatview=function(flatviewcontainer, anchortext){
var instanceOfBox=this
var flatviewhtml=""
var anchortext=anchortext || new Array()
for (var i=0; i<this.pagecount; i++){
if (typeof anchortext[i]!="undefined") //if custom anchor text for this link exists
flatviewhtml+='<a href="#flatview" rel="'+i+'">'+anchortext[i]+'</a> ' //build pagination link using custom anchor text
else
flatviewhtml+='<a href="#flatview" rel="'+i+'">'+(i+1)+'</a> ' //build  pagination link using auto incremented sequential number instead
}
flatviewcontainer.innerHTML=flatviewhtml
this.flatviewlinks=flatviewcontainer.getElementsByTagName("a")
for (var i=0; i<this.flatviewlinks.length; i++){
this.flatviewlinks[i].onclick=function(){
instanceOfBox.flatviewlinks[instanceOfBox.currentpage].className="" //"Unhighlight" last flatview link clicked on...
this.className="selected" //while "highlighting" currently clicked on flatview link (setting its class name to "selected"
instanceOfBox.showpage(this.getAttribute("rel"))
return false
}
}
this.flatviewlinks[this.currentpage].className="selected" //"Highlight" current page
this.flatviewpresent=true //indicate flat view links are present
}

virtualpaginate.prototype.paginate_build_cpinfo=function(cpspan){
this.cpspan=cpspan
cpspan.innerHTML='Página '+(this.currentpage+1)+'/'+this.pagecount
}

/**
 * Cria rodapé de navegação para cada pagina com <div class="virtualpagefooter"></div>
 * @param integer page - número da pagina 
*/
virtualpaginate.prototype.changeFooterLink=function(linktext, linkurl, imgurl) {
if (linktext) this.footer_linktext=linktext;
if (linkurl) this.footer_linkurl=linkurl;
if (imgurl) this.footer_imgurl=imgurl;
}

virtualpaginate.prototype.viewfooter=function(classfooter, viewmode){
var instanceOfBox=this;
var footers = new Array();
var linktop = "<div class='"+classfooter+"_top'><a href='"+this.footer_linkurl+"'>"+this.footer_linktext+"</a></div>";
var str = "";
for (var j=0; j<this.pieces.length; j++){
	var str='<hr /><a href="#navbar" rel="previous">Anterior</a><span class="paginateinfo"><strong>'+this.optnavtext[j]+'</strong>&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;&nbsp; Página '+(j+1)+'/'+this.pagecount+'</span> <a href="#navbar" rel="next">Pr&oacute;xima</a>';
	
	footers=this.pieces[j].getElementsByTagName("div"); //Look for span tags within passed div
	for (var i=0; i<footers.length; i++){
		if (footers[i].className==classfooter) {
			footers[i].innerHTML=(viewmode=="show")?linktop+str:linktop;
			this.paginate_build_regularlinks_anchor(footers[i].getElementsByTagName("a"));		
//			footers[i].style.display=(viewmode=="show")?"block":"none";
		}
	}
}
}

/**
 * Cria um indice composto de 2 graus
*/
virtualpaginate.prototype.index=function(){
	var optnavtext=new Array();
	//cria índice composto de 2 graus
	if (this.pieces.length>0) { 
		var str = "<ul>";
		for (var j=0; j < this.pieces.length; j++) {
		//lê e cria índice dos títulos
			var titles = this.pieces[j].getElementsByTagName("h1");
				if (titles.length>0) {
					for (var m=0; m < titles.length; m++) {
						var tlinks = titles[m].getElementsByTagName("a");
							for (var l=0; l < tlinks.length; l++) {
								if(tlinks[l].name.length > 0) {
								tlinks[l].innerHTML=(j+1)+". "+tlinks[l].innerHTML;
								str += "<li><a href='#"+tlinks[l].name+"' rel='"+j+"'>"+tlinks[l].innerHTML+"</a>";	
								//opções de navegação da lista
								optnavtext[j]=tlinks[l].innerHTML;

					//lê e cria o índice dos subtítulos
			var subtitles = this.pieces[j].getElementsByTagName("h2");						
					if (subtitles.length>0) {
						str += "<ul>";
						for (var sm=0; sm < subtitles.length; sm++) {
							var stlinks = subtitles[sm].getElementsByTagName("a");
								for (var sl=0; sl < stlinks.length; sl++) {
									if(stlinks[sl].name.length > 0) {
									stlinks[sl].innerHTML=(j+1)+"."+(sm+1)+". "+stlinks[sl].innerHTML;
									str += "<li><a href='#"+stlinks[sl].name+"' rel='"+j+"'>"+stlinks[sl].innerHTML+"</a></li>";
									
									}
						}
					}
						str += "</ul>";
				}
				//fim índice subtítulos
						str += "</li>";
						}
					}
				}					
				}
		//fim índice títulos		
			}
			str += "</ul>";
			this.index=str;
			this.optnavtext=optnavtext;
		}
	//fim cria índice
}


/**
 * Atribui o indece criado ao conteúdo de uma tag ou várias tags
 * @param string indexwrappers - id das tags
*/
virtualpaginate.prototype.attachIndex=function(indexwrappers){

if(indexwrappers){
	this.indexwrappers = indexwrappers;
	if (typeof indexwrappers=="string"){
		var temp = document.getElementById(indexwrappers);
		temp.innerHTML = this.index;
		this.paginate_build_indexlinks(temp.getElementsByTagName("a"));
	}
	else {
		for (var lm=0; lm < indexwrappers.length; lm++) {	
			var temp = document.getElementById(indexwrappers[lm]);
			temp.innerHTML = this.index;
			this.paginate_build_indexlinks(temp.getElementsByTagName("a"));
			}
		}
	}
}

virtualpaginate.prototype.findAnchors=function(paginateanchors){
var anchorname;
var allanchors=new Array();
var n=0;
for (var m=0; m<paginateanchors.length; m++) {
			if (paginateanchors[m].href.length>0 && paginateanchors[m].href.indexOf("#")!=-1) {
			anchorname=paginateanchors[m].href.substring(paginateanchors[m].href.indexOf("#")+1);
				for (var jm=0; jm<this.pieces.length; jm++) {
					if (this.pieces[jm].getElementsByTagName("a").length>0) {
						var attlinks=this.pieces[jm].getElementsByTagName("a");
						for (var mm=0; mm<attlinks.length; mm++) {
							if (anchorname==attlinks[mm].name) {
								paginateanchors[m].rel=jm;
								allanchors[n]=paginateanchors[m];
								n++;
							}
						}
					}
				}
			
			}
		}
		return allanchors;
}

virtualpaginate.prototype.paginate_build_linkAnchors=function(){
for (var j=0; j<this.pieces.length; j++) {
	if (this.pieces[j].getElementsByTagName("a").length>0) {
		var alllinks=this.pieces[j].getElementsByTagName("a");
			this.paginate_build_normallinks(this.findAnchors(alllinks));		
	}
}
}

virtualpaginate.prototype.linkAnchors_dropdown=function(popupid){
if (document.getElementById(popupid)) {
this.popupid=popupid;
var allanchorpopup=document.getElementById(popupid).getElementsByTagName("a");
this.paginate_build_normallinks(this.findAnchors(allanchorpopup));
}
}
virtualpaginate.prototype.linkAnchors_tag=function(tag){
if (document.getElementsByTagName(tag)) {
var allanchorpopup=document.getElementsByTagName(tag);
this.paginate_build_normallinks(this.findAnchors(allanchorpopup));
}
}

// -------------------------------------------------------------------
// PRIVATE: buildpagination()- Create pagination interface by calling one or more of the paginate_build_() functions
// -------------------------------------------------------------------

virtualpaginate.prototype.buildpagination=function(divid){
var instanceOfBox=this;
/*var optnavtext=optnavtext || new Array()
if (typeof optnavtext[i]=="undefined"){//if custom anchor text for this link exists
}
*/

if(instanceOfBox.firsttime) {
	this.index();
	this.paginate_build_linkAnchors();
	instanceOfBox.firsttime=false;	
	}
this.divid=divid;

var paginatediv=document.getElementById(divid)

	if (this.chunksize==this.pieces.length){ //if user has set to display all pieces at once, no point in creating pagination div
		paginatediv.style.display="none"		
		this.viewfooter("navfooter", "hide")
		return
	}
	else {
		paginatediv.style.display="block"		
		this.viewfooter("navfooter", "show")
	}
var paginationcode=paginatediv.innerHTML //Get user defined, "unprocessed" HTML within paginate div
if (paginatediv.getElementsByTagName("select").length>0) //if there's a select menu in div
	this.paginate_build_selectmenu(paginatediv.getElementsByTagName("select")[0], this.optnavtext)
if (paginatediv.getElementsByTagName("a").length>0) //if there are links defined in div
	this.paginate_build_regularlinks(paginatediv.getElementsByTagName("a"))
var allspans=paginatediv.getElementsByTagName("span") //Look for span tags within passed div
for (var i=0; i<allspans.length; i++){
	if (allspans[i].className=="flatview")
		this.paginate_build_flatview(allspans[i], this.optnavtext)
	else if (allspans[i].className=="paginateinfo")
		this.paginate_build_cpinfo(allspans[i])
}
this.paginatediv=paginatediv
}

// -------------------------------------------------------------------
// PUBLIC: function(chunksize) - Change de exibhition mode: virtualpages | blog
// -------------------------------------------------------------------

virtualpaginate.prototype.viewmode=function(chunksize){
	var instanceOfBox=this;
	this.chunksize=(typeof chunksize=="undefined")? 1 : (chunksize>0 && chunksize <this.pieces.length)? chunksize : this.pieces.length;
	this.currentpage=(this.chunksize==this.pieces.length)? 0: this.currentpage; 
	this.pagecount=Math.ceil(this.pieces.length/this.chunksize);
	instanceOfBox.buildpagination(this.divid);
	instanceOfBox.showpage(this.currentpage);
	instanceOfBox.attachIndex(this.indexwrappers);
	instanceOfBox.paginate_build_linkAnchors();
//	instanceOfBox.paginate_build_linkAnchors_dropdown(this.popupid);
}

// -------------------------------------------------------------------
// PRIVATE: navigate(keyword)- Calls this.showpage() with the currentpage property preset based on entered keyword
// -------------------------------------------------------------------

virtualpaginate.prototype.navigate=function(keyword){
if (this.flatviewpresent)
this.flatviewlinks[this.currentpage].className="" //"Unhighlight" previous page (before this.currentpage increments)
if (keyword=="previous")
this.currentpage=(this.currentpage>0)? this.currentpage-1 : (this.currentpage==0)? this.pagecount-1 : 0
else if (keyword=="next")
this.currentpage=(this.currentpage<this.pagecount-1)? this.currentpage+1 : 0
else if (keyword=="first")
this.currentpage=0
else if (keyword=="last")
this.currentpage=this.pieces.length-1
this.showpage(this.currentpage)
if (this.selectmenupresent)
this.paginatediv.getElementsByTagName("select")[0].selectedIndex=this.currentpage
if (this.flatviewpresent)
this.flatviewlinks[this.currentpage].className="selected" //"Highlight" current page
}

/**
 * Navegação pelo número da página
 * @param integer page - número da pagina 
*/
virtualpaginate.prototype.navigatelinks=function(numpage){
this.showpage(numpage);
if (this.selectmenupresent)
this.paginatediv.getElementsByTagName("select")[0].selectedIndex=numpage;
if (this.flatviewpresent)
this.flatviewlinks[numpage].className="selected"; //"Highlight" page
}