//<!--

var req;
var alvo;
var host = 'http://localhost/bockus/imagens/'
var carregando = '<table width="100%" border="0"><tr><td width="100%" style="color:#666666"><img src="imagens/loader.gif" border="0"></td></tr></table>';

function loadXMLDoc(url){
	req = null;

	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange1;
		req.open("GET", url, true);
		req.send('');
	} else if (window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP.4.0");
		} catch(e) {
			try {
				req = new ActiveXObject("Msxml2.XMLHTTP.3.0");
			} catch(e) {
				try {
					req = new ActiveXObject("Msxml2.XMLHTTP");
				} catch(e) {
					try {
						req = new ActiveXObject("Microsoft.XMLHTTP");
					} catch(e) {
						req = false;
					}
				}
			}
		}
		if (req) {
			req.onreadystatechange = processReqChange1;
			req.open("GET", url, true);
			req.send('');
		}
	}
}

function processReqChange1(){ 
	if (req.readyState == 4) {
		if (req.status == 200) {
			texto = req.responseText.replace(/\+/g," ");
			
			extraiScript(texto);

			document.getElementById(alvo).innerHTML = req.responseText;
		} else {
			alert("Houve um problema ao atualizar os dados:\n" + req.statusText);
		}
	} else {
		document.getElementById(alvo).innerHTML = carregando;
	}
}

function atualiza(url, target){
	alvo = target;
	
	loadXMLDoc(url);
}

function extraiScript(texto){
	/*
	 * Autor: SkyWalker.TO do imasters/forum 
	 * http://forum.imasters.com.br/index.php?showtopic=165277
	 * 
	 * Permite a esecução de um script/função como retorno do HttpRequest/Ajax
	 */
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            //eval(codigo);
            /**********************
            * Alterado por Micox - micoxjcg@yahoo.com.br
            * Alterei pois com o eval não executava funções.
            ***********************/
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}

function marcar(){
	d = document.formMailing;
	
	for (i = 0; i < d['sel[]'].length; i++){
		if (! d['sel[]'][i].checked) {
			d['sel[]'][i].checked = 'checked';
		} else {
			d['sel[]'][i].checked = '';
		}
	}
}

function validaForm(id){
	switch (id)	{
		case 1:
			f = document.formFale;
		
			nome     = f.nome.value;
			email    = f.email.value;
			telefone = f.tel.value;
			assunto  = f.assunto.value;
			mensagem = f.msg.value;
alert
			er1 = /[0-9]{4}/;
			er3 = /[A-Za-z0-9_.-]+@([A-Za-z0-9_-]+)+\.[A-Za-z]{2,}/;
			er4 = /[A-Za-z]{3,}/;
			
			if(! er4.test(nome) || ! er3.test(email) || ! er1.test(telefone) || assunto == 'Selecione uma Opção' || ! er4.test(mensagem)) {
				msgErro(1);
			}
			else
			{
				f.submit();
			}
			
			break;
	}
}

function msgErro(tipo){
	switch (tipo) {
		case 1:
			msg = 'Preencha todos os campos do formulário. Obrigado.';
					
			break;

	}

	alert (msg);
}

function sair(){
	if (! confirm('Encerrar o sistema?')){
		return false;
	}
	
	window.open('logout.php', '_self');
}

function confirma(id, comp) {
	switch (id){
		case 1:
			if (!confirm('Confirma a exclusão?')){
				return false;
			}
			
			window.open('usuarios.php?cod=5&id=' + comp, '_self');

			break;

		case 2:
			if (!confirm('Confirma a exclusão?')){
				return false;
			}
			
			window.open('links.php?cod=5&id=' + comp, '_self');

			break;
			
		case 3:
			if (!confirm('Confirma a exclusão?')){
				return false;
			}
			
			window.open('convenios.php?cod=5&id=' + comp, '_self');

			break;
			
		case 4:
			if (!confirm('Confirma a exclusão?')){
				return false;
			}
			
			window.open('paginas12.php?cod=5&id=' + comp, '_self');

			break;
			
		case 5:
			if (!confirm('Confirma a exclusão?')){
				return false;
			}
			
			window.open('paginas34.php?cod=5&id=' + comp, '_self');

			break;
			
		case 6:
			if (!confirm('Confirma a exclusão?')){
				return false;
			}
			
			window.open('paginas34.php?cod=14&id=' + comp, '_self');

			break;
	}
}

// FORMATADOR

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all) { // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
		nTecla = evtKeyPress.which;
	} else {
		nTecla = evtKeyPress.which;
		if (nTecla == 8) {
			return true;
		}
	}

	sValue = objForm[strField].value;
	// Limpa todos os caracteres de formatação que
	// já estiverem no campo.
	sValue = sValue.toString().replace(/\-/g, "");
	sValue = sValue.toString().replace(/\./g, "");
	sValue = sValue.toString().replace(/\//g, "");
	sValue = sValue.toString().replace(/\(/g, "");
	sValue = sValue.toString().replace(/\)/g, "");
	sValue = sValue.toString().replace(/\s/g, "");
	fldLen = sValue.length;
	mskLen = sMask.length;

	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;

	while (i <= mskLen) {
	bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ":") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
	bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

	if (bolMask) {
		sCod += sMask.charAt(i);
		mskLen++;
	} else {
		sCod += sValue.charAt(nCount);
		nCount++;
	}
	i++;
	}

	objForm[strField].value = sCod;
	if (nTecla != 8) { // backspace
		if (sMask.charAt(i-1) == "9") { // apenas números...
			return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
		else { // qualquer caracter...
			return true;
		}
	} else {
		return true;
	}
}

//Fim da Função Máscaras Gerais

/***
* AUTO TAB - ao prencher o campo, automaticamente manda o foco para o próximo!
***/
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }

function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
        found = true;
    else
        index++;
        return found;
    }

function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
        if (input.form[i] == input)index = i;
        else i++;
        return index;
    }
    return true;
}

// FORMATADOR - fim

//

function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
aux = validos.indexOf(valor.substring(i, i+1));
if (aux>=0) {
result += aux;
}
}
return result;
}

//Formata número tipo moeda usando o evento onKeyDown

function Formata(campo,tammax,teclapres,decimal) {
var tecla = teclapres.keyCode;
vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal

if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

if (tecla == 8 )
{ tam = tam - 1 ; }

if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
{

if ( tam <= dec )
{ campo.value = vr ; }

if ( (tam > dec) && (tam <= 5) ){
campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
}
if ( (tam >= 9) && (tam <= 11) ){
campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
} 

}

//

/*************************************************************************
 * Upload sem refresh
 * SCript by Micox (esse é o cara do JS *obs minha =)
 *************************************************************************/

/* funçõezinhas padrão pra facilitar */
function $m(quem){
 //apelido só pra não ficar repetindo o document.getElementById
 return document.getElementById(quem)
}
function remove(quem){
 quem.parentNode.removeChild(quem);
}
function addEvent(obj, evType, fn){
 //o velho do elcio.com.br/crossbrowser
    if (obj.addEventListener)
        obj.addEventListener(evType, fn, true)
    if (obj.attachEvent)
        obj.attachEvent("on"+evType, fn)
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, fn );
  } else {
    obj.removeEventListener( type, fn, false ); }
} 
/* a que faz o serviço pesado */
function micoxUpload(form,url_action,id_elemento_retorno,html_exibe_carregando,html_erro_http){
/******
* micoxUpload - Submete um form para um iframe oculto e pega o resultado. Consequentemente pode
*               ser usado pra fazer upload de arquivos de forma assíncrona.
* Use a vontade mas coloque meu nome nos créditos. Licença Creative Commons.
* Versão: 1.0 - 03/03/2007 - Testado no FF2.0 IE6.0 e OP9.1
* Autor: Micox - Náiron JCG - elmicox.blogspot.com - micoxjcg@yahoo.com.br
* Parametros:
* form - o form a ser submetido ou seu ID
* url_action - url pra onde deve ser submetido o form
* id_elemento_retorno - id do elemento que irá receber a informação de retorno
* html_exibe_carregando - Texto (ou imagem) que será exibido enquanto se carrega o upload
* html_erro_http - texto (ou imagem) que será exibido se der erro HTTP.
*******/

 //testando se passou o ID ou o objeto mesmo
 form = typeof(form)=="string"?$m(form):form;
 
 var erro="";
 if(form==null || typeof(form)=="undefined"){ erro += "O form passado no 1o parâmetro não existe na página.\n";}
 else if(form.nodeName!="FORM"){ erro += "O form passado no 1o parâmetro da função não é um form.\n";}
 if($m(id_elemento_retorno)==null){ erro += "O elemento passado no 3o parâmetro não existe na página.\n";}
 if(erro.length>0) {
  alert("Erro ao chamar a função micoxUpload:\n" + erro);
  return;
 }

 //criando o iframe
 var iframe = document.createElement("iframe");
 iframe.setAttribute("id","micox-temp");
 iframe.setAttribute("name","micox-temp");
 iframe.setAttribute("width","0");
 iframe.setAttribute("height","0");
 iframe.setAttribute("border","0");
 iframe.setAttribute("style","width: 0; height: 0; border: none;");
 /* Não usei display:none pra esconder o iframe
    pois tem uma lenda que diz que o NS6 ignora
    iframes que tenham o display:none */
 
 //adicionando ao documento
 form.parentNode.appendChild(iframe);
 window.frames['micox-temp'].name="micox-temp"; //ie sucks
 
 //adicionando o evento ao carregar
 var carregou = function() { 
   removeEvent( $m('micox-temp'),"load", carregou);
   var cross = "javascript: ";
   cross += "window.parent.$m('" + id_elemento_retorno + "').innerHTML = document.body.innerHTML; void(0); ";
   
   texto = document.body.innerHTML.replace(/\+/g," ");
   
   cross += extraiScript(texto);
   
   $m(id_elemento_retorno).innerHTML = html_erro_http;
   $m('micox-temp').src = cross;
   //deleta o iframe
   setTimeout(function(){ remove($m('micox-temp'))}, 250);
  }
 addEvent( $m('micox-temp'),"load", carregou)
 
 //setando propriedades do form
 form.setAttribute("target","micox-temp");
 form.setAttribute("action",url_action);
 form.setAttribute("method","post");
 form.setAttribute("enctype","multipart/form-data");
 form.setAttribute("encoding","multipart/form-data");
 //submetendo
 form.submit();
 
 //se for pra exibir alguma imagem ou texto enquanto carrega
 if(html_exibe_carregando.length > 0){
  $m(id_elemento_retorno ).innerHTML = html_exibe_carregando;
 }
 
}

//

/**********************************************************************************   
SideScrollMenu 
*   Copyright (C) 2001 <a href="/dhtmlcentral/thomas_brattli.asp">Thomas Brattli</a>
*   This script was released at DHTMLCentral.com
*   Visit for more great scripts!
*   This may be used and changed freely as long as this msg is intact!
*   We will also appreciate any links you could give us.
*
*   Made by <a href="/dhtmlcentral/thomas_brattli.asp">Thomas Brattli</a>  and modified by Michael van Ouwerkerk
*********************************************************************************/

function lib_bwcheck(){ //Browsercheck (needed)
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=this.agent.indexOf("Opera 5")>-1
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0; 
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")>-1
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0; 
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
	return this
}
var bw=new lib_bwcheck()

/**************************************************************************
Variables to set.
***************************************************************************/
sLeft = 0         //The left placement of the menu
sTop = 120        //The top placement of the menu
sMenuheight = 62  //The height of the menu
sArrowwidth = 11  //Width of the arrows
sScrollspeed = 20 //Scroll speed: (in milliseconds, change this one and the next variable to change the speed)
sScrollPx = 8     //Pixels to scroll per timeout.
sScrollExtra = 15 //Extra speed to scroll onmousedown (pixels)

/**************************************************************************
Scrolling functions
***************************************************************************/
var tim = 0
var noScroll = true
function mLeft(){
	if (!noScroll && oMenu.x<sArrowwidth){
		oMenu.moveBy(sScrollPx,0)
		tim = setTimeout("mLeft()",sScrollspeed)
	}
}
function mRight(){
	if (!noScroll && oMenu.x>-(oMenu.scrollWidth-(pageWidth))-sArrowwidth){
		oMenu.moveBy(-sScrollPx,0)
		tim = setTimeout("mRight()",sScrollspeed)
	}
}
function noMove(){
	clearTimeout(tim);
	noScroll = true;
	sScrollPx = sScrollPxOriginal;
}
/**************************************************************************
Object part
***************************************************************************/
function makeObj(obj,nest,menu){
	nest = (!nest) ? "":'document.'+nest+'.';
	this.elm = bw.ns4?eval(nest+"document.layers." +obj):bw.ie4?document.all[obj]:document.getElementById(obj);
   	this.css = bw.ns4?this.elm:this.elm.style;
	this.scrollWidth = bw.ns4?this.css.document.width:this.elm.offsetWidth;
	this.x = bw.ns4?this.css.left:this.elm.offsetLeft;
	this.y = bw.ns4?this.css.top:this.elm.offsetTop;
	this.moveBy = b_moveBy;
	this.moveIt = b_moveIt;
	this.clipTo = b_clipTo;
	return this;
}
var px = bw.ns4||window.opera?"":"px";
function b_moveIt(x,y){
	if (x!=null){this.x=x; this.css.left=this.x+px;}
	if (y!=null){this.y=y; this.css.top=this.y+px;}
}
function b_moveBy(x,y){this.x=this.x+x; this.y=this.y+y; this.css.left=this.x+px; this.css.top=this.y+px;}
function b_clipTo(t,r,b,l){
	if(bw.ns4){this.css.clip.top=t; this.css.clip.right=r; this.css.clip.bottom=b; this.css.clip.left=l;}
	else this.css.clip="rect("+t+"px "+r+"px "+b+"px "+l+"px)";
}
/**************************************************************************
Object part end
***************************************************************************/

/**************************************************************************
Init function. Set the placements of the objects here.
***************************************************************************/
var sScrollPxOriginal = sScrollPx;
function sideInit(){
	//Width of the menu, Currently set to the width of the document.
	//If you want the menu to be 500px wide for instance, just 
	//set the pageWidth=500 in stead.
	pageWidth = 500;
	
	//Making the objects...
	oBg = new makeObj('divBg')
	oMenu = new makeObj('divMenu','divBg',1)
	oArrowRight = new makeObj('divArrowRight','divBg')
	
	//Placing the menucontainer, the layer with links, and the right arrow.
	oBg.moveIt(sLeft,sTop) //Main div, holds all the other divs.
	oMenu.moveIt(sArrowwidth,null)
	oArrowRight.css.width = sArrowwidth;
	oArrowRight.moveIt(pageWidth-sArrowwidth,null)
	
	//Setting the width and the visible area of the links.
	if (!bw.ns4) oBg.css.overflow = "hidden";
	if (bw.ns6) oMenu.css.position = "relative";
	oBg.css.width = pageWidth+px;
	oBg.clipTo(0,488,sMenuheight,12)
	oBg.css.visibility = "visible";
}

function loadXMLDoc2(url){
	req = null;

	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange2;
		req.open("GET", url, true);
		req.send('');
	} else if (window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP.4.0");
		} catch(e) {
			try {
				req = new ActiveXObject("Msxml2.XMLHTTP.3.0");
			} catch(e) {
				try {
					req = new ActiveXObject("Msxml2.XMLHTTP");
				} catch(e) {
					try {
						req = new ActiveXObject("Microsoft.XMLHTTP");
					} catch(e) {
						req = false;
					}
				}
			}
		}
		if (req) {
			req.onreadystatechange = processReqChange2;
			req.open("GET", url, true);
			req.send('');
		}
	}
}

function processReqChange2(){ 
	if (req.readyState == 4) {
		if (req.status == 200) {
			texto = req.responseText.replace(/\+/g," ");
			
			extraiScript(texto);

			document.getElementById(alvo).innerHTML = req.responseText;
			
			sideInit();
		} else {
			alert("Houve um problema ao atualizar os dados:\n" + req.statusText);
		}
	} else {
		document.getElementById(alvo).innerHTML = carregando;
	}
}

function atualiza2(url, target){
	alvo = target;
	
	loadXMLDoc2(url);
}

//-->
