window.onload = callload;

function load(){}//dummy
var g_workarea = '';
var maxnumalert = 0, lastobj = null;


function KeyIsEnter(event)
{
	if ( event.type == 'keypress' )
	{
		var whichCode = (window.Event) ? event.which : event.keyCode;
		if (whichCode == 13) return true;
		else return false;  
	}
}

function MinorFrom(a,b)
{
	if (a > b) return b;
	else return a;
}

function BiggerFrom(a,b)
{
	if (a > b) return a;
	else return b;
}


function intpart(arg)
{
	return parseInt(arg);
}

function isvalidtype(arg)
{
	if (  arg != 'undefined' ) return true;
	else return false;
}

function div(a,b)
{
	if( b==0 ) return 0;
	else return (a/b);
}

function browseBy(frm)
{
	with (frm)
	{
		action += "&op=browseBy"
		submit();
	}
}

function browseBy()
{
	with (document.forms[0])
	{
		action += "&op=browseBy"
		submit();
	}
}

function orderby(column,order)
{
	var frm = document.forms[0];
	var ordstr = column + ' ' + order;
	with (frm)
	{
		frm.ordem.value = ordstr;
		action += "&op=browseBy";
		submit();
	}
}





function URLInsertParam(url,par,val)
{
	var qrystart,page,qry,ret;

	par = par + '=' + val;

	if (url.indexOf('?') < 0 ) 
	{
		qrystart = url.length;
		page = url.substring(0, qrystart);
		qry = '';
	}	
	else
	{
		qrystart = url.indexOf('?')
		page = url.substring(0, qrystart);
		qry = url.substring(qrystart + 1 , url.length);
	}
	
	ret = page + '?' + par + '&' + qry;
	return ret;

}

function nocache(url)
{
	return URLInsertParam(url,'nocache',Math.random());
}

function EncodedURLInsertParam(url,par,val)
{
	var ret;
	ret =  unescape(url);
	ret = URLInsertParam(ret,par,val);
	ret = escape(ret);
	return ret;
}


function URLHasPar(url,par)
{
	var m1 = '?' + par + '=';
	var m2 = '&' + par + '=';

	if ( strhaspart(url,m1) || strhaspart(url,m2)) return true;
		else return false;
}


function EncodedURLHasPar(url,par)
{
	return URLHasPar(unescape(url),par)
}




function callload()
{
	if(exists(load))
		load();
}

function somentenumeros(cod)
{
	var ret = "";
	for(var i=0;i<cod.length;i++) 
	{
		if (isnumber(cod.charAt(i)))
			ret+=cod.charAt(i);
	
	}
	return ret;
}


function log10(num)
{
   return (Math.log(num)/Math.log(10))
}

function tonum(str)
{
	var temp;
	var partes = str.split(",");
	if ( partes.length > 1 ) temp = parseFloat( partes.join(".") );
	else temp = parseFloat( str );
	if (isNaN(temp)) return 0;
	else return temp;
}

function nz(val)
{
	if (isNaN(val)) return 0;
	else return val;
}


function fixfloat(num,dec)
{
	var ax = Math.pow(10,dec)
	return (Math.round(num * ax)/ax);
}


function isnumber(arg)
{
	if (!isvoid(arg) && !isNaN(arg) ) return true;
	else return false;
}


function isvoid(str)
{
	if (str.length==0) return true
	else return false;
}

function todate(str)
{
	var fld = str.split("/");
	var day = fld[0];
	var month = fld[1]-1;
	var year = fld[2];
	return new Date(year,month,day);
}

function isdate(str)
{
	var fld = str.split("/")
	var day = fld[0];
	var month = fld[1];
	var year = fld[2];
	var dt = new Date(year,month-1,day)
	if( (year>1900) && (year<2050) )
		if( month >=1 && month <=12)
			if( day >=1 && day <=31)
				if (!isNaN(dt))return true;
				else return false;
}


function lcase(str){return str.toLowerCase()}
function ucase(str){return str.UpperCase()}



function left(str,howmany)
{
	var a,b;
	if (!isvoid(str))
	{
		a = 0
		b = howmany-1;	
		return str.substring(a,b)
	}
	else return ""
}

function right(str,howmany)
{
	var a,b;
	if (!isvoid(str))
	{
		b = str.length;	
		a = b - howmany
		return str.substring(a,b)
	}
	else return ""
}

function trimleft(str)
{
	var a,b;
	if (!isvoid(str))
	{
		a = 1;
		b = str.length;	
		return str.substring(a,b)
	}
	else return ""
}

function trimright(str)
{
	var a,b;
	if (!isvoid(str))
	{
		a = 0;
		b = str.length-1;	
		return str.substring(a,b)
	}
	else return ""
}

function exists(arg)
{
	if (  typeof(arg) != 'undefined' ) return true;
	else return false;
}


function ocultar()
{
	var aux;

	if (g_workarea == '')
	{
		g_workarea = parent.workarea.cols
		parent.workarea.cols = '0,*'
	}
	else
	{
		aux = g_workarea;
		g_workarea = parent.workarea.cols;
		parent.workarea.cols = aux;
	}
}


/************************************************
* function helpWindow(url)
* abre janelinha com o  arquivo de ajuda para a tarefa especifica
*		Para sintetizar o Javascript
* Parâmetro(s): URL
************************************************/

function helpWindow(url)
{
	open (url, 'help_window', 'scrollbars=yes,status=no,width=300,height=300');

}

/************************************************
* function jump(url)
* Vá para a página especificada. 
*		Para sintetizar o Javascript
* Parâmetro(s): URL
************************************************/

function jump(url)
{
	location.href = url
}


function newwin(url)
{
	open (url, '_blank', 'toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, resizable=yes, width=600, height=400');
}



function popup(url,name,width,height)
{
	open (url, name, 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=no, width=' + width + ', height=' + height + '');
}



/************************************************
* function VerificaForm(frm)
* Verifica há campos vazios.
* Parâmetro(s): formulario a ser verificado
************************************************/
var sendLock = false;
function VerificaForm(frm)
{
	if (isvalidtype(typeof(localconditionsmet)))
		if ( !localconditionsmet() )
			return false;

	if ( exists(frm.required) )
	with(frm)
	{
		for (var i=0;i<length; i++)
		{

			var checks = false;
			buffI = i; //Javascript destroi referencias após certas operações,é preciso salvar contexto
			if (strhaspart(frm.required.value,elements[i].name))
			{
		
				if ((elements[i].type=="text" || elements[i].type=="password" || elements[i].type=="textarea" ) && elements[i].value=="")
				{
					alert("Por favor, preencha o campo indicado.");
					elements[i].focus();
					return false;
				}
				else if ( (elements[i].type=="hidden") && elements[i].value=="")
				{
					alert("Por favor, preencha o campo indicado.");
					return false;
				}


				else if ((elements[i].type=="select-one") && ( elements[i].options[elements[i].selectedIndex].value == "" ) )		
				{
					alert("Por favor, selecione uma opção válida para o campo indicado.");
					elements[i].focus();
					return false;
				}

				else if (elements[i].type=="select-multiple")		
				{
					if ( elements[i].selectedIndex != -1 )
						if ( elements[i].options[elements[i].selectedIndex].value.length > 0 )
							checks = true;

					if(!checks)
					{
						alert("Por favor, selecione uma opção válida para o campo indicado.");
						elements[i].focus();
						return false;
					}
				}

			
			}

	

			i = buffI; // recuperando contexto
		}
	}
	return true;
}


function clear(frm)
{
	if ( confirm("O \"reset\" do formulário equivale a critérios que selecionam todos os registros do BD.\nDeseja continuar?") )
		with(frm)
		{
			for (i=0;i<length; i++)
			{
				if ( (elements[i].type=="text" || elements[i].type=="textarea" ) )
					elements[i].value=""
				else if(elements[i].type=="select-one")
					elements[i].options[0].selected=true      
			}
		}
}


/************************************************
* function erase(url)
* Apaga registro após confirmação,indo para URL 
*		Para sintetizar o Javascript
* Parâmetro(s): URL
************************************************/
function erase(url)
{
	if ( confirm("Você está EXCLUINDO DEFINITIVAMENTE um registro E TODOS os campos relacionados.\nDeseja continuar?") )
	{
		location.href = url;
	}
}


/************************************************
* function formatData(campo)
* completa a data COM BARRAS A medida que vai sendo preenchida
* Parâmetro(s): URL
************************************************/

function formatData(campo)
{
	flds = campo.value.split("/")
	data = new Date(data[2],data[1],data[0]);
	campo.value = ""
}




function confirmaSenha(campo)
{
	if ( prompt("Confirme sua senha") != campo.value )
	{
			alert("Redigite sua senha!"," ");
			campo.focus();
	}
}

function cgc(pcgc)
{
	// verifica o tamanho
	pcgc = somentenumeros(pcgc)
	if (pcgc.length != 14)
	{
		return false;		
	}
	else 
	{
		sim = true
	}

	if (sim)  // verifica se e numero
	{
		for (i=0;((i<=(pcgc.length-1))&& sim); i++)
		{
			val = pcgc.charAt(i)
			if ( isNaN(val) ){sim=false}
		}

		if (sim)  // se for numero continua
		{
			m2 = 2
			soma1 = 0
			soma2 = 0
			for (i=11;i>=0;i--)
			{
				val = eval(pcgc.charAt(i))
				m1 = m2
				if (m2<9) { m2 = m2+1}
				else {m2 = 2}
				soma1 = soma1 + (val * m1)
				soma2 = soma2 + (val * m2)
			}  // fim do for de soma

			soma1 = soma1 % 11
			if (soma1 < 2) {  d1 = 0}
			else { d1 = 11- soma1}
			soma2 = (soma2 + (2 * d1)) % 11
			if (soma2 < 2) { d2 = 0}
			else { d2 = 11- soma2}
			if ((d1==pcgc.charAt(12)) && (d2==pcgc.charAt(13))) return true;
			else return false;
		}
	}

}


function cpf(pcpf)
{

	pcpf = somentenumeros(pcpf)
	if (pcpf.length != 11) {sim=false}
	else {sim=true}

	if (sim )  // valida o primeiro digito
	{
		for (i=0;((i<=(pcpf.length-1))&& sim); i++)
		{
			val = pcpf.charAt(i)
			if (isNaN(val)){sim=false}
		}

			if (sim)
			{
				soma = 0
				for (i=0;i<=8;i++)
				{
					val = eval(pcpf.charAt(i))
					soma = soma + (val*(i+1))
				}

				resto = soma % 11
				if (resto>9) dig = resto -10
				else  dig = resto
				if (dig != eval(pcpf.charAt(9))) { sim=false }
				else   // valida o segundo digito
				{
					soma = 0
					for (i=0;i<=7;i++)
					{
						val = eval(pcpf.charAt(i+1))
						soma = soma + (val*(i+1))
					}

					soma = soma + (dig * 9)
					resto = soma % 11
					if (resto>9) dig = resto -10
					else  dig = resto
					if (dig != eval(pcpf.charAt(10)))
					{
						sim = false;
					}
					else sim = true
				}
			}
	}

	if (sim) return true;
	else return false;
}

/************************************************
* function isValidEmail(campo)
* esta função verifica se um campo contem um email valido
* Parâmetro(s): URL
************************************************/


function isValidCEP(txt)
{
	txt = somentenumeros(txt)
	var num = txt.length
	if (num == 8) return true;
	else return false;
}

function isValidEmail(txt)
{
	var validEmailPattern = /[^\s]*\@[^\s]+/;
	if ( txt.match( validEmailPattern ) == null ) return false;
	else return true;
}

function senhaConfere(Senha,Confirmacao)
{
	if ( Senha.value != Confirmacao.value )
	{
		alert("Senha e confirmação não conferem.\nPor favor, redigite ambos.");
		Senha.value = "";
		Confirmacao.value = "";
		Senha.focus();
		return false;
	}

	else return true;
}


function EnlargedViewCombo(obj)
{
	obj.style.width = 'auto';
}

function NormalViewCombo(obj)
{
	obj.style.width = '100%';
}

function janela(url)
{
	prop = 'left=0,top=0,height=600,width=400,scrollbars=yes,toolbar=no,location=no,status=yes'
	open(url,'nu',prop);
}

function combovalues(combo)
{
		var values = "";
		for (var i=0; i<combo.length; i++)
			if (combo.options[i].selected)
				if (isvoid(values)) values = combo.options[i].value
				else values += ", " + combo.options[i].value;
		return values;
}


function strhaspart(str,chars)
{
	return (str.indexOf( chars ) != -1);
}

function hasonlychars(obj,chars)
{
	var str = obj.value
	for (var i = 0; i < str.length; i++)
		if (chars.indexOf( str.charAt(i) ) == -1) return false; 
	return true
}

function update_go(_url)
{
	var frm = document.forms[0];
	if ( VerificaForm(frm) )
		with(frm)
		{	action += "?op=save&returnto=" + _url;
			submit();
		}
}

function delete_go(_url)
{
	var frm = document.forms[0];
	if ( confirm('Deseja realmente apagar este registro?') )
		with(frm)
		{	action += '?op=delete&returnto=' + _url;
			submit();
		}
}

function cmbreset(obj){	obj.options[0].selected=true }
function cmb_reset(objstr){	var obj = documentitembyname(objstr); obj.options[0].selected=true }
function cmbmultiple_reset(obj)
{
	if (obj.type == "select-multiple")
	{	for (var i=0; i < obj.length; i++)
			obj.options[i].selected = false;
	}	
}
function cmbtext(obj) {	return obj.options[obj.selectedIndex].text }


function cmbmultipletext(obj)
{
	var  cmbtext = ""	
	if (obj.type == "select-multiple")
	{
		for (var i = 0; i < obj.options.length; i++ )
		{
			if ( obj.options[i].selected)
			{
				if (!isvoid(cmbtext)) cmbtext += ', '	
				cmbtext += obj.options[i].text
			}
		}
	
	}
	return cmbtext;
}


function swap_multiple(commalist)
{
	var itens = commalist.split(",");
	for (var i=0;i<itens.length;i++ )
	{
		eval("swapitem('" + itens[i] + "')");
	}

}

function css_show_multiple(commalist)
{
	var itens = commalist.split(",");
	for (var i=0;i<itens.length;i++ )
	{
		eval("css_show('" + itens[i] + "')");
	}

}

function css_hide_multiple(commalist)
{
	var itens = commalist.split(",");
	for (var i=0;i<itens.length;i++ )
	{
		if (exists(documentitembyname(itens[i])))
			eval("css_hide('" + itens[i] + "')");
	}

}
function hide_swap(hidelist,swaplist)
{
	css_hide_multiple(hidelist)
	swap_multiple(swaplist)
}




function documentitembyname(objstr){ return eval('document.all.item(\'' + objstr + '\')'); }
function formitembyname(objstr){ return eval('document.forms[0].' + objstr); }
function css_show(objstr){	var obj = documentitembyname(objstr); obj.style.visibility = 'visible';	obj.style.position = 'relative'; }
function css_hide(objstr){ var obj = documentitembyname(objstr); obj.style.visibility = 'hidden'; obj.style.position = 'absolute'; }
function input_disable(objstr){ eval('document.forms[0].' + objstr + '.disabled = true'); }
function input_enable(objstr){ eval('document.forms[0].' + objstr + '.disabled = false');}


function input_disable_obj(obj){ obj.disabled = true; }
function input_enable_obj(obj){ obj.disabled = false; }

function text_reset(obj){ obj.value = ''}
function text_setreadonly(obj){ obj.readOnly = true; }
function text_unsetreadonly(obj){ obj.readOnly = false;}

function swapitem(objstr)
{
	var obj = documentitembyname(objstr);
	if( obj.style.visibility == 'hidden' ) css_show(objstr);
	else css_hide(objstr);
}

function maxlength(fld,maxlength)
{
	if (fld.value.length > maxlength)
	{
		alert('Tamanho máximo é ' + maxlength + ' caracteres.');
		fld.focus();
		return false;
	}
	else return true;

}

function domaindir(dir)
{
	var base,lastchar;
	base = 'http://' + location.host
	return ( base + dir );
}