function debug(texto) {
	$("debug").style.display = "block";
	$("debug").value = texto;
}

function $N(name) {
	return document.getElementsByName(name);
}

function Trim(str){
	return str.replace(/^\s+|\s+$/g,"");
}

function enter(evt) {
	var r = false;	
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;
	if (key_code == 13) {
		r = true;
	}
	return r;
}

function InitSite() {
	//ListaUsuarios('',1);
	//ListaFormularios('',1);
	//ListaMensagens('');
	StartBanner();
}

function TelaCheia(pagina, janela) {	
	var numWidth = 4;
	var nomeNavegador = navigator.appName;
	if (nomeNavegador == "Netscape") {
		numWidth = 0;
	}	
	tela = window.open(pagina,janela,"type=fullWindow,directories=0,location=0,menubar=0,resizable=0,scrollbars=1,toolbar=0,left=0,top=0,width=" + (screen.availWidth - numWidth) + ",height=" + (screen.availHeight - 30));
}

function AddOption(objCombo, strValue, strDescricao, defaultSelected, selected) {
    var Nova_Opcao = new Option(strDescricao, strValue, defaultSelected, selected);
    $(objCombo).options[$(objCombo).length] = Nova_Opcao;
}

function DelOption(objCombo, strIndice) {
	$(objCombo).options[strIndice] = null;
	//$(objCombo).options.remove(strIndice);
}

function Menu(opcao) {
	AguardeBotaoImagem("", "li_aguarde_menu", true);
	switch(opcao) {
		case "inicial":
			//InitSite();
			location.href = location.href;
			break;
		case "meusforms":
			AjaxInclude('form_meus.php','div_sistema'); 
			//new Effect.Fade("div_corpo");			
			//new Effect.Appear("div_sistema");
			$("div_corpo").style.display = "none";
			$("div_sistema").style.display = "block";
			$("div_container").style.backgroundColor = "#99CC00"; // retorna o verde do fundo
			break;
		case "meusdados":
			Janela('usuario_form2.php', 'Meus Dados Cadastrados');
			AguardeBotaoImagem("", "li_aguarde_menu", false);
			break;			
		case "sair":
			Logoff();
			break;			
	}
}

// Funçao que desabilita/habilita o botão e exibe/oculta a imagem de aguarde
// Variáveis de escopo global para ocultar após carregar páginas via ajax
var GLOBAL_AGUARDE1 = "";
var GLOBAL_AGUARDE2 = "";
function AguardeBotaoImagem(id_botao, id_obj, sim) {
	var vis = "hidden";	
	if (sim) { vis = "visible"; }
	if (id_botao != "") { $(id_botao).disabled = sim; }
	if (id_obj != "") { $(id_obj).style.visibility = vis; }
	GLOBAL_AGUARDE1 = id_botao;
	GLOBAL_AGUARDE2 = id_obj;
}

// Pega a cordenada TOP de um elemento da tela
function GetTop(element) {
	var pos = 0;
	do pos += element.offsetTop;
	while(element=element.offsetParent);
	return pos;
}

//--| Retorna a posição X ou Y do mouse
function CoordenadaMouse(evt, coordenada) {
	var ie = ((navigator.userAgent.indexOf("MSIE")>-1)) ? true : false;
	var ns = ((navigator.userAgent.indexOf("Gecko")>-1)) ? true: false;
	var x;
	var y;
		
	if (ie) {
		x = (evt.clientX + document.documentElement.scrollLeft);
		y = (evt.clientY + document.documentElement.scrollTop);
	} else {
		x = evt.pageX;
		y = evt.pageY;
	}
	if (coordenada.toLowerCase() == "x") {
		return x;
	} else {
		return y;
	}
}

// Exibe o exemplo do campo
function ExemploCampo(evt, exibe, id) {
	var x = 0;
	var y = 0;
	var div = "div_exemplo_campo"+id;
	if (!exibe) {
		$(div).style.display = "none";
	} else {
		x = CoordenadaMouse(evt,"x");
		y = CoordenadaMouse(evt,"y");		
		$(div).style.left = (x)+'px';
		$(div).style.top = (y+20)+'px';
		$(div).style.display = "block";
	}
}

// Exibe a caixa de mensagem na pagina inicial
function BoxMensagem(evt, exibe, mensagem_id) {
	var x = 0;
	var y = 0;
	var div = "div_box_mensagem";
	if (!exibe) {
		$(div).innerHTML = "";
		$(div).style.display = "none";
	} else {
		if ($(div).innerHTML == "") {
			$(div).innerHTML = "Aguarde...";
			AjaxInclude("/mensagem/box?mensagem_id="+mensagem_id, div); // inclue a pagina com os dados da mensagem
		}
		// exibe o box
		x = CoordenadaMouse(evt,"x");
		y = CoordenadaMouse(evt,"y");
		$(div).style.left = (x)+'px';
		$(div).style.top = (y+20)+'px';
		$(div).style.display = "block";
	}
}

// Muda a classe css do item da lista ao passar o mouse
function LiFormHover(li,sim) {		
	if (li.className != "li-form-click") { // se não estiver selecionado
		var img = li.getElementsByTagName("img")[0]; // imagem do botão de excluir campo
		if (sim) {
			li.className = "li-form-hover";
			img.style.visibility = "visible";
		} else {
			li.className = "";
			img.style.visibility = "hidden";
		}
	}
}

// Muda a classe css do item da lista de meus formularios ao clicar
function LinkFormClick(a) {
	var lista = $N("a_form");	
	// coloca o css de selecionado no <li> clicado e retira dos outros
	for (i = 0; i < lista.length; i++) { 
		if (lista[i] == a) {
			lista[i].className = "click";
		} else {
			lista[i].className = "lista";
		}
	}	
}

// Muda a classe css do item da lista ao clicar
function LiFormClick(li) {
	var img;
	var lista = $("ul_formulario").getElementsByTagName("li");		
	// coloca o css de selecionado no <li> clicado e retira dos outros
	for (i = 0; i < lista.length; i++) { 
		img = lista[i].getElementsByTagName("img")[0]; // imagem do botão de excluir campo
		if (lista[i] == li) {
			lista[i].className = "li-form-click";
			img.style.visibility = "visible";
		} else {
			lista[i].className = "";
			img.style.visibility = "hidden";			
		}
	}
}

// Muda a classe css do item da lista ao clicar
function LiFocus(input, tipo, mensagem) {

	var li = input.parentNode; // <li> atual
	var h4 = li.getElementsByTagName("h4");; // <h4> atual
	var lista = $("ul_formulario").getElementsByTagName("li");
	var h4s = $("ul_formulario").getElementsByTagName("h4");
	var css = "li-form-click"

	// onblur
	if (tipo == "sai") {
		li.className = "";
		input.erro = "N";
		h4[0].innerHTML = "";
		return;
	}	

	// feito desta forma para funcionar no IE6
	if (tipo == "erro") { input.erro = "S";	}
	if (input.erro == "S") { 
		input.focus();
		css = "li-form-erro"; 
	}
	
	// coloca o css de selecionado no <li> selecionado e retira dos outros
	for (i = 0; i < lista.length; i++) {
		if (lista[i] == li) {
			lista[i].className = css;
			if (mensagem) {				
				h4s[i].innerHTML = mensagem;
			}
		} else {
			lista[i].className = "";
			h4s[i].innerHTML = "";
		}
	}	
}

// Cria a lista de ordenação na edição do formulário
function SortableListaForm() {
	Sortable.create('ul_formulario',{overlap:'vertical',onUpdate:function(){}});
}

// Função para criação do campo de data no formulário
function Calendario(id_input, id_button) {
	Calendar.setup ({
		inputField: id_input, // ID of the input field
		ifFormat: "%d/%m/%Y", // the date format
		button: id_button // ID of the button
	});
}


function LetraNumero(evt) {
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;

	// Backspace, Tab, Del
	if (key_code == 8 || key_code == 9) {
		return true;
	}	

	// numeros de 0 a 9 ou letras de 'A' a 'Z' ou letras de 'A' a 'Z'
	if ((key_code > 47 && key_code < 58) || (key_code >= 65 && key_code <= 90) || (key_code >= 97 && key_code <= 122)) { 
		return true;
	} else {
		if (key_code != 8) { // backspace
			return false;
		} else {
			return true;
		}
	}
}

// Permite apenas digitar numeros
function Numero(evt) {
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;

	// Backspace, Tab, Del
	if (key_code == 8 || key_code == 9) {
		return true;
	}	
	
	if (key_code > 47 && key_code < 58) { // numeros de 0 a 9
		return true;
	} else {
		if (key_code != 8) { // backspace
			return false;
		} else {
			return true;
		}
	}
}

// Permite apenas digitar numeros e uma virgula
function Valor(evt,obj) {
	
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;
	
	// Backspace, Tab, Del, Ponto e Virgula
	if (key_code == 8 || key_code == 9) {
		return true;
	}	

	// Só permite digitar a virgula 1 vez
	if ((key_code == 44) && (obj.value.indexOf(",") == -1)) {
		return true;
	}
	
	if (key_code > 47 && key_code < 58) { // numeros de 0 a 9
		return true;
	} else {
		if (key_code != 8) { // backspace
			return false;
		} else {
			return true;
		}
	}
}

// Formata o campo em reais R$ ###.###,##
function FormataValor(obj) {
	
	var num = obj.value.replace(",","").replace(".",""); // retira os pontos e virgulas
	var tam = num.length;	
	var retorno = "";

	for (i = tam; i >= 0; i--) {
		//alert( num.substr(i,1) );
		if (i == (tam-3)) {
			retorno = "," + retorno;
		}
		if ((i == (tam-6)) || (i == (tam-9)) || (i == (tam-12))) {
			retorno = "." + retorno;
		}
		retorno = num.charAt(i) + retorno;
	}
	obj.value = retorno;
}


// Formata o campo de data
function Data(evt,obj) {
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;
	if (obj.value.length == 2 || obj.value.length == 5) {
		obj.value += "/";
	}
	if (key_code > 47 && key_code < 58) { // numeros de 0 a 9
		return true;
	} else {
		if ((key_code != 8) && (key_code != 9)) { // backspace e tab
			return false;
		} else {
			return true;
		}
	}
}

// Simula o .click() do elemento, para funcionar no FF
function EventoMouse(element, eventName) {
	if (window.ActiveXObject) { // IE
		document.getElementById(element).click();
	} else {
		var oEvent = document.createEvent("MouseEvents");
		oEvent.initMouseEvent(eventName, true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, document.getElementById(element));
		document.getElementById(element).dispatchEvent(oEvent);
	}
}

// Abre a janela do LightWindow no site
function Janela(href, titulo){
	var link = "a_window";
	$(link).href = href;
	$(link).title = titulo;
	EventoMouse(link, "click");
}

var banner_ff = "";
function StartBanner() { 
	if (banner_ff == "") {
		banner_ff = window.setInterval('Banner()', 10000);
	}
}
function StopBanner() { 
	clearInterval(banner_ff); 
}
function Banner() {
	var div = $("div_banner");
	var img = $("img_banner");
	var ind = $("hdn_banner").value;
	if (ind == 8) { // total de imagens
		ind = 1;
	} else {
		ind++;
	}
	$("hdn_banner").value = ind;
	img.src = "images/banners/"+ind+".jpg";
	Effect.BlindDown(div);
}

// marca/desmarca todos os checkbox
function MarcaCheckboxs(name, sim) {
	var chks = $N(name);
	for (i = 0; i < chks.length; i++) {
		chks[i].checked = sim;
	}
}

function Demonstracao() {
	Janela('demonstracao.php','Vídeos de Demonstração do FormFacil.com');
}

function ExibeVideo(video) {
	AguardeBotaoImagem("", "img_aguarde", true);
	AjaxInclude('video.php?video='+video,'div_video'); 
}

function Sobre() {
	Janela('sobre.php','Sobre o FormFacil.com');
}

function Blog() {
	Janela('blog.php','Blog do FormFacil');
}

// Valida o email (expressão regular)
function EmailValido(email) {
	var exp = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	return exp.test(email);
}