﻿var anunciotxt = "";

star1 = new Image();
star1.src = "../siv/imagens/estrela1.gif";
star2 = new Image();
star2.src = "../siv/imagens/estrela2.gif";

function Abrir(lugar) {
    open(lugar, "_self");
}

function Voltar() {
    history.back();
}

function VerMapas() {
    var aurl = "/htmx/SobreProjetoPopup.asp";
    var popupmapas = OpenPopup(aurl, 510, 432);
}

function VerSistemas() {
    var aurl = "/html/Educacao.Saneamento.Popup.asp"
    var popup = OpenPopup(aurl, 506, 460)
}

function MM_openBrWindow(theURL, winName, features) {
    window.open(theURL, winName, features);
}

function InitAnuncio() {
	if (document.aspnetForm) {
		MudouTipo();
	}
}

function MudouTipo() {
	valor1 = document.aspnetForm["Master$Formulario2$controle$xid_tipo"][0].checked;
	valor2 = document.aspnetForm["Master$Formulario2$controle$xid_tipo"][1].checked;
	valor3 = document.aspnetForm["Master$Formulario2$controle$xid_tipo"][2].checked;
	valor4 = document.aspnetForm["Master$Formulario2$controle$xid_tipo"][3].checked;
	
	if (valor1) {
		document.aspnetForm["Master$Formulario2$controle$id_tipo"].value = "1";
		SomeApareceGrupo("TBODY", "TB_Apartamento", "");
		SomeApareceGrupo("TBODY", "TB_Villagio", "none");
		SomeApareceGrupo("TBODY", "TB_Quadra", "none");
		SomeApareceGrupo("TBODY", "TB_Lote", "none");
		SomeApareceGrupo("TBODY", "TB_Dormitorios", "");
		SomeApareceGrupo("TBODY", "TB_Vagas", "");
		SomeApareceGrupo("TBODY", "TB_Unidades", "");
		SomeApareceGrupo("TBODY", "TB_AreaTerreno", "");
		SomeApareceGrupo("TBODY", "TB_AreaTotal", "none");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo1", "none");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo2", "none");
		SomeApareceGrupo("TBODY", "TB_ImovelVago", "");
		
		anunciotxt = " logradouro != '' && edificio != '' && apartamento != '' && dormitorios != '' && suites != '' && " +
					 " modulo != '' && vagas != '' && pavimentos != '' && unidades != '' && areaterreno != '' && " +
					 " areautil != '' && chaves != '' && valor != '' ";
	} else if (valor2) {
		document.aspnetForm["Master$Formulario2$controle$id_tipo"].value = "2";
		SomeApareceGrupo("TBODY", "TB_Apartamento", "none");
		SomeApareceGrupo("TBODY", "TB_Villagio", "none");
		SomeApareceGrupo("TBODY", "TB_Quadra", "");
		SomeApareceGrupo("TBODY", "TB_Lote", "");
		SomeApareceGrupo("TBODY", "TB_Dormitorios", "");
		SomeApareceGrupo("TBODY", "TB_Vagas", "");
		SomeApareceGrupo("TBODY", "TB_Unidades", "none");
		SomeApareceGrupo("TBODY", "TB_AreaTerreno", "");
		SomeApareceGrupo("TBODY", "TB_AreaTotal", "");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo1", "none");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo2", "none");
		SomeApareceGrupo("TBODY", "TB_ImovelVago", "");
		
		anunciotxt = " logradouro != '' && dormitorios != '' && suites != '' && " +
					 " modulo != '' && vagas != '' && pavimentos != '' && areaterreno != '' && " +
					 " areautil != '' && areatotal != '' && chaves != '' && valor != '' ";
	} else if (valor3) {
		document.aspnetForm["Master$Formulario2$controle$id_tipo"].value = "3";
		SomeApareceGrupo("TBODY", "TB_Apartamento", "none");
		SomeApareceGrupo("TBODY", "TB_Villagio", "none");
		SomeApareceGrupo("TBODY", "TB_Quadra", "");
		SomeApareceGrupo("TBODY", "TB_Lote", "");
		SomeApareceGrupo("TBODY", "TB_Dormitorios", "none");
		SomeApareceGrupo("TBODY", "TB_Vagas", "none");
		SomeApareceGrupo("TBODY", "TB_Unidades", "none");
		SomeApareceGrupo("TBODY", "TB_AreaTerreno", "none");
		SomeApareceGrupo("TBODY", "TB_AreaTotal", "");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo1", "");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo2", "");
		SomeApareceGrupo("TBODY", "TB_ImovelVago", "none");
		
		anunciotxt = " logradouro != '' && modulo != '' && areatotal != '' && limpo != '' && valor != '' ";
	} else if (valor4) {
		document.aspnetForm["Master$Formulario2$controle$id_tipo"].value = "4";
		SomeApareceGrupo("TBODY", "TB_Apartamento", "none");
		SomeApareceGrupo("TBODY", "TB_Villagio", "");
		SomeApareceGrupo("TBODY", "TB_Quadra", "");
		SomeApareceGrupo("TBODY", "TB_Lote", "");
		SomeApareceGrupo("TBODY", "TB_Dormitorios", "");
		SomeApareceGrupo("TBODY", "TB_Vagas", "");
		SomeApareceGrupo("TBODY", "TB_Unidades", "none");
		SomeApareceGrupo("TBODY", "TB_AreaTerreno", "");
		SomeApareceGrupo("TBODY", "TB_AreaTotal", "");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo1", "none");
		SomeApareceGrupo("TD", "TD_TerrenoLimpo2", "none");
		SomeApareceGrupo("TBODY", "TB_ImovelVago", "");
		
		anunciotxt = " logradouro != '' && villagio != '' && dormitorios != '' && suites != '' && " +
					 " modulo != '' && vagas != '' && pavimentos != '' && areaterreno != '' && " +
					 " areautil != '' && areatotal != '' && chaves != '' && valor != '' ";
	}
}

function SomeApareceGrupo(grupo, yid, xdisplay) {
	tbs = document.getElementsByTagName(grupo);
	for (i=0; i < tbs.length; i++) {
		xid = tbs[i].id;
		if (xid == yid) {
			tbs[i].style.display = xdisplay;
		}
	}
}

function EnviarAnuncio() {
	var erro = false;
	var passou2 = false;
	
	villagio = document.aspnetForm["Master$Formulario2$controle$villagio"].value;
	edificio = document.aspnetForm["Master$Formulario2$controle$edificio"].value;
	apartamento = document.aspnetForm["Master$Formulario2$controle$apartamento"].value;
	modulo = document.aspnetForm["Master$Formulario2$controle$modulo"].value;
	logradouro = document.aspnetForm["Master$Formulario2$controle$logradouro"].value;
	dormitorios = document.aspnetForm["Master$Formulario2$controle$dormitorios"][document.aspnetForm["Master$Formulario2$controle$dormitorios"].selectedIndex].value;
	suites = document.aspnetForm["Master$Formulario2$controle$suites"][document.aspnetForm["Master$Formulario2$controle$suites"].selectedIndex].value;
	vagas = document.aspnetForm["Master$Formulario2$controle$vagas"][document.aspnetForm["Master$Formulario2$controle$vagas"].selectedIndex].value;
	pavimentos = document.aspnetForm["Master$Formulario2$controle$pavimentos"][document.aspnetForm["Master$Formulario2$controle$pavimentos"].selectedIndex].value;
	unidades = document.aspnetForm["Master$Formulario2$controle$unidades"][document.aspnetForm["Master$Formulario2$controle$unidades"].selectedIndex].value;
	areatotal = document.aspnetForm["Master$Formulario2$controle$areatotal"].value;
	areaterreno = document.aspnetForm["Master$Formulario2$controle$areaterreno"].value;
	areautil = document.aspnetForm["Master$Formulario2$controle$areautil"].value;
	limpo = document.aspnetForm["Master$Formulario2$controle$limpo"][document.aspnetForm["Master$Formulario2$controle$limpo"].selectedIndex].value;
	chaves = document.aspnetForm["Master$Formulario2$controle$chaves"][document.aspnetForm["Master$Formulario2$controle$chaves"].selectedIndex].value;
	valor = document.aspnetForm["Master$Formulario2$controle$valor"].value;
	
	nome = document.aspnetForm["Master$Formulario2$controle$nome"].value;
	profissao = document.aspnetForm["Master$Formulario2$controle$profissao"].value;
	telefone = document.aspnetForm["Master$Formulario2$controle$telefone"].value;
	email = document.aspnetForm["Master$Formulario2$controle$email"].value;
	var emailvalido = EmailValido(email);
	bairro = document.aspnetForm["Master$Formulario2$controle$bairro"].value;
	cidade = document.aspnetForm["Master$Formulario2$controle$cidade"].value;
	estado = document.aspnetForm["Master$Formulario2$controle$estado"].value;
	
	var passou1 = eval(anunciotxt);
	
	if (nome != "" && profissao != "" && telefone != "" && email != "" && emailvalido == true && 
		bairro != "" && cidade != "" && estado != "") {
		passou2 = true;
	} else {
		passou2 = false;
	}
	
	if (passou1 && passou2) {
		bt_salvar = xGetElementById("Master_Formulario2_controle_bt_salvar");
        bt_salvar.click();
	} else {
		alert("Preencha todos os campos");
	}
}

function AddFavorito(id_imovel, popup) {
	ajax = criaAJAX();
	ajax.open("POST", "exec.aspx", true);
	ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajax.setRequestHeader("Content-length", 2);
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4) {
			if (ajax.responseText == "1") {
				if (popup == null) {
					alert("Imóvel adicionado com sucesso!");
				}
			} else {
				alert("Erro! Tente novamente.");
			}
		};
	};
	ajax.send("act=addfavorito&id_imovel=" + id_imovel);
	
	MudaEstrela(id_imovel);
}

function DeleteFavorito(id_imovel, popup) {
	ajax = criaAJAX();
	ajax.open("POST", "exec.aspx", true);
	ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajax.setRequestHeader("Content-length", 2);
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4) {
			if (ajax.responseText == "1") {
				if (popup == null) {
					alert("Imóvel exluído com sucesso!");
				}
			} else {
				alert("Erro! Tente novamente.");
			}
		};
	};
	ajax.send("act=deletefavorito&id_imovel=" + id_imovel);
	
	MudaEstrela(id_imovel);	
}

function MudaEstrela(id_imovel) {
	if (document.images["estrela" + id_imovel]) {
		star = document.images["estrela" + id_imovel];
		file = star.src;
		
		if (file.indexOf("estrela1.gif") != -1) {
			star.src = eval("star2.src");
			star.alt = "Excluir dos Favoritos";
			xGetElementById("LINK" + id_imovel).href = "javascript:AddFavorito('" + id_imovel + "')";
		} else {
			star.src = eval("star1.src");
			star.alt = "Adicionar aos Favoritos";
			xGetElementById("LINK" + id_imovel).href = "javascript:DeleteFavorito('" + id_imovel + "')";
		}
	}
}

function Solicitar(nome, email, ddd, telefone, periodo, mensagem, info) {
	//alert(nome + " - " + email);
	if (nome != "" && email != "" && mensagem != "") {
		var txt = "act=solicitar&nome=" + escape(nome) + "&email=" + escape(email) + 
				  "&ddd=" + escape(ddd) + "&telefone=" + escape(telefone) + 
				  "&periodo=" + escape(periodo) + "&mensagem=" + escape(mensagem) + 
				  "&info=" + escape(info);
		
		ajax = criaAJAX();
		ajax.open("POST", "exec.aspx", true);
		ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajax.setRequestHeader("Content-length", 2);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.responseText == "1") {
					alert("Enviado com sucesso!");
				} else {
					alert("Erro! Tente novamente.\n" + ajax.responseText.substring(1000, 5000));
				}
			};
		};
		ajax.send(txt);
	} else {
		alert("Preencha os campos");
	}
}

function Amigo(nome, email, nome2, email2, mensagem) {
	//alert(nome2 + " - " + email2);
	if (nome != "" && email != "" && mensagem != "") {
		var txt = "act=amigo&nome=" + escape(nome) + "&email=" + escape(email) + 
				  "&nome2=" + escape(nome2) + "&email2=" + escape(email2) + 
				  "&mensagem=" + escape(mensagem);
		
		ajax = criaAJAX();
		ajax.open("POST", "exec.aspx", true);
		ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajax.setRequestHeader("Content-length", 2);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.responseText == "1") {
					alert("Enviado com sucesso!");
				} else {
					alert("Erro! Tente novamente.\n" + ajax.responseText);
				}
			};
		};
		ajax.send(txt);
	} else {
		alert("Preencha os campos");
	}
}

function xtractFile(data) {
	var filename = data.replace(/^.*\\/, '');
	return filename;
}

function TecladoLogin() {
	if (window.event.keyCode == 13) {
		LogarNoSite();
	}
}

function lojas() {
    var aurl = "http://rivie1br.teliumhosting.com.br/web/site/cadastro_empresa.asp";
    var popup = OpenPopup(aurl, 900, 530, "lojas");
}

function Buscar() {
    busca = document.dadosBusca["Master$busca"].value;
    
    if (busca != "") {
        document.dadosBusca.submit();
    } else {
        alert("Preencha o campo de busca");
    }
}

function alteraMenu() { }

function MudouCombo(obj) {
    if (obj.value != "") {
        open("area-," + obj.value + ".html", "_self");
    }
}

function LogarNoSite() {
    email = document.dadosLogin["Master$Esquerda$Controle$email"].value;
    senha = document.dadosLogin.senha.value;

    if (email != "" && senha != "") {
        document.dadosLogin.submit();
    } else {
        alert("Preencha os campos obrigatórios");
    }
}

function NoPopup(pagina) {
    obj = xGetElementById("BGFundo");
    if (!obj) {
        obj = parent.xGetElementById("BGFundo");
    }

    if (obj.style.display == "none") {
        obj.style.display = "";
        if (!IsIE()) {
            TiraFlashs();
        }
        document.body.scrollTop = "0";
        document.body.style.overflowY = "hidden";
        open(pagina, "ifr_nopopup");
    } else {
        obj.style.display = "none";
        if (!IsIE()) {
            PoeFlashs();
        }
        document.body.style.scrollTop = "0";
        document.body.style.overflowY = "scroll";
    }
}

function TiraFlashs() {
    xGetElementById("SoblocoFlash").style.display = "none";
    xGetElementById("menuFlash2").style.display = "none";
}

function PoeFlashs() {
    xGetElementById("SoblocoFlash").style.display = "";
    xGetElementById("menuFlash2").style.display = "";
}

function Editor(id_area, pai) {
    obj = xGetElementById("BGFundo");
    if (!obj) {
        obj = parent.xGetElementById("BGFundo");
    }
    
    var area = "";
    if (id_area != null) {
        area = "&id_area=" + id_area;
    }
    var xpai = "";
    if (pai != null) {
        xpai = "&pai=" + pai;
    }
    
    if (obj.style.display == "none") {
        open("edit/?x=1" + area + xpai, "ifr_editor");
        obj.style.display = "";
    } else {
        //open("about:blank", "ifr_editor");
        obj.style.display = "none";
    }
}

function Imprimir(fram, tipo) {
    if (fram != null) {
        if (tipo == null) {
            top.document.frames[fram].focus();
        } else {
            parent.document.frames[fram].focus();
        }
    }
    window.print();
}

function apagaLayer(layer) {
    document.getElementById(layer).style.visibility = 'hidden';
}

function acendeLayer(layer) {
    document.getElementById(layer).style.visibility = 'visible';
}

function apagaAcende(apaga, acende) {
    document.getElementById(apaga).style.visibility = 'hidden';
    document.getElementById(acende).style.visibility = 'visible';
}

function Modal(pagina, largura, altura) {
    window.showModalDialog(pagina, window, "status: no; dialogWidth: " + largura + "px; dialogHeight: " + altura + "px; help: no; resizable: no; scroll: no;");
}

function PopProduto(id_produto) {
    w = 300; h = 650;
    x = (screen.availWidth - w) / 2;
    y = (screen.availHeight - h) / 2;
    pagina = "popup.aspx?id_produto=" + id_produto;
    JP = window.open(pagina, "janela1", "toolbar=0, status=0, width=" + w + ", height=" + h + ", left=" + x + ", top=" + y + ", menubar=0, resizable=0, fullscreen=0, scrollbars=0");
    JP.focus();
}

function Checando(obj, func) {
    if (obj.checked == true) {
        var check = true;
        obj.title = "Desmarcar Todos";
    } else {
        var check = false;
        obj.title = "Marcar Todos";
    }
    x = document.getElementsByTagName("input");

    for (i = 0; i < x.length; i++) {
        nome = x[i].name;
        if (x[i].type == "checkbox" && nome.indexOf("CHK_") != -1) {
            if (x[i].checked != check) {
                x[i].checked = check;
                if (func != null) {
                    eval(func);
                }
            }
        }
    }
}

function EscolherSelecionados(vars) {
    var erro = true;
    var uniqkey = "";
    var valuniq = "";
    var xval = "";
    elementos = document.getElementsByTagName("input");

    if (vars != null) {
        xvars = vars.split(";");
        uniqkey = xvars[0];
    }

    for (i = 0; i < elementos.length; i++) {
        nome = elementos[i].name;
        if (elementos[i].type == "radio") {
            if (elementos[i].checked == true) {
                erro = false;
                valuniq = elementos[i].value;
                valuniq = valuniq.replace("CHK_", "");
            }
        }
    }

    if (erro == true) {
        alert("Selecione ao menos um cadastro");
    } else {
        if (opener.document.forms.length > 0) {
            if (opener.document.forms[0][uniqkey]) {
                opener.document.forms[0][uniqkey].value = valuniq;
                if (vars != null) {
                    xvars = vars.split(";");
                    for (i = 1; i < xvars.length; i++) {
                        xval = document.forms[1][xvars[i] + "_" + valuniq].value;
                        opener.document.forms[0][xvars[i]].value = xval;
                    }
                }
            } else if (opener.document.forms[0]["Master$Formulario2$" + uniqkey]) {
                opener.document.forms[0]["Master$Formulario2$" + uniqkey].value = valuniq;
                if (vars != null) {
                    xvars = vars.split(";");
                    for (i = 1; i < xvars.length; i++) {
                        xval = document.forms[1][xvars[i] + "_" + valuniq].value;
                        opener.document.forms[0]["Master$Formulario2$" + xvars[i]].value = xval;
                    }
                }
            }
        } else {
            if (vars != null) {
                xvars = vars.split(";");
                for (i = 1; i < xvars.length; i++) {
                    xval = document.forms[1][xvars[i] + "_" + valuniq].value;
                    if (opener.document.getElementById("inpImgURL")) {
                        opener.document.getElementById("inpImgURL").value = "/content/" + xval;
                    } else if (opener.document.getElementById("inpSwfURL")) {
                        opener.document.getElementById("inpSwfURL").value = "/content/" + xval;
                    }
                }
            }
        }

        top.close();
    }
}

function Apagar(pagina, uniqkey, valuniq, vars, redirect) {
    if (vars == null || vars == "") {
        vars = "";
    }
    if (confirm("Tem certeza de que deseja excluir este cadastro?")) {
        open(pagina + "?act=delete&" + uniqkey + "=" + valuniq + vars + "&redirect=" + escape(redirect), "_self");
    }
}

function ApagarSelecionados(pagina, uniqkey, vars, redirect) {
    if (vars == null || vars == "") {
        vars = "";
    }
    var str = "";
    x = document.getElementsByTagName("input");

    for (i = 0; i < x.length; i++) {
        nome = x[i].name;
        if (x[i].type == "checkbox" && nome.indexOf("CHK_") != -1 && x[i].checked == true) {
            str += "&" + uniqkey + "=" + nome.replace("CHK_", "");
        }
    }

    // Rotina para não trazer duas vezes dois valores
    if (redirect.indexOf(vars) != -1) {
        redirect = redirect.replace(vars, null);
    }

    if (str == "") {
        alert("Selecione ao menos um registro");
    } else {
        if (confirm("Tem certeza de que deseja excluir este(s) cadastro(s)?")) {
            open(pagina + "?act=del" + str + vars + "&redirect=" + redirect, "_self");
        }
    }
}

function ApagarSelecionados2(xnome) {
    var str = "";
    x = document.getElementsByTagName("input");
    
    for (i = 0; i < x.length; i++) {
        nome = x[i].name;
        if (x[i].type == "checkbox" && nome.indexOf("CHK_") != -1 && x[i].checked == true) {
            str += "&" + xnome + "=" + nome.replace("CHK_", "");
        }
    }
    
    if (str == "") {
        alert("Selecione ao menos um registro");
    } else {
        if (confirm("Tem certeza de que deseja excluir este(s) cadastro(s)?")) {
            open("[thispage1]?act=del" + str + "&redirect=[thispage]", "_self");
        }
    }
}

function SelectInputs(nome, num) {
    obj = xGetElementById(nome);
    len = xGetElementById(nome).length;
    //alert(obj.checked);
}

function Loading(num) {
    if (num != null) {
        Tamanho(num);
    }
    Init();
}

function Tamanho(numero) {
	var cont = 1;
	var linhas = 0;
	
	if (xGetElementById("TR_Linha")) {
		obj = document.getElementsByTagName("tr");
		
		for (i=0; i<obj.length; i++) {
			if (obj[i].id == "TR_Linha") {
				linhas++;
			}
		}
	} else {
		linhas = 1;
	}

	if (xGetElementById("V1")) {
	    for (i = 1; i <= numero * linhas; i++) {
	        xGetElementById("V" + i).width = xGetElementById("T" + cont).clientWidth;

	        if (cont % numero == 0) {
	            cont = 1;
	        } else {
	            cont++;
	        }
	    }
	}
}

function AbreGrupo(nome) {
    if (document.all["TBH_" + nome].style.display == "none") {
        document.all["TBH_" + nome].style.display = "";
        document.images["IMG_" + nome].src = eval("menos.src");
    } else {
        document.all["TBH_" + nome].style.display = "none";
        document.images["IMG_" + nome].src = eval("mais.src");
    }
}

function doLink(lugar, targ) {
    open(lugar, targ);
}

function xGetElementById(e) {
	if (typeof(e) != 'string') return e;
	if (document.getElementById) e = document.getElementById(e);
	else if (document.all) e = document.all[e];
	else e = null;
	return e;
}

function isURL(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(s);
}

function EmailValido(email) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(email)) {
        return true;
    } else {
        return false;
    }
}

function FormatCPF(cpf) {
    if (cpf != "") {
        cpf = cpf.substring(0, 3) + "." + cpf.substring(3, 6) + "." + cpf.substring(6, 9) + "-" + cpf.substring(9, 11);
        return (cpf);
    } else {
        return ("");
    }
}

function FormatRG(rg) {
    if (rg != "") {
        rg = rg.substring(0, 2) + "." + rg.substring(2, 5) + "." + rg.substring(5, 8) + "-" + rg.substring(8, 9);
        return (rg);
    } else {
        return ("");
    }
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else
        var expires = ""; 
    
    document.cookie = name + "=" + value + expires + "; path=/";
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function TecladoFF(e) {
	if (!IsIE()) {
		evt.stopPropagation();
		evt.preventDefault();
	}
}

function Submitando(evt) {
	if (IsIE()) {
		event.cancelBubble = true;
		event.returnValue = false;
	} else {
		if (evt.stopPropagation) {
			evt.stopPropagation();
			evt.preventDefault();
		}
	}
}

function Limpar() {
    document.dados.reset();
}

function LimparCampo(formulario, campo) {
    document[formulario][campo].value = "";
}

function img_on(nome) {
    if (memo != null) {
        document.images[memo].src = eval(memo + "off.src");
    }
    document.images[nome].src = eval(nome + "on.src");
}

function img_off(nome) {
    if (memo != null) {
        document.images[memo].src = eval(memo + "on.src");
    }
    document.images[nome].src = eval(nome + "off.src");
}

function Lupinha(pagina, largura, altura, filtros, filtros2, filtros3, filtros4, targt) {
    var plus, plus1, plus2;

    pagina = pagina.toString();
    if (filtros != null) {
        filtros = filtros.toString();
    } else {
        filtros = "";
    }
    if (filtros2 != null) {
        filtros2 = filtros2.toString();
        if (filtros != "") {
            plus = "&";
        } else {
            plus = "";
        }
    }
    if (filtros3 != null) {
        xfiltros3 = eval(filtros3);
        plus1 = xfiltros3.toString();
    } else {
        plus1 = "";
    }
    if (filtros4 != null) {
        xfiltros4 = eval(filtros4);
        if (xfiltros4 != false) {
            plus2 = xfiltros4;
        } else {
            plus2 = "";
            return;
        }
    } else {
        plus2 = "";
    }
    page = pagina + "?" + filtros + plus + filtros2 + plus1 + plus2;
    w = altura; h = altura;
    x = (screen.availWidth - w) / 2;
    y = (screen.availHeight - h) / 2;
    if (targt == null) {
        JP = window.open(page, "janela1", "toolbar=0, status=1, width=" + w + ", height=" + h + ", left=" + x + ", top=" + y + ", menubar=0, resizable=0, fullscreen=0, scrollbars=0");
        JP.focus();
    } else {
        open(page, targt);
    }
}

function ColocaArea(id_area, area) {
    if (document.aspnetForm["Master$id_area"]) {
        document.aspnetForm["Master$id_area"].value = id_area;
    } else if (document.aspnetForm["Master$Formulario2$id_area"]) {
        document.aspnetForm["Master$Formulario2$id_area"].value = id_area;
    }
    xGetElementById("Master_Formulario2_TD_Area").innerHTML = area;
}

function LimparCampos(campos) {
    campos = campos.split(",");
    for (i = 0; i < campos.length; i++) {
        document.dados[campos[i]].value = "";
    }
}

function SoNumeros(e) {
    if (IsIE()) {
        var e = window.event;
        code = e.keyCode;
    } else {
        code = e.which;
    }

    if (!e.shiftKey) {
        if ((code < 48 || code > 57) && (code < 96 || code > 105) &&
			(code != 8 && code != 9 && code != 35 && code != 36 && code != 37 &&
			code != 38 && code != 39 && code != 40 && code != 46 && code != 13)) {
            if (IsIE()) {
                e.cancelBubble = true;
                e.returnValue = false;
            } else {
                e.preventDefault();
            }
        }
    } else {
        if (IsIE()) {
            e.cancelBubble = true;
            e.returnValue = false;
        } else {
            e.preventDefault();
        }
    }
}

function CampoDinheiro(e) {
    if (IsIE()) {
        var e = window.event;
        code = e.keyCode;
    } else {
        code = e.which;
    }

    if (!e.shiftKey) {
        if ((code < 48 || code > 57) && (code < 96 || code > 105) &&
			(code != 8 && code != 9 && code != 35 && code != 36 && code != 37 &&
			code != 38 && code != 39 && code != 40 && code != 46 && code != 188)) {
            if (IsIE()) {
                e.cancelBubble = true;
                e.returnValue = false;
            } else {
                e.preventDefault();
            }
        }
    } else {
        if (IsIE()) {
            e.cancelBubble = true;
            e.returnValue = false;
        } else {
            e.preventDefault();
        }
    }
}

function Pula(campo, proximo) {
    if (campo.value.length == campo.maxLength) {
        document.dados[proximo].focus();
    }
}

function CampoData() {
    code = event.keyCode;
    if (!event.shiftKey) {
        if ((code < 48 || code > 57) && (code < 96 || code > 105) &&
			(code != 8 && code != 9 && code != 35 && code != 36 && code != 37 &&
			code != 38 && code != 39 && code != 40 && code != 46 && code != 191 &&
			code != 111)) {
            event.cancelBubble = true;
            event.returnValue = false;
        }
    } else {
        event.cancelBubble = true;
        event.returnValue = false;
    }
}

function SemCaractere(caracs) {
    code = event.keyCode;
    if (caracs != null) {
        caracs = caracs.split(",");
        for (i = 0; i < caracs.length; i++) {
            if (code == caracs[i]) {
                event.cancelBubble = true;
                event.returnValue = false;
            }
        }
    }
}

function FormatHora(campo) {
    var formu;
    nome = campo.name;
    codigo = event.keyCode;
    if (!event.shiftKey) {
        if ((codigo < 48 || codigo >= 58) &&
			(codigo < 96 || codigo >= 106) && codigo != 46 &&
			codigo != 45 && codigo != 35 && codigo != 36 &&
			codigo != 37 && codigo != 39 && codigo != 8 &&
			codigo != 9) {
            event.cancelBubble = true;
            event.returnValue = false;
        }
    } else {
        event.cancelBubble = true;
        event.returnValue = false;
    }

    if (codigo != 46 && codigo != 8) {
        if (document.forms[0][nome]) {
            obj = document.forms[0][nome].value;
            formu = 0;
        } else if (document.forms[1][nome]) {
            obj = document.forms[1][nome].value;
            formu = 1;
        } else {
            alert("Erro! Nenhum formulário encontrado");
        }

        if (obj) {
            tamanho = obj.length;
            if (tamanho == 2) {
                document.forms[formu][nome].value += ":";
            }
        }
    }
}

function FormatNota(campo) {
    nome = campo.name;
    codigo = event.keyCode;
    if (!event.shiftKey) {
        if ((codigo < 48 || codigo >= 58) &&
			(codigo < 96 || codigo >= 106) && codigo != 46 &&
			codigo != 45 && codigo != 35 && codigo != 36 &&
			codigo != 37 && codigo != 39 && codigo != 8 &&
			codigo != 9) {
            event.cancelBubble = true;
            event.returnValue = false;
        }
    } else {
        event.cancelBubble = true;
        event.returnValue = false;
    }

    if (codigo != 46 && codigo != 8) {
        obj = document.dados[nome].value;
        tamanho = obj.length;
        if (tamanho == 2) {
            document.dados[nome].value += ",";
        }
    }
}

function CNPJ(campo) {
    nome = campo.name;
    codigo = window.event.keyCode;
    if ((codigo < 48 || codigo >= 58) &&
		(codigo < 96 || codigo >= 106) && codigo != 46 &&
		codigo != 45 && codigo != 35 && codigo != 36 &&
		codigo != 37 && codigo != 39 && codigo != 8 &&
		codigo != 9) {
        window.event.returnValue = false;
        window.event.keyCode = 0;
    }

    if (codigo != 46 && codigo != 8) {
        cnpj = document.dados[nome].value;
        tamanho = cnpj.length;
        if (tamanho == 3) {
            document.dados[nome].value += ".";
        } else if (tamanho == 7) {
            document.dados[nome].value += ".";
        } else if (tamanho == 11) {
            document.dados[nome].value += "/";
        } else if (tamanho == 16) {
            document.dados[nome].value += "-";
        }
    }
}

function CPF(campo) {
    nome = campo.name;
    codigo = window.event.keyCode;
    if ((codigo < 48 || codigo >= 58) &&
		(codigo < 96 || codigo >= 106) && codigo != 46 &&
		codigo != 45 && codigo != 35 && codigo != 36 &&
		codigo != 37 && codigo != 39 && codigo != 8 &&
		codigo != 9) {
        window.event.returnValue = false;
        window.event.keyCode = 0;
    }

    if (codigo != 46 && codigo != 8) {
        cpf = document.dados[nome].value;
        tamanho = cpf.length;
        if (tamanho == 3) {
            document.dados[nome].value += ".";
        } else if (tamanho == 7) {
            document.dados[nome].value += ".";
        } else if (tamanho == 11) {
            document.dados[nome].value += "-";
        }
    }
}

function Ocorrencias(campo, txt) {
    var contador = 0;
    if (campo != "") {
        tam = campo.length;
        tam2 = txt.length;
        for (i = 0; i < tam; i++) {
            if (campo.substring(i, tam2 + i) == txt) {
                contador++;
            }
        }
    }
    return contador;
}

function IsNumeric(strString) {
    if (strString.toString() != "") {
        var strValidChars = "0123456789.";
        var strChar;
        var blnResult = true;

        for (i = 0; i < strString.length && blnResult == true; i++) {
            strChar = strString.charAt(i);
            if (strValidChars.indexOf(strChar) == -1) {
                blnResult = false;
            }
        }
        return blnResult;
    } else {
        return false;
    }
}

function replace2(str, valor1, valor2) {
    var str2 = "";
    for (q = 0; q < str.length; q = q + valor1.length) {
        if (str.substring(q, q + valor1.length) == valor1) {
            str2 += valor2;
        } else {
            str2 += str.substring(q, q + valor1.length);
        }
    }
    return str2;
}

function TiraHTML(txt) {
    var novo_txt = "";
    var sinal_maior = false;
    var quebra = new RegExp("\n", "gi");

    if (txt != "") {
        sinal_maior = false;

        for (i = 0; i < txt.length; i++) {
            if (txt.substring(i, i + 1) != "<" && sinal_maior == false) {
                novo_txt += txt.substring(i, i + 1);
            } else if (txt.substring(i, i + 1) == "<") {
                sinal_maior = true;
            } else if (txt.substring(i, i + 1) == ">") {
                sinal_maior = false;
            }
        }
        novo_txt = novo_txt.replace(quebra, "<br>");

        return novo_txt;
    }
}

function IsIE() {
    if (document.all) {
        return true;
    } else {
        return false;
    }
}

function Calendar2(nome, xform, xobj, xdiv, func) {
    if (xGetElementById("calendario").style.display != "") {
        formu = xform.name;
        
        if (document[formu][xobj]) {
            obj = document[formu][xobj].name;
        } else if (document[formu]["Master$Formulario2$" + xobj]) {
            obj = document[formu]["Master$Formulario2$" + xobj].name;
        }
        
        if (xGetElementById(xdiv)) {
            div = xdiv;
        } else {
            div = "Master_" + xdiv;
        }
        
        if (document[formu][obj].value != "") {
            data = document[formu][obj].value;
            dia = data.substring(0, data.indexOf("/"));
            mes = data.substring(data.indexOf("/") + 1, data.lastIndexOf("/"));
            ano = data.substring(data.lastIndexOf("/") + 1, data.length);
            //document.calendario.document.location = "inc_calendario.asp?dia=" + dia + "&mes=" + mes + "&ano=" + ano + "&objeto=" + obj + "&formulario=" + formu;
        } else {
            //document.calendario.document.location = "inc_calendario.asp?objeto=" + obj + "&formulario=" + formu;
        }

        DesapareceSels();
        
        if (div != null) {
            scrolltop = xGetElementById(div).scrollTop;
            scrollleft = xGetElementById(div).scrollLeft;
            altura = xGetElementById(div).scrollHeight;
            largura = xGetElementById(div).scrollWidth;
        } else {
            scrolltop = document.body.scrollTop;
            scrollleft = document.body.scrollLeft;
            altura = document.body.scrollHeight;
            largura = document.body.scrollWidth;
        }
        eval(nome).style.position = "absolute";
        if (eval(nome).offsetLeft + 201 > largura) {
            x = eval(nome).offsetLeft - (scrollleft + (eval(nome).offsetLeft + 201 - largura));
        } else {
            x = eval(nome).offsetLeft - scrollleft;
        }
        //y = eval(nome).offsetTop + 20;
        if (eval(nome).offsetTop + 214 > altura) {
            y = eval(nome).offsetTop - (scrolltop + (eval(nome).offsetTop + 214 - altura));
        } else {
            y = eval(nome).offsetTop - scrolltop;
        }
        if (div != null) {
            xGetElementById(div).style.position = "absolute";
            if (IsIE()) {
                posdiv = parseInt(xGetElementById(div).offsetTop);
            } else {
                posdiv = 0;
            }
            xGetElementById(div).style.position = "static";
            y = y + posdiv + 19;
        }
        //y = y - scrolltop;
        eval(nome).style.position = "static";
        xGetElementById("calendario").style.visibility = "visible";
        xGetElementById("calendario").style.left = x;
        xGetElementById("calendario").style.top = y;
        xGetElementById("calendario").style.display = "";
        
        if (IsIE()) {
            //document.Form1.objeto.value = obj;
            document.calendario.document.Form1.form.value = formu
            document.calendario.document.Form1.objeto.value = obj;
        } else {
            xGetElementById("calendario").contentWindow.document.Form1.form.value = obj;
            xGetElementById("calendario").contentWindow.document.Form1.objeto.value = obj;
            //xGetElementById("calendario").contentWindow.document.cal.objeto.value = document[formu][obj].name;
        }
        if (func != null) {
            if (IsIE()) {
                //xGetElementById("calendario").document.cal.func.value = func;
            } else {
                //xGetElementById("calendario").contentWindow.document.cal.func.value = func;
            }
        }
    } else {
        xGetElementById("calendario").style.display = "none";
        ApereceSels();
    }
}

function DesapareceCalendario() {
    xGetElementById("calendario").style.display = "none";
    ApereceSels();
}

function DesapareceSels() {
    elem = document.getElementsByTagName("select");
    total = document.getElementsByTagName("select").length;
    for (i = 0; i < total; i++) {
        eval(elem[i]).style.visibility = "hidden";
    }

    iframes = document.getElementsByTagName("iframe");
    for (i = 0; i < iframes.length; i++) {
        eval(iframes[i]).style.visibility = "hidden";
    }
}

function ApereceSels() {
    elem = document.getElementsByTagName("select");
    for (i = 0; i < elem.length; i++) {
        eval(elem[i]).style.visibility = "visible";
    }

    iframes = document.getElementsByTagName("iframe");
    for (i = 0; i < iframes.length; i++) {
        eval(iframes[i]).style.visibility = "visible";
    }
}

function Trim(txt) {
    var i = 0;
    while (txt.charAt(i) == " ") {
        i = i + 1;
    }
    var j = txt.length - 1
    while (txt.charAt(j) == " ") {
        j = j - 1;
    }
    return txt.substr(i, j - i + 1)
}

function FormataCampo(campo) {
    if (campo) {
        vax = campo.value;
        vax = Formata2(vax);
        vax = parseFloat(vax);
        if (isNaN(vax) == false) {
            campo.value = Formata(vax, '');
        } else {
            campo.value = "0,00";
        }
    }
}

function Formata(numero, tipo) {
    if (numero != "") {
        numero = numero.toString();
        numero = replace2(numero, " ", "");
        numero = Trim(numero);

        num = ""; num2 = ""; sinal = "";
        count = 0; jafoi = false;
        if (numero < 0) {
            sinal = "-";
            numero = numero.toString();
            numero = numero.replace("-", "");
        } else {
            numero = numero.toString();
        }
        tamanho = numero.length;
        //		if (numero.indexOf(",") != -1 && (numero.indexOf(".") == -1)) {
        //			numero = replace2(numero, ".", "");
        //			numero = replace2(numero, ",", ".");
        //			numero = parseFloat(numero);
        //			numero = numero.toString();
        //		}

        if (numero.indexOf(".") != -1) {
            for (j = tamanho; j > 0; j--) {
                if (jafoi == true) {
                    if (count % 3 == 0) {
                        if (count != 0) {
                            num += ".";
                        } else {
                            num += ":";
                        }
                    }
                    count++;
                }
                if (numero.substring(j, j - 1) == ".") {
                    jafoi = true;
                } else {
                    num += numero.substring(j, j - 1);
                }
            }
            if (num.indexOf(":") == 1) {
                num = "0" + num;
            }
        } else {
            for (j = tamanho; j > 0; j--) {
                num += numero.substring(j, j - 1);
                count++;
                if (count % 3 == 0 && j != 1) {
                    if (count != 0) {
                        num += ".";
                    } else {
                        num += ":";
                    }
                }
            }

            //			if (num.substring(0, 1) == ".") {
            //				num = num.replace(".", "");
            //			}
            num = "00," + num;
        }

        for (j = num.length; j > 0; j--) {
            num2 += num.substring(j, j - 1);
        }
        num2 = num2.replace(":", ",");

        if (num2.indexOf(",") != -1) {
            diferenca = num2.length - (num2.indexOf(",") + 1);
            if (diferenca > 2) {
                num2 = num2.substring(0, num2.indexOf(",") + 3);
            }
        }

        if (tipo == "P") {
            num2 = sinal + num2 + "%";
        } else if (tipo == "R") {
            num2 = "R$ " + sinal + num2;
        } else {
            num2 = sinal + num2;
        }
        return num2;
    } else {
        if (tipo == "P") {
            num2 = "0,00%";
        } else if (tipo == "R") {
            num2 = "R$0,00";
        } else {
            num2 = "0,00";
        }
        return num2;
    }
}

function Formata2(valor) {
    if (valor != "" && valor != null) {
        if (valor.indexOf(",") != -1) {
            valor = replace2(valor, ".", "");
            valor = replace2(valor, ",", ".");
        }
        return valor;
    } else {
        return "";
    }
}

function criaAJAX() {
    var xmlhttp = false;
    try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) {
        try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (E) { xmlhttp = false; }
    }
    if (!xmlhttp) xmlhttp = new XMLHttpRequest();
    return xmlhttp;
}

function XMLParser() {
    var xmlDoc, ie;
    
    this.create = function() {
        var pser = null;
        if (window.ActiveXObject) {
            pser = new ActiveXObject("Microsoft.XMLDOM");
            pser.async = false;
            this.ie = true;
        } else if (document.implementation && document.implementation.createDocument) {
            pser = document.implementation.createDocument("", "", null);
            this.ie = false;
        }
        return pser;
    }
    
    this.load = function(file) {
        this.xmlDoc.load(file);
        if (this.ie)
            this.callback();
        else
            this.xmlDoc.onload = this.callback;
    }
    
    this.xmlDoc = this.create();
    
    this.callback = function() {
        alert("Funçao de callback não definida");
    };
}

function basicAJAX(page, data) {
    var i, retorno, data_qtt = 0;
    if (data != undefined && data.length > 0) {
        data_qtt++;
        for (i = 0; i < data.length; i++) if (data.substr(i, 1) == '&') data_qtt++;
    }
    ajax.open("POST", page, true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("Content-length", data_qtt);
    ajax.onreadystatechange = function() { if (ajax.readyState == 4) return (ajax.responseText); }
    ajax.send(data);
}

function xStr(s) {
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])!='string') return false;}
  return true;
}

function xDef() {
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
  return true;
}

function xOpacity(e, o) {
  var set = xDef(o);
  //  if (set && o == 1) o = .9999; // FF1.0.2 but not needed in 1.5
  if(!(e=xGetElementById(e))) return 2; // error
  if (xStr(e.style.opacity)) { // CSS3
    if (set) e.style.opacity = o + '';
    else o = parseFloat(e.style.opacity);
  }
  else if (xStr(e.style.filter)) { // IE5.5+
    if (set) e.style.filter = 'alpha(opacity=' + (100 * o) + ')';
    else if (e.filters && e.filters.alpha) { o = e.filters.alpha.opacity / 100; }
  }
  else if (xStr(e.style.MozOpacity)) { // Gecko before CSS3 support
    if (set) e.style.MozOpacity = o + '';
    else o = parseFloat(e.style.MozOpacity);
  }
  else if (xStr(e.style.KhtmlOpacity)) { // Konquerer and Safari
    if (set) e.style.KhtmlOpacity = o + '';
    else o = parseFloat(e.style.KhtmlOpacity);
  }
  return isNaN(o) ? 1 : o; // if NaN, should this return an error instead of 1?
}

function xDocSize(xdoc) {
  var b=xdoc.document.body, e=xdoc.document.documentElement;
  var esw=0, eow=0, bsw=0, bow=0, esh=0, eoh=0, bsh=0, boh=0;
  if (e) {
    esw = e.scrollWidth;
    eow = e.offsetWidth;
    esh = e.scrollHeight;
    eoh = e.offsetHeight;
  }
  if (b) {
    bsw = b.scrollWidth;
    bow = b.offsetWidth;
    bsh = b.scrollHeight;
    boh = b.offsetHeight;
  }
//  alert('compatMode: ' + document.compatMode + '\n\ndocumentElement.scrollHeight: ' + esh + '\ndocumentElement.offsetHeight: ' + eoh + '\nbody.scrollHeight: ' + bsh + '\nbody.offsetHeight: ' + boh + '\n\ndocumentElement.scrollWidth: ' + esw + '\ndocumentElement.offsetWidth: ' + eow + '\nbody.scrollWidth: ' + bsw + '\nbody.offsetWidth: ' + bow);
  return {w:Math.max(esw,eow,bsw,bow),h:Math.max(esh,eoh,bsh,boh)};
}

function xScrollTop(e, bWin) {
  var w, offset=0;
  if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    w = window;
    if (bWin && e) w = e;
    if(w.document.documentElement && w.document.documentElement.scrollTop) offset=w.document.documentElement.scrollTop;
    else if(w.document.body && xDef(w.document.body.scrollTop)) offset=w.document.body.scrollTop;
  }
  else {
    e = xGetElementById(e);
    if (e && xNum(e.scrollTop)) offset = e.scrollTop;
  }
  return offset;
}

function xScrollLeft(e, bWin) {
  var w, offset=0;
  if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    w = window;
    if (bWin && e) w = e;
    if(w.document.documentElement && w.document.documentElement.scrollLeft) offset=w.document.documentElement.scrollLeft;
    else if(w.document.body && xDef(w.document.body.scrollLeft)) offset=w.document.body.scrollLeft;
  }
  else {
    e = xGetElementById(e);
    if (e && xNum(e.scrollLeft)) offset = e.scrollLeft;
  }
  return offset;
}

var xWinScrollWin = null;
function xWinScrollTo(win,x,y,uTime) {
  var e = win;
  if (!e.timeout) e.timeout = 15;
  var st = xScrollTop(e, 1);
  var sl = xScrollLeft(e, 1);
  e.xTarget = x; 
  e.yTarget = y; e.slideTime = uTime; e.stop = false;
  e.yA = e.yTarget - st;
  e.xA = e.xTarget - sl; // A = distance
  e.B = Math.PI / (2 * e.slideTime); // B = period
  e.yD = st;
  e.xD = sl; // D = initial position
  var d = new Date(); e.C = d.getTime();
  if (!e.moving) {
    xWinScrollWin = e;
    _xWinScrollTo();
  }
}

function _xWinScrollTo() {
  var e = xWinScrollWin || window;
  var now, s, t, newY, newX;
  now = new Date();
  t = now.getTime() - e.C;
  if (e.stop) { e.moving = false; }
  else if (t < e.slideTime) {
    setTimeout("_xWinScrollTo()", e.timeout);
    s = Math.sin(e.B * t);
    newX = Math.round(e.xA * s + e.xD);
    newY = Math.round(e.yA * s + e.yD);
    e.scrollTo(newX, newY);
    e.moving = true;
  }  else {
    e.scrollTo(e.xTarget, e.yTarget);
    xWinScrollWin = null;
    e.moving = false;
  }  
}