// Keeping Compact Forms Accessible
// http://www.alistapart.com/d/makingcompactformsmoreaccessible/

function initOverLabels () {
  if (!document.getElementById) return;  	

  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // LABELs with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
	
    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      }

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to LABEL elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}


// VALIDAÇÃO DE FORMS
function isEmpty( str){
	regexp = '^[\s ]*$';
	if (str.value.search(regexp) == -1)	{ 
		return false;
	} else {
		return true;
	}
}

function notValidEmail( str ){
	regexp = '^[\._a-z0-9-]+@[\.a-z0-9-]+[\.]{1}[a-z]{2,4}$';
	if (str.value.search(regexp) == -1)	{ 
		return true;
	} else {
		return false;
	}	
}

function notChecked( box ){
    if( box.checked ){
        return false;
    }
    else{
        return true;
    }
}



function troca(id){
var img_id = 'img_' + (id); 

	if (document.getElementById)
	{
		if(document.getElementById(id).style.display == 'none')
		{
		   document.getElementById(id).style.display = 'block';
		   if(document.getElementById(img_id)){
			   document.getElementById(img_id).src="/images/ico_menos.gif";
		   }	   

		} else 
		{
		   document.getElementById(id).style.display = 'none';
		   if(document.getElementById(img_id)){
			   document.getElementById(img_id).src="/images/ico_mais.gif";
		   }

		}
		
		return false;
	}
}
				
				
				
function trocaAbreGalhoIndice(id){

	var galho = 'galho_' + id;
	var alca = 'alcaGalho_' + id;
	var ico = 'icoGalho_' + id;


	if (document.getElementById)
	{
		if(document.getElementById(galho).style.display == 'none')
		{
		   document.getElementById(galho).style.display = 'block';
		   document.getElementById(ico).className = 'icoMenos';		   

		} else {
		   document.getElementById(galho).style.display = 'none';
		   document.getElementById(ico).className = 'icoMais';		   
		}
		
		return false;
	}
}

	function moveTam(campo,limite,proximo)
	{
		if(document.getElementById(campo).value.length==limite){
			document.getElementById(proximo).focus();
		}
	}
	
	function limitaTam(limitField, limitNum) {
	
		if (limitField.value.length > limitNum) {

			limitField.value = limitField.value.substring(0, limitNum);

		}
	}


function formataValor(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	s = s.split(".").join(",");
	return s;
}

function ajuda(id,texto){
	var bloco_id = 'legenda_' + (id); 
	document.getElementById(bloco_id).className = 'legendaOn';		   
	document.getElementById(bloco_id).innerHTML=texto;
  
 }

 function ajudaFecha(id){
	var bloco_id = 'legenda_' + (id); 
	document.getElementById(bloco_id).className = 'legendaOff';	
	document.getElementById(bloco_id).innerHTML='';
  
 }

var editoresGerados = new Array();

function abas(container, idBloco, idAba, editorSelecionado){

	var editorSelecionado;
	
	var textareas = $$('textarea');
	// Desativa todos os editores que estão em abas
	if(textareas){
		if(typeof(xinha_editors) != "undefined"){
			for (var i = 0; i < textareas.length; i++) {
				if(in_array(textareas[i],editoresGerados)){
					xinha_editors.textareas[i].deactivateEditor();
				}
			}
		}
	}

/*
	// Remove da lista aqueles editores que não estão visíveis
	if(!idEditores[textareas[i]]){
		alert('Cade? '+textareas[i]);
		//visibleIds.splice(visibleIds.indexOf(5), 1);
	}
*/	
	
	// CONTROLE DOS BLOCOS E ABAS
	var blocos = $(container).getElements('div.bloco');
	// Esconde todas os blocos
	for (var i = 0; i < blocos.length; i++) {
		blocos[i].style.display = "none";			
	}

	var abas = $(container).getElements('div.abaSelecionada');
	// Zera todas as classes das abas
	for (var i = 0; i < abas.length; i++) {
		$(abas[i]).className = "aba";	
	}
	
	// Mostra bloco selecionado
	$(idBloco).style.display = "block";

	// Marca aba
	$(idAba).className = "abaSelecionada";

	// Gera ou ativa editores
	if(typeof(idEditores) != "undefined"){
		if(idEditores && editorSelecionado){
		
			// Tem editor?
			if(!xinha_editors){
	 			// Iniciando Xinha agora
				xinha_editors = Xinha.makeEditors(idEditores, xinha_config);
				xinha_editors[editorSelecionado].generate();
				editoresGerados[editorSelecionado] = true;
			} else {
				// Xinha já foi iniciado			
				if(editoresGerados[editorSelecionado] != true){
					// Gera editor
					xinha_editors[editorSelecionado].generate();
					editoresGerados[editorSelecionado] = true;
					
				} else {
					// Ativa editor selecionado
				}						
			
			}
		}
	}	
		
		
}				

function geraEditor(editorSelecionado){

	var editorSelecionado;
	// Adiciona novo editor ao idEditores
	if(!idEditores[editorSelecionado]){
		idEditores.push(editorSelecionado);
	}
	var textareas = $$('textarea');
	// Desativa todos os editores que estão em abas
	if(textareas){
		if(xinha_editors){
			for (var i = 0; i < textareas.length; i++) {
				if(in_array(textareas[i],editoresGerados)){
					xinha_editors.textareas[i].deactivateEditor();
				}
			}
		}
	}
	
	// Gera ou ativa editores
	if(idEditores && editorSelecionado){
	
	
			// Iniciando Xinha agora
		xinha_editors = Xinha.makeEditors(idEditores, xinha_config);
		xinha_editors[editorSelecionado].generate();
		editoresGerados[editorSelecionado] = true;
		
	}		

}
				
// ONLOAD

window.onload = function () {
  setTimeout(initOverLabels, 50);
};			

window.addEvent('domready', function(){

	// Desativa SmoothScrool para casos específicos
	// em que a performance é ruim, como leis grandes.
	if(undefined===window.semSmoothScroll){
		if (Browser.Engine.trident4){
		} else {
			new SmoothScroll({ duration:700 }, window); 
		}	
	}
	
	if ($('loginLink')){

		$('loginLink').addEvent('click', function(e){	

			var modalOverlay = new Element('div', {
				'id': 'modalOverlay',
				'styles': {
					'height': document.getCoordinates().height
				}
			});

			
			modalOverlay.inject(document.body);
			if (Browser.Engine.trident4){
				var modalFix = new Element('iframe', {
					'id': 'modalFix',							 
					'scrolling': 'no',
					'marginWidth': 0,
					'marginHeight': 0,
					'src': '',
					'styles': {
						'height': document.getCoordinates().height
					}				
				}).inject(document.body);
			}	

			var modalOpen = new Fx.Morph('modalOverlay').set({
				duration: 200
			});
			modalOpen.start({
				'opacity': [0, .6]
			}).chain(function(){ 
				// Exibe janela do login
				$('login').setStyle('display', 'block');
			});

		
			modalOverlay.addEvent('click', function(e){	
			
				var modalClose = new Fx.Morph('modalOverlay').set({
					duration: 200
				});
				modalClose.start({
					'opacity': 0
				}).chain(function(){ 
					document.body.removeChild(modalOverlay);		
				});			
				$('login').setStyle('display', 'none');
		
			});


			window.addEvent('resize', function(){
				setModalSize();
			});
	
		});
		
		return false;
	}
	
	function setModalSize(){
		$('modalOverlay').setStyle('height', document.getCoordinates().height);
		if (Browser.Engine.trident4){
			$('modalFix').setStyle('height', document.getCoordinates().height);			
		}
	}
	
});


function in_array(myValue,myArray) {
    function equals(a,b) {
        return (a === b);
    }

    for (var i in myArray) {
        if (equals(myArray[i],myValue))
            return true;
    }

    return false;
}


function processaVoto(orientacao, codigoNode){

	// Marca o campo da avaliação como em processamento
	document.getElementById('avaliacao_comentario_' + codigoNode).innerHTML = "<img src='/images/loading.gif' class='loading' />";

	// Confere
	var comando = new Request(
	{
		method: 'post', 
		url: '/votoProcessar.php',
		onSuccess: function(responseText, responseXML) {

			// Marca o campo da avaliação com o resultado da avaliação
			document.getElementById('avaliacao_comentario_' + codigoNode).innerHTML = "[" + responseText + "]";

		}
	}).send('orientacao=' + orientacao + '&codigoNode=' + codigoNode);

}

function addUploadSlot(num){

	var up = document.getElementById('uploadBox');
	var dv = document.createElement("div");
	
	dv.innerHTML = 'Nome: <input name="nomeAnexo_' + num + '" value="Anexo ' + (num+1) + '" class="txt" style="width: 120px; margin-left: 10px; margin-right: 10px" /> Arquivo: <input type="file" id="upfile_' + num + '" name="upfile_' + num + '" onChange="addUploadSlot('+(num+1)+')" style="width: 220px;" value=""/>';
	up.appendChild(dv);

}		

// Tamanho da barra, em pixels
var tamanhoMaximo = 510;
var uploadIniciado = 0;

function tamanhoBarra(tamanho,objeto){

	if(tamanho <= tamanhoMaximo){
	
		var fx = new Fx.Morph(objeto, {duration:500, wait:false});	
		fx.start({
			'width': tamanho
		});			
	} else {
		$(objeto).setStyle('width', tamanhoMaximo);
	}	
}
			
