function ShowHideLayer(id) {
	f = document.getElementById(id);
	if (f.style.display == "none") {
		f.style.display = "block";
	}
	else {
		f.style.display = "none";
	}
}

function opnwindow (url,width,height,larguramax,titulo) {
	if (titulo==undefined) titulo = "";
	var left = (screen.availWidth-width)/2;
	var top = (screen.availHeight-height)/2;
	janela = window.open ('', '_blank', "top="+top+",left="+left+",toolbar=0,location=0,directories=0,status=0,scrollbars=yes,menubar=no,resizable=1,width="+width+",height="+height)
	janela.document.write("<HTML><head><TITLE>["+titulo+"]</TITLE></head>\n"
	+"<BODY BGCOLOR='#COCOCO' text='black' link='blue' vlink='blue' alink='blue' background='/images/fundo1.gif'><CENTER>"
	+"\n<table border='0'><tr><td>"
	+"\n<div style='background-color:#fff; padding:7px; border:1px solid #636531'><img src='"+url+"' width='"+larguramax+"' alt='Clique para Fechar' onclick='window.close()'></div>"
	+"\n</td></tr></table>"
	+"\n<BR><p align=right>[<a href=javascript:self.close()>Fechar Janela</a>]</p>"
	+"\n</body></html>");
}

function opnwin(url,width,height,OPENWINDOW)  {
	if (OPENWINDOW == "" || OPENWINDOW == undefined) OPENWINDOW = "_blank";
	var left = (screen.availWidth-width)/2;
	var top = (screen.availHeight-height)/2;
	var new_win = window.open(url, OPENWINDOW, "menubar=0,toolbar=1,location=0,directories=0,status=1,scrollbars=1,resizable=0,width="+width+",height="+height+",top="+top+",left="+left);
	
	return true;
}

/* ao clicar o botao ? */
function get_modulo_ajuda(ancora) // 13.02.2004
{
	if(!ancora) ancora='';
	mid = getSelectValue(fNome,fModulos);
	url = "./modulo_ajuda.php?mid=" + mid + "#" + ancora;
	prop = 'resizable=yes, scrollbars=yes , width=300, height=100, left=100, top=100';
	window.open(url,'modulo_ajuda',prop);
}



// TODO: Limpar todos os Campos TEXT
function limparCampos(form)
{
	o = document.formulario;
}

/* Seta um valor pelo ID */
function SetObjID(nome,a,v) // 20.01.2004
{
	__objID(nome,a,v,"set")
}
/* Obtem um valor pelo ID */
function GetObjID(nome,a) // 20.01.2004
{
	return __objID(nome,a,"","get");
}
/* Usado pelas funcoes Set/Get ObjID */
function __objID(nome,a,v,sg) // 20.01.2004
{
	o = eval("document.getElementById('" +nome+"')");
	if(sg == "set") o = eval("o." + a + "='" +v+"'");
	else return eval("o." + a);
}


// Transforma 20.100,35 -> 20100.35
function parseNum(v)
{
	nv = v.replace(/\./gi,"");
	v = nv.replace(/,/gi,".");
	return parseFloat(v);
}

function WriteDate()
{
	hoje = new Date()
	dia = hoje.getDate()
	dias = hoje.getDay()
	mes = hoje.getMonth()
	ano = hoje.getYear()
	if (dia < 10)
	dia = "0" + dia
	if (ano < 2000)
	ano = 1900 + ano
	function CriaArray (n) { this.length = n }
	NomeDia = new CriaArray(7)
	NomeDia[0] = "Domingo"
	NomeDia[1] = "Segunda-feira"
	NomeDia[2] = "Ter&ccedil;a-feira"
	NomeDia[3] = "Quarta-feira"
	NomeDia[4] = "Quinta-feira"
	NomeDia[5] = "Sexta-feira"
	NomeDia[6] = "S&aacute;bado"
	//
	NomeMes = new CriaArray(12)
	NomeMes[0] = "Janeiro"
	NomeMes[1] = "Fevereiro"
	NomeMes[2] = "Mar&ccedil;o"
	NomeMes[3] = "Abril"
	NomeMes[4] = "Maio"
	NomeMes[5] = "Junho"
	NomeMes[6] = "Julho"
	NomeMes[7] = "Agosto"
	NomeMes[8] = "Setembro"
	NomeMes[9] = "Outubro"
	NomeMes[10] = "Novembro"
	NomeMes[11] = "Dezembro"
document.write ("<font color='#FFFFFF'>&nbsp;Curitiba " + dia + " de " + NomeMes[mes] + " de " + ano + " </font>");
}


// Quando nao carrega a foto, mostrar uma imagem padrao
function imgNL(o)
{
	//o.style.visibility="hidden";
	o.src='/includes/imagens/icons/caution.gif';
}

function msgHelp(msg)
{
	messageWindow("Ajuda", msg);
}
// Example:
// value1 = 3; value2 = 4;
// messageBox("text message %s and %s", value1, value2);
// this message box will display the text "text message 3 and 4"
function messageBox()
{
  var i, msg = "", argNum = 0, startPos;
  var args = messageBox.arguments;
  var numArgs = args.length;
  if(numArgs)
  {
    theStr = args[argNum++];
    startPos = 0;  endPos = theStr.indexOf("%s",startPos);
    if(endPos == -1) endPos = theStr.length;
    while(startPos < theStr.length)
    {
      msg += theStr.substring(startPos,endPos);
      if (argNum < numArgs) msg += args[argNum++];
      startPos = endPos+2;  endPos = theStr.indexOf("%s",startPos);
      if (endPos == -1) endPos = theStr.length;
    }
    if (!msg) msg = args[0];
  }
  alert(msg);
}


function messageWindow(title, msg)
{
  var width="300", height="125";
  var left = (screen.width/2) - width/2;
  var top = (screen.height/2) - height/2;
  var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top;
  var msgWindow = window.open("","msgWindow", styleStr);
  var head = '<head><title>'+title+'</title></head>';
  var body = '<center>'+msg+'<br><p><form><input type="button" value="   Fechar   " onClick="self.close()"></form>';
  msgWindow.document.write(head + body);
}

function confirmaRemover()
{
	if(confirm("Deseja remover os registros selecionados?\n\nContinuar?")) return true;
	else return false;
}
function confirmaDeletar()
{
	if(confirm("Deseja remover este registro?\n\nContinuar?")) return true;
	else return false;
}

/*
Check all checkbox
	formName	= Form Name
	boxName		= Name of input type=checkbox
Usage:
	Put :
	<input type="checkbox" name="sellall" onClick="CheckAll('formName')">

formName = name of form

*/
function CheckAll(formName,boxName) { //v0.2
	if (!boxName) boxName = "selall";
	if (!formName) formName = "form";

	for (var i=0 ; i < eval("document." + formName + ".elements.length") ; i++)
	{
		var x = eval("document." + formName + ".elements["+ i + "]");
		status=x.name;
		if (x.name != boxName)
		      x.checked = eval("document."+ formName + "." + boxName + ".checked");
	}
}
/*
Check all especific checkbox
	formName	= Form Name
	inputName	= Checkbox will be checked
	boxName		= Name of input type=checkbox
Usage:
	Put :
	<input type="checkbox" name="sellall" onClick="CheckAll('formName')">

formName = name of form

*/
function checkBoxEsp(formName,inputName, boxName) { //v0.2
	//dumpObj(obj,inputName);
	//boxName = formName.name;

	for (var i=0 ; i < eval("document." + formName + ".elements.length") ; i++)
	{
		var x = eval("document." + formName + ".elements["+ i + "]");
		status=x.name;

		if (x.name != boxName && x.name == inputName)
		      x.checked = eval("document."+ formName + "." + boxName + ".checked");
	}
}

/* FORMADOR DE NUMEROS */
dec_delimiter = ",";
mil_delimiter = ".";

/*
num = Numero
*/
function cleanNumber(num)
{
	var sVal='';
	var nVal = num.length;
	var sChar='';
	if(!mil) mil = ".";
	if(!dec) dec = ",";
	try
	{
		for(i=0;i<nVal;i++)
		{
			sChar = num.charAt(i);
			nChar = sChar.charCodeAt(0);
			if(sChar == mil || sChar == dec) { sVal += sChar; continue; }
			if ((nChar >=48) && (nChar <=57))  { sVal += num.charAt(i);   }
		}
	}
	catch (exception) { alert('Erro') }
	// Formatando em numero flutuante

	return sVal;
}
/*
Formata 1000000.00 -> 1.000.000,00
** Nao altera a precisao, se estiver no formato acima, sendo o separador(ponto)
*/
function formataNumero(num)
{
	var sVal='';
	var minus='';
	try
	{
		if(!num) return "";
		num = num.toString();
		dec = ","; mil=".";
		val = num.split(".");
		if(val[1] == undefined) val = "00";
		else val = val[1];
		if (num.lastIndexOf("-") == 0) { minus='-'; }
		num = parseInt(num);
		var samount = new String(num);
		for (var i = 0; i < Math.floor((samount.length-(1+i))/3); i++)
		{
			samount = samount.substring(0,samount.length-(4*i+3)) + mil + samount.substring(samount.length-(4*i+3));
		}
		return minus + samount + "," + val;
	}
	catch (exception) { alert("Erro na função: formataNumero()"); }
	return "";
}


/*

PS: form name should be "form"

Date Format in Brazilian
Usage into tag INPUT TEXT:
onKeyDown=DateFormatBr("fieldName",event)

*/
function DateFormatBr(fieldName,keyPressed) { // v0.1
	if(!formName) formName = "form";
	DateFormat_BR(formName,fieldName,keyPressed);
}

function DateFormat_BR(formName,fieldName,keyPressed)
{
	o = eval("document." + formName + "." + fieldName);
	var KeyPress = keyPressed.keyCode;
	vr = o.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	size = vr.length + 1;

	if ( KeyPress != 9 && KeyPress != 8 ){
		if ( size > 2 && size < 5 )
			o.value = vr.substr( 0, size - 2  ) + '/' + vr.substr( size - 2, size );
		if ( size >= 5 && size <= 10 )
			o.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); }

}

/*
PS: form name should be "form"

Description:	Value Format type Money in Brazilian

Usage on tag INPUT TEXT AND TEXTAREA
onKeyDown="ValueFormatBr('fieldName',<MaxSize>,event)"
 - MaxSize can be a value of 0 until 17

*/

function ValueFormatBr(fieldName,maxSize,keyPressed,precisao) { //v0.1
	if(!formName) formName = "form";
	ValueFormat_Br(formName,fieldName,maxSize,keyPressed,precisao);
}

function ValueFormatBrID(IDname,maxSize,keyPressed,precisao)
{
	ValueFormat_Br('',IDname,maxSize,keyPressed,1,precisao);
}

function ValueFormat_Br(formName,fieldName,maxSize,keyPressed,byID,precisao) {
	var tecla = keyPressed.keyCode;
	if(!precisao) precisao = 2;
	if(byID)	o = document.getElementById(fieldName);
	else		o = eval("document." + formName + "." + fieldName);

	vr = o.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	size = vr.length;
	if (size < maxSize && tecla != 8){ size = vr.length + 1 ; }

	if (tecla == 8 ){	size = size - 1 ; } // Backspace

	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105){
		count = 0;
		if ( size <= 2 ){
			count=0;
	 		o.value = vr ;
			}
	 	if ( (size > 2) && (size <= 5) ){
			count=1;
	 		o.value = vr.substr( 0, size - 2 ) + ',' + vr.substr( size - 2, size ) ;
			}
	 	if ( (size >= 6) && (size <= 8) ){
			count=2;
	 		o.value = vr.substr( 0, size - 5 ) + '.' + vr.substr( size - 5, 3 ) + ',' + vr.substr( size - 2, size ) ;
			}
	 	if ( (size >= 9) && (size <= 11) ){
			count=3;
	 		o.value = vr.substr( 0, size - 8 ) + '.' + vr.substr( size - 8, 3 ) + '.' + vr.substr( size - 5, 3 ) + ',' + vr.substr( size - 2, size ) ;
			}
	 	if ( (size >= 12) && (size <= 14) ){
			count=4;
	 		o.value = vr.substr( 0, size - 11 ) + '.' + vr.substr( size - 11, 3 ) + '.' + vr.substr( size - 8, 3 ) + '.' + vr.substr( size - 5, 3 ) + ',' + vr.substr( size - 2, size ) ;
			}
	 	if ( (size >= 15) && (size <= 17) ){
			count=5;
	 		o.value = vr.substr( 0, size - 14 ) + '.' + vr.substr( size - 14, 3 ) + '.' + vr.substr( size - 11, 3 ) + '.' + vr.substr( size - 8, 3 ) + '.' + vr.substr( size - 5, 3 ) + ',' + vr.substr( size - 2, size ) ;
			}
	}
	status = size;
	if (size == maxSize)
	{
		o.value = o.value.substring(0, maxSize+count - 1);
	}
}


/*
	dumpObj objects and contents
	Use: dumpObj(this,NomeDoCampo)
*/
function dumpObj (obj, str) { // v0.1
var s = new Array ();
var i;
var j = 0;
  for (i in obj) {   // get all objects, and contents
    s[j] = i + ": " + obj[i];
    j = j + 1;
  }
  s.sort ();         // sort them data down
  document.open ("text/html");  // open a new document
  document.write ("<html><head>");  //  with full XHTML style
  document.write ("<title>Dump page</title>");
  document.write ("</head><body>");
  document.write ("<p><b>");  // make it kosher
  document.write (str, " contents.<br />");
  document.write (navigator.appName, "<br />");
  document.write (navigator.userAgent, "</b><br /><br />");
  for (i=0; i<j; i++) {
    document.write (s[i], "<br />");
  }
  document.write ("</p>");
  document.write ("</body></html>");
  document.close ();  // close down output stream
}


function textCounter(form_name,campo,maxlimit,show_text_len) {
	// show_text_len = eh para mostrar o valor num campo text
	// Para Usar: onKeyUp="textCounter('form1','mensagem','125')"

	if (eval("document." +form_name+ "." +campo+ ".value.length") > maxlimit)
		eval("document." +form_name+ "." +campo+ ".value = document." +form_name+"." +campo+ ".value.substring(0, " +maxlimit+ ");");

	else
		status = eval("document." +form_name+ "." +campo+ ".value.length;") + " de " + maxlimit;

	// Insira um campo chamado <input type="text" name="len">
	show_text_len=2;
	if (show_text_len == 1) {
		eval("document."+ form_name + ".len.value = document." + form_name + "." +campo+ ".value.length;");
	}

}

/* toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=800,height=600' */
function ct_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


function ct_findObj(n, d) { //v4.0
	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=ct_findObj(n,d.layers[i].document);
	if(!x && document.getElementById)
		x=document.getElementById(n); return x;
}

function ct_validateForm()
{ //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=ct_validateForm.arguments;

  for (i=0; i<(args.length-2); i+=3)
	{
	test=args[i+2];
	val=ct_findObj(args[i]);
    if (val)
	{
		nm=val.name;
		if ((val=val.value)!="")
		{
			if (test.indexOf('isEmail')!=-1)
			{
				p=val.indexOf('@');
				if (p<1 || p==(val.length-1))
					errors+='- '+nm+' deve conter um endereco de e-mail.\n';
			}
			else
				if (test!='R')
				{
					if (isNaN(val)) errors+='- '+nm+' deve conter um numero.\n';
					if (test.indexOf('inRange') != -1)
					{
						p=test.indexOf(':');
						min=test.substring(8,p); max=test.substring(p+1);
						if (val<min || max<val) errors+='- '+nm+' deve conter um número entre '+min+' e '+max+'.\n';
					}
				}
			}
		else
			if (test.charAt(0) == 'R') errors += '- '+nm+' é obrigatório.\n';
		}
	}
  if (errors)
	  alert('O(s) seguinte(s) erro(s) ocorreu(ram):\n'+errors);
	  document.ct_returnValue = (errors == '');
}

function ct_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.ct_p) d.ct_p=new Array();
    var i,j=d.ct_p.length,a=ct_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.ct_p[j]=new Image; d.ct_p[j++].src=a[i];}}
}

function ct_swapImgRestore() { //v3.0
  var i,x,a=document.ct_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function ct_swapImage() { //v3.0
  var i,j=0,x,a=ct_swapImage.arguments; document.ct_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=ct_findObj(a[i]))!=null){document.ct_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function ct_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function ct_showHideLayers() { //v6.0
  var i,p,v,obj,args=ct_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=ct_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}



/*
Toggle
Use:
<img id="text_icon" src="/includes/imagens/plus.gif" border="0" onClick="toggle('text')"> <a href=""> Expandir </a>
<div id="text_div" style="display:none">Conteudo</div>
*/
function toggle(treeitem, expand, ico)
{
	img_minus = "/includes/imagens/minus.gif";
	if (ico) img_plus = "/includes/imagens/plus.gif";
	var div = document.getElementById(treeitem + "_div");     // W3C DOM level 2
	var icon = document.getElementById(treeitem + "_icon");     // W3C DOM level 2
	if(expand == true){
		div.style.display = "";
		if (ico) icon.src = img_minus;
	}
	else{
		if (div.style.display == "")
		{
			div.style.display = "none";
			if (ico) icon.src = img_plus
			return;
		}
		else
		{
			div.style.display = "";
			if (ico) icon.src = img_minus;
		}
	}
	window.location.hash = treeitem;
}


/*
Esconde ou mostra um Div ou outra TAG que tenha ID=****_div
divIDName = Lista de nome dos ID, nao pode ter espacos e separado por virgula
hide = true-esconde false=mostra
*/
function hideDiv(divIDName, hide)
{
	_divID = divIDName.split(",");
	for(i=0 ; i < _divID.length; i++)
	{
		var div = document.getElementById(_divID[i] + "_div");     // W3C DOM level 2
		if (hide == true)
		{
			div.style.display = "none";
			continue;
		}
		else
		{
			div.style.display = "";
		}
		//window.location.hash = _divID[i];
	}
}
/*
Mostra imagem quando é carregad no campo de envio.
ex.: onChange="img_preview(this,'foto_preview')"
<img src="" width="180" id="thumb" style="visibility: hidden">
*/
function img_preview(o,img_nome)
{
	img = document.getElementById(img_nome);
	img.style.visibility = "";
	img.width=180;
    if(o.value) img.src=o.value;
}

/* Link Voltar */
function voltar()
{
	if(history.length > 1) history.back();
	else alert("Não tem como");
}


function KeyboadCode()
{
	status=event.keyCode;
}
//document.onkeypress=KeyboadCode;


/* Automaticament muda de pagina apos selecionar uma opcao da lista do menu drop 
ex.: onChange="ct_jumpMenuDrop(this,'n_opcoes')"
*/
function ct_jumpMenuDrop(selObj,varName) // 15.04.2004
{
  eval("document.location='" + document.location + "&" + varName + "=" + selObj.options[selObj.selectedIndex].value+"'");
}
