


function openWindow(url,name,width,height,toolbar,directories,status,menubar,scrollbars,resizable) {
	win = open(url,name,"width="+width+",height="+height+",toolbar="+toolbar+",directories="+directories+",status="+status+",menubar="+menubar+",scrollbars="+scrollbars+",resizable="+resizable);
}

function menu(item,action,item2) {
	if(action=='show'){ 
		document.getElementById(item).style.display='block'; 
		document.getElementById(item2).style.display='none'; 
	}else{ 
		document.getElementById(item).style.display='none';
		document.getElementById(item2).style.display='block';
	} 
}



function showDiv(area) {
	if(document.getElementById(area).style.display=='none'){
		document.getElementById(area).style.display='block';
	}else{
		document.getElementById(area).style.display='none';
	}
}

//***************************************
//Mostra / Oculta os selects da página
//***************************************
function selectsVisibility(varVisible){
	for (j=0 ; j<document.forms.length ; j++){
	  for (i=0; i<document.forms[j].elements.length ; i++){
		if (document.forms[j].elements[i].type == 'select-one'){
	    	if(varVisible==0){
			   document.forms[j].elements[i].style.visibility = 'hidden';
			}else if(varVisible==1){
			   document.forms[j].elements[i].style.visibility = 'visible';
			}
		}
	  }
	}
}



//***************************************
//
//***************************************



function getFrameAnswer(){
	if(document.getElementById("iframeRequest").readyState=="complete"){
		var objXML = new ActiveXObject("Microsoft.XMLDOM");
	
		objXML.loadXML(frames["iframeRequest"].document.body.innerText);
		if(objXML.documentElement.childNodes.length){
			document.getElementById("divMessage").innerText="";
			document.getElementById("divMessage").style.display="none";
			document.getElementById("btnActivate").disabled=false;
			
			var varExpDate=objXML.documentElement.childNodes[0].getAttribute("expireDate");
			
			document.getElementById("txtExpiration").value=varExpDate%100+"/"+Math.floor(varExpDate/100)%100+"/"+Math.floor(varExpDate/10000);
			document.getElementById("txtCourse").value=objXML.documentElement.childNodes[0].getAttribute("course");
			document.getElementById("txtKeyId").value=objXML.documentElement.childNodes[0].getAttribute("id");
		}else{
			document.getElementById("divMessage").innerHTML="<table border=0><tr><td valign=middle><img src=/contents/home/erro.gif></td><td valign=middle style='color:#FFFFFF;font-weight:bold;'>&nbsp;Esta chave de acesso é inválida!</td></tr></table>";
			document.getElementById("divMessage2").innerHTML="<div style=background-color:#FFFFCC;width:620px;>Verifique se digitou corretamente a chave que consta na página 3 do livro.<br><br><b><font color=red>Atenção:</font></b>&nbsp;&nbsp;Não confunda número 0 com a letra O, número 1 com a letra I, número 4 com a letra A e número 6 com a letra G.</div>";
			document.getElementById("divMessage").style.display="";
			document.getElementById("btnActivate").disabled=true;
		}
	}
}

function createIFrame(){
	var objIFrame=document.createElement("iframe");
	objIFrame.setAttribute("id","iframeRequest");
	objIFrame.setAttribute("name","iframeRequest");
	document.getElementsByTagName("body")[0].appendChild(objIFrame);
	document.getElementById("iframeRequest").style.width=document.getElementById("iframeRequest").style.height=0;
	document.getElementById("iframeRequest").style.display="none";
}

function searchKey(obj){
	if((obj.id == "txt_chave_05") && (obj.value.length == 8)){
		var varKey = document.getElementById("txt_chave_01").value+""+document.getElementById("txt_chave_02").value+""+document.getElementById("txt_chave_03").value+""+document.getElementById("txt_chave_04").value+""+document.getElementById("txt_chave_05").value;
		
		document.getElementById("iframeRequest").onreadystatechange=getFrameAnswer;
		document.getElementById("iframeRequest").src="/asp/keyadmin/getkeyinfo.asp?key="+varKey;
	}else{
		document.all.txtCourse.value="";
		document.all.txtExpiration.value="";
		document.getElementById("btnActivate").disabled=true;
	}
}


//** Variável Gambeteishons criada pelo rafinha pra controlar o submit dos campos WYSIWYG
var varDoSubmitWYSIWYGForm=false;



//***************************************
//Abrir imagens
//***************************************
	  function open_kortti(image) {
	    var hh=320 , ww=370
	    var leftPos = (screen.width - ww) / 2;
	    var topPos = (screen.height - hh) / 2;
	    photoWin = window.open( "", "photo","width=" + ww +",height=" + hh +",status=0,scrollbars=1,resizable=1,screenX=20,screenY=40,left=20,top=40");
	    photoWin.document.write('<html><head><title>Thumbnail</title></head>');
	    photoWin.document.write('<link rel="stylesheet" href="/LIB/site.css" type="text/css">');
	    photoWin.document.write('<BODY BGCOLOR=#ffffff>');
	    photoWin.document.write('<center><img src="' + image + '"></center>');
	    photoWin.document.write('<div align="right"><br><br><a style="font: bold 11px Verdana,Arial" href="Javascript:window.close();"><b>fechar</b></a></div>');
	    photoWin.document.write('</body></html>');
	    photoWin.document.focus();
	    photoWin.document.close();
	   // If we are on NetScape, we can bring the window to the front
	  	if (navigator.appName.substring(0,8) == "Netscape") photoWin.focus();
	  }


//***************************************
//Validar formulário de login
//***************************************
function validaForm(Formulario){
	var err_str = '';
	if (Formulario.username.value == ''){
		err_str += '- você deve preencher o campo "Login"\n';
	}
	if (Formulario.password.value == ''){
		err_str += '- você deve preencher o campo "Senha"\n';
	}
	if (err_str != ''){
		alert('Ocorreram os seguintes erros no preenchimento do formulário: \n\n' + err_str + '\ncorrija-os e tente novamente.');
		return false;
	}
	//setTimeout('trocaValores(Formulario)',15000);
}
function trocaValores(Formulario2){
	 Formulario2.username.value=' login'; 
	 Formulario2.password.value='senha';
}
function validaForm2(Form){
	var err='';
	if (Form.username.value == '')
		err += '- o campo "Login" não foi preenchido. \n';
	if (Form.senha_atual.value =='')
		err += '- o campo "Senha atual" não foi preenchido. \n';
	if (Form.senha_nova.value =='')
		err += '- o campo "Senha Nova" não foi preenchido. \n';
	if (Form.senha_nova_conf.value =='')
		err += '- o campo "Confirmar Senha" não foi preenchido. \n';
	if (Form.senha_nova.value.length < 6)
		err += '- a nova senha cadastrada deve conter, no mínimo, 6 dígitos. \n';
	if (Form.senha_nova.value == Form.senha_nova_conf.value){
	  if(Form.senha_nova.value == Form.senha_atual.value)
  	  err += '- os campos "Senha atual" e "Nova senha" não podem ser iguais. \n';
  }  	  
  else
		err += '- as senhas digitadas nos campos "Senha Nova" e "Confirmar Senha" não conferem. \n';

	if (err){
		alert('Ocorreram os segunites erros no preenchimento do formulário: \n' + err + 'Corrija-os e tente novamente.');
		return false
	}
}

//***************************************
//Mostrar e Ocultar Objetos (tabelas, imagens, layers etc.) das páginas
//***************************************

function showmore(Atual,Total) {
  var el, i, d=document;
  IdItem='divConteudo';
  IdImagem='moreImage';
	if(d.getElementById) {
		// Netscape >6:
		if(d.getElementById(IdItem+Atual).style.display=="none"){
			varaction="open";
		}else{
			varaction="close";
		}
		for(i=0; i<Total; i++){
			el = d.getElementById(IdItem+i);
			el.style.display='none';
			
			el = d.getElementById(IdImagem+i);
			el.src='/contents/bullets/more.gif';
		}
		if(varaction=="open"){
			el = d.getElementById(IdItem+Atual);
			el.style.display='';
			
			el = d.getElementById(IdImagem+Atual);
			el.src='/contents/bullets/less.gif';
		}
	} else {
		if (d.layers) {
			// Netscape <6:
			for(i=0; i<d.layers; i++) {
				if (d.layers[i].id == IdItem[Atual]) {
			   		d.layers[i].display = "";
			 	}else{
					d.layers[i].display = "none";
				}
			}
		}else{
			// IE:
			if(IdItem[Atual].style.display=="none"){
				varaction="open";
			}else{
				varaction="close";
			}
			for(i=0; i<Total; i++){
				eval(IdItem+"["+i+"].style.display='none'");
				eval(IdImagem+"["+i+"].src='/contents/bullets/more.gif'");
			}
			eval(IdItem+"["+Atual+"].style.display=''");
			eval(IdImagem+"["+Atual+"].src='/contents/bullets/more.gif'");
		}
	}  
  }
//***************************************
//***************************************


function checkViewItem(totalQuestions,showPage,fcolor,id_curso) 
{
	
	var viewPage;
	var setCursor;
	
	viewPage=document.all("actual").value;
	
	//fecha item corrente - FF
	document.all("Q"+viewPage).style.display='none';
	document.all("P"+viewPage).style.cursor=setCursor='pointer';
	document.all("dvi_"+viewPage).style.backgroundImage='none';
	
	//inibe negrito do item corrente - FF
	document.all("P"+viewPage).style.color=fcolor;

	if (showPage=="back") {
		if(viewPage==1){
			viewPage=1;
			//FF
			document.all("back").style.cursor=setCursor='default';
			document.all("back").style.color='gray';
			document.all("next").style.cursor=setCursor='pointer';
			document.all("next").style.color=fcolor;
			
		} else {
			//FF
			viewPage=parseInt(document.all("actual").value)-1;
			document.all("back").style.cursor=setCursor='pointer';
			document.all("back").style.color=fcolor;
			document.all("next").style.cursor=setCursor='pointer';
			document.all("next").style.color=fcolor;
		}
		if(viewPage==1){
			//FF
			document.all("back").style.cursor=setCursor='default';
			document.all("back").style.color='gray';
		}
	} else if (showPage=="next"){
		if(document.all("actual").value==totalQuestions){
			viewPage=totalQuestions;
			//FF
			document.all("back").style.cursor=setCursor='pointer';
			document.all("back").style.color=fcolor;
			document.all("next").style.cursor=setCursor='default';
			document.all("next").style.color='gray';
		} else {
			//FF
			viewPage=parseInt(document.all("actual").value)+1;
			document.all("back").style.cursor=setCursor='pointer';
			document.all("back").style.color=fcolor;
			document.all("next").style.cursor=setCursor='pointer';
			document.all("next").style.color=fcolor;
		}
		if(viewPage==totalQuestions){
			//FF
			document.all("next").style.cursor=setCursor='default';
			document.all("next").style.color='gray';
		}
	} else {
		viewPage=showPage;
		
		if(viewPage==1){
			//FF
			document.all("back").style.cursor=setCursor='default';
			document.all("back").style.color='gray';
			document.all("next").style.cursor=setCursor='pointer';
			document.all("next").style.color=fcolor;
			
		} else if(viewPage==totalQuestions){
			//FF
			document.all("back").style.cursor=setCursor='pointer';
			document.all("back").style.color=fcolor;
			document.all("next").style.cursor=setCursor='default';
			document.all("next").style.color='gray';
		} else {
			//FF
			document.all("back").style.cursor=setCursor='pointer';
			document.all("back").style.color=fcolor;
			document.all("next").style.cursor=setCursor='pointer';
			document.all("next").style.color=fcolor;
		}
	}
	if (totalQuestions==1){
		//FF
		document.all("back").style.cursor=setCursor='default';
		document.all("back").style.color='gray';
		document.all("next").style.cursor=setCursor='default';
		document.all("next").style.color='gray';
	}
	
	//FF
	document.all("actual").value=viewPage;
	
	
	//abre item solicitado - FF
	document.all("Q"+viewPage).style.display='block';

	//altera fonte para negrito para item solicitado - FF
	
	//Se o curso for teens
	if (id_curso == 87) {
		document.all("P"+viewPage).style.color='#a70b0b';
	}
	else {
		document.all("P"+viewPage).style.color='gray';
	}
	document.all("P"+viewPage).style.cursor=setCursor='default';
	document.all("P"+viewPage).style.cursor=setCursor='default';
	document.all("dvi_"+viewPage).style.backgroundImage="url('/asp/activities/img/weblessons_rodape_seta_"+id_curso+".gif')";
	
}

//***************************************
//Mostrar e Ocultar itens de uma listagem
//***************************************
function mostraItem(area,valor,tot) {
	for (var i=0;i<tot;i++)
		fechaItem(eval(area+(i+1)));
		abreItem(eval(area+valor));
}
function fechaItem(obj) {
	obj.style.display='none';
}
function abreItem(obj) {
	obj.style.display='block';
}


//**************************************
//Função p/ mudar a image "Principais Executivos"
//**************************************


function changeImage(id_image){
  var img_src   = "var src = document.all."+id_image+".src";
  var img_mais  = "document.all."+id_image+".src='http://200.204.147.13/templates/sample/img/temp/mais.gif'";
  var img_menos = "document.all."+id_image+".src='http://200.204.147.13/templates/sample/img/temp/menos.gif'";
  execScript (img_src,"Javascript")
  if(src == 'http://200.204.147.13/templates/sample/img/temp/menos.gif'){
    execScript (img_mais,"Javascript")
  } else if (src == 'http://200.204.147.13/templates/sample/img/temp/mais.gif'){
    execScript(img_menos,"Javascript")
  }	
}	


  
//**************************************
// Checar formulário Trabalhe Conosco
//**************************************

function CheckTrabalhe() {
  if (document.Trabalhe.frm_name.value == "") {
  	alert("Por favor digite o seu NOME.");
  	document.Trabalhe.frm_name.focus();
  	return false;
	}
	if (document.Fale.frm_email.value.indexOf("@") == -1) {
  	alert("O seu e-mail está incorreto. O formato deve ser algo do tipo 'seunome@suaempresa.com'.");
  	document.Fale.frm_email.focus();
  	return false;
	}
return true;
}


//Replicar um valor em outro campo
function Preencher(formFill,formFill2) {
  if (formFill2.value == "") {
    formFill2.value = formFill.value;
  }
}


////////////////////////////////////////////////////////////////////
//Valida numeracao com caracteres
////////////////////////////////////////////////////////////////////

function ValidaConteudoCampo(intervalo,caracter){ 
//Autor: João Carlos B. Morgado (Advice Netbisiness) 
//Data: 23/10/2001 
//Descrição: Função para barra que seja digitado um conteúdo inválido no campo 
//intervalo = 'A..Z' ou se tiver mais de um, faz-se: 'A..Z;a..z' 
//caracter = '-/@!$' 
//ex.: <input type="text" name="questao1[]" size="1" onkeypress="JavaScript:ValidaConteudoCampo('1..5','NULL');"> 
 var bvalido = false; 
 if(((caracter.toUpperCase) != 'NULL') || (caracter != '')){ 
  if(caracter == "PONTUACAO"){caracter = 'ãáâéêíîõóôúûçÃÁÂÉÊÍÎÕÓÔÚÛÇ ';} 
  for(i=0;i<=(caracter.length);i++){ 
     if((event.keyCode) == (caracter.charCodeAt(i))){ 
      bvalido = true; 
     } 
   } 
 } 
 if(!bvalido){ 
  var Inicio    = ""; 
 var Fim    = ""; 
 var bRetornaFalso  = false; 
 var bEncontrou  = false; 
 var location   = -1; 
 location = intervalo.indexOf(";"); 
 if((location) > -1){ 
   var restricoes = intervalo.split(";"); 
  for(i=0;i<=(restricoes.length-1);i++){ 
   Inicio  = restricoes[i].substring(0,1); 
   Fim  = restricoes[i].substring(3,4); 
    if((event.keyCode >= Inicio.charCodeAt()) && (event.keyCode <= Fim.charCodeAt())){ //48 57 
    bEncontrou = true; 
    i = restricoes.length; 
     } 
  } 
  if(!bEncontrou){ 
   bRetornaFalso = true; 
  } 
 } 
 else if(intervalo.length == 4){ 
  Inicio  = intervalo.substring(0,1); 
  Fim  = intervalo.substring(3,4); 
   if((event.keyCode >= Inicio.charCodeAt()) && (event.keyCode <= Fim.charCodeAt())){ //48 57 
   bEncontrou = true; 
    } 
  if(!bEncontrou){ 
   bRetornaFalso = true; 
  } 
 } 
 if(bRetornaFalso){ 
  event.returnValue = false; 
 } 
} 
} 
//***********************************
//Função de validação de CPF
//***********************************

function isCPF(st) {
if (st == "") 
  return (false);
l = st.length;
//alterando para se usuário não digitar os zeros na frente do CPF, completar sozinho
if ((l == 9) || (l == 8))
{
	for (i = l ; i < 10; i++)
	{
		st = '0' + st
	}
}
l = st.length;
st2 = "";
for (i = 0; i < l; i++) {
  caracter = st.substring(i,i+1);
  if ((caracter >= '0') && (caracter <= '9'));
     st2 = st2 + caracter;
}
if ((st2.length > 11) || (st2.length < 10))
   return (false);
if (st2.length==10)
   st2 = '0' + st2;
digito1 = st2.substring(9,10);
digito2 = st2.substring(10,11);
digito1 = parseInt(digito1,10);
digito2 = parseInt(digito2,10);
sum = 0; mul = 10;
for (i = 0; i < 9 ; i++) {
    digit = st2.substring(i,i+1);
    tproduct = parseInt(digit ,10) * mul;
    sum += tproduct;
    mul--;
}
dig1 = ( sum % 11 );
if ( dig1==0 || dig1==1 )
   dig1=0;
else
  dig1 = 11 - dig1;
if (dig1!=digito1)
  return (false);
sum = 0;
mul = 11;
for (i = 0; i < 10 ; i++) {
    digit = st2.substring(i,i+1);
    tproduct = parseInt(digit ,10)*mul;
    sum += tproduct;
    mul--;
}
dig2 = (sum % 11);
if ( dig2==0 || dig2==1 )
  dig2=0;
else
  dig2 = 11 - dig2;  
if (dig2 != digito2)
  return (false);
return (true);
}  


//Limpar um campo
function Limpar(formClear) {
  if (formClear.value == "PROCURAR") {
    formClear.value = "";
  }
}






//Mouse over para alterar cor de celulas

function mOvr(src,clrOver) {
if (!src.contains(event.fromElement)) {
	src.bgColor = clrOver;
	}
}
function mOut(src,clrIn) {
if (!src.contains(event.toElement)) {
	src.bgColor = clrIn; 
	}
}


//<script LANGUAGE="JavaScript">


  function imgOn(image,imgName,dir) {
    document[image].src = dir + '/' + [imgName];
  }
  function imgOff(image,imgName,dir) {
    document[image].src = dir + '/' + [imgName];
  }


  // NOME : ampliar_foto
  // Descrição : Página para imagem de produtos ampliada
  // Parametros FileName    -> Nome da foto sem o caminho, sem a extensão e sem o sufixo G, 
  //                           que define qual o tamanho da foto a ser exibida
  // Parametros ProductName -> Nome do produto

  function Thumb(image) {
    var hh=320 , ww=370
    var leftPos = (screen.width - ww) / 2;
    var topPos = (screen.height - hh) / 2;
    photoWin = window.open( "", "photo","width=" + ww +",height=" + hh +",status=0,scrollbars=1,resizable=0,screenX=20,screenY=40,left=20,top=40");
    photoWin.document.write('<html><head><title>Thumbnail</title></head>');
    photoWin.document.write('<link rel="stylesheet" href="/LIB/site.css" type="text/css">');
    photoWin.document.write('<BODY BGCOLOR=#ffffff>');
    photoWin.document.write('<table width=330 height=280><tr><td height=240 valign=middle>');
    photoWin.document.write('<center><img src="' + image + '"></center>');
    photoWin.document.write('</td></tr><tr><td valign=bottom height=10>');
    photoWin.document.write('<div align="right"><br><br><a style="font: bold 11px Verdana,Arial" href="Javascript:window.close();"><b>fechar</b></a></div>');
    photoWin.document.write('</td></tr></table>');
    photoWin.document.write('</body></html>');
    photoWin.document.focus();
    photoWin.document.close();
   // If we are on NetScape, we can bring the window to the front
  	if (navigator.appName.substring(0,8) == "Netscape") photoWin.focus();
  }
  
  function open_kortti(image,cls,legend) {
  //alert(image +" - "+ cls + " - " + legend)
    if (legend == undefined) {
        var legend="";
    }
    var hh=450 , ww=480
    var leftPos = (screen.width - ww) / 2;
    var topPos = (screen.height - hh) / 2;
    photoWin = window.open( "", "photo","width=" + ww +",height=" + hh +",status=0,scrollbars=1,resizable=1,screenX=20,screenY=40,left=20,top=40");
    photoWin.document.write('<html><head><title>Thumbnail</title></head>');
    photoWin.document.write('<link rel="stylesheet" href="/LIB/site.css" type="text/css">');
    photoWin.document.write('<BODY BGCOLOR=#ffffff>');
    photoWin.document.write('<center><img src="' + image + '"></center>');
    photoWin.document.write('<div align="center"><br><br><a style="font: bold 11px Verdana,Arial"><b>'+legend+'</b></a></div>');
    photoWin.document.write('<div align="right"><br><br><a style="font: bold 11px Verdana,Arial" href="Javascript:window.close();"><b>'+cls+'</b></a></div>');
    photoWin.document.write('</body></html>');
    photoWin.document.focus();
    photoWin.document.close();
   // If we are on NetScape, we can bring the window to the front
  	if (navigator.appName.substring(0,8) == "Netscape") photoWin.focus();
  }
  // NOME : ampliar_foto
  // Descrição : Página para imagem de produtos ampliada
  // Parametros FileName    -> Nome da foto sem o caminho, sem a extensão e sem o sufixo G, 
  //                           que define qual o tamanho da foto a ser exibida
  // Parametros ProductName -> Nome do produto

  function Thumb2(image,w,h) {
    var hh=h , ww=w
    var leftPos = (screen.width - ww) / 2;
    var topPos = (screen.height - hh) / 2;
    photoWin = window.open( "", "photo","width=" + ww +",height=" + hh +",status=0,scrollbars=1,resizable=0,screenX=20,screenY=40,left=20,top=40");
    photoWin.document.write('<html><head><title>Thumbnail</title></head>');
    photoWin.document.write('<link rel="stylesheet" href="/LIB/site.css" type="text/css">');
    photoWin.document.write('<BODY BGCOLOR=#ffffff>');
    photoWin.document.write('<center><img src="' + image + '"></center>');
    photoWin.document.write('<table width=100%><tr><td valign=bottom height=10>');
    photoWin.document.write('<div align="right"><br><br><a style="font: bold 11px Verdana,Arial" href="Javascript:window.close();"><b>fechar</b></a></div>');
    photoWin.document.write('</td></tr></table>');
    photoWin.document.write('</body></html>');
    photoWin.document.focus();
    photoWin.document.close();
   // If we are on NetScape, we can bring the window to the front
  	if (navigator.appName.substring(0,8) == "Netscape") photoWin.focus();
  }

  
  ////////////////////////////////////////////////////////////////////////////
  // NOME : valida_numeros()
  // Descrição : Valida Apenas Números *****Deve ser usado do evento KeyPress
  // Parametros
  ///////////////////////////////////////////////////////////////////////////
  
  function valida_numero() {
    if (event.keyCode < 45 || event.keyCode > 57) 
     event.returnValue = false;
  }
  function valida_data(obj) {
    if (event.keyCode < 48 || event.keyCode > 57) 
     event.returnValue = false;
    else {
     if ((len(obj.value) == 3 && obj.value.substring(3,1) == '/') ||  (len(obj.value) == 6 && obj.value.substring == '/'))
       event.returnValue = false;
    } 
  }
  ////////////////////////////////////////////////////////////////////////////
  // NOME : valida_alfanum()
  // Descrição : Valida Apenas Alfa Númericos *****Deve ser usado do evento KeyPress
  // Parametros
  ///////////////////////////////////////////////////////////////////////////
  
  function valida_alfanum() {
    if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97))
     event.returnValue = false;
  }
 
  ////////////////////////////////////////////////////////////////////////////
  // NOME : valida_alfanum1()
  // Descrição : Valida Apenas Alfa Númericos *****Deve ser usado do evento KeyPress
  // Parametros
  ///////////////////////////////////////////////////////////////////////////

  function valida_alfanum1() {
    if (event.keyCode == 39)
     event.returnValue = false;
  }

  ////////////////////////////////////////////////////////////////////////////
  // NOME : ignoraEspaco()
  // Descrição : Tirar os espaços da String 
  // Parametros Entrada :String com Espaçoss
  //            Saída   :String sem Espaços
  //
  ///////////////////////////////////////////////////////////////////////////

  function ignoraEspaco(string) {
    var temp = "";
    string = '' + string;
    splitstring = string.split("  ");
    for(i = 0; i < splitstring.length; i++)
    temp += splitstring[i];
    return temp;
  }  

 ////////////////////////////////////////////////////////////////////////////
 // NOME : Bloquear Input 
 // Descrição : <input ... readonly >
 ///////////////////////////////////////////////////////////////////////////

 ////////////////////////////////////////////////////////////////////////////
 // NOME : inicialMaisculo
 // Descrição :Converte as Letras Iniciais para Maisculo
 // Parametro Entra: str que será convertida para maisculo
 //           Saída: String que returna a string convertida
 ///////////////////////////////////////////////////////////////////////////
  
function inicialMaisculo(str) {
  var index;
  var tmpStr;
  var tmpChar;
  var preString;
  var postString;
  var strlen;
  tmpStr = str.toLowerCase();
  strLen = tmpStr.length;
  if (strLen > 0)  
    {
      for (index = 0; index < strLen; index++)  
        {
          if (index == 0)  
            {
              tmpChar = tmpStr.substring(0,1).toUpperCase();
              postString = tmpStr.substring(1,strLen);
              tmpStr = tmpChar + postString;
            }
          else 
            {
              tmpChar = tmpStr.substring(index, index+1);
                  if (tmpChar == " " && index < (strLen-1))   
                    {
                      tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
                      preString = tmpStr.substring(0, index+1);                    
                      postString = tmpStr.substring(index+2,strLen);                      
                      tmpStr = preString + tmpChar + postString;
                    }
            }
       }
    }
    return tmpStr;
}

 ////////////////////////////////////////////////////////////////////////////
 // NOME : mascara_data
 // Descrição :
 // Parametro 
 ///////////////////////////////////////////////////////////////////////////
 
 function mascara_data(obj) { 
   var mydata = ''; 
   mydata = mydata + obj.value; 
    if (mydata.length == 2)
      { 
        mydata = mydata + '/'; 
        obj.value = mydata; 
      } 
    if (mydata.length == 5)
      { 
        mydata = mydata + '/'; 
        obj.value = mydata; 
      } 
 } 

 ////////////////////////////////////////////////////////////////////////////
 // NOME : verifica_data
 // Descrição :
 // Parametro :
 ///////////////////////////////////////////////////////////////////////////

 
 function verifica_data (obj,msg) { 
     dia = (obj.value.substring(0,2)); 
     mes = (obj.value.substring(3,5)); 
     ano = (obj.value.substring(6,10)); 
     situacao = ""; 
     // verifica o dia valido para cada mes 
     if ((dia < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31) { 
         situacao = "falsa"; 
        } 
     // verifica se o mes e valido 
     if (mes < 01 || mes > 12 ) { 
         situacao = "falsa"; 
        } 
     // verifica se e ano bissexto 
     if (mes == 2 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
         situacao = "falsa"; 
        }     
      if (obj.value == "") { 
                situacao = "falsa"; 
        } 
      if (situacao == "falsa") { 
                alert(msg); 
                obj.value ='';
                obj.focus(); 
                return false;
        } 
     return true;
 } 
 
  ////////////////////////////////////////////////////////////////////////////
 // NOME : mascara_hora
 // Descriçã- xxxxxxxxxxxxxo :
 // Parametro :
 ///////////////////////////////////////////////////////////////////////////

 function mascara_hora(hora) { 
      var myhora = ''; 
      myhora = myhora + hora; 
       if (myhora.length == 2) { 
                  myhora = myhora + ':'; 
                  document.forms[0].hora.value = myhora; 
          } 
              if (myhora.length == 5) {
                  verifica_hora(); 
              } 
          } 

  ////////////////////////////////////////////////////////////////////////////
 // NOME : verifica_hora
 // Descrição :
 // Parametro :
 ///////////////////////////////////////////////////////////////////////////
           
          function verifica_hora() { 
              hrs = (document.forms[0].hora.value.substring(0,2)); 
              min = (document.forms[0].hora.value.substring(3,5)); 
               
              alert('hrs '+ hrs); 
              alert('min '+ min); 
               
              situacao = ""; 
              // verifica data e hora 
              if ((hrs < 00 ) || (hrs > 23) || ( min < 00) ||( min > 59)){ 
                  situacao = "falsa"; 
              } 
               
              if (document.forms[0].hora.value == "") { 
                  situacao = "falsa"; 
              } 

              if (situacao == "falsa") { 
                  alert("Hora inválida!"); 
                  document.forms[0].hora.focus(); 
              } 
          } 
  ////////////////////////////////////////////////////////////////////////////
 // NOME : formataMoeda
 // Descrição :
 // Parametro :
 ///////////////////////////////////////////////////////////////////////////

  function formataMoeda(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
      cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + 'R$' + num + '.' + cents);
  }

//////////////////////////////////////////////////////////////////////////
// NOME        : ValidaIntervalo
// Descricao   : Valida intervalo entre datas
// Parametros  : Data1 - data inicial
//               Data2 - data final
///////////////////////////////////////////////////////////////////////////

function ValidaIntervalo(Data1, Data2) {
	var DataValorInicial = Data1;
	pos0 = DataValorInicial.indexOf("/");
	pos1 = DataValorInicial.indexOf("/", pos0 + 1);

	dia = DataValorInicial.substring(0,pos0);
	mes = DataValorInicial.substring(pos0 + 1, pos1);
	ano = DataValorInicial.substring(pos1 + 1, DataValorInicial.length);
  DataInicial = ano + mes + dia;
    
  var DataValorFinal = Data2;
 	pos0 = DataValorFinal.indexOf("/");
	pos1 = DataValorFinal.indexOf("/", pos0 + 1);

	dia = DataValorFinal.substring(0,pos0);
	mes = DataValorFinal.substring(pos0 + 1, pos1);
	ano = DataValorFinal.substring(pos1 + 1, DataValorFinal.length);
	DataFinal = ano + mes + dia;
	
	if(DataFinal < DataInicial) {
			return false
		}	
	return true;	
}
//////////////////////////////////////////////////////////////////////////
// NOME        : VeriPreench
// Descricao   : Verifica se o campo foi preenchido
// Parametros  : Campo - campo do formulário
///////////////////////////////////////////////////////////////////////////

function VerPreench(Campo,MSG) {
	if (Campo.value.length==0) {
		window.alert(MSG);
		return false;
	}
	else {
		return true;
	}
}
///////////////////////////////////////////////////////////////////////////
// NOME        : ChecaMail
// Descricao   : Verificar consistencia de e-mail
// Parametros  : eMail -> Campo eMail do formulario
//               MSG   -> Mensagem de erro
///////////////////////////////////////////////////////////////////////////
function ChecaMail(eMail,MSG) {
if (eMail == "") { 
  alert(MSG);
  eMail.focus();
  return(false); 
 }
 var Temp   = eMail;
 var AtSym  = Temp.value.indexOf('@');
 var Period = Temp.value.lastIndexOf('.');
 var Space  = Temp.value.indexOf(' ');
 var Length = Temp.value.length - 1;
 if ((AtSym < 1) || (Period <= AtSym+1) || (Period == Length ) || (Space  != -1)) { 
  alert(MSG);
  Temp.focus();
  return(false);
 }
}
///////////////////////////////////////////////////////////////////////////
// NOME       : chkCount
// Descricao  : Retorna o número de checkbox selecionados
// Parametros : obj -> objeto checkbox a ser verificado
///////////////////////////////////////////////////////////////////////////

function chkCount(obj) {
 var c
 c = 0;
 if (typeof(obj.length)=="undefined"){
   if (obj.checked) 
   	c=c+1;
 }
 else {
	 for(i=0;i<obj.length;i++)
	 {
	  if (obj[i].checked)
		c=c+1;   
	 }
 }
 return c;
}

///////////////////////////////////////////////////////////////////////////
// NOME       : chkSel
// Descricao  : Concatena os valores dos checkbox selecionados
// Parametros : obj -> objeto checkbox a ser verificado
///////////////////////////////////////////////////////////////////////////

function chkSel(obj) {
 var str
 str = "";
 if (typeof(obj.length)=="undefined"){
   if (obj.checked) 
   	str=obj.value+";";
 }
 else {
	 for(i=0;i<obj.length;i++) {
	  if (obj[i].checked)
	    str=str+obj[i].value + ";";
	 }    
 }
 return str;
}

//-->
  

///////////////////////////////////////////////
//  COOKIES //////////////////////////////////

setCookie2('mainpage','[pages|2|url]',null,'/','','');
function setCookie2(name, value, minutes, path, domain, secure) // Asettaa cookien
	{
        var curCookie = name + "=" + escape(value) + ((minutes)?(";expires=" + ((new Date((new Date()).getTime() + parseInt(minutes)*60000)).toGMTString())):"") + ((path)?";path=" + path:"") + ((domain)?";domain=" + domain:"") + ((secure)?";secure":"");
        document.cookie = curCookie;
	}



function getCookie2(name) // Palauttaa cookien arvon
{
        var dc = document.cookie;
        var prefix = name + "=";
        var begin = dc.indexOf("; " + prefix);
        if (begin == -1) {
        begin = dc.indexOf(prefix);
                if (begin != 0) return null;
        } else { begin += 2 }
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) { end = dc.length; }
        return unescape(dc.substring(begin + prefix.length, end));
}


function OnlyValidChars()
{
	/*
	    if ((window.event.keyCode >= 48 && window.event.keyCode <= 57) ||
		    (window.event.keyCode >= 65 && window.event.keyCode <= 90) ||
		    (window.event.keyCode >= 97 && window.event.keyCode <= 122)||
		    window.event.keyCode == 32	)
    */
		return true;
} 


function OnlyNumbers() {
    if (event.keyCode < 45 || event.keyCode > 57) 
     event.returnValue = false;
  }

function Trim(sValue)
{ 
	return(sValue.replace( /^\s+|\s+$/gi, "" ).replace( /\s{2,}/gi, " " ) ) 
}


function ValidateAll(objForm, bForceExit) 
{

    if (bForceExit)
        return true;
        
	var iForm;
	var iElement;

    if (!objForm)
    {
	    for(iForm=0; iForm < document.forms.length; iForm++)
	    {
		    for(iElement=0; iElement < document.forms[iForm].elements.length; iElement++)
		    {
			    if (document.forms[iForm].elements[iElement].required == "yes" && Trim(document.forms[iForm].elements[iElement].value.toString()) == "")
			    {
				    alert(document.forms[iForm].elements[iElement].messageError) ;
				    document.forms[iForm].elements[document.forms[iForm].elements[iElement].name].focus();
				    return false;
			    }
			    if(!(document.forms[iForm].elements[iElement].lenrequired == "undefined" || document.forms[iForm].elements[iElement].lenrequired == ""))
			    {
				    if (document.forms[iForm].elements[iElement].lenrequired > document.forms[iForm].elements[iElement].value.length)
				    {
					    var iqtd = document.forms[iForm].elements[iElement].lenrequired;
    					
					    if (iqtd.toString().length==1)
						    iqtd="0"+iqtd;
    					
					    alert("Este campo deve conter "+iqtd+" caracteres");
					    document.forms[iForm].elements[document.forms[iForm].elements[iElement].name].focus();
					    return false;
				    }
			    }	
		    }
	    }
	}
	else
	{
	    for(iElement=0; iElement < objForm.elements.length; iElement++)
		{
			if (objForm.elements[iElement].required == "yes" && Trim(objForm.elements[iElement].value.toString()) == "")
			{
				alert(objForm.elements[iElement].messageError) ;
				objForm.elements[objForm.elements[iElement].name].focus();
				return false;
			}
			if(!(objForm.elements[iElement].lenrequired == "undefined" || objForm.elements[iElement].lenrequired == ""))
			{
				if (objForm.elements[iElement].lenrequired > objForm.elements[iElement].value.length)
				{
					var iqtd = objForm.elements[iElement].lenrequired;
    				
					if (iqtd.toString().length==1)
						iqtd="0"+iqtd;
    				
					alert("Este campo deve conter "+iqtd+" caracteres");
					objForm.elements[objForm.elements[iElement].name].focus();
					return false;
				}
			}	
		}
	}
	return true;
}


/* PAULO/RAFA - 18/05/2005
* Troca a posição do elemento do combo 
* 'objSelect'  = referencia para o objeto select html 
* 'argDirection' = {-1 = mover para cima | 1 = mover para baixo}
*/
    function SelectSwap(objSelect, argDirection)
    {
        try
        {
            if ((objSelect.selectedIndex > 0 && argDirection==-1) || (objSelect.selectedIndex < objSelect.options.length -1 && argDirection==1))
            {
                var auxIndex, auxText, auxValue;
                auxIndex = objSelect.selectedIndex;
                auxText = objSelect.options[auxIndex].text; 
                auxValue = objSelect.options[auxIndex].value; 
                
                objSelect.options[auxIndex].text = objSelect.options[auxIndex+argDirection].text;
                objSelect.options[auxIndex].value = objSelect.options[auxIndex+argDirection].value;
                objSelect.options[auxIndex+argDirection].text = auxText;
                objSelect.options[auxIndex+argDirection].value = auxValue;
                objSelect.selectedIndex+=argDirection;
            }
         }
         catch(E)
         {
         }
    }
    
    

function New(type)
{
	var tit = eval(wTitle);
	tit.innerHTML = "";
	
	tit.innerHTML = "&nbsp;Criar";

	document.all.CheckSigla.value = "";

	switch(type)
	{
		case "curso":
		{
			document.all.txtIdCurso.value = "";
			document.all.txtCurso.value = "";
			document.all.txtSigla.value = "";			
			break;
		}
		case "nivel":
		{
			document.all.txtIdNivel.value = "";
			document.all.txtNivel.value = "";
			document.all.txtSigla.value = "";			

			var cb = eval(document.all.cbCurso);
			cb.selectedIndex = 0;

			break;
		}
		case "subnivel":
		{
			document.all.txtIdSubNivel.value = "";
			document.all.txtSubNivel.value = "";
			document.all.txtSigla.value = "";	
			
			var ComboVinculado =document.all.ComboVinculado;
            ComboVinculado.style.display="";
            
			var cb = eval(document.all.cbCreateNivel);
			cb.selectedIndex = 0;
							
			break;
		}		
	}

}

function Edit(iID, sCurso, sSigla, type, iParent, sBookName, sBookImage)
{
	var tit = eval(wTitle);
	tit.innerHTML = "";
	tit.innerHTML = "&nbsp;Editar";

	document.all.CheckSigla.value = sSigla;
	
	switch(type)
	{
		case "curso":
		{
			document.all.txtIdCurso.value = iID;
			document.all.txtCurso.value = sCurso;
			document.all.txtSigla.value = sSigla;			
			break;
		}
		case "nivel":
		{
			document.all.txtIdNivel.value = iID;
			document.all.txtNivel.value = sCurso;
			document.all.txtSigla.value = sSigla;		
			
			var cb = eval(document.all.cbCurso);
			cb.selectedIndex = 0;
			
			for(i=0 ; i< cb.options.length ; i++ )
				if (cb.options[i].value == iParent)
					cb.selectedIndex = i;	
			break;
		}
		case "subnivel":
		{
			document.all.txtIdSubNivel.value = iID;
			document.all.txtSubNivel.value = sCurso;
			document.all.txtSigla.value = sSigla;
			document.all.txtNomeLivro.value = sBookName;
			document.all.txtImagemLivro.value = sBookImage;
            
			var cb = eval(document.all.cbCreateNivel);
			cb.selectedIndex = 0;
			
			for(i=0 ; i< cb.options.length ; i++ )
				if (cb.options[i].value == iParent)
					cb.selectedIndex = i;	
			
			break;		
		}		
	}

}

function setRequired(objToSet, bStatus)
{
	objToSet.required = bStatus;
}

function setUpperCase(objToSet)
{
	objToSet.value=objToSet.value.toUpperCase();
}


function OnSaveRecord()
{
	if (SiglaExiste(document.all.txtSigla.value))
	{
		alert("A Sigla já está cadastrada.");
		return false;
	}
		
	if (!ValidateAll())
		return false;
		
	return true;
}


/*Validador das questoes*/
function OnClientCreateControl(iTotalControls)
{
	var i=0;
	for(i=1;i<=iTotalControls;i++)
	{
		if (i==iTotalControls+1)
			return;
		if(document.getElementById("sp_"+i).style.display=="none")
		{
			document.getElementById("sp_"+i).style.display=""; 
			return;
		}
	}
}


function OnClientRemoveControl(iTotalControls)
{
	var i=0;
	for(i=1;i<=iTotalControls+1;i++)
	{
		if(i==iTotalControls || document.getElementById("sp_"+(i+1)).style.display=="none")
		{	
			if (i<=2)
				return;

			var rd=document.all.ans_bStatus[(i-1)];
			rd.checked=false;

			document.getElementById("sp_"+(i)).style.display="none"; 
			
			document.getElementById("ans_sFeedback_"+(i)).value="";
			document.getElementById("ans_exclued_"+(i)).value=1;
			
			var objDiv = eval(document.getElementById("div_ans_sCorrectAnswer_"+i));
			var objTextArea = eval(document.getElementById("txt_ans_sCorrectAnswer_"+i));
			
			objDiv.innerHTML="";
			objTextArea.value="";
			
			//doInsert("txtResp_"+i,"");
			return;
		}
	}
}

function OnSubmitValidate_FormTrueOrFalse()
{
	if(document.getElementById("qst_iWeight").value==""){
		alert("O Campo Peso da Pergunta Precisa ser Preenchido.");
		document.getElementById("qst_iWeight").focus();
		return false;
	}		
			
	if(document.getElementById("div_qst_sQuestion").innerHTML==""||document.getElementById("txt_qst_sQuestion").value){
		alert("O Campo Pergunta Precisa ser Preenchido.");
		document.getElementById("div_qst_sQuestion").focus();
		return false;
	}
	var i=0;
	var bChecked=false;

		for (i=1; i<=2; i++)
		{

		    if(document.getElementById("div_ans_sCorrectAnswer_"+i).innerHTML==""||document.getElementById("div_ans_sCorrectAnswer_"+i).value){
			    alert("A Resposta "+(i<10 ? "0"+i.toString() : i)+", Precisa ser Preenchida.");
			    document.getElementById("div_ans_sCorrectAnswer_"+i).focus();
			    return false;
		    }
    		
		    var rd=eval(document.frmQuestoes.ans_bStatus[i-1]);					
			
		    if(rd.checked){
			    bChecked=true;
		    }
    		
		    if(document.getElementById("sp_2").style.display=="none"){
			    alert("É necessário ter ao menos duas respostas para uma pergunta.");
			    return false;
		    }
		}
		
		if(!bChecked){
			alert("É necessário selecionar a resposta correta.");
			return false;
		}
		
	return true;
}

function OnSubmitValidate_FormMultipliChoice()
{	
    /*		
	if(document.getElementById("div_qst_sEnunciate").innerHTML==""||document.getElementById("txt_qst_sEnunciate").value){
		alert("O Campo Enunciado Precisa ser Preenchido.");
		document.getElementById("div_qst_sEnunciate").focus();
		return false;
	}
	*/
	if(document.getElementById("qst_iWeight").value==""){
		alert("O Campo Peso da Pergunta Precisa ser Preenchido.");
		document.getElementById("qst_iWeight").focus();
		return false;
	}		
			
	if(document.getElementById("div_qst_sQuestion").innerHTML==""||document.getElementById("txt_qst_sQuestion").value){
		alert("O Campo Pergunta Precisa ser Preenchido.");
		document.getElementById("div_qst_sQuestion").focus();
		return false;
	}
	var i=0;
	var bChecked=false;
	while(!(document.all("sp_"+(i+1)).style.display=="none"))
	{
		i++;
		
		if(document.getElementById("div_ans_sCorrectAnswer_"+i).innerHTML==""||document.getElementById("div_ans_sCorrectAnswer_"+i).value){
			alert("A Resposta "+(i<10 ? "0"+i.toString() : i)+", Precisa ser Preenchida.");
			document.getElementById("div_ans_sCorrectAnswer_"+i).focus();
			return false;
		}
			
		var rd=eval(document.frmQuestoes.ans_bStatus[i-1]);							
		if(rd.checked){
			bChecked=true;
		}
				
		
		if(document.getElementById("sp_2").style.display=="none"){
			alert("É necessário ter ao menos duas respostas para uma pergunta.");
			return false;
		}
		
		if(i == 10){
			break;
		}
		
	}
       
    if(!bChecked){
		alert("É necessário selecionar a resposta correta.");
		return false;
	}
		
    return true;
}

function OnSubmitValidateOrder()
{								
	if(document.getElementById("qst_iWeight").value==""){
	alert("O Campo Peso da Questão Precisa ser Preenchido.");
	document.getElementById("qst_iWeight").focus();
	return false;
	}		
			
	if(document.getElementById("div_qst_sQuestion").innerHTML==""||document.getElementById("txt_qst_sQuestion").value){
		alert("O Campo 'Pergunta' Questão ser Preenchido.");
		document.getElementById("div_qst_sQuestion").focus();
		return false;
	}
		
	var i=0;
	while(!(document.getElementById("sp_"+(i+1)).style.display=="none"))
	{
		i++;

		if(document.getElementById("div_ans_sCorrectAnswer_"+i).innerHTML==""||document.getElementById("div_ans_sCorrectAnswer_"+i).value){
			alert("Existem linhas no diálogo que não foram preenchidas.");
			document.getElementById("div_ans_sCorrectAnswer_"+i).focus();
			return false;
		}
			
		if(document.getElementById("sp_2").style.display=="none"){
			alert("É necessário ter ao menos duas respostas para uma pergunta.");
			return false;
		}
	}
	return true;
}

function OnSubmitValidateConnect()
{								
	if(document.getElementById("qst_iWeight").value==""){
	    alert("O Campo Peso da Questão Precisa ser Preenchido.");
	    document.getElementById("qst_iWeight").focus();
	    return false;
	}		
			
	if(document.getElementById("div_qst_sQuestion").innerHTML==""||document.getElementById("txt_qst_sQuestion").value){
		alert("O Campo 'Pergunta' Questão ser Preenchido.");
		document.getElementById("div_qst_sQuestion").focus();
		return false;
	}
	
	
	/* coloquei um item de checkagem de objeto - MSLF */
	var i=0;
	while ((!(document.getElementById("sp_"+(i+1)).style.display=="none")) &&
			(document.all.item("sp_"+((i+1)+1)) != null))
	{
		i++;
		
		if(document.getElementById("div_ans_sCorrectAnswer_"+i).innerHTML==""||document.getElementById("div_ans_sCorrectAnswer_"+i).value){
			alert("A Resposta "+(i<10 ? "0"+i.toString() : i)+", Precisa ser Preenchida.");
			document.getElementById("div_ans_sCorrectAnswer_"+i).focus();
			return false;
		}
		if(document.getElementById("div_ans_sConnectAnswer_"+i).innerHTML==""||document.getElementById("div_ans_sConnectAnswer_"+i).value){
			alert("A Resposta de conexão "+(i<10 ? "0"+i.toString() : i)+", Precisa ser Preenchida.");
			document.getElementById("div_ans_sConnectAnswer_"+i).focus();
			return false;
		}
			
		if(document.getElementById("sp_2").style.display=="none"){
			alert("É necessário ter ao menos duas respostas para uma pergunta.");
			return false;
		}
	}
	return true;
}


function OnSubmitValidateWithCheckBox()
{	

	if(document.getElementById("qst_iWeight").value==""){
		alert("O Campo Peso da Pergunta Precisa ser Preenchido.");
		document.getElementById("qst_iWeight").focus();
		return false;
	}		
			
	if(document.getElementById("div_qst_sQuestion").innerHTML==""||document.getElementById("txt_qst_sQuestion").value){
		alert("O Campo Pergunta Precisa ser Preenchido.");
		document.getElementById("div_qst_sQuestion").focus();
		return false;
	}
	
	var i=0;
	var bChecked=false;
	while(!(document.getElementById("sp_"+(i+1)).style.display=="none")) 
	{
	
		i++;

		if(document.getElementById("div_ans_sCorrectAnswer_"+i).innerHTML==""||document.getElementById("div_ans_sCorrectAnswer_"+i).value){
			alert("A Resposta "+(i<=10 ? "0"+i.toString() : i)+" precisa ser preenchida.");
			document.getElementById("div_ans_sCorrectAnswer_"+i).focus();
			return false;
		}
		
		var rd=document.getElementById("ck_"+i)
		
		if(rd.checked){
			bChecked=true;
		}
		
		if(document.getElementById("sp_2").style.display=="none"){
			alert("É necessário ter ao menos duas respostas para uma pergunta.");
			return false;
		}
		
		if (i==10){
			break;
		}
		
	}
	

	
	if(!bChecked){
		alert("É necessário selecionar ao menos uma resposta correta.");
		return false;
	}
	
	return true;

}

function OnClientRemoveControlOrder(iTotalControls)
{
	var i=0;
	var valor;
	for(i=1;i<=iTotalControls+1;i++)
	{
		if(i==iTotalControls || document.getElementById("sp_"+(i+1)).style.display=="none")
		{	
			document.getElementById("flag").value=i;
			if (i<=2) return;
			
			document.getElementById("sp_"+(i)).style.display	="none";
			
			document.getElementById("ans_sFeedback_"+(i)).value	="";			
			document.getElementById("ans_exclued_"+(i)).value=1
			
			//alert('id_question' + document.getElementById("question_id_"+(i)).value);
			//alert('excluido' + document.getElementById("ans_exclued_"+(i)).value);
			//valor=document.getElementById("ans_sFeedback_"+(i)).value;
			//alert('questao' + valor);
			
			var objDiv 		= eval(document.getElementById("div_ans_sCorrectAnswer_"+i));
			var objTextArea = eval(document.getElementById("txt_ans_sCorrectAnswer_"+i));
			
			objDiv.innerHTML="";
			objTextArea.value="";
			
			//doInsert("txtResp_"+i,"");
			return;
		}
	}
}

function OnClientRemoveControlConnect(iTotalControls)
{
var i=0;
	for(i=1;i<=iTotalControls+1;i++)
	{
		if(i==iTotalControls || document.getElementById("sp_"+(i+1)).style.display=="none")
		{	
			if (i<=2)
				return;

			document.getElementById("sp_"+(i)).style.display="none"; 
			
			document.getElementById("ans_sFeedback_"+(i)).value="";
			document.getElementById("ans_exclued_"+(i)).value=1;
			
			var objDiv = eval(document.getElementById("div_ans_sCorrectAnswer_"+i));
			var objTextArea = eval(document.getElementById("txt_ans_sCorrectAnswer_"+i));
			objDiv.innerHTML="";
			objTextArea.value="";
			
			var objDiv = eval(document.getElementById("div_ans_sConnectAnswer_"+i));
			var objTextArea = eval(document.getElementById("txt_ans_sConnectAnswer_"+i));
			objDiv.innerHTML="";
			objTextArea.value="";

			return;
		}
	}
}
function OnClientRemoveControlWithCheck(iTotalControls)
{
    var i=0;
	for(i=1;i<=iTotalControls+1;i++)
	{
		if(i==iTotalControls || document.getElementById("sp_"+(i+1)).style.display=="none")
		{	
			if (i<=2)
				return;

			var rd=document.getElementById("ck_"+i)	
			rd.checked=false;

			document.getElementById("sp_"+(i)).style.display="none"; 
			
			document.getElementById("ans_sFeedback_"+(i)).value	="";			
			document.getElementById("ans_exclued_"+(i)).value=1
			
			var objDiv = eval(document.getElementById("div_ans_sCorrectAnswer_"+i));
			var objTextArea = eval(document.getElementById("txt_ans_sCorrectAnswer_"+i));
			
			objDiv.innerHTML="";
			objTextArea.value="";
			
			//doInsert("txtResp_"+i,"");
			return;
		}
	}
}


function replaceAll(str,str1,str2){
	var re,ret;
	re=new RegExp(str1,"gi");
	ret=str.replace(re,str2);
	re=null;
	return ret;
}
function doInsert(fieldname,sText){
	// Unprotect special NAS-characters
	tag=replaceAll(sText,"!!1//","[");
	tag=replaceAll(sText,"!!2//","|");
	tag=replaceAll(sText,"!!3//","]");
	tag=replaceAll(sText,"!!4//","\\");

	var ret
	ret=window.parent.insertTagFromIframe(sText);

	alert("fez doInsert()");
	return;

	window.parent.document.all("div_"+fieldname).innerHTML=sText;
}






//**************************************************************************************************************
//***  CÓDIGOS PARA PEGAR A TAB DE CORES DO WYSIWYG                                                                                           ****
//**************************************************************************************************************
	function _CloseOnEsc() {
	  if (event.keyCode == 27) { window.close(); return; }
	}
	function vInitColor() {                                                       // run on page load
	  document.body.onkeypress = _CloseOnEsc;
	
	  color = window.dialogArguments;
	  color = ValidateColor(color) || '000000';
	  sViewColor(color);                                                          // set default color
	}
	function sViewColor(color) {                  // preview color
	  document.all.ColorPreview.style.backgroundColor = '#' + color;
	  document.all.ColorHex.value = '#' + color;
	}
	function sGetColor(string) {                   // select color
	  color = ValidateColor(string);
	  if (color == null) { alert("Invalid color code: " + string); }        // invalid color
	  else {                                                                // valid color
		sViewColor(color);                          // show selected color
		//window.returnValue = color;           // set return value
		var sel,range,temp;
		sel = document.selection;
		range = sel.createRange();
		range.execCommand("forecolor", false,"#"+color);
	  }
	}
	function ValidateColor(string) {                // return valid color code
	  string = string || '';
	  string = string + "";
	  string = string.toUpperCase();
	  chars = '0123456789ABCDEF';
	  out   = '';
	
	  for (i=0; i<string.length; i++) {             // remove invalid color chars
		schar = string.charAt(i);
		if (chars.indexOf(schar) != -1) { out += schar; }
	  }
		
	  if (out.length != 6) { return null; }            // check length
	  return out;
	} 
	
	
	function doInsert(fieldname,tag){
	// Unprotect special NAS-characters
	tag=replaceAll(tag,"!!1//","[");
	tag=replaceAll(tag,"!!2//","|");
	tag=replaceAll(tag,"!!3//","]");
	tag=replaceAll(tag,"!!4//","\\");
	// Insert tag to specified field
	// We need some how know the selected range where to insert
	// This function is called in an iframe...
	var ret
	// ret==true jos onnistui, muutoin out of focus
	ret=window.parent.insertTagFromIframe(tag);

	return;
	// Vanha koodi
	// Append tag to specified field
	window.parent.document.all("div_"+fieldname).innerHTML+=tag
}


//********************************************************//

// Função para gerar o flash sem a borda

function GerarSWF($arquivo,$largura,$altura,$id,$flashvars){
    document.writeln('    <object id="globalnav-object" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + $largura + '" height="' + $altura + '" id="' + $id + '" name="' + $id + '">');
    document.writeln('        <param name="movie" value="' + $arquivo + '" />');
    document.writeln('        <param name="FlashVars" value="loc=en_US&htmlApp=false&gatewayURL=gwurl&' + $flashvars + '" />');
    document.writeln('        <param name="bgcolor" value="#ffffff" />');
    document.writeln('        <param name="menu" value="false" />');
    document.writeln('        <param name="quality" value="high" />');
    document.writeln('        <param name="salign" value="tl" />');
    document.writeln('        <param name="scale" value="noscale" />');
    document.writeln('        <param name="wmode" value="transparent" />');
    document.writeln('        <embed id="globalnav-embed" src="' + $arquivo + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" flashvars="loc=en_US&htmlApp=false&gatewayURL=gwurl" bgcolor="#ffffff" menu="false" quality="high" salign="tl" scale="noscale" id="' + $id + '" width="' + $largura + '" height="' + $altura + '"></embed>');
    document.writeln('    </object>');
}




//********************************************************//

// Funções dos Módulos //

function SwapPicture(objImg) {
	if(objImg.src.substr(objImg.src.length-8)=="mais.gif") {
		objImg.src="/templates/img/auxiliar/menos.gif";
	} else {
		objImg.src="/templates/img/auxiliar/mais.gif";
	}
}

function ShowMe(act_id) {
    var objEnabled=null;
    var objDisabled=null;
    for (i=1;i<acts.length;i++) {
        objEnabled=document.getElementById("act_"+acts[i]);
		objDisabled=document.getElementById("act_"+acts[i]+"_N");
        if (objEnabled.id!="act_"+act_id||objEnabled.style.display!="none") {
			objEnabled.style.display="none";
			if(objDisabled!=null) {
				objDisabled.style.display="";
			}
        } else {
            objEnabled.style.display="";
            if(objDisabled!=null) {
				objDisabled.style.display="none";
			}
        }
    }
    location.href=location.href.toString().replace("#top","")+"#top";  
}

function destaque(cod,argcolor) {	
	event.srcElement.style.color= argcolor;
	return;
	if (cod==1){
		event.srcElement.style.color= "orange";
	} else {
		event.srcElement.style.color= argcolor;
	}
}

//********
// FÓRUM
//********

function forum_ShowLayer(layerName){
    if (document.getElementById){
		var targetElement = document.getElementById(layerName);
		targetElement.style.visibility = 'visible';
	}
}

function forum_HideLayer(layerName) {
	if (document.getElementById) {
		var targetElement = document.getElementById(layerName);
		targetElement.style.visibility = 'hidden';
	}
}

//************



//**************
// Image Rollover
//**************

function ShowLayer(layerName){
    if (document.getElementById){
		var targetElement = document.getElementById(layerName);
		targetElement.style.visibility = 'visible';
	}
}

function HideLayer(layerName) {
	if (document.getElementById) {
		var targetElement = document.getElementById(layerName);
		targetElement.style.visibility = 'hidden';
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->

//************


//function SaveQuestions() {
//	controle=document.all("control_save").value;
	
//	if(controle==0){
//		document.all("control_save").value=1;
//		return true;
//	}else{
//		alert("aguarde... carregando...")
//		return false;
//	}
//	return false;
//}
