

function HTMLTimer(sys, formID, code, com, form, name){	
	
/**
 * Flags que indicam o estado do temporizador
 */

  this.STOPPED = 1;
  this.STARTED = 2;
  this.PAUSED = 3;
	
  this.create(sys, formID, code, null, null, null, null, '', name);
  
  // Nome que identifica um temporizador
  this.id = name;
  
  // Componente do tipo texto no qual o temporizador será exibido		
  this.com = com;
  
  // Formulário no qual o componente acima está inserido
  this.form = form;
  
  // Tempo inicial
  this.time = 0;
  
  // Status inicial
  this.status = this.STOPPED;
   
  // Intervalo inicial de atualização do Componente
  this.interval = null;
  
  // Tempo que o temporizador esteve pausado
  this.timeStopped = 0;
  
  // Cria um novo array de temporizadores caso não haja um e adiciona o temporizador corrente na última posição do array
  if (!document.timers) {
    document.timers = new Array();
  }
  document.timers[document.timers.length] = this;
}

HTMLTimer.prototype.name = 'HTMLTimer';
HTMLTimer.prototype.tabable = false;

HTMLTimer.inherits(HTMLElementBase);

HTMLTimer.prototype.designComponent = function(doc) {
	
}

/**
 * Inicializa a contagem, caso o temporizador esteja parado, define o intervalo de atualização do componente texto definido no construtor
 * e reinicia a contagem. Caso esteja pausado, continua a contagem desconsiderando o tempo em que o temporizador esteve parado.
 * Muda o status do temporizador para: iniciado.
 */
HTMLTimer.prototype.start = function(){
  var now = new Date();
  
  switch(this.status){
    case this.STOPPED: { 
	    this.time = now.getTime();
	    this.interval = setInterval('timerRefresh(\''+this.id+'\')', 1);
	    this.status = this.STARTED;
	    break;
    }
    
	  case this.PAUSED: { 
	    this.interval = setInterval.call(this, 'timerRefresh(\''+this.id+'\')', 1);
	    this.time += (now.getTime() - this.timeStopped);
	    this.status = this.STARTED;
	    break;
    }
  }
}

HTMLTimer.prototype.getFormatedTime = function() {
	var now = new Date();
  var timePassed = (now.getTime() - this.time) / 1000;
  
  var minutesInSeconds = timePassed % 3600;
  
  // Encontra horas, minutos e segundos 
  var hours = Math.floor(timePassed / 3600);
  var minutes = Math.floor(minutesInSeconds / 60);
  var seconds = Math.floor(minutesInSeconds % 60);
  
  if (hours < 10) hours = '0' + hours;
  if (minutes < 10) minutes = '0' + minutes;
  if (seconds < 10) seconds = '0' + seconds;
  
  return {hour: hours, minute: minutes, second: seconds};
}

/**
 * Atualiza o temporizador.
 * Obtém a data atual em milissegundos, diminui da data em milissegundos desde o inicio da contagem, 
 * Obtém horas, minutos e segundos, monta a string de saída e a coloca no componente texto definido no construtor.
 */
HTMLTimer.prototype.refresh = function() {
  var time = this.getFormatedTime();
  var result = time.hour + ':' + time.minute + ':' + time.second;
  
  var component = controller.getElementById(this.com, this.form);
  if (component) {
    component.setValue(result);
  }
}

/**
 * Pausa o temporizador 
 * Se este estive iniciado simplesmente limpa o intervalo de atualização e armazena a data em milissegundos na qual o temporizador foi pausado e muda o status para pausado
 * Caso este esteja pausado, define novamente o intervalo de atualização desconsiderando o tempo em que o temporizador esteve parado e muda o status para iniciado	 
*/
HTMLTimer.prototype.pause = function() {
  var now = new Date();
  
  switch(this.status){
    case this.STARTED: {   
      clearInterval(this.interval);
  	  this.timeStopped = now.getTime();
  	  this.status = this.PAUSED;
   	  break;
    }
      
    case this.PAUSED: {
      this.interval = setInterval('timerRefresh(\''+this.id+'\')', 1);
      this.time += (now.getTime() - this.timeStopped);
      this.status = this.STARTED;
      break;
    }
  }
}

/**
 * Reinicia o temporizador.
 * Muda a data de inicio em milissegundos para a data atual, caso o status do temporizador esteja pausado, a função faz com que este pare,
 * através da função stop(). 
 * Atualiza o componente com o valor 00:00:00. 
 */
HTMLTimer.prototype.reset = function() {
  var now = new Date();
  this.time = now.getTime();
  
  if (this.status == this.PAUSED) {
	  this.timeStopped = 0;
	  this.stop();
  }
  
  var component = controller.getElementById(this.com, this.form);
  if (component) {
    component.setValue('00:00:00');
  }	
}

/**
 * Muda o status para pausado e limpa o intervalo de repetição. 
 */
HTMLTimer.prototype.stop = function() {
  this.status = this.STOPPED;
  clearInterval(this.interval);
}

/**
 * Função para atualizar o temporizador recebendo seu ID como parâmetro
 */
function timerRefresh(id) { 
  var element = getTimerById(id);
  
  if (element) {
	  element.refresh();
  }
}

/**
 * Função que percorre o array de timers, e retorna o timer que tiver o id que foi passado como parâmetro.
 * Retorna nulo caso não encontre.
 */
function getTimerById(id) {
  if (document.timers) {
    for (var index = 0; index < document.timers.length; index++) {
      if (document.timers[index].id == id) {
        return document.timers[index];
      }
    }
  }
  return null;
}