// JavaScript Document
function SurfleNews(imageID, textID, timer) {
  this.elementos = new Array();
  this.imageElement = document.getElementById(imageID);
  this.textElement = document.getElementById(textID);
  this.quantidade = 0;
  this.indiceAtual = 0;
  this.interval;
  this.useControls = true;
  this.timer = timer
}

SurfleNews.prototype.add = function(text, imagem, link) {
  // Notação JSON
  var newElement = {
    text: text,
    link: link,
    image: imagem
  };
  
  this.elementos.push(newElement);
  this.quantidade++;
  
  if(this.useControls) {
	  var controleAssociado = document.getElementById(this.imageElement.id + "_control_" + this.quantidade);
	  var quantidade = this.quantidade
	  var surfle = this;
	  controleAssociado.onclick = function() {
		  surfle.goto(quantidade);
	  }
  }
}

SurfleNews.prototype.start = function() {
	var surfle = this;
	this.execute();
	
	this.interval = setInterval(function() {
	   surfle.next();
	}, this.timer); 
}

SurfleNews.prototype.stop = function() {
  clearInterval(this.interval);
}

SurfleNews.prototype.next = function() {
  this.indiceAtual++;
	
  if(this.indiceAtual == this.quantidade)
	this.indiceAtual = 0;
	
  this.execute();
}

SurfleNews.prototype.back = function() {
  this.indiceAtual--;
  
  if(this.indiceAtual < 0)
    this.indiceAtual = this.quantidade - 1;
  
  this.execute();
}

SurfleNews.prototype.goto = function(index) {
  // Verifica se o índice está na faixa
  index = index - 1;
  
  if((index >= this.quantidade) || (index < 0)) 
    return;
	
  this.indiceAtual = index;
  this.stop();
  this.start();
    
}

SurfleNews.prototype.execute = function() {
  // Pega o elemento atual
  var currentElement = this.elementos[this.indiceAtual];
  
  if(currentElement) {
 
    if(this.imageElement) {
      this.imageElement.src = currentElement.image;
      this.imageElement.parentNode.href = currentElement.link;
    }
  
    if(this.textElement) {
      this.textElement.innerHTML  =  currentElement.text;  
      this.textElement.parentNode.href = currentElement.link;  
    }
   
    // verifica se os controles estão ativos
    if(this.useControls)
      this.updateControls();
    }
}

SurfleNews.prototype.updateControls = function() {
  // desabilita todos os controles
  var urlBase;
  var controlElement;
  for(i = 1; i <= this.quantidade; i++) {
	 controlElement = document.getElementById(this.imageElement.id + "_control_" + i);
	 urlBase = controlElement.src;
	 urlBase = urlBase.replace(".gif","").replace("_disabled", "");
	 
	 if(i == (this.indiceAtual + 1)) {
	   urlBase += ".gif";
	 } else {
	   urlBase += "_disabled.gif";
	 }
	 
	 controlElement.src = urlBase;
  }
}