

// funcao basica para as operacoes em ajax .. nao me pergunte com funcionao pq eh assim eh pronto
function GetXmlObject(){
var xmlhttp=null;
try
  {  xmlhttp=new XMLHttpRequest();  }
catch (e)
  {
try
    {    xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");    }  
catch (e)
    {    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
  }
return xmlhttp;
}

function atualiza_ordem_geral(id_pagina,tabela, campo) {
 ordem = document.getElementById('ordem'+id_pagina).value;

if(!isNaN(ordem))
 {
xmlhttp = GetXmlObject()
 url2="atualiza_ordem.asp?id_pagina=" + id_pagina +"&ordem="+ ordem + "&tabela=" + tabela + "&campo=" + campo +"&tm="+Math.random();
xmlhttp.open("GET",url2,true);
xmlhttp.send(null);
 }
 else
 {
	alert("Digite somente Números!");
	return false;
 }
   

   
}

// funcao basica em ajax para atualizar os checks box sem refresh
function pronto_img(img,url,valor_box,id_id){
	if (valor_box==0){img.src="../imagens/unlock.gif";} else {img.src="../imagens/lock.gif";}
	xmlhttp = GetXmlObject()
	var url2=url+".asp";
url2 = url2+"?id_id="+id_id
url2 = url2+"&valor_box="+valor_box
url2 = url2+"&tm="+Math.random();
//xmlhttp.onreadystatechange=ajax_div;
//alert(url2)
xmlhttp.open("GET",url2,true);
xmlhttp.send(null);
	
}

function pronto(id_id,url,nome_box,n_itens){

var conf=confirm("Voce tem certeza que deseja modificar esse item?")

if (conf==true){
//alert(conf)

var valor_box;

if(typeof(n_itens)!="undefined"){
uncheckAll(n_itens)
document.getElementById(nome_box).checked=true
}
if(document.getElementById(nome_box).checked==true){

valor_box="1";
}
else{
valor_box="0";

}
//alert(valor_box)
xmlhttp = GetXmlObject()
if (xmlhttp==null){
alert('Seu navegador não suporta Ajax');
return;
}

var url2=url+".asp";
url2 = url2+"?id_id="+id_id
url2 = url2+"&valor_box="+valor_box
url2 = url2+"&tm="+Math.random();
//xmlhttp.onreadystatechange=ajax_div;
//alert(url2)
xmlhttp.open("GET",url2,true);
xmlhttp.send(null);
}
else
{
	if(document.getElementById(nome_box).checked==true){
	document.getElementById(nome_box).checked=false	
	}else{document.getElementById(nome_box).checked=true}
}
}


function at_td_sel (id_id,div_pop,id_campo,url) {
	
valor_box=document.getElementById(id_campo).value	
	xmlhttp = GetXmlObject()
	var url2=url+".asp";
url2 = url2+"?id_id="+id_id
url2 = url2+"&valor_box="+valor_box
url2 = url2+"&tm="+Math.random();
//xmlhttp.onreadystatechange=ajax_div;
//alert(url2)
xmlhttp.open("GET",url2,true);
xmlhttp.send(null);
mostra_id(div_pop)
document.getElementById("td_"+id_id).innerHTML=document.getElementById(id_campo).value
}

//funcao para descelecionar todos os checks box de um form
function uncheckAll(n_itens) {
for (var j = 1; j <= n_itens; j++) {
box = document.p + j; 
if (box.checked == true) box.checked = false;
   }
}
// funcao em ajax para atualizar automaticamente o conteudo de um caixa de selecao dependente de outra


function selecao(id_id,url,id_id2){
id_id2=document.getElementById(id_id2).value
//alert(id_id2)
xmlhttp = GetXmlObject()
if (xmlhttp==null){
alert('Seu navegador não suporta Ajax');
return;
}
id_id_fixo=id_id
var url2=url+"";
url2 = url2+"?id_id2="+id_id2
//url2 = url2+"&valor_box="+valor_box
url2 = url2+"&tm="+Math.random();
xmlhttp.onreadystatechange=ajax_id;
xmlhttp.open("GET",url2,true);
xmlhttp.send(null);

}

// funcao q faz a atualizacao do target do ajax. ela tem consegue recarregar scripts dentro de scrips
function ajax_id(){
	var switcher = document.getElementById(id_id_fixo);
	if(xmlhttp.readyState<=3){
switcher.innerHTML = "<table cellspacing='5' cellpadding='9' border='0' class='tab1_div'><tr><td valign='middle' align='left' class='td_nor'>Carregando... <center><img src='../../imagens/loading.gif' width='25px'></center></table>"
}
	
	if(xmlhttp.readyState==4){	
     if(xmlhttp.status == 200){
                var texto=xmlhttp.responseText;
                if(texto.indexOf(" ")<0) texto=texto.replace(/\+/g," ");
                //texto=unescape(texto); //descomente esta linha se tiver usado o urlencode no php ou asp
             
                extraiScript(texto);
            }

switcher.innerHTML=xmlhttp.responseText;
}
}
function ajax_id2(){
	var switcher2 = document.getElementById(id_id_fixo2);
	if(xmlhttp2.readyState<=3){
switcher2.innerHTML2= "<table cellspacing='5' cellpadding='9' border='0' class='tab1_div'><tr><td valign='middle' align='left' class='td_nor'>Carregando... <center><img src='../../imagens/loading.gif' width='25px'></center></table>"
}
	
	if(xmlhttp2.readyState==4){	
     if(xmlhttp2.status == 200){
                var texto2=xmlhttp2.responseText;
                if(texto2.indexOf(" ")<0) texto2=texto2.replace(/\+/g," ");
                //texto=unescape(texto); //descomente esta linha se tiver usado o urlencode no php ou asp
                  extraiScript(texto2);
            }

switcher2.innerHTML=xmlhttp2.responseText;
}

}
function ajax_id_simples(){
	var switcher = document.getElementById(id_id_fixo);
	
	if(xmlhttp.readyState==4){	
     if(xmlhttp.status == 200){
                var texto=xmlhttp.responseText;
                if(texto.indexOf(" ")<0) texto=texto.replace(/\+/g," ");
                //texto=unescape(texto); //descomente esta linha se tiver usado o urlencode no php ou asp
             
                extraiScript(texto);
            }


switcher.innerHTML=xmlhttp.responseText;

}

}

function mostra_id(id)
{
	if (document.getElementById(id).style.display == "none")
	{
		document.getElementById(id).style.display = "inline";
	}
	else
	{
		document.getElementById(id).style.display = "none";
	if (typeof(black_div)!="undefined"){	
	if (black_div=="x"){ef_black2()} else {black_div="x";} }
	
		if (typeof(white_div)!="undefined"){	
	
		if (white_div=="x"){geral_ef2()}}
	}	
}
// mostra ou oculta uma determinada tag pelo seu ID, e aplica o efeito de fade
function mostra_ef_id(id)
{
	if (document.getElementById(id).style.display == "none")
	{
		Effect.BlindDown(id);
		//document.getElementById(id).style.display = "inline";
	
	Effect.Fade('geral', {to: 0.3});
  //Effect.SwitchOff('geral');
		//document.getElementById("geral").switchOff();
		// document.getElementById("geral").style.display="inline-block";
		//document.getElementById("geral").onclick=alert('xxx');return false;
	}
	else
	{
		
		document.getElementById(id).style.display = "none";
		Effect.Appear('geral', {to: 1});
		//document.getElementById("geral").onclick=alert('xxx');return false;
	}	
}

function geral_ef1()
{	
	white_div="x"
	Effect.Fade('geral', {to: 0.3});
	

}
function geral_ef2()
{	
white_div=""
Effect.Appear('geral', {to: 1});

}
function ef1(div_show)
{	//alert("dsds")	

	document.getElementById(div_show).style.height = "450px"
	document.getElementById(div_show).style.width = "960px" 
	Effect.BlindDown(div_show);
	Effect.Appear(div_show, {duration:2.0 ,from: 0.0,to: 0.95})
;
//Effect.Appear(div_show, {to: 1});
//Effect.Appear(div_show, {duration:1.0 ,from: 0.0,to: 0.5}); return false;
}

function ef_black1()
{
	if ( typeof(black_div)=="undefined"  || black_div==""){
	document.getElementById('black').style.height = pag_size()[1]+"px"
	document.getElementById('black').style.width = pag_size()[0]+"px" 
	black_div="x"
	Effect.Appear('black', {duration:1.0 ,from: 0.0,to: 0.6}); return false;
	}else
{black_div="y";}
	}

	function ef_black2()
{
		black_div=""
new Effect.Appear('black', {duration:0.5, to: 0.0}); 
var xxxx = function testexx (){document.getElementById('black').style.display = "none";}
setTimeout(xxxx, 1000)
}

// funcao para popup
function popExec( URLStr, w, h )
{
	var left = (screen.width / 2) - (w / 2);
	var top = (screen.height / 2) - (h / 2);
    window.open(URLStr, 'VARExe', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=no,width='+w+',height='+h+',left='+left+', top='+top+'');
}


// funcao para tooltips, carrega uma div na posicao atual do mouse
function show_usuarios(event,id_perfil,div,larg_div,urlx){
	
xmlhttp = GetXmlObject()
if (xmlhttp==null){
alert('Seu navegador não suporta Ajax');
return;
}
id_id_fixo=div

if (typeof(urlx)=="undefined"){url=div;}
else{
if (urlx==""){url=div}
else{
	url=urlx;
	}}

var url2=url+'.asp';
url2 = url2+"?id_perfil="+id_perfil
url2 = url2+"&tm="+Math.random();
xmlhttp.onreadystatechange=ajax_id;
xmlhttp.open("GET",url2,true);
xmlhttp.send(null);
tool_tip_div(event,id_id_fixo,larg_div)
ef_black1()

}




function ajax_geral(idx,div,n_par,urlx){
xmlhttp = GetXmlObject()

id_id_fixo=div
if (typeof(urlx)=="undefined"){url=div}
else{
if (urlx==""){url=div}
else{url=urlx}}
var url2=url+'.asp';
url2 = url2+"?idx="+idx
if (typeof(n_par)!="undefined"){
	n_par = n_par.split(',');
	//alert(n_par.length)
	
	for (i=0; i<n_par.length-1;i++)
	{
		
	url2 = url2+"&par"+ i +"="+document.getElementById(n_par[i]).value
	}
}
url2 = url2+"&tm="+Math.random();
xmlhttp.onreadystatechange=ajax_id;
xmlhttp.open("GET",url2,true);
xmlhttp.send(null);

}


function ajax_geral2(idx,div,n_par,urlx){
xmlhttp2 = GetXmlObject()

id_id_fixo2=div
if (typeof(urlx)=="undefined"){url=div}
else{
if (urlx==""){url=div}
else{url=urlx}}
var url2=url+'.asp';
url2 = url2+"?idx2="+idx
if (typeof(n_par)!="undefined"){
	n_par = n_par.split(',');
	//alert(n_par.length)
	
	for (i=0; i<n_par.length-1;i++)
	{
		
	url2 = url2+"&par2"+ i +"="+document.getElementById(n_par[i]).value
	}
}
url2 = url2+"&tm="+Math.random();
xmlhttp2.onreadystatechange=ajax_id2;
xmlhttp2.open("GET",url2,true);
xmlhttp2.send(null);

}

// funcao para carregar popups, depende da popExec
function altera_pop(cd,urlx,xx,yy)
{	 
		var urlstr = urlx+'.asp?cd='+cd;
		popExec(urlstr,xx,yy);
}


function mostra_menu(){
	
	
	if (document.getElementById('td_menu').style.display=="none"){
		document.getElementById('td_menu2').style.width = 160+'px';
	document.getElementById('td_menu').style.display="inline";
	document.getElementById('menu_show').innerHTML="(-) Ocultar Menu";}
	else {
		document.getElementById('td_menu2').style.width = 1+'px';
	document.getElementById('td_menu').style.display="none";
	document.getElementById('menu_show').innerHTML="(+) Mostrar Menu";
}	}

function extraiScript(texto){
//Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
//http://forum.imasters.com.br/index.php?showtopic=165277&
    // 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 tool_tip_div(event,div_mov,larg_div){
	
	if (typeof(larg_div)=="undefined"){
		var ajuste=10
		}
		else{
		if (larg_div==""){var ajuste=10}
		else{
		var ajuste = (1*larg_div+30)*(-1)
		document.getElementById(div_mov).style.width = larg_div+'px';
		}
		}
	
mouse_xy(event)
_x=_x-9
_y=_y-9

document.getElementById(div_mov).style.top = _y+'px';
document.getElementById(div_mov).style.left = (_x+ajuste)+'px';
document.getElementById(div_mov).style.display="block";

}
function box_new(event,valor,id_campo,div_url){
	if (valor=="0")
	{
		show_usuarios(event,id_campo,div_url,'350');
		
	}
	else 
	
	{
		
		
		
			}
		
		}
	
function mouse_xy(event){
	
var marginX = 2; //distancia do mouse em x
var marginY = 2; //distancia do mouse em y
var opacity = 75; // 0 a 100
 _x = -1;
 _y = -1;
var padding = "2px 5px";
var position = "absolute";
var lar_janela = document.body.clientWidth || innerWidth

	if (document.all) {//IE
		_x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
		_y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		_x += (window.event.clientX+marginX);
		_y += (window.event.clientY+marginY);
	} else {//Good Browsers
		_x = (event.pageX+marginX);
		_y = (event.pageY+marginY);
	}


}
function IsDate(day, month, year) {
	//IsDate(29, 2, 2005)
	//IsDate(29, 2, 2004)
	var date = new Date();
	var blnRet = false;
	var blnDay;
	var blnMonth;
	var blnYear;

	date.setFullYear(year, month -1, day);

	blnDay   = (date.getDate()      == day);
	blnMonth = (date.getMonth()     == month -1);
	blnYear  = (date.getFullYear()  == year);

	if (blnDay && blnMonth && blnYear)
	blnRet = true;

	return blnRet;
}
function autoTab(input,len, e) {
	var isNN = (navigator.appName.indexOf("Netscape")!=-1);
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;
}

function auto_tab(ini,len,itemx){
	
if (ini.value.length==len){document.getElementById(itemx).focus()}
}
function pag_size()
{
	        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	}
      function ob_resolucao(idxx){ 
		if(document.getElementById("id_sts_oc"+idxx).value == '2')
		{
			if(document.getElementById("resolucao"+idxx).value == '')
			{
			alert("Para colocar o status resolvido, preencha a resolução !")
				return false;
			}
			else{
			return valida();}
		}else{
			return valida();}
		 
		 } 
		 
		    function ob_sts2(idxx){ 
			 	if(document.getElementById("id_sts_oc2"+idxx).value != '1' && document.getElementById("id_sts_oc2"+idxx).value != '')
		{ if(document.getElementById("id_rede"+idxx).value == '' || document.getElementById("id_rede"+idxx).value == '' || document.getElementById("ddata_cons"+idxx).value == '' || document.getElementById("mdata_cons"+idxx).value == '' || document.getElementById("ydata_cons"+idxx).value == '' || document.getElementById("hhora_cons"+idxx).value == '' || document.getElementById("thora_cons"+idxx).value == '')
		{alert("Escolha uma opção da Rede Credenciada, e coloque a data e o horario.")
		return false;}
		
		}
			
		if(document.getElementById("id_sts_oc"+idxx).value == '2')
		{
			if(document.getElementById("id_sts_oc2"+idxx).value == '4' || document.getElementById("id_sts_oc2"+idxx).value == '5')
			{
					//if(document.getElementById("id_aval"+idxx).value == '' )
					//{alert("Para colocar o status resolvido, preencha a Avaliação !")
				//return false;}
				//else{
				return valida();//}
			
			}
			else{alert("Para colocar o status resolvido, preencha o Status da consulta c/ Relizado ou Não Realizado !")
				return false;
			}
		}else{
			return valida();}
		 
		
		 
		
		} 
		// Drag and drop
		  var objSelecionado = null;
var mouseOffset = null;
function addEvent(obj, evType, fn) { //Função adaptada da original de Christian Heilmann, em http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4. html
if (typeof obj == "string") {
  if (null == (obj = document.getElementById(obj))) {
   throw new Error("Elemento HTML não encontrado. Não foi possível adicionar o evento.");
  }
}
if (obj.attachEvent) {
  return obj.attachEvent(("on" + evType), fn);
} else if (obj.addEventListener) {
  return obj.addEventListener(evType, fn, true);
} else {
  throw new Error("Seu browser não suporta adição de eventos.");
}
}
document.onmousemove = function(ev) {
var ev = ev || window.event;
var mousePos = mouseCoords(ev);
if (objSelecionado) {
  document.getElementById(objSelecionado).style.left = mousePos.x - mouseOffset.x + 'px';
  document.getElementById(objSelecionado).style.top = mousePos.y - mouseOffset.y + 'px';
  document.getElementById(objSelecionado).style.margin = '0px';
  return false;
}
}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
  return {x:ev.pageX, y:ev.pageY};
}
return {
  x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
  y:ev.clientY + document.body.scrollTop  - document.body.clientTop
};
}
function getPosition(e, ev){
e = document.getElementById(e);
var left = 0;
var top  = 0;
var coords = mouseCoords(ev);
while (e.offsetParent){
  left += e.offsetLeft;
  top  += e.offsetTop;
  e     = e.offsetParent;
}
left += e.offsetLeft;
top  += e.offsetTop;
return {x: coords.x - left, y: coords.y - top};
}
document.onmouseup = function() {
//a//lert('dsdsd')
objSelecionado = null;
}
function dragdrop(local_click, caixa_movida) {
document.getElementById(local_click).style.cursor = 'move';
addEvent(local_click, 'mousedown', function(ev) {
  objSelecionado = caixa_movida;
  mouseOffset = getPosition(caixa_movida, ev);
});
}
  function dragdrop2(caixa_movida, ev) {
//alert("dsdsd")
  objSelecionado = caixa_movida;
  mouseOffset = getPosition(caixa_movida, ev);

}
