var Checar
Checar = true;
var NNav = ((navigator.appName == "Netscape"));
var debugNav = false;
var AgntUsr	= navigator.userAgent.toLowerCase();
var AppVer	= navigator.appVersion.toLowerCase();
var DomYes	= document.getElementById ? 1:0;
var NavYes	= AgntUsr.indexOf('mozilla') != -1 && AgntUsr.indexOf('compatible') == -1 ? 1:0;
var ExpYes	= AgntUsr.indexOf('msie') != -1 ? 1:0;
var Opr		= AgntUsr.indexOf('opera')!= -1 ? 1:0;
var NavYes	= AgntUsr.indexOf('mozilla') != -1 && AgntUsr.indexOf('compatible') == -1 ? 1:0;
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

function montaCombo(frm,comboSource,comboDestination,counter,letter)
{
	//alert(counter);
	//alert(comboSource.value);

	comboLen=comboDestination.length;
	for (c=1;c<comboLen+1;c++)
	{
		comboDestination.options[1]=null;
	}
	//alert(comboDestination.options[1].text);
	
	for(k=1;k<counter;k++)
	{
		str=frm.item(letter + k).value;
		strPos=str.indexOf("-");
		strTest=str.substr(0,strPos)
		//alert("-" + strTest + "-" + comboSource.value + "-");
		if (strTest == comboSource.value)
		{
			//alert("entrou");
			str=str.substr(strPos+1);
			strPos=str.indexOf("-");
			sig_campo=str.substr(0,strPos);
			nom_campo=str.substr(strPos+1);
			//alert(sig_campo + " - " + nom_campo);
			var newOption = new Option(nom_campo, sig_campo);
			//alert(comboDestination.length);
			comboDestination.options[comboDestination.length]=newOption;
		}	
	}
}

//--- Funçoes inseridas no prototipo dos objetos embutidos do jscript. ---//
//--- Isaque                                                     ---//

//Insercao da funcao trim dentro da classe string		
String.prototype.trim = function()
{
    return this.replace(/(^\s*)|(\s*$)/g, "");
}


//Insercao da funcao format dentro da classe number		
Number.prototype.format = function(intSize)
{
	var s = this.toString();
	var l = s.length;

	for (var i = 0; i < intSize - l; i++)
	{
		s = "0" + s;	
	}

	return s;
}

//Insercao da funcao now na classe date
Date.prototype.now = function()
{
		var dia;
		var d;
				
		dia = new Date();
		d = dia.getDate().format(2) + "/";
		d += (dia.getMonth() + 1).format(2) + "/";
		d += dia.getFullYear();
		
		return d;
}

//Transforma uma hora em uma data - hora, e uma data em uma data - hora.
String.prototype.toDate = function()
{
	var args = arguments;
	var d = new Date(0);
	var strDate = this.valueOf();
		
	strDate = strDate.trim();
		
	if (args.length > 0)
	{
		if (args[0])
		{
			var tmpY = strDate.substr(0, 4);
			var tmpM = strDate.substr(5, 2);
			var tmpD = strDate.substr(8, 2);
			
			strDate = tmpD + "/" + tmpM + "/" + tmpY;
		}
	}
	
	var j = 0;
	var i = strDate.indexOf("/", j);

	if (i > 0)
	{
		d.setDate(strDate.substr(j, i - j));
	}
		
	j = i + 1;
	var i = strDate.indexOf("/", j);

	if (i > 0)
	{
		d.setMonth(strDate.substr(j, i - j) - 1);
	}

	j = i + 1;
	var i = strDate.indexOf(" ", j);

	if (i > 0)
	{
		var y = strDate.substr(j, i - j);
		if (y.length <= 2)
		{
			if (y.length == 1) y = "0" + y;
			
			var ny = now.getFullYear().toString(); 
			y = ny.substr(0, ny.length - 2) + y; 			
		}
		
		d.setFullYear(y);
	}

	j = i + 1;
	var i = strDate.indexOf(":", j);

	if (i > 0)
	{
		d.setHours(strDate.substr(j, i - j));
	}

	j = i + 1;
	var hasTime = false;
	var i = strDate.indexOf(":", j);

	if (i > 0)
	{
		hasTime = true;
		d.setMinutes(strDate.substr(j, i - j));
	}

	j = i + 1;
	if (hasTime)
	{
		d.setSeconds(strDate.substr(j, strDate.length - j + 1));
	}
	
	return d;
}
 
//Insercao da funcao dateDiff na classe date
Date.prototype.dateDiff = function(unit, dini, dout)
{
	
	unit = unit.toLowerCase();
	switch(unit)
	{		
		//Retorna o intervalo em segundos.
		case "s":
			return Math.floor((dout - dini) / 1000);			
			break;

		//Retorna o intervalo em minutos.
		case "n":
			return Math.floor((dout - dini) / 60000);			
			break;

		//Retorna o intervalo em horas.
		case "h":
			return Math.floor((dout - dini) / 3600000);			
			break;

		//Retorna o intervalo em dias.
		case "d":
			return Math.floor((dout - dini) / 86400000);			
			break;

		//Retorna o intervalo em mês.
		case "m":
			return Math.floor((dout - dini) / 2592000000);			
			break;

		//Retorna o intervalo em anos.
		case "y":
			return Math.floor((dout - dini) / 946080000000);			
			break;
	}
	
	return null;
}


//Retorna true se a string ou char for composta somente por letras.
String.prototype.isAlpha = function()
{
	return (this.toLowerCase().match(/[a-z]+/g) == this.valueOf().toLowerCase());
}

//Retorna true se a string ou char for composta somente por numeros.
String.prototype.isNum = function()
{
	return (this.match(/[0-9]+/g) == this.valueOf());
}

//Retorna true se a string ou char for composta somente por letras e numeros.
String.prototype.isAlphaNum = function()
{
	return (this.toLowerCase().match(/([a-z]|[0-9])+/g) == this.valueOf().toLowerCase());
}

//Retorna true se a string estiver num formato valido de data(nao verifica mes, dia ou ano somente o formato).
String.prototype.isDate = function()
{
	return (this.match(/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2}([0-9]{2}){0,1})/g) == this.valueOf());
}

function dateValid(ObjDate) 
{
var err = "";
var strDay;
var strMonth;
var strYear;
var strHour;
var strMin;

strDate = ObjDate.value;

if (strDate.length == 0)
	return;

if (strDate.length > 9 && strDate.length < 15)
{
	strDay = strDate.substr(0, 2);
	strMonth = strDate.substr(3, 2);
	strYear = strDate.substr(6, 4);
	strHour = "00";
	strMin = "00";
}

if (strDate.length>15) 
{
	strDay = strDate.substr(0, 2);
	strMonth = strDate.substr(3, 2);
	strYear = strDate.substr(6, 4);
	strHour = strDate.substr(11, 2);
	strMin = strDate.substr(14, 2);
}

intday = parseInt(strDay, 10);
if (isNaN(intday))
	err = "O dia da sua data não é um número \n";

intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth))
	err += "O mês de sua data é invalido \n";

intYear = parseInt(strYear, 10);
if (isNaN(intYear))
	err += "O ano de sua data é invalido \n";

if (intMonth>12 || intMonth<1)
	err += "O mês de sua data é invalido \n";

if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
	err += "O dia da sua data é invalido \n";

if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
	err += "O dia da sua data é invalido \n";

if (intMonth == 2)
	if (intday < 1)
		err += "O dia da sua data é invalido \n";

if (LeapYear(intYear) == true) 
{
	if (intMonth==2 && intday > 29) {
		err += "O dia da sua data é invalido \n";
		}
}
else 
{
	if (intMonth==2 && intday > 28) 
	{
		err += "O dia da sua data é invalido \n";
    }
}

intHour = parseInt(strHour, 10);
if (intHour > 23 || intHour < 0) 
	err += "A sua hora é invalida \n";

intMin = parseInt(strMin,10);
if (intMin > 59 || intMin < 0)
	err += "Os seus minutos são invalidos \n";
	
if (err != "")
{
	alert(err);
	ObjDate.focus();
	return false;
}

return true;
}

function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}

function SaltaCampo (campo,prox,tammax,teclapres)
{
	tecla = teclapres.keyCode
	vr = campo.value
	if(tecla==109 || tecla==188 || tecla==110 || tecla==111 || tecla==223 || tecla==108 )
		campo.value = vr.substr(0,vr.length-1)
	else
	{
	 	vr = vr.replace("-","")
	 	vr = vr.replace("/","")
	 	vr = vr.replace("/","")
	 	vr = vr.replace(",","")
	 	vr = vr.replace(".","")
	 	vr = vr.replace(".","")
	 	vr = vr.replace(".","")
	 	vr = vr.replace(".","")
	 	tam = vr.length	

	 	if (tecla!=0 && tecla!=9 && tecla!=16)
			if (tam==tammax)	
				prox.focus()
	}
}

function CheckNumerico(campo,tammax,teclapres)
{
	var tecla = teclapres.keyCode;
	if ((tecla >= 48) && (tecla <= 57))
		return;

	if ((tecla >= 96) && (tecla <= 105))
		return;

	if ((tecla == 16) || (tecla == 37) || (tecla == 39) || (tecla == 8) || (tecla == 9) || (tecla == 46))
		return;
				
	return false;
}

function FormataValor(campo,tammax,teclapres,prec) 
{
	//pegar tecla e definir valor de virgula
	var tecla = teclapres.keyCode;
	var virgula = ',';
	
	//pegar valor do campo atual e remover todas virgulas, pontos, barras etc...
	vr = campo.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	
	//se precisao for 0 definir virgula como inexistente para n?o aparecer	
	if (prec==0)
		virgula='';
	
	//antes de checar tamanho do campo remover 0s da frente do campo	
	for (k=0;k<prec;k++)
	{
		if (vr.substr(0,1) == '0')
			vr=vr.substr(1,prec+1);
	}
	
	//pegar tamanho dos valores j? limpos
	tam = vr.length;
	
	//se tamanho for zero n?o fazer nada
	if (tam==0)
		return
		
	//se teclas apertadas forem numericas, backspace, del etc.... entrar em if
	if (!tecla || tecla==8 || tecla==46 || ((tecla <= 57 && tecla >= 48) || (tecla <=105 && tecla >= 96)))
	{
		//if para campos de valores fracionais ate 0,999
		if ( tam <= prec + 1){
			campo.value = '0' + virgula;
			for (k=1;k<=prec-tam;k++) 
			{
				campo.value += '0' ; 
			}
			campo.value+=vr;
		}
		
		//if para campos com valores at? 999,999
		if ( (tam > prec) && (tam <= prec + 3) ){
			campo.value = vr.substr(0,tam-prec) + virgula + vr.substr(tam-prec,prec+1) ; }
	 	
	 	//if para campos com valores at? 999.999,999	
		if ( (tam > prec + 3) && (tam <= prec + 6) ){
			campo.value = vr.substr(0, tam-(prec+3)) + '.' + vr.substr(tam-(prec+3), 3) + virgula + vr.substr(tam-prec, prec+1) ; }
	 	
	 	//if para campos com valores at? 999.999.999,999	
		if ( (tam > prec + 6) && (tam <= prec + 9) ){ 	
			campo.value = vr.substr(0, tam-(prec+6) ) + '.' + vr.substr(tam-(prec+6), 3) + '.' + vr.substr(tam-(prec+3),3 ) + virgula + vr.substr(tam-prec, prec+1) ; }

		//if para campos com valores at? 999.999.999.999,999				
		if ( (tam > prec + 9) && (tam <= prec + 12) ){
			campo.value = vr.substr(0, tam-(prec+9)) + '.' + vr.substr(tam-(prec+9), 3) + '.' + vr.substr(tam-(prec+6), 3) + '.' + vr.substr(tam-(prec+3), 3) + virgula + vr.substr(tam-prec,prec+1) ; }
			
		//if para campos com valores at? 999.999.999.999.999,999				
		if ( (tam > prec + 12) && (tam <= prec + 15) ){
			campo.value = vr.substr(0, tam-(prec+12)) + '.' + vr.substr(tam-(prec+12), 3) + '.' + vr.substr(tam-(prec+9), 3) + '.' + vr.substr(tam-(prec+6), 3) + '.' + vr.substr(tam-(prec+3), 3) + virgula + vr.substr(tam-prec,prec+1) ; }
	 		
		//if ( (tam >= 15) && (tam <= 17) ){
		//	campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + virgula + vr.substr( tam - 2, tam ) ;}
	}
	
	return;
	
}



function FormataData(Campo,teclapres) {
	tecla = teclapres.keyCode
	vr = Campo.value
	vr = vr.replace("-", "")
	vr = vr.replace(".", "")
	vr = vr.replace("/", "")
	vr = vr.replace("/", "")
	vr = vr.replace(" ", "")
	tam = vr.length + 1
	
	if (tecla!=9 && tecla!=8 && tecla!=190 && tecla!=108 && tecla!=109 && tecla!=189 && tecla!=111 && tecla!=223)
	{
		if (tam==3)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,tam)
		if (tam==5)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,tam)
		if (tam==9)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,tam) + ' '
		if (tam==11) 
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,4) + ' ' + vr.substr(8,2) + ":"	
	}
}

function checkTicked(campo,formulario)
{
	if (campo!=null)
	{
		for (k=0;k<campo.length;k++)
		{
			if (campo.item(k).checked)
			{
				formulario.submit();
				return true;
			}
		}
		if (campo.checked)
		{
			formulario.submit();
			return true;
		}
		
	}
	alert("Você deve selecionar pelo menos um item!")
}

function enableSave(divID,divIDDisabled)
{
	divID.style.display="";
	if (divIDDisabled)
		divIDDisabled.style.display="none";
}

function checkSaveEnabled(divID,form,clicked)
{
	if (divID.style.display=="" && !clicked)
		{
			event.returnValue = "Registro não foi salvo, deseja sair sem salvar ?";
		}
}

function trim(str)
{
	while(''+str.value.charAt(0)==' ')str.value=str.value.substring(1,str.value.length);
	while(str.value.charAt(str.value.length) == ' ')str.value=str.value.substring(1,str.value.length-1); 
}

function strim(str)
{
	while(''+str.value.charAt(0)==' ') str.value=str.value.substring(1,str.value.length)
	while(str.value.charAt(str.value.length-1)==' ') str.value=str.value.substring(0,str.value.length-1)
}
function FormataDataMesAno(Campo,teclapres) {

  //=======================================================
  //Por Júlio César Jardim Júnior em 23/01/2002
  //Formata Campo de Edição no padrão "DD/MMMM"
  //=======================================================

		tecla = teclapres.keyCode
		vr = Campo.value
		vr = vr.replace("-", "")
		vr = vr.replace(".", "")
		vr = vr.replace("/", "")
		vr = vr.replace("/", "")
		vr = vr.replace(" ", "")
		tam = vr.length + 1
		if (tecla!=9 && tecla!=8 && tecla!=190 && tecla!=108 && tecla!=109 && tecla!=189 && tecla!=111 && tecla!=223)
				{
				  if (tam==3) Campo.value = vr.substr(0,2) + '/' + vr.substr(3,tam)
				}
}

function ValidaDataMesAno(ObjDate) {

		//=======================================================
  //Por Júlio César Jardim Júnior em 23/01/2002
		//Valida Campo de Edição no padrão "DD/MMMM"
  //=======================================================

  //Variáveis Gerais		
  var strErro = "";
		var strDate;
		var strMonth;
		var strYear;
  var intMonth;
  var intYear;
		
		//Principal
  strDate = ObjDate.value;
		if (strDate.length == 0) return;
		if (strDate.substr(2, 1) != "/" || strDate.length != 7) strErro = "Formato DD/MM, inválido! \n";
		if (strDate.length == 7)
				{
						strMonth = strDate.substr(0, 2);
	     strYear = strDate.substr(3, 4);
						intMonth = parseInt(strMonth, 10);
						if (isNaN(intMonth)) strErro += "O mês de sua data é invalido \n";
						intYear = parseInt(strYear, 10);
						if (isNaN(intYear)) strErro += "O ano de sua data é invalido \n";
						if (intMonth>12 || intMonth<1) strErro += "O mês de sua data é invalido \n";
				}
		if (strErro != "") 
  {
    alert(strErro);
    ObjDate.focus();
    return false;
  }
		return true;

}

function CheckUnicoDireciona(chkCheck, strDireciona, strParametros) {

		//===============================================================
  //Por Júlio César Jardim Júnior em 25/01/2002
		//Se encontrar apenas um "Check" marcado redireciona a página
  //===============================================================

  var intI;
  var intCount;
  var strChaves; 
  var intPos;
  var strParte; 
  var intPos2;
  var strParte2; 

  intCount = 0;

  if (chkCheck.value) 
    {
      strChaves = chkCheck.value;
      intCount++;
    }

  if (chkCheck!=null)
  {
				for (intI=0;intI<chkCheck.length;intI++)
						{
								if (chkCheck.item(intI).checked) 
										{
												strChaves = chkCheck.item(intI).value;
												intCount++;
										}
								if (intCount >= 2) 
										{
												alert('Existe mais de um item selecionado na lista.');
												return;
										}
						}
  }

  if (intCount == 0)
    {
      alert('Selecione pelo menos um item da Lista.');
      return;
    }

  if (strDireciona!= '' && intCount == 1) 
    {
      intPos = strParametros.indexOf(";");
      intPos2 = strChaves.indexOf(";");
		while ( intPos != -1 ) 
        {
		  strParte = strParametros.substr(0,intPos);
          strParte2 = strChaves.substr(0,intPos2);
          strDireciona = strDireciona + '&' + strParte + '=' + strParte2
          strParametros = strParametros.substr(intPos + 1);
          strChaves = strChaves.substr(intPos2 + 1);
          intPos = strParametros.indexOf(";");
          intPos2 = strChaves.indexOf(";");
		}
      strDireciona = strDireciona + '&' + strParametros + '=' + strChaves
      document.location=strDireciona;
    }

}
//===============================================================
  //Por isaque  em 10/09/2002
//   altera "de" para "strPara" na varíavel informada 
  //===============================================================
function fReplace(campo,strDe,strPara)
{
  while ( campo.indexOf(strDe) != -1 )
  {
    campo = campo.replace(strDe,strPara);
   }
  return campo;
}

//===============================================================
// Alterado por isaque  em 25/02/2003
// formata hora
// ==============================================================
function FormataHora(Campo,teclapres) {
	tecla = teclapres.keyCode
	vr = Campo.value
	vr = vr.replace("-", "")
	vr = vr.replace(".", "")
	vr = vr.replace("/", "")
	vr = vr.replace("/", "")
	vr = vr.replace(" ", "")
	vr = vr.replace(":", "")
	tam = vr.length + 1
	
	if (tecla!=9 && tecla!=8 && tecla!=190 && tecla!=108 && tecla!=109 && tecla!=189 && tecla!=111 && tecla!=223)
	{
		if (tam==3)
			Campo.value = vr.substr(0,2) + ':' + vr.substr(2,tam)
		if (tam==5)
			Campo.value = vr.substr(0,2) + ':' + vr.substr(2,2) 
	}
}

function TimeValid(ObjDate) 
{
var err = "";
var strHour;
var strMin;

strDate = ObjDate.value;


if (strDate.length == 0)
	return;

if (strDate.length > 4) 
{
	strHour = strDate.substr(0, 2);
	strMin = strDate.substr(3, 2);

  intHour = parseInt(strDate.substr(0, 2), 10);
  if (intHour > 23 || intHour < 0) 
	err += "A sua hora é invalida \n";

  intMin = parseInt(strDate.substr(3, 2),10);
  if (intMin > 59 || intMin < 0)
	err += "Os seus minutos são invalidos \n";
}	
if (err != "")
{
	alert(err);
	ObjDate.focus();
	return false;
}

return true;
}

   function CheckAll(ObjForm, NameButton)
    {
	var len = ObjForm.elements.length;
	for (var i = 0; i < len; i++) {
	    var e = ObjForm.elements[i];
	    if (e.name == NameButton) {
		e.checked = true;
	    }
	}
    }

    function ClearAll(ObjForm, NameButton)
    {    
	var len = ObjForm.elements.length;
	for (var i = 0; i < len; i++) {
	    var e = ObjForm.elements[i];
	    if (e.name == NameButton) {
		e.checked = false;
	    }
	}
    }
	function AllChecked(ObjForm, NameButton)
    {
	len = ObjForm.elements.length;
	for(var i = 0 ; i < len ; i++) {
	    if (ObjForm.elements[i].name == NameButton && !ObjForm.elements[i].checked) {
		return false;
	    }
	}
	Checar = false;
	return true;
    }
	function Toggle(e, ObjForm, NameButton)
    {
	if (e.checked) {
	    AllChecked(ObjForm, NameButton);
	}
	else {
	    Checar = true;
	}
    }

    function ToggleAll(ObjForm, NameButton)
    {
	if (Checar) {
	    CheckAll(ObjForm, NameButton);
		Checar = false;
	}
	else {
	    ClearAll(ObjForm, NameButton);
		Checar = true;
	}
    }
    
    
    function ComparaDataHora(dtmaior, dtmenor)
{
//compara duas datas e retorna true se dtmaior for maior que a dtmenor ou false se não for
//converte as datas para tipo Date()

	var Date_Maior;
	var Date_Menor;
	
    dtmaior = dtmaior.substr(0,16);
    dtmenor = dtmenor.substr(0,16);
    
	Date_Maior = dtmaior.substr(dtmaior.length-10,4) + dtmaior.substr(3,2) + dtmaior.substr(0,2) + dtmaior.substr(11,2) + dtmaior.substr(14,2);
	Date_Menor = dtmenor.substr(dtmenor.length-10,4) + dtmenor.substr(3,2) + dtmenor.substr(0,2) + dtmenor.substr(11,2) + dtmenor.substr(14,2);

	return (Date_Maior > Date_Menor);
}

function ComparaData(dtmenor, dtmaior)
{
//compara duas datas e retorna true se data maior for maior que a menor ou false se não for
//converte as datas para tipo Date()

	var Date_Ini;
	var Date_Fin;
	
    dtini = dtmenor.substr(0,10);
    dtfin = dtmaior.substr(0,10);
    
	Date_Ini = dtmenor.substr(dtini.length-4,4) + dtmenor.substr(3,2) + dtmenor.substr(0,2);
	Date_Fin = dtmaior.substr(dtfin.length-4,4) + dtmaior.substr(3,2) + dtmaior.substr(0,2);


	return (Date_Ini <= Date_Fin);
}

function ComparaPeriodo(dtini, dtfin)
{
//retorna periodo em dias entre as duas datas

	var Date_Ini;
	var Date_Fin;
	dtfin = dtfin.substr(0,10);
	
	Date_Ini = dtini.substr(3,2) + '/' + dtini.substr(0,2) + '/' + dtini.substr(dtini.length-4,4);
	Date_Fin = dtfin.substr(3,2) + '/' + dtfin.substr(0,2) + '/' + dtfin.substr(dtfin.length-4,4);

    dtini = new Date(Date_Ini);
    dtfin = new Date(Date_Fin);
        
	return (dtfin - dtini) / 86400000;
	}
	
	function timeFormat(strTime)
	{
		var h = 0;
		var m = 0;
		
		strTime = strTime.trim();
		if (strTime == "") return "";
		
		var i = strTime.indexOf(":");
		if (i >= 0)
		{
			h = strTime.substr(0, i);
			m = strTime.substr(i+1, strTime.length - i);
		}
		else
		{
			h = strTime;
			m = 0;
		}
		
		if (m == "") m = 0;

		if (m > 59) return "";
		if (h > 23) return "";
		
		if (h.toString().length == 1) h = "0" + h;
		if (m.toString().length == 1) m = "0" + m;
		
		return h + ":" + m;
	}


/*
Funções que transformam uma combo numa combo com pesquisa dinâmica
Isaque  - Att/Ps
17/07/2003
*/
	function SimpleCombo(obj)
	{
		obj.auxValue = "";
		obj.onkeypress = Combo_KeyPress;
		obj.onkeydown  = Combo_KeyDown;
		obj.onclick = Combo_Click;
		
		
	}

	function Combo_KeyPress()
	{		
		var old = this.auxValue;
		var val = old + String.fromCharCode(event.keyCode).toLowerCase();
		var ind = this.selectedIndex;
		
		if (this.onchange)
		  {
		    this.onchange();
		  }

		for (var i = 0; i < this.options.length; i++)
		{
			var txt = this.options[i].label.toLowerCase();
			
			if (txt.indexOf(val) == 0)
			{
				this.selectedIndex = i;
				this.auxValue = val;
				return false;
			}
		}
						
		return false;
	}

	function Combo_KeyDown()
	{
	   
       if (event.keyCode == 8)
		{
			this.auxValue = this.auxValue.substr(0, this.auxValue.length - 1);

			for (var i = 0; i < this.options.length; i++)
			{
				var txt = this.options[i].label.toLowerCase();
				
				if (txt.indexOf(this.auxValue) == 0)
				{
					this.selectedIndex = i;
					return false;
				}
			}
		}		
	   else if (event.keyCode == 13)
		{
		    this.auxValue = '';
            return;
			
		}		
	
	}	
	function Combo_Click()
	 {
	    this.auxValue = '';
        return;
      }
	  
	function mask(textbox, mask){
	var str = textbox.value;
	var strRet = '';
	var m = null;
	var v = null;
	for (var i = 0; i < str.length; i++){
		m = mask.substring(i, i+1);
		v = str.substring(i, i+1);
		if (v != m && m != '#'){
			if (mask.length == i+1)
				strRet = strRet + m;
			else
				strRet = strRet + m + v;
		}else{
			strRet = strRet + v;
		}
	}
	textbox.value = strRet;
	return true;
	}	  


	function formataTelefone(campo,evt)
	{
	    var tecla = evt.keyCode;
		
		vr = campo.value;
	    tam = vr.length;
		
		if ( tecla != 9 && tecla != 8 && tecla != 0 )
	    {
	        if ( tam == 1){
	            vr = '('+vr;
	        }    
	        if ( tam > 1 && tam < 5 ){	            
	            vr = vr.substr( 0, tam );
	        }    
	        if(tam == 4){
		        vr = vr+')';
		    }    
	        if( tam > 6 && tam < 10 ){     
	            vr = vr.substr( 0, tam );
	        }    
	        if(tam == 9){
		        vr = vr+'-';
		    }    
	        if( tam > 11 && tam <= 15 ){     
	        	vr = vr.substr( 0, tam );
	        }   
			campo.value =  vr;
						  
	        return false;
	    }
	}
	
	function PopUp(ref)
	{	
		var strFeatures="toolbar=no,status=no,menubar=no,location=no"
		strFeatures=strFeatures+",scrollbars=yes,resizable=yes,dialogWidth:300, dialogHeight:200"
		newWin = window.open(ref,"TellObj","resizable=yes,scrollbars=yes,width=300,height=200");
		//newWin.opener = top;
	}
	
	function janela(url,wa,ha,props,alvo,max,posX,posY) {
	var w = 720;
	var h = 350;
	var t = "";
	var p = "";
	var win;

	if (arguments[1] && arguments[1] != "" && arguments[1] != "0") //Largura
		w = wa;
	if (arguments[2] && arguments[2] != "" && arguments[2] != "0") //Altura
		h = ha;
	p = "resizable=yes,scrollbars=yes,width="+w+",height="+h;
	if (arguments[3] && arguments[3] != "") //Propriedades
		p = props;
	if (arguments[4] && arguments[4] != "") //Alvo
		t = alvo;

	win = window.open(url,t,p);

	if (arguments[5] && arguments[5] != "" && arguments[5] != "N") //Redimensiona
	{
		//Retirar ap?s resolver problema de privil?gios para Mozilla
		if(!NavYes)
			redimensiona(win);
	}
	else if(url.indexOf("http") == -1 && (props == "" || ""+props == "undefined"))
	{
		var posCentro = getPosicaoCentro(w,h,posX, posY);
		win.moveTo(posCentro.moveCentroX,posCentro.moveCentroY);
	}

	return win;
}

/**
* Fun??o que recupera o correto posicionamento central para uma janela popup
* @param w Largura da janela. [String, OB]
* @param h Altura da janela. [String, OB]
* @param posX posi??o x onde a janela deve ser criada. [String, OP]
* @param posY posi??o y onde a janela deve ser criada. [String, OP]
* @return posicaoCentro Objeto com os valores para posicionamento da janela [Object]
*/
function getPosicaoCentro(w,h,posX, posY){

	var moveCentroX 	= 0;
	var moveCentroY 	= 0;

	if( (posX && posX != "") || (posY && posY != "") ) {
		if(posX && posX != "")
			moveCentroX = posX;
		if(posY && posY != "")
			moveCentroY = posY;
	}
	else {
		//Centralizar janela popup
		if(NavYes)
		{
			moveCentroX 	= window.screenX + ((window.outerWidth - w) / 2);
			moveCentroY 	= window.screenY + ((window.outerHeight - h) / 2);
			//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
		}
		else
		{
			moveCentroX = (screen.availWidth/2);
			moveCentroX = moveCentroX - (w/2);
			moveCentroY = (screen.availHeight/2);
			moveCentroY = moveCentroY - (h/2);
		}
	}

	var posicaoCentro = new Object(moveCentroX, moveCentroY);
	posicaoCentro.moveCentroX 	= moveCentroX;
	posicaoCentro.moveCentroY 	= moveCentroY;
	return posicaoCentro;
}

function enviaPage(url, metodo, modo, tagId, parametros)
{
    goAjax( url+"?"+parametros+"&rnd"+ Math.random() , metodo, modo , tagId); 
}

function goAjax(url, metodo, modo, tagRetorno, parametros) {
        document.getElementById(tagRetorno).innerHTML='<div align="center" class="carregando"><br /><br />carregando...</div>'

            if(metodo == "GET") {
                xmlhttp.open("GET", url, modo);
            } else {        
                xmlhttp.open("POST", url, modo);
                xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
                xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
                xmlhttp.setRequestHeader("Pragma", "no-cache");
            }    
            
            xmlhttp.onreadystatechange = function() {
                if(xmlhttp.readyState == 4) {
                    retorno=xmlhttp.responseText
                    document.getElementById(tagRetorno).innerHTML=retorno
                    //findScript(retorno)
                }
            }
            if(metodo == "GET") {
                xmlhttp.send(null);
            } else {        
                xmlhttp.send(parametros);
            }
}

	function AtualizaCidades(display)
	{
		if(display!='X'){		
			frmComboCidade.navigate("../actions.asp?op=1&seq_uf=" + document.formulario.seq_uf.value + "&seq_cidade=" + document.formulario.seq_cidade_aux.value + "&diplaybairro=" + display);
			return;
		}else{
			frmComboCidade.navigate("actions.asp?op=1&seq_uf=" + document.formularioPesquisa.seq_uf_pesq.value + "&seq_cidade=" + document.formularioPesquisa.seq_cidade_aux_pesq.value + "&diplaybairro=" + display + "&pesquisa=" + true);	
		}
	}
	
	function AtualizaBairros(concate)	
	{
		try{		  
		  if(concate!='X'){			  	
			frmComboBairro.navigate(concate + "actions.asp?op=2&seq_cidade=" + document.formulario.seq_cidade.value + "&seq_bairro=" + document.formulario.seq_bairro_aux.value);
			return;
		  }else{			
			frmComboBairro.navigate("actions.asp?op=2&seq_cidade=" + document.formularioPesquisa.seq_cidade_pesq.value + "&seq_bairro=" + document.formularioPesquisa.seq_bairro_aux_pesq.value + "&pesquisa=" + true);			
			return;  
		  }
		}catch(e){}
		
	}
	
	// validate.js v 1.98
// a generic form validator 
// by Brian Lalonde http://webcoder.info/downloads/
// This work is licensed under the Creative Commons Attribution-Share Alike 3.0 License. 
// To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ 
// or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.

function formFocus()
{ // convenient way to start the form onLoad
  if(!document.forms.length) return;
  var els= document.forms[0].elements;
  for(var i= 0; i < els.length; i++)
    if(els[i].type != 'hidden') { els[i].focus(); return; }
}

function fieldname(fld)
{ // get the field label text or name
  if(fld.id && document.getElementsByTagName)
  {
    for(var i= 0, lbl= document.getElementsByTagName('LABEL'); i < lbl.length; i++)
      if(lbl[i].htmlFor==fld.id) return lbl[i].nodeValue||lbl[i].textContent||lbl[i].innerText;
    for(var i= 0, lbl= document.getElementsByTagName('label'); i < lbl.length; i++)
      if(lbl[i].htmlFor==fld.id) return lbl[i].nodeValue||lbl[i].textContent||lbl[i].innerText;
  }
  return fld.name;
}

function requireValue(fld)
{ // disallow a blank field
  if(fld.disabled) return true;
  if(!fld.value.length)
  { status= 'The '+fieldname(fld)+' field cannot be left blank.'; return false; }
  return true;
}

function requireChecked(fld)
{ // require a checkbox to be checked
  if(fld.disabled) return true;
  if(!fld.checked)
  { status= 'The '+fieldname(fld)+' checkbox must be checked.'; return false; }
  return true;
}

function requireConfirmation(fld,confirmfld)
{ // require fields to match
  if(fld.disabled) return true;
  if(fld.value != confirmfld.value)
  { status= 'The '+fieldname(fld)+' field does not match the '+fieldname(confirmfld)+' field.'; return false; }
  return true;
}

function requireRadio(radios)
{ // require at least one radio in this group to be checked
  if(!radios.length) return true; // invalid parameter
  var visible= false, enabled= false;
  for(var i= 0; i < radios.length; i++)
  {
    if(!enabled) enabled= !radios[i].disabled;
    if(radios[i].checked) return true;
    else if(typeof(radios[i].offsetWidth) == 'undefined' || radios[i].offsetWidth > 0) visible= true;
  }
  if(!visible||!enabled) return true; // no visible/enabled options in this group
  status= 'You must select one of the '+radios[0].name+' options.';
  return false;
}

function requireLength(fld,min,max)
{ // set minimum and/or maximum field lengths
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var len= fld.value.length;
  if(min > -1 && len < min)
  { status= 'The '+fieldname(fld)+' field must be at least '+min+
    ' characters long; it is currently '+len+' characters long.'; return false; }
  if(max > -1 && len > max)
  { status= 'The '+fieldname(fld)+' field must be no more than '+max+
    ' characters long; it is currently '+len+' characters long.'; return false; }
  return true;
}

function dependants(enabled,elements)
{ // convenience function to enable/disable dependant fields, passed in as an array 
  if(!elements.length) return true;
  for(var i= 0; i < elements.length; i++)
    elements[i].disabled= !enabled;
}

function allowChars(fld,chars)
{ // provide a string of acceptable chars for a field
  if(fld.disabled) return true;
  for(var i= 0; i < fld.value.length; i++)
  {
    if(chars.indexOf(fld.value.charAt(i)) == -1)
    { status= 'The '+fieldname(fld)+' field may not contain "'+fld.value.charAt(i)+'" characters.'; return false; }
  }
  return true;
}

function disallowChars(fld,chars)
{ // provide a string of unacceptable chars for a field
  if(fld.disabled) return true;
  for(var i= 0; i < fld.value.length; i++)
  {
    if(chars.indexOf(fld.value.charAt(i)) != -1)
    { status= 'The '+fieldname(fld)+' field may not contain "'+fld.value.charAt(i)+'" characters.'; return false; }
  }
  return true;
}

function checkEmail(fld)
{ // simple email check
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var phony= /@(\w+\.)*example\.(com|net|org)$/i;
  if(phony.test(fld.value))
  { status= 'Please enter your email address in the '+fieldname(fld)+' field.'; return false; }
  var emailfmt= /^\w+([.-]\w+)*@\w+([.-]\w+)*\.\w{2,8}$/;
  if(!emailfmt.test(fld.value))
  { status= 'The '+fieldname(fld)+' field must contain a valid email address.'; return false; }
  return true;
}

function checkIntRange(fld,minVal,maxVal,sep)
{
  if(!fixInt(fld)) return false;
  var val= parseInt(fld.value);
  if(val < minVal) { status= 'The '+fieldname(fld)+' field must be no less than '+minVal+'.'; return false; }
  if(val > maxVal) { status= 'The '+fieldname(fld)+' field must be no greater than than '+maxVal+'.'; return false; }
  return true;
}

function checkFloatRange(fld,minVal,maxVal,sep)
{
  if(!fixFloat(fld)) return false;
  var val= parseFloat(fld.value);
  if(val < minVal) { status= 'The '+fieldname(fld)+' field must be no less than '+minVal+'.'; return false; }
  if(val > maxVal) { status= 'The '+fieldname(fld)+' field must be no greater than than '+maxVal+'.'; return false; }
  return true;
}

function fixInt(fld,sep)
{ // integer check/complainer 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
  val= parseInt(val);
  if(isNaN(val))
  { // parse error 
    status= 'The '+fieldname(fld)+' field must contain a whole number.';
    return false;
  }
  fld.value= val;
  return true;
}

function fixFloat(fld,sep)
{ // decimal number check/complainer 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
  val= parseFloat(fld.value);
  if(isNaN(val))
  { // parse error 
    status= 'The '+fieldname(fld)+' field must contain a number.';
    return false;
  }
  fld.value= val;
  return true;
}

function fixMoney(fld,sep)
{ // monetary field check
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
  if(val.indexOf('$') == 0)
    val= parseFloat(val.substring(1,40));
  else
    val= parseFloat(val);
  if(isNaN(val))
  { // parse error 
    status= 'The '+fieldname(fld)+' field must contain a dollar amount.';
    return false;
  }
  var sign= ( val < 0 ? '-': '' );
  val= Number(Math.round(Math.abs(val)*100)).toString();
  while(val.length < 2) val= '0'+val;
  var len= val.length;
  val= sign + ( len == 2 ? '0' : val.substring(0,len-2) ) + '.' + val.substring(len-2,len+1);
  fld.value= val;
  return true;
}

function fixFixed(fld,dec,sep)
{ // fixed decimal fields 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  if(typeof(sep)!='undefined') val= val.replace(new RegExp(sep,'g'),'');
  val= parseFloat(fld.value);
  if(isNaN(val))
  { // parse error 
    status= 'The '+fieldname(fld)+' field must contain a number.';
    return false;
  }
  var sign= ( val < 0 ? '-': '' );
  val= Number(Math.round(Math.abs(val)*Math.pow(10,dec))).toString();
  while(val.length < dec) val= '0'+val;
  var len= val.length;
  val= sign + ( len == dec ? '0' : val.substring(0,len-dec) ) + '.' + val.substring(len-dec,len+1);
  fld.value= val;
  return true;
}

function fixDate(fld)
{ // tenacious date correction 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  var dt= new Date(val.replace(/\D/g,'/'));
  if(!dt.valueOf())
  { // the date was unparseable 
    status= 'The '+fieldname(fld)+' field has the wrong date.';
    return false;
  }
  fld.value= (dt.getMonth()+1)+'/'+dt.getDate()+'/'+dt.getFullYear();
  return true;
}

function fixRecentDate(fld,minyear)
{ // tenacious date correction 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  var dt= new Date(val.replace(/\D/g,'/'));
  if(!dt.valueOf())
  { // the date was unparseable 
    status= 'The '+fieldname(fld)+' field has the wrong date.';
    return false;
  }
  while(dt.getFullYear() < minyear) { dt.setFullYear(dt.getFullYear()+100); }
  fld.value= (dt.getMonth()+1)+'/'+dt.getDate()+'/'+dt.getFullYear();
  return true;
}

function fixTime(fld,starthour) 
{ // tenacious time correction 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var hour= 0; 
  var mins= 0;
  var ampm= 'am';
  val= fld.value;
  var dt= new Date('1/1/2000 ' + val);
  if(('9'+val) == parseInt('9'+val))
  { hour= val; }
  else if(dt.valueOf())
  { hour= dt.getHours(); mins= dt.getMinutes(); }
  else
  {
    val= val.replace(/\D+/g,':');
    hour= parseInt(val);
    mins= parseInt(val.substring(val.indexOf(':')+1,20));
    if(val.indexOf('pm') > -1) ampm= 'pm';
    if(isNaN(hour)) hour= 0;
    if(isNaN(mins)) mins= 0;
  }
  if(hour < starthour) { ampm= 'pm'; }
  while(hour > 12) { hour-= 12; ampm= 'pm'; }
  while(mins > 60) { mins-= 60; hour++; }
  if(mins < 10) mins= '0' + mins;
  if(!hour)
  { // the date was unparseable 
    status= 'The '+fieldname(fld)+' field has the wrong time.';
    return false;
  }
  fld.value= hour + ':' + mins + ampm;
  return true;
}

function fixTime24(fld) 
{ // tenacious time correction 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var hour= 0; 
  var mins= 0;
  val= fld.value;
  var dt= new Date('1/1/2000 ' + val);
  if(('9'+val) == parseInt('9'+val))
  { hour= val; }
  else if(dt.valueOf())
  { hour= dt.getHours(); mins= dt.getMinutes(); }
  else
  {
    val= val.replace(/\D+/g,':');
    hour= parseInt(val);
    mins= parseInt(val.substring(val.indexOf(':')+1,20));
    if(isNaN(hour)) hour= 0;
    if(isNaN(mins)) mins= 0;
    if(val.indexOf('pm') > -1) hour+= 12;
  }
  hour%= 24;
  mins%= 60;
  if(mins < 10) mins= '0' + mins;
  fld.value= hour + ':' + mins;
  return true;
}

function fixPhone(fld,defaultAreaCode,sep,noext)
{ // tenacious phone # correction 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  if(typeof(sep)=='undefined') sep= '-';
  if(typeof(defaultAreaCode)!='undefined') defaultAreaCode= defaultAreaCode + sep;
  var ext= '', val= fld.value.toLowerCase();
  if(val.indexOf('x') > 0)
  {
    if(!noext) ext= ' x'+val.substr(val.indexOf('x')).replace(/\D/g,'');
    val= val.substr(0,val.indexOf('x'));
  }
  val= val.replace(/\D/g,'');
  if(val.length == 7)
  {
    fld.value= defaultAreaCode + val.substring(0,3) + sep + val.substring(3,20) + ext;
    return true;
  }
  if(val.length == 10)
  {
    fld.value= val.substring(0,3) + sep + val.substring(3,6) + sep + val.substring(6,20) + ext;
    return true;
  }
  if(val.length < 7)
  {
    status= 'The phone number you supplied for the '+fieldname(fld)+' field was too short.';
    return false;
  }
  if(val.length > 10)
  {
    status= 'The phone number you supplied for the '+fieldname(fld)+' field was too long.';
    return false;
  }
  status= 'The phone number you supplied for the '+fieldname(fld)+' field was wrong.';
  return false;
}

function fixSSN(fld)
{ // tenacious SSN correction; fieldname isn't a big consideration, probably only one SSN per form 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  val= val.replace(/\D/g,'');
  if( val.length < 9 )
  {
    status= 'The Social Security Number you provided is not long enough.';
    return false;
  }
  if( val.length > 9 )
  {
    status= 'The Social Security Number you provided is too long.';
    return false;
  }
  fld.value= val.substring(0,3)+'-'+val.substring(3,5)+'-'+val.substring(5,12);
  return true;
}

function fixCreditCard(fld)
{ // tenacious credit card correction; fieldname isn't a big consideration, probably only one card per form 
  if(!fld.value.length||fld.disabled) return true; // blank fields are the domain of requireValue 
  var val= fld.value, ctype= 'credit card';
  val= val.replace(/\D/g,'');
  var prefix2= parseInt(val.substr(0,2));
  if( val.substr(0,1) == '4' )
  { // Visa
    ctype= 'Visa\xae';
    if( val.length == 16 );
    else if( val.length == 13 ); // very old #, should be reassigned
    else if( val.length < 13 )
    { status= 'The Visa\xae number you provided is not long enough.'; return false; }
    else if( val.length > 16 )
    { status= 'The Visa\xae number you provided is too long.'; return false; }
    else
    { status= 'The Visa\xae number you provided is either not long enough, or too long.'; return false; }
  }
  else if( prefix2 >= 51 && prefix2 <= 55 )
  { // MC
    ctype= 'MasterCard\xae';
    if( val.length < 16 )
    { status= 'The MasterCard\xae number you provided is not long enough.'; return false; }
    else if( val.length > 16 )
    { status= 'The MasterCard\xae number you provided is too long.'; return false; }
  }
  else if( (prefix2 == 34) || (prefix2 == 37) )
  { // AmEx
    ctype= 'American Express\xae card';
    if( val.length < 15 )
    { status= 'The American Express\xae card number you provided is not long enough.'; return false; }
    else if( val.length > 15 )
    { status= 'The American Express\xae card number you provided is too long.'; return false; }
  }
  else if( val.substr(0,4) == '6011' )
  { // Novus/Discover
    ctype= 'Discover\xae card';
    if( val.length < 16 )
    { status= 'The Discover\xae card number you provided is not long enough.'; return false; }
    else if( val.length > 16 )
    { status= 'The Discover\xae card number you provided is too long.'; return false; }
  }
  else
  { // other
    if( val.length < 13 )
    { status= 'The credit card number you provided is not long enough.'; return false; }
    if( val.length > 19 )
    { status= 'The credit card number you provided is too long.'; return false; }
  }
  var sum= 0, dbl= false;
  for(var i= val.length-1; i >= 0; i--)
  {
    var digit= parseInt(val.charAt(i))*((dbl=!dbl)?1:2);
    sum+= ( digit > 9 ? (digit%10)+1 : digit );
  }
  if(sum%10)
  {
    status= 'The '+ctype+' number you provided is not valid.\nPlease double-check it and try again.';
    return false;
  }
  fld.value= val;
  return true;
}

function nameContains(name,str)
{ // Check for nontrivial inclusion 
  // OK, *some* trivial cases must be handled...
  if(name == str || name.toLowerCase() == str.toLowerCase()) return true;
  var nlen= name.length;
  var slen= str.length;
  var endat= nlen - slen;
  // too small to fit?
  if(nlen > str) return false;
  if(name.toLowerCase() == name || name.toUpperCase() == name)
  { // all lower/upper case name? underscores separate
    if(name.indexOf('_') == -1) return false;
    str= str.toLowerCase();
    if( name.indexOf(str+'_') == 0 ||
      name.indexOf('_'+str+'_') > -1 ||
      name.substring(endat-1,nlen+1) == ('_'+str) )
      return true;
  }
  else
  { // proper case name? uppercase starts new words 
    var sep= name.substring(slen,slen+1);
    if( name.indexOf(str) == 0 && sep == sep.toUpperCase() ) return true;
    if( name.indexOf(str.toLowerCase()) == 0 && sep == sep.toUpperCase() ) return true;
    var sep= name.substring(endat-1,endat);
    if( name.substring(endat,nlen+1) == str ) return true;
    for(var index= name.indexOf(str); index > -1; index= name.indexOf(str,index+1))
    { // for each occurence of the word, is it followed by a non-lowercase char? 
      endat= index+slen;
      sep= name.substring(endat,endat+1);
      if(sep == sep.toUpperCase()) return true;
    }
  }
  return false;
}

function autocheckByName(frm) 
{ // uses names of form elements to determine type 
  for(var index= 0; index < frm.elements.length; index++)
  {
    var el= frm.elements[index];
    if(!el.type) continue;
    if(el.type == 'text' || el.type == 'password')
    { // text fields 
      if(( el.name.substring(0,1) == el.name.substring(0,1).toUpperCase() || 
        nameContains(el.name,'Required')) && el.value.length == 0)
      { alert('The '+fieldname(el)+' field cannot be left blank.'); el.focus(); return false; }
      if(nameContains(el.name,'Date') && !fixDate(el))
      { alert(status); el.focus(); return false; }
      if(nameContains(el.name,'Time24') && !fixTime24(el))
      { alert(status); el.focus(); return false; }
      if(nameContains(el.name,'Time') && !fixTime(el))
      { alert(status); el.focus(); return false; }
      if(nameContains(el.name,'SSN') && !fixSSN(el))
      { alert(status); el.focus(); return false; }
      if(nameContains(el.name,'CC') && !fixCreditCard(el))
      { alert(status); el.focus(); return false; }
      if(nameContains(el.name,'Email') && !checkEmail(el))
      { alert(status); el.focus(); return false; }
      if( ( nameContains(el.name,'Phone') ||
        nameContains(el.name,'Fax') || 
        nameContains(el.name,'Pager') ) &&
        !fixPhone(el))
      { alert(status); el.focus(); return false; }
    }
    // handle required select and select-multiple 
    else if(el.type.substring(0,3) == 'sel' && 
      (el.name.substring(0,1) == el.name.substring(0,1).toUpperCase() || 
      nameContains(el.name,'Required')) && el.selectedIndex == -1)
    { alert(status); el.focus(); return false; }
    // handle required checkbox
    else if(el.type == 'checkbox' && 
      (el.name.substring(0,1) == el.name.substring(0,1).toUpperCase() || 
      nameContains(el.name,'Required')) && !requireChecked(el))
    { alert(status); el.focus(); return false; }
    else if(el.type == 'radio' && !requireRadio(frm[el.name]))
    { alert(status); frm.elements[index].focus(); return false; }
  }
  for(var index= 0; index < frm.elements.length; index++)
    if(frm.elements[index].type == 'submit') frm.elements[index].disabled= true;
  return true;
}

function isMemberOf(elem,classname)
{ // checks to see if elem is a member of the (style) class 
  // trivial cases first: no membership or simple equality
  if(!elem.className)
    return false
  else if(elem.className == classname)
    return true;
  else if(elem.className.indexOf(' ') > -1)
  { // multiple class names; use split, if avail 
    if(parseInt(navigator.appVersion) >= 4)
    {
      var names= elem.className.split(' ');
      for(var index= 0; index < names.length; index++)
        if(names[index] == classname)
          return true;
    }
    // older browsers can fake it 
    // WARNING: "fine" can be found in "oldRefined"
    else if(elem.className.indexOf(classname) > -1)
      return true;
  }
  return false;
}

function checkClass(el)
{ // validate the field, based on class membership
  if(el.type == 'text' || el.type == 'password')
  { // text fields 
    if(isMemberOf(el,'required') && !requireValue(el)) return false;
    if(isMemberOf(el,'date') && !fixDate(el)) return false;
    if(isMemberOf(el,'time') && !fixTime(el)) return false;
    if(isMemberOf(el,'time24') && !fixTime24(el)) return false;
    if(isMemberOf(el,'ssn') && !fixSSN(el)) return false;
    if(isMemberOf(el,'cc') && !fixCreditCard(el)) return false;
    if(isMemberOf(el,'phone') && !fixPhone(el)) return false;
    if(isMemberOf(el,'money') && !fixMoney(el)) return false;
    if(isMemberOf(el,'int') && !fixInt(el)) return false;
    if(isMemberOf(el,'float') && !fixFloat(el)) return false;
    if(isMemberOf(el,'email') && !checkEmail(el)) return false;
  } // handle required select and select-multiple 
  else if(el.type == 'checkbox' && 
    isMemberOf(el,'required') && !requireChecked(el)) return false;
  else if(el.type.substring(0,3) == 'sel' && 
    isMemberOf(el,'required') && el.selectedIndex == -1) return false;
  return true;
}

function autocheckByClass(frm) 
{ // uses the CSS class of form elements to determine type 
  for(var index= 0; index < frm.elements.length; index++)
  {
    var el= frm.elements[index];
    if(!el.type) continue;
    if(el.type == 'radio' && !requireRadio(frm[el.name]))
    { alert(status); frm.elements[index].focus(); return false; }
    else if(!checkClass(frm.elements[index])) 
    { alert(status); frm.elements[index].focus(); return false; }
  }
  for(var index= 0; index < frm.elements.length; index++)
    if(frm.elements[index].type == 'submit') frm.elements[index].disabled= true;
  return true;
}

function autocheckByBlur(frm)
{ // uses the onBlur handler of form elements to check value 
  status= '';
  for(var index= 0; index < frm.elements.length; index++)
  {
    var el= frm.elements[index];
    if(!el.type) continue;
    if(el.type == 'radio' && !requireRadio(frm[el.name]))
    { alert(status); frm.elements[index].focus(); return false; }
    else if(el.type != 'hidden' && el.name && el.onblur)
    {
      el.onblur();
      if(status) { alert(status); el.focus(); return false; }
    }
  }
  for(var index= 0; index < frm.elements.length; index++)
    if(frm.elements[index].type == 'submit') frm.elements[index].disabled= true;
  return true;
}

function canCheckByBlur(frm)
{ // determines whether programmatic invocation of form element onblur is available
  for(var index= 0; index < frm.elements.length; index++)
  {
    var el= frm.elements[index];
    if(!el.type) continue;
    if(el.type != 'hidden' && el.name && typeof(el.onblur)=='function') return true;
  }
  return false;
}

function autocheck(frm)
{ // uses the best available method to check form values 
  var bchar= navigator.appName.substring(0,1);
  if(isMemberOf(frm,'autocheck'))
  { return autocheckByClass(frm); }
  else if(canCheckByBlur(frm))
  { return autocheckByBlur(frm); }
  else
  { return autocheckByName(frm); }
}


function isEmail(string) {
return (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}

function isValidURL(url) {
	var urlRegxp = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
	if (urlRegxp.test(url) != true) {
		return false;
	} else {
		return true;
	}
}
