function criaxmlhttp() {
   try {
      xmlhttp = new XMLHttpRequest();
   } catch(ee) {
      try {
         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(e) {
         try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(E) {
            xmlhttp = false;
        }
      }
   }
   return xmlhttp;
}
function leCodigo(url, div, limpa_c, textarea) {
   a = criaxmlhttp();
   var checa = url.split('?');
    tinymceDeactivate();
//   if (textarea != '') unsetTextareaToTinyMCE(textarea);
   if (limpa_c == 'S') document.getElementById('complemento').innerHTML = '';
   document.getElementById('extra').innerHTML = "<img src=\"progress.gif\" alt=\"\" />";
   url += "timestamp="+new Date().getTime();
   a.open("GET", url, true);
   a.onreadystatechange=function() {
      if (a.readyState==4) {
         if (a.status == 200) {
            var c=document.getElementById(div)
            var aDados= a.responseText;
            c.innerHTML = aDados;
            if (textarea != '') setTextareaToTinyMCE(textarea);
            var aju = document.getElementsByTagName("b");
            var valor = aju.length;
            for (i=0;i<valor;i++) { 
                var aux = aju[i].id;
                var aux1 = aux.split("_");
                var nomelay = aux + "a";
                if (aux1[0] == 'info') ajuda(aju[i].innerHTML,nomelay,aux);
            }
			c_form = document.getElementById('form_cad');
            if (c_form) document.form_cad.elements[0].focus();
            document.getElementById('extra').innerHTML = "";
         }
      }
   }  
   xmlhttp.send(null)
}

function grava(theform,rotina,textarea) {
    criaxmlhttp();
//	var theform = document.form_cad;
    if (document.getElementById('mensagem')) document.getElementById('mensagem').value = "Gravando ...";
	var checa = rotina.split('?');
	var url='';
	if (typeof(checa[1]) != 'undefined') url = rotina+'&'; 
    else url = checa[0]+"?";
    for (i=0;i<theform.length;i++) {
	  if (document.form_cad.elements[i].type == 'radio') { 
	     if (document.form_cad.elements[i].checked == true)
		    url = url + document.form_cad.elements[i].name + "=" + document.form_cad.elements[i].value + "&";
		    continue;
	     } else if (document.form_cad.elements[i].type == "checkbox") {
	        if (document.form_cad.elements[i].checked == true)
		    url = url + document.form_cad.elements[i].name + "=" + document.form_cad.elements[i].value + "&";
		    continue;
         } else {
	       url = url + document.form_cad.elements[i].name + "=" + (document.form_cad.elements[i].name != textarea ? url_encode(document.form_cad.elements[i].value) : url_encode(tinyMCE.getContent(textarea))) + "&";
	  }
    }	
    url += "timestamp="+new Date().getTime();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState==4) {
          var aDados=eval((xmlhttp.responseText));
	      if (aDados[0] == 1) {
             document.form_cad.mensagem.value = aDados[1];
             document.form_cad.elements[0].focus();
          }
	      if (aDados[0] == 0) {
             alert(aDados[1]);
			 document.form_cad.mensagem.value = '';
             document.form_cad.elements[0].focus();
             return;
          }
		  if (checa[0] == 'q_grava_questionario.php') {
		  	 leCodigo('q_questionario_i.php?','resposta','S');
		  }
		  if (checa[0] == 'q_grava_pergunta.php') {
	         var chave = document.form_cad.elements[0].value;
			 leCodigo('q_pergunta.php?chave_quest='+chave+'&','resposta','S',textarea);
		  	 q_cons_perguntas(chave);
		  }	 
		  if (checa[0] == 'q_grava_resposta.php') {
	         var chave_quest = document.form_cad.elements[0].value;
	         var chave_perg = document.form_cad.elements[1].value;
			 leCodigo('q_resposta.php?chave_quest='+chave_quest+'&chave_perg='+chave_perg+'&','resposta','S', textarea);
		  	 q_cons_respostas(chave_quest,chave_perg);
		  }	 
		  if (checa[0] == 'q_grava_gabarito.php') {
	         var chave = document.form_cad.elements[0].value;
			 leCodigo('q_gabarito.php?chave_quest='+chave+'&','resposta','S',textarea);
		  	 q_cons_gabarito(chave);
		  }	 
		  if (checa[0] == 'q_grava_solucao.php') {
	         var chave = document.form_cad.elements[0].value;
			 leCodigo('q_solucao.php?chave_quest='+chave+'&','resposta','S',textarea);
		  }	 
		  var lim = theform.length - 3;
		  for (i=0;i<lim;i++) {
             document.form_cad.elements[i].value = '';
		  }
	   }
	}
    xmlhttp.send(null)
}

function deleta(chave,tipo) {
   criaxmlhttp();   
   document.getElementById('extra').innerHTML = "<img src=\"progress.gif\" alt=\"\" /> ";
   var url = "q_deleta.php?chave="+chave+"&tipo="+tipo+"&timestamp="+new Date().getTime();
   xmlhttp.open("GET", url, true);
   xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
         if (xmlhttp.status == 200) {
            var aDados=eval((xmlhttp.responseText));
	        if (aDados[0] == 1) {
			   alert(aDados[1]);
			}
		    if (tipo == 'Q') {
		  	   leCodigo('q_questionario_i.php?','resposta');
		       document.getElementById('complemento').innerHTML = '';
		    }
		    if (tipo == 'P') {
		  	   q_cons_perguntas(aDados[2]);
		    }
		    if (tipo == 'R') {
		  	   q_cons_respostas(aDados[2],aDados[3]);
		    }
         }
      }
   }  
   xmlhttp.send(null)
}
function get_focus(campo) {
	document.getElementById(campo).focus();
}

function valida_campo(p1, p2, p3, p4, p5) {
    criaxmlhttp();
    var mens = document.getElementById('mensagem');
    mens.value = '';
    var url = "verifica_campo.php?id="+p1+"&tp_obg="+p2+"&tp_num="+p3+"&funcao="+p4+"&timestamp="+new Date().getTime();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) {
           if (xmlhttp.status == 200) {   
              var resposta = url_decode(xmlhttp.responseText);
              var aDados=resposta.split('^');
		  // Verifica a Resposta
		   if (aDados[0] == '0') {
		      for (var i=1;i<aDados.length;i++) {
		        aDados[i]= aDados[i];
		        document.form_cad.elements[i].value = aDados[i];
		     }
	       }
		   if (aDados[0] == '1') {
		      mens.value = url_decode(aDados[1]);
		      get_focus(p5); 
			  return false;
		   }
           if (aDados[0] == '2') {
              mens.value = url_decode(aDados[1]);
           }
	    }	  
     }
   }
   xmlhttp.send(null)
}
    // url_encode version 1.0 
function url_encode(str) { 
   var hex_chars = "0123456789ABCDEF"; 
   var noEncode = /^([a-zA-Z0-9\_\-\.])$/; 
   var n, strCode, hex1, hex2, strEncode = ""; 

   for(n = 0; n < str.length; n++) { 
      if (noEncode.test(str.charAt(n))) { 
         strEncode += str.charAt(n); 
      } else { 
         strCode = str.charCodeAt(n); 
         hex1 = hex_chars.charAt(Math.floor(strCode / 16)); 
         hex2 = hex_chars.charAt(strCode % 16); 
         strEncode += "%" + (hex1 + hex2); 
      } 
   } 
   return strEncode; 
} 

function url_decode(str) { 
    var n, strCode, strDecode = ""; 

    for (n = 0; n < str.length; n++) { 
        if (str.charAt(n) == "%") { 
            strCode = str.charAt(n + 1) + str.charAt(n + 2); 
            strDecode += String.fromCharCode(parseInt(strCode, 16)); 
            n += 2; 
        } else { 
            strDecode += str.charAt(n); 
        } 
    } 
    return strDecode; 
}
function buscaPerg(chave_quest,gabarito){
    criaxmlhttp();

    //limpa o select
    var c=document.getElementById("pergunta")
    while(c.options.length>0) c.options[0]=null
    c.options[0]=new Option(" -- Aguarde ... -- "," -- Aguarde ... -- ")
    
	url = "q_buscaperg.php?chave_quest="+chave_quest;
	if (gabarito) url += "&gabarito="+gabarito;

    //Monta a url com as perguntas
    xmlhttp.open("GET", url ,true);

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            //limpa o select
            var c=document.getElementById("pergunta")
            while(c.options.length>0)c.options[0]=null
            //Transforma a lista de perguntas JSON em Javascript
            var aPerg = eval((xmlhttp.responseText))
            //popula o select com a lista de perguntas obtida
            for (var i=0;i<aPerg.length;i+=2) {
                aPerg[i]=unescape(aPerg[i])
                c.options[c.options.length]=new Option(aPerg[i+1],aPerg[i])
            }
			if (gabarito) q_cons_gabarito(chave_quest);
        }
    }

    xmlhttp.send(null)
}
function buscaSolucao(chave_quest,chave_perg) {
   criaxmlhttp();   
   document.getElementById('extra').innerHTML = "<img src=\"progress.gif\" alt=\"\" /> ";
   var url = "q_buscasolucao.php?chave_quest="+chave_quest+"&chave_perg="+chave_perg+"&timestamp="+new Date().getTime();
   xmlhttp.open("GET", url, true);
   xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
         if (xmlhttp.status == 200) {
            var aDados=eval((xmlhttp.responseText));
	        if (aDados[0] == 1) {
			   alert(aDados[1]);
			   return
			}
			tinyMCE.setContent(aDados[1]);
			document.form_cad.publica.value = aDados[2];
            document.getElementById('extra').innerHTML = "";
			q_cons_respostas(chave_quest,chave_perg,'');
         }
      }
   }  
   xmlhttp.send(null)
}

function q_cons_perguntas(quest) {
	criaxmlhttp();
    document.getElementById('complemento').innerHTML = "<img src=\"progress.gif\" alt=\"\" />";
	
	var url = 'q_consulta_perguntas.php?';
	url += 'quest=' + quest + "&";
    url += "timestamp="+new Date().getTime();
 
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange=function() {
       if (xmlhttp.readyState==4) {
          var aDados = xmlhttp.responseText;
          var c=document.getElementById('complemento');
          c.innerHTML = aDados;
          document.form_cad.elements[0].focus();
       }
   }
   xmlhttp.send(null)
}

function q_cons_respostas(quest,perg,gabarito) {
	criaxmlhttp();
    document.getElementById('complemento').innerHTML = "<img src=\"progress.gif\" alt=\"\" />";
	
	var url = 'q_consulta_respostas.php?';
	url += 'quest=' + quest + "&perg=" + perg + "&gabarito=" + gabarito + "&";
    url += "timestamp="+new Date().getTime();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange=function() {
       if (xmlhttp.readyState==4) {
          var aDados = xmlhttp.responseText;
          var c=document.getElementById('complemento');
          c.innerHTML = aDados;
          document.form_cad.elements[0].focus();
       }
    }
    xmlhttp.send(null)
}
function q_gabarito(quest,perg,resp,totalResp,item_r,marcado,gabarito) {
	criaxmlhttp();
    document.getElementById('r['+item_r+']').innerHTML = "<img src=\"progress.gif\" alt=\"\" />";
	
	var url = 'q_grava_gabarito.php?';
	url += 'quest=' + quest + "&perg=" + perg + "&resp=" + resp + "&marcado=" + marcado + "&";
    url += "timestamp="+new Date().getTime();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange=function() {
       if (xmlhttp.readyState==4) {
          var aDados = xmlhttp.responseText;
		  for (i=1;i<=totalResp;i++) {
              document.getElementById('r['+i+']').innerHTML = '';
		  }  
          var c=document.getElementById('r['+item_r+']');
          if (marcado == 'N') c.innerHTML = "<img src=image/apply.gif />";
		  if (gabarito != 'undefined') q_cons_gabarito(quest)
		  else q_cons_respostas(quest,perg);
       }
    }
    xmlhttp.send(null)
}
function q_cons_gabarito(quest) {
	criaxmlhttp();
    document.getElementById('complemento').innerHTML = "<img src=\"progress.gif\" alt=\"\" />";
	
	var url = 'q_consulta_gabarito.php?';
	url += 'quest=' + quest + "&";
    url += "timestamp="+new Date().getTime();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange=function() {
       if (xmlhttp.readyState==4) {
          var aDados = xmlhttp.responseText;
          var c=document.getElementById('complemento');
          c.innerHTML = aDados;
       }
    }
    xmlhttp.send(null)
}
function resultado(theform,rotina,textarea) {
	var checa = rotina.split('?');
	var url='';
	if (typeof(checa[1]) != 'undefined') url = rotina+'&'; 
    else url = checa[0]+"?";
    for (i=0;i<theform.length;i++) {
	  if (theform.elements[i].type == 'radio') { 
	     if (theform.elements[i].checked == true)
		    url = url + theform.elements[i].name + "=" + theform.elements[i].value + "&";
		    continue;
	     } else if (theform.elements[i].type == "checkbox") {
	        if (theform.elements[i].checked == true)
		    url = url + theform.elements[i].name + "=" + theform.elements[i].value + "&";
		    continue;
         } else {
	       url = url + theform.elements[i].name + "=" + (theform.elements[i].name != textarea ? url_encode(theform.elements[i].value) : url_encode(tinyMCE.getContent(textarea))) + "&";
	  }
    }	
    url += "timestamp="+new Date().getTime();
    window.open(url,"Resultado da Avaliação", "scrollbars=yes,toolbar=no,menubar=no,width=800,height=500,resizable=yes")
}
function fechar() {
    leCodigo('q_questionario_i.php?','resposta','S');
}
var activatedAreas = new Array();   
 
function setTextareaToTinyMCE(sEditorID) 
{
  var oEditor = document.getElementById(sEditorID);
    if(oEditor) 
  {
    if(activatedAreas[sEditorID] == true)
      unsetTextareaToTinyMCE(sEditorID);
    try {
      activatedAreas[sEditorID] = true;
      tinyMCE.execCommand("mceAddControl", true, sEditorID);                    
    }
    catch(e)
    {
      alert("Error activating element " + sEditorID + "\n" + e);
    }
  }
}
 
function unsetTextareaToTinyMCE(sEditorID) 
{
  var oEditor = document.getElementById(sEditorID);
  if(oEditor && (activatedAreas[sEditorID] == true)) 
  {
    try 
   {
      tinyMCE.execCommand("mceRemoveControl", true, sEditorID);
      activatedAreas[sEditorID] = false;
    }
    catch(e)
    {
      alert("Error deactivating element " + sEditorID + "\n" + e);
    }
  }
}
 
function tinymceDeactivate() {
  
  for(var i in activatedAreas)
  {
    if(activatedAreas[i] == true) 
    {
       unsetTextareaToTinyMCE(i);
    }
  }
}
function hidelayer(lay) {
	if (document.getElementById(lay)) document.getElementById(lay).style.visibility = "hidden";
}

function showlayer(lay) {
	if (document.getElementById(lay)) document.getElementById(lay).style.visibility = "visible";
}
	
image3 = new Image();
image3.src = "image/help.gif";

function ajuda(msg,nomeDoLayer,aux) {
	document.getElementById(aux).innerHTML = '<span class=\"janela-ajuda\" style=\"position: absolute;\" id=\"'+nomeDoLayer+'\">'+msg+'</span>'
	+ '<span class=\"janela_img\" onmouseout=\"hidelayer(\''+nomeDoLayer+'\');image3.src=\'image/help.gif\';\" onmouseover=\"showlayer(\''+nomeDoLayer+'\');image3.src=\'image/help.gif\';\"><img src=\"image/help.gif\" name=\"image3\" width=\"15\" height=\"15\" border=\"0\"></span>'; 
	hidelayer(nomeDoLayer); 
}