//<!--

var req;
var alvo;
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 exibe(imagem, id){
	d = 'divD' + id;
	
	document.getElementById(d).style.backgroundColor = '#B4B4B4';
	document.getElementById(imagem).style.visibility = 'visible';
}

function esconde(imagem, id){
	d = 'divD' + id;
	
	document.getElementById(d).style.backgroundColor = '#FFFFFF';
	document.getElementById(imagem).style.visibility = 'hidden';
}

function validaForm(id){
	switch (id)	{
		case 1:
			nome     = document.formContato.nome.value;
			email    = document.formContato.email.value;
			telefone = document.formContato.tel.value;
			tipo     = document.formContato.tipo.value;

			er1 = /\([0-9]{2}\)[0-9]{4}-[0-9]{4}/;
			er2 = /[^0-9()-]/;
			er3 = /[A-Za-z0-9_.-]+@([A-Za-z0-9_-]+)+\.[A-Za-z]{2,}/;
			er4 = /[A-Za-z]{3,}/;
			er5 = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/; // data
			er6 = /[A-Za-z0-9]{2,}/;
			
			if(! er4.test(nome) || ! er3.test(email) || ! er1.test(telefone) || er2.test(telefone)) {
				msgErro(1);
				
				return false;
			}
			
			if(tipo == 1){
				assunto  = document.formContato.assunto.value;
				mensagem = document.formContato.mensagem.value;
				
				if(! er4.test(assunto) || ! er4.test(mensagem)){
					msgErro(1);
				
					return false;
				}
			} else {
				dt = document.formContato.data.value;
				hora = document.formContato.hora.value;
				especialidade = document.formContato.especialidade.value;
				
				if(! er5.test(dt) || ! er6.test(hora) || ! er4.test(especialidade)){
					msgErro(1);
				
					return false;
				}
			}
			
			return true;
			
			break;
	}
}

function msgErro(tipo){
	switch (tipo) {
		case 1:
			if(document.formContato.lang.value == 2) {
				msg = 'Please, fill out all the fields. Thank you.';
			} else {
				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('documentos.php?cod=5&id=' + comp, '_self');

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

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

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

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

			break;
			
		case 7:
			if (!confirm('Confirma a exclusão?')){
				return false;
			}
			
			window.open('categorias.php?cod=44&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 ) ;}
} 

}

//

var timeBeforeAutoHide = 100;	// Microseconds to wait before auto hiding menu(1000 = 1 second)
var slideSpeed_out = 10;	// Steps to move sub menu at a time ( higher = faster)
var slideSpeed_in = 10;
	

var slideTimeout_out = 25;	// Microseconds between slide steps ( lower = faster)
var slideTimeout_in = 10;	// Microseconds between slide steps ( lower = faster)

var showSubOnMouseOver = true;	// false = show sub menu on click, true = show sub menu on mouse over
var fixedSubMenuWidth = false;	// Width of sub menu items - A number(width in pixels) or false when width should be dynamic

var xOffsetSubMenu = 0; 	// Offset x-position of sub menu items - use negative value if you want the sub menu to overlap main menu

var slideDirection = 'right';	// Slide to left or right ?

/* Don't change anything below here */

var activeSubMenuId = false;
var activeMainMenuItem = false;
var currentZIndex = 1000;		
var autoHideTimer = 0;
var submenuObjArray = new Array();
var okToSlideInSub = new Array();
var subPositioned = new Array();


function stopAutoHide()
{
	autoHideTimer = -1;
}

function initAutoHide()
{
	autoHideTimer = 0;
	if(autoHideTimer>=0)autoHide();
}

function autoHide()
{
	
	if(autoHideTimer>timeBeforeAutoHide)
	{
		
		if(activeMainMenuItem){
			activeMainMenuItem.className='';
			activeMainMenuItem = false;
		}
		
		if(activeSubMenuId){
			var obj = document.getElementById('subMenuDiv' + activeSubMenuId);
			showSub();
		}
	}else{
		if(autoHideTimer>=0){
			autoHideTimer+=50;
			setTimeout('autoHide()',50);
		}
	}
}	

function getTopPos(inputObj)
{		
  var returnValue = inputObj.offsetTop;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
  return returnValue;
}

function getLeftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
  return returnValue;
}

function showSub()
{
	var subObj = false;
	if(this && this.tagName){
		var numericId = this.parentNode.id.replace(/[^0-9]/g,'');
		okToSlideInSub[numericId] = false;
		var subObj = document.getElementById('subMenuDiv' + numericId);
		if(activeMainMenuItem)activeMainMenuItem.className='';
		if(subObj){
			if(!subPositioned[numericId]){
				if(slideDirection=='right'){
					subObj.style.left = getLeftPos(submenuObjArray[numericId]['parentDiv']) + submenuObjArray[numericId]['parentDiv'].offsetWidth + xOffsetSubMenu + 'px';
				}else{
					subObj.style.left = getLeftPos(submenuObjArray[numericId]['parentDiv']) + xOffsetSubMenu + 'px';
					
				}
				submenuObjArray[numericId]['left'] = subObj.style.left.replace(/[^0-9]/g,'');
				subObj.style.top = getTopPos(submenuObjArray[numericId]['parentDiv']) + 'px';
				subPositioned[numericId] = true;
			}				
			subObj.style.visibility = 'visible';
			subObj.style.zIndex = currentZIndex;
			currentZIndex++;	
			this.className='activeMainMenuItem';
			activeMainMenuItem = this;
		}
	}else{
		var numericId = activeSubMenuId;
	}
	if(activeSubMenuId && (numericId!=activeSubMenuId || !subObj))slideMenu(activeSubMenuId,(slideSpeed_in*-1));
	if(numericId!=activeSubMenuId && this && subObj){
		subObj.style.width = '0px';	
		slideMenu(numericId,slideSpeed_out);
		activeSubMenuId = numericId;
	}else{
		if(numericId!=activeSubMenuId)activeSubMenuId = false;
	}
	if(showSubOnMouseOver)stopAutoHide();
}

function slideMenu(menuIndex,speed){
	var obj = submenuObjArray[menuIndex]['divObj'];
	var obj2 = submenuObjArray[menuIndex]['ulObj'];
	var width = obj.offsetWidth + speed;
	if(speed<0){
		if(width<0)width = 0;
		obj.style.width = width + 'px';
		if(slideDirection=='left'){
			obj.style.left = submenuObjArray[menuIndex]['left'] - width + 'px';
			obj2.style.left = '0px';
		}else{
			obj2.style.left = width - submenuObjArray[menuIndex]['width'] + 'px' 
		}
		if(width>0 && okToSlideInSub[menuIndex])setTimeout('slideMenu(' + menuIndex + ',' + speed + ')',slideTimeout_in); else{
			obj.style.visibility = 'hidden';
			obj.style.width = '0px';
			if(activeSubMenuId==menuIndex)activeSubMenuId=false;
		}
		
	}else{
		if(width>submenuObjArray[menuIndex]['width'])width = submenuObjArray[menuIndex]['width'];
		if(slideDirection=='left'){
			obj.style.left = submenuObjArray[menuIndex]['left'] - width + 'px';
			obj2.style.left = '0px';
		}else{
			obj2.style.left = width - submenuObjArray[menuIndex]['width'] + 'px' 
		}		
		
		obj.style.width = width + 'px';
		if(width<submenuObjArray[menuIndex]['width']){
			setTimeout('slideMenu(' + menuIndex + ',' + speed + ')',slideTimeout_out);
		}else{
			okToSlideInSub[menuIndex] = true;
		}
	}
}
function resetPosition()
{
	subPositioned.length = 0;
}
		
function initLeftMenu()
{
	var isMSIE = navigator.userAgent.indexOf('MSIE')>=0?true:false;
	var browserVersion = parseInt(navigator.userAgent.replace(/.*?MSIE ([0-9]+?)[^0-9].*/g,'$1'));
	if(!browserVersion)browserVersion=1;
	
	var menuObj = document.getElementById('dhtmlgoodies_menu');	
	var mainMenuItemArray = new Array();
	
	var mainMenuItem = menuObj.getElementsByTagName('LI')[0];
	while(mainMenuItem){
		if(mainMenuItem.tagName && mainMenuItem.tagName.toLowerCase()=='li'){
			mainMenuItemArray[mainMenuItemArray.length] = mainMenuItem;
			var aTag = mainMenuItem.getElementsByTagName('A')[0];
			if(showSubOnMouseOver)
				aTag.onmouseover = showSub;	
			else
				aTag.onclick = showSub;	
		}
		mainMenuItem = mainMenuItem.nextSibling;
	}		
	
	var lis = menuObj.getElementsByTagName('A');
	for(var no=0;no<lis.length;no++){
		if(!showSubOnMouseOver)lis[no].onmouseover = stopAutoHide;
		lis[no].onmouseout = initAutoHide;
		lis[no].onmousemove = stopAutoHide;
	}
			
	for(var no=0;no<mainMenuItemArray.length;no++){
		var sub = mainMenuItemArray[no].getElementsByTagName('UL')[0];
		if(sub){
			mainMenuItemArray[no].id = 'mainMenuItem' + (no+1);
			var div = document.createElement('DIV');
			div.className='dhtmlgoodies_subMenu';
			document.body.appendChild(div);
			div.appendChild(sub);
			if(slideDirection=='right'){
				div.style.left = getLeftPos(mainMenuItemArray[no]) + mainMenuItemArray[no].offsetWidth + xOffsetSubMenu + 'px';
			}else{
				div.style.left = getLeftPos(mainMenuItemArray[no]) + xOffsetSubMenu + 'px';
			}
			div.style.top = getTopPos(mainMenuItemArray[no]) + 'px';
			div.id = 'subMenuDiv' + (no+1);
			sub.id = 'submenuUl' + (no+1);
			sub.style.position = 'relative';	

			if(navigator.userAgent.indexOf('Opera')>=0){
				submenuObjArray[no+1] = new Array();
				submenuObjArray[no+1]['parentDiv'] = mainMenuItemArray[no];
				submenuObjArray[no+1]['divObj'] = div;
				submenuObjArray[no+1]['ulObj'] = sub;
				submenuObjArray[no+1]['width'] = sub.offsetWidth;
				submenuObjArray[no+1]['left'] = div.style.left.replace(/[^0-9]/g,'');
			}
			sub.style.left = 1 - sub.offsetWidth + 'px';	
			
			
			
			if(browserVersion<7 && isMSIE)div.style.width = '1px';	
				
			if(navigator.userAgent.indexOf('Opera')<0){
				submenuObjArray[no+1] = new Array();
				submenuObjArray[no+1]['parentDiv'] = mainMenuItemArray[no];
				submenuObjArray[no+1]['divObj'] = div;
				submenuObjArray[no+1]['ulObj'] = sub;
				submenuObjArray[no+1]['width'] = sub.offsetWidth;
				
				
				
				submenuObjArray[no+1]['left'] = div.style.left.replace(/[^0-9]/g,'');
				if(fixedSubMenuWidth)submenuObjArray[no+1]['width'] = fixedSubMenuWidth;
			}	

			if(!document.all)div.style.width = '1px';			
				
		}			
	}
		

	
	
	menuObj.style.visibility = 'visible';
	
	window.onresize = resetPosition;
}

//-->
