var browserType;

if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {browserType= "gecko"}

function imprimir( mostraMensagem )
{
  if( mostraMensagem )
  {
    alert('Ao imprimir as informações não são gravadas.\nLembre-se de utilizar o botão \"Salvar\" para garantir que as informações de sua inscrição foram gravadas com sucesso.');
  }
  window.print();
}

// Valida maioridade do proponente
function validaMaioridade(oField)
{
  var result = true;
  // Create date object using birth date str
  var birthDate = new Date(oField.value);
  // Create todays date
  var today = new Date();

  // getTime returns date in milliseconds, so need
  // to divide by number of milliseconds in year
var miliHoje = today.getTime();
var miliBirth = birthDate.getTime();
  var age = (miliHoje - miliBirth) /(365*24*60*60*1000);
  if (age < 18)
  {
    oField.select();
    result = false;
  }

  return result;
}

// Valida maioridade do proponente
function validaAno4Digitos(oField)
{
  var result = true;
  // Create date object using birth date str
  var birthDate = new Date(oField.value);
  // Create todays date
  var birthStr = new String(oField.value);
  var birthLen = birthStr.length;

if( birthLen < 10 )
{
  result = false;
}
  return result;
}

function liberaBotao( botao )
{
  if( document.forms[0].botao.disabled )
  {
    document.forms[0].botao.disabled = false;
    document.forms[0].botao.className='enviar2';
  }
  else
  {
    document.forms[0].botao.disabled = true;
    document.forms[0].botao.className='enviarDisabled';
  }
}

function submit(obj, metodo)
{
  obj.disabled = true;
  blockSubmitMetodo(obj, metodo);
}

function blockSubmit(obj)
{
  location.hash = 'TOPO_REF';
  exibirCarregando();
  obj.disabled = true;
  document.forms[0].submit();

}

function maioridadeSubmit(obj, campo, nomeCampo)
{
  obj.disabled = true;
  if(!validaAno4Digitos(campo))
  {
    alert(nomeCampo + " - O ano deve ser digitado com 4 digitos");
    obj.disabled = false;
    return;
  }
  location.hash = 'TOPO_REF';
  exibirCarregando();
  document.forms[0].submit();

}


function blockSubmitMetodo(obj, metodo)
{
  location.hash = 'TOPO_REF';
  exibirCarregando();
  obj.disabled = true;
  document.forms[0].metodo.value = metodo;
  document.forms[0].submit();

}

function blockSubmitMetodo_novaJanela(metodo)
{
  document.forms[0].target="_blank";
  document.forms[0].metodo.value = metodo;
  document.forms[0].submit();

}

function submitMetodo(metodo)
{
  document.forms[0].metodo.value = metodo;
  document.forms[0].submit();

}


function submitMetodoAction( action, metodo )
{
  document.forms[0].metodo.value = metodo;
  if( action != '' )
    document.forms[0].action = action;
  document.forms[0].submit();
}

function blockSubmitMetodoAction( obj, action, metodo )
{
  obj.disabled = true;
  document.forms[0].metodo.value = metodo;
  if( action != '' )
    document.forms[0].action = action;
  exibirCarregando();
  document.forms[0].submit();
}


function submitMetodoAlterar(metodo, id)
{
  location.hash = 'TOPO_REF';
  exibirCarregando();
  document.forms[0].metodo.value = metodo;
  document.forms[0].elementId.value = id;
  document.forms[0].submit();
}

function blockSubmitMetodoAlterar(obj, metodo, id)
{
  location.hash = 'TOPO_REF';
  exibirCarregando();
  obj.disabled = true;
  document.forms[0].metodo.value = metodo;
  document.forms[0].elementId.value = id;
  document.forms[0].submit();
}


function exibirCarregandoIndice()
{
	document.poppedLayerVisible = eval('document.getElementById(\'hidden\')');
        document.poppedLayerVisible.style.visibility = "visible";
}

function exibirCarregando()
{
	if( document.getElementById('hidden') != null && document.getElementById('visible') != null )
        {
          document.poppedLayerVisible                  = eval('document.getElementById(\'hidden\')');
          document.poppedLayer                         = eval('document.getElementById(\'visible\')');
          document.poppedLayer.style.visibility        = "hidden";
          document.poppedLayerVisible.style.visibility = "visible";
        }
}

function verificaCampos( frm )
{

  var vlrPeriodicidade = '';
  var elemPeriodicidade = frm["projetoFestival.prfe_In_PeriodicidadeStr"];
  if( elemPeriodicidade != undefined )
  {
    for ( i=0; i < elemPeriodicidade.length; i++ )
    {
      if ( elemPeriodicidade[i].checked == true )
        vlrPeriodicidade = elemPeriodicidade[i].value;
    }

    if( vlrPeriodicidade == '0' )
    {
      frm["projetoFestival.prfe_Tx_Periodicidade"].disabled = false;
    }
    else
    {
      frm["projetoFestival.prfe_Tx_Periodicidade"].value="";
      frm["projetoFestival.prfe_Tx_Periodicidade"].disabled = true;
    }
  }

  var vlrPronac = '';
  var elemPronac = frm["projeto.proj_In_Lei_RouanetStr"];
  for ( i=0; i < elemPronac.length; i++ )
  {
    if ( elemPronac[i].checked == true )
      vlrPronac = elemPronac[i].value;
  }

  if( vlrPronac == 'N' )
  {
    frm["projeto.proj_Nr_PronacStr"].disabled = true;
    frm["projeto.proj_Dt_Pronac_DoStr"].disabled = true;
    for( i = 0; i < frm["projeto.proj_In_Artigo_PronacStr"].length; i++ )
    {
      frm["projeto.proj_In_Artigo_PronacStr"][i].disabled = true;
    }
  }
  else
  {
    frm["projeto.proj_Nr_PronacStr"].disabled = false;
    frm["projeto.proj_Dt_Pronac_DoStr"].disabled = false;
    for( i = 0; i < frm["projeto.proj_In_Artigo_PronacStr"].length; i++ )
    {
      frm["projeto.proj_In_Artigo_PronacStr"][i].disabled = false;
    }
  }

  var vlrEdicoes = '';
  var elemEdicoes = frm["projeto.proj_In_ApresentadoStr"];
  for ( i=0; i < elemEdicoes.length; i++ )
  {
    if ( elemEdicoes[i].checked == true )
      vlrEdicoes = elemEdicoes[i].value;
  }
  if( vlrEdicoes == 'N' )
  {
    for( i = 0; i < frm["edicoesAnteriores"].length; i++ )
    {
      frm["edicoesAnteriores"][i].disabled = true;
    }
  }
  else
  {
    for( i = 0; i < frm["edicoesAnteriores"].length; i++ )
    {
      frm["edicoesAnteriores"][i].disabled = false;
    }
  }

  var vlrContemplado = '';
  var elemContemplado = frm["projeto.proj_In_Contemplado_AnteriorStr"];
  if( elemContemplado != undefined )
  {
    for ( i=0; i < elemContemplado.length; i++ )
    {
    if ( elemContemplado[i].checked == true )
    vlrContemplado = elemContemplado[i].value;
    }
    if( vlrContemplado == 'N' )
    {
    frm["projeto.proj_Tx_Resultados_Obtidos"].disabled = true;
    }
    else
    {
    frm["projeto.proj_Tx_Resultados_Obtidos"].disabled = false;
    }
  }
  
  var vlrCaptacoes = '';
  var elemCaptacoes = frm["projeto.proj_In_Presenca_Fonte_ContribStr"];
  if (elemCaptacoes != undefined) {
	  for (i=0; i < elemCaptacoes.length; i++) {
		  if (elemCaptacoes[i].checked == true) {
			  vlrCaptacoes = elemCaptacoes[i].value;
			  break;
		  }
	  }
	  if (vlrCaptacoes == 'N') {
		  document.getElementById("captacoes").style.display = "none";
	  } else {
		  document.getElementById("captacoes").style.display = "block";
	  }
  }
}

function cleanFieldEspecifique(vlr,frm)
{
  if( vlr == '0' )
  {
    frm["projetoFestival.prfe_Tx_Periodicidade"].disabled = false;
  }
  else
  {
    frm["projetoFestival.prfe_Tx_Periodicidade"].value="";
    frm["projetoFestival.prfe_Tx_Periodicidade"].disabled = true;
  }
}

function cleanFieldPronac(vlr,frm)
{
  if( vlr == 'N' )
  {
    frm["projeto.proj_Nr_PronacStr"].value="";
    frm["projeto.proj_Nr_PronacStr"].disabled = true;
    frm["projeto.proj_Dt_Pronac_DoStr"].value="";
    frm["projeto.proj_Dt_Pronac_DoStr"].disabled = true;
    for( i = 0; i < frm["projeto.proj_In_Artigo_PronacStr"].length; i++ )
    {
      frm["projeto.proj_In_Artigo_PronacStr"][i].checked = false;
      frm["projeto.proj_In_Artigo_PronacStr"][i].disabled = true;
    }
  }
  else
  {
    frm["projeto.proj_Nr_PronacStr"].disabled = false;
    frm["projeto.proj_Dt_Pronac_DoStr"].disabled = false;
    for( i = 0; i < frm["projeto.proj_In_Artigo_PronacStr"].length; i++ )
    {
      frm["projeto.proj_In_Artigo_PronacStr"][i].disabled = false;
    }
  }
}

function cleanFieldParticipacao(vlr,frm)
{
  if( vlr == 'N' )
  {
    for( i = 0; i < frm["edicoesAnteriores"].length; i++ )
    {
      frm["edicoesAnteriores"][i].checked = false;
      frm["edicoesAnteriores"][i].disabled = true;
    }
  }
  else
  {
    for( i = 0; i < frm["edicoesAnteriores"].length; i++ )
    {
      frm["edicoesAnteriores"][i].disabled = false;
    }
  }
}

function cleanFieldResultados(vlr,frm)
{
  if( vlr == 'N' )
  {
    frm["projeto.proj_Tx_Resultados_Obtidos"].value="";
    frm["controleResultados"].value = "4000";
    frm["projeto.proj_Tx_Resultados_Obtidos"].disabled = true;
  }
  else
  {
    frm["projeto.proj_Tx_Resultados_Obtidos"].disabled = false;
  }
}

function cleanFieldFontes(vlr,frm)
{
  if( vlr == 'N' )
  {
    frm["fontes"].disabled = true;
  }
  else
  {
    frm["fontes"].disabled = false;
  }
}

function mostraAjuda(link)
{
  var linkDaAjuda= "/cultural/publico/prepareRoteiro.do?metodo=prepararRoteiro#" + link;
  window.open(linkDaAjuda,'Cultural',"left=80,top=100,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no")
}

function maxTextArea(textArea, countfield, maxlimit) {
	with (textArea.value.replace(/\r?\n/g, "\r\n"))
		if (length > maxlimit) {
			textArea.value = slice(0, maxlimit).replace(/\r\n/g, "\n");
			alert("Limite de " + maxlimit + " caracteres alcançado.");
		} else {
			countfield.value = maxlimit - length;
		}
}

function verificaDataCurta(data, e)
{
  var mes = data.value.substr(0,2);
  var ano = data.value.substr(3,4);
  var strCheck = '0123456789';
  var strData = '0123456789/';
  var msg = "";

  if( e.keyCode ==13 )
  {
    e.returnValue=false;
    return ;
  }
  var whichCode = (window.Event) ? e.which : e.keyCode;
  var key = String.fromCharCode(whichCode);

  var tmpSaida = ""
  for( i = 0; i < data.value.length; i++ )
  {
    if ( strData.indexOf(data.value.charAt(i)) != -1 )
    {
      tmpSaida += data.value.charAt(i)
    }
  }

  data.value = tmpSaida

  if ( data.value.length != 3 )
  {
    var ultimo = data.value.charAt( data.value.length - 1 );
    if ( strCheck.indexOf(ultimo) == -1 )
    {
      data.value = data.value.substring( 0, data.value.length - 1 );
    }
  }

  if ( data.value.length == 2 )         // checa o mes
  {
    if ( mes.length == 2 )
    {
      if (mes > 0 && mes < 13)
      {
        data.value = mes + "/";
        data.focus();
        return true;
      }
      else
      {
        data.value = "";
        data.focus();
        return false;
      }
    }
  }
  else if ( data.value.length == 6 )   // checa o ano
  {
    if ( ano.length == 4 )
    {
      data.focus();
      return true;
    }
    return true;
  }
  return true;
}

function verificaData(data, e)
{
  var dia = data.value.substr(0,2);
  var mes = data.value.substr(3,2);
  var ano = data.value.substr(6,4);
  var strCheck = '0123456789';
  var strData = '0123456789/';
  var msg = "";

  var whichCode = (window.Event) ? e.which : e.keyCode;

  var key = String.fromCharCode(whichCode);
  if( e.keyCode == 13 )
  {
    e.returnValue = false;
    return;
  }

  var tmpSaida = ""
  for(i = 0; i < data.value.length; i++ )
  {
    if (strData.indexOf(data.value.charAt(i)) != -1)
    {
      tmpSaida += data.value.charAt(i)
    }
  }

  data.value = tmpSaida

  if ( data.value.length == 2 )         // checa o dia
  {
    if ( dia.length == 2 )
    {
      if (dia > 31)
      {
        data.value = "";
        data.focus();
        return false;
      }
      else
      {
        data.value = dia + "/";
        data.focus();
        return true;
      }
    }
  }
  else if ( data.value.length == 5 )    //checa o mês
  {
    if ( mes.length == 2 )
    {
      if ( mes < 1 || mes > 12 )
      {
        data.value = dia + "/" + "";
        data.focus();
        return false;
      }
      else if ( mes == 02 && dia > 29 )
      {
        data.value = "";
        data.focus();
        return false;
      }
      else if ( mes != 2 )
      {
        if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 )
        {
          if ( dia < 1 || dia > 30 )
          {
            data.value = "";
            data.focus();
            return false;
          }
          else
          {
            data.value = dia + "/" + mes + "/";
            data.focus();
            return true;
          }
        }
        else
        {
          data.value = dia + "/" + mes + "/";
          data.focus();
          return true;
        }
      }
      else
      {
        data.value = dia + "/" + mes + "/";
        data.focus();
        return true;
      }
    }
  }
  else if ( data.value.length == 10 || data.value.length == 8)   // checa o ano
  {
    if ( ano.length == 4 )
    {
      if ( dia > 31 )
      {
        dia.value = "";
        data.focus();
        return false;
      }
      else if ( mes < 1 || mes > 12 )
      {
        mes.value = "";
        data.focus();
        return false;
      }
      else if ( mes == 2 )
      {
        if ( (ano%4) == 0 && (dia <  1 || dia > 29 ) )
        {
          data.focus();
          return false;
        }
        else if ( (ano%4) != 0 && (dia < 1 || dia > 28 ) )
        {
          alert('Data inválida, o ano informado não &eacute; bissexto.');  // ano não &eacute; bissexto
          data.focus();
          return false;
        }
      }
      else if ( mes != 2 ) //inop
      {
        if ( mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12 )
        {
          if ( dia < 1 || dia > 31 )
          {
            alert('Data inválida.');   //  mes com 31 dias
            data.focus();
            return false;
          }
        }
        else if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 ) //inop
        {
          if ( dia < 1 || dia > 30 )
          {
            alert('Data inválida, mês com 30 dias.');  //mes com 30 dias
            data.focus();
            return false;
          }
        }
      }
      return true;
    }
    else if ( data.value.substr(6,2) == 19 || data.value.substr(6,2) == 20 || data.value.substr(6,2) == 21 )
    {
      return true;
    }
    return true;
  }
  return true;
}

function verificaDataCompleta(data, e)
{
  var dia    = data.value.substr(0,2);
  var mes    = data.value.substr(3,2);
  var ano    = data.value.substr(6,4);
  var hora   = data.value.substr(11,2);
  var minuto = data.value.substr(14,2);

  var strCheck = '0123456789';
  var strData = '0123456789/';
  var msg = "";

  var whichCode = (window.Event) ? e.which : e.keyCode;

  var key = String.fromCharCode(whichCode);
  if( e.keyCode == 13 )
  {
    e.returnValue = false;
    return;
  }

  var tmpSaida = ""
  for(i = 0; i < data.value.length; i++ )
  {
    if (strData.indexOf(data.value.charAt(i)) != -1)
    {
      tmpSaida += data.value.charAt(i)
    }
  }

  data.value = tmpSaida

  if ( data.value.length == 2 )         // checa o dia
  {
    if ( dia.length == 2 )
    {
      if (dia > 31)
      {
        data.value = "";
        data.focus();
        return false;
      }
      else
      {
        data.value = dia + "/";
        data.focus();
        return true;
      }
    }
  }
  else if ( data.value.length == 5 )    //checa o mês
  {
    if ( mes.length == 2 )
    {
      if ( mes < 1 || mes > 12 )
      {
        data.value = dia + "/" + "";
        data.focus();
        return false;
      }
      else if ( mes == 02 && dia > 29 )
      {
        data.value = "";
        data.focus();
        return false;
      }
      else if ( mes != 2 )
      {
        if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 )
        {
          if ( dia < 1 || dia > 30 )
          {
            data.value = "";
            data.focus();
            return false;
          }
          else
          {
            data.value = dia + "/" + mes + "/";
            data.focus();
            return true;
          }
        }
        else
        {
          data.value = dia + "/" + mes + "/";
          data.focus();
          return true;
        }
      }
      else
      {
        data.value = dia + "/" + mes + "/";
        data.focus();
        return true;
      }
    }
  }
  else if ( data.value.length == 10 )    //checa o ano
  {
    if ( ano.length == 4 )
    {
      data.value = dia + "/" + mes + "/" + ano + " ";
      data.focus();
      return true;
    }
  }
  else if ( data.value.length == 13 )    //checa a hora
  {
    if ( hora.length == 2 )
    {
      if ( hora > 24 )
      {
        data.value = dia + "/" + mes + "/" + ano;
        data.focus();
        return false;
      }
      else
      {
        data.value = dia + "/" + mes + "/" + ano + " " + hora + ":";
        data.focus();
        return true;
      }
    }
  }
  else if ( data.value.length == 16 )    //checa os minutos
  {
    if ( minuto.length == 2 )
    {
      if ( minuto > 59 )
      {
        data.value = dia + "/" + mes + "/" + ano + " " + hora;
        data.focus();
        return false;
      }
      else
      {
        data.value = dia + "/" + mes + "/" + ano + " " + hora + ":" + minuto;
        if ( mes == 2 )
        {
          if ( (ano%4) == 0 && (dia <  1 || dia > 29 ) )
          {
            alert('Data inválida');
            data.focus();
            return false;
          }
          else if ( (ano%4) != 0 && (dia < 1 || dia > 28 ) )
          {
            alert('Data inválida, o ano informado não &eacute; bissexto.');  // ano não &eacute; bissexto
            data.focus();
            return false;
          }
        }
        else if ( mes != 2 ) //inop
        {
          if ( mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12 )
          {
            if ( dia < 1 || dia > 31 )
            {
              alert('Data inválida.');   //  mes com 31 dias
              data.focus();
              return false;
            }
          }
          else if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 ) //inop
          {
            if ( dia < 1 || dia > 30 )
            {
              alert('Data inválida, mês com 30 dias.');  //mes com 30 dias
              data.focus();
              return false;
            }
          }
        }
        data.focus();
        return true;
      }
    }
  }
  return true;
}

function keyPress()
{
  if(event.keyCode == 13 ) event.returnValue  =false;
}

function numeros()
{
  if( (event.keyCode != 13) && ( (event.keyCode <48) || (event.keyCode>57) ) )
  {

    alert("Digite apenas números");
    event.returnValue  = false;
  }
}

function currencyFormat(fld, milSep, decSep, e)
{
  if (fld.value.length > 14)
    return;
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;
  if( e.keyCode ==13 )
  {
    e.returnValue=false;
    return ;
  }  // Enter
  key = String.fromCharCode(whichCode);  // Get key value from key code
  //if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
  if (strCheck.indexOf(key) == -1)
  {
    if (whichCode == 8)
    { //backspace
      alert(formatDinheiro(fld.value));
    }
    return false;
  }
  len = fld.value.length;
  for(i = 0; i < len; i++)
    if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep))
      break;
  aux = '';
  for(; i < len; i++)
    if (strCheck.indexOf(fld.value.charAt(i))!=-1)
      aux += fld.value.charAt(i);
  aux += key;
  len = aux.length;
  if (len == 0)
    fld.value = '';
  if (len == 1)
    fld.value = '0'+ decSep + '0' + aux;
  if (len == 2)
    fld.value = '0'+ decSep + aux;
  if (len > 2)
  {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--)
    {
      if (j == 3)
      {
	aux2 += milSep;
	j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
      fld.value += aux2.charAt(i);
    fld.value += decSep + aux.substr(len - 2, len);
  }
  return false;
}

function Numero( t_valor )
{
	valor = new String( t_valor );

	if (valor == "")
		return "0,00";


	valor = replaceAll( valor, ".", "" );
	return  valor;
}

function formatNumber( t_valor )
{
	valor = new String( t_valor );

	if (valor == "")
		return "";


	valor = replaceAll( valor, ".", "" );
        valor = replaceAll( valor, ",", "." );
	return  valor;
}

function pegaInteiros( num )
{
	num = Numero( num );

	if ( num.indexOf( "," ) == -1 )
		return num;

	retorno = num.substring( 0, num.indexOf( "," ) );

	if ( retorno.length == 0 )
		return "0";

	return retorno;
}

function pegaCentavos( num )
{
	num = Numero( num );
        if ( num.indexOf( "," ) == -1 )
		return "00";

	retorno = num.substring( num.indexOf( "," ) + 1  , num.length );
        if ( retorno.length == 0 )
		return "00";

	if ( retorno.length == 1 )
		return ( retorno + "0" );

	return retorno;
}

function Dinheiro(num)
{
  _VALOR_MUITO_GRANDE = 9999999999999999999999999;
  numero = "";
  part = "";
  num = new String( num );

  if ( num.length == num.indexOf( "." ) + 2 )
    num = num + "0";

  centavos = num.substring( num.length -2 , num.length );
  numero   = num.substring( 0, num.length -3 );

  n = 0;
  var ultimaPosicao = _VALOR_MUITO_GRANDE;

  while( n <= numero.length )
  {
    if ( ( n != 0 ) && ( ( n % 3 ) == 0 ) )
    {
      posicao = numero.length - n;
      if ( part == "" )
      {
        part = numero.substring( posicao , posicao + 3 )
      }
      else
      {
        part = numero.substring(  posicao , posicao + 3 ) + "." + part;
      }
      ultimaPosicao = posicao;
    }
    n++;
  }

  if( ( ultimaPosicao != 0 ) && ( ultimaPosicao != _VALOR_MUITO_GRANDE ) )
  {
    part = numero.substring( 0, ultimaPosicao ) + "." + part + "," + centavos;
  }
  else if( ultimaPosicao == _VALOR_MUITO_GRANDE )
  {
    part = numero + "," + centavos;
  }
  else
  {
    part = part + "," + centavos;
  }
  return part;
}

function aviso(frm)
{
  var centavos = 0;
  var inteiros = 0;
  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_AgenciamentoStr"].value) ) );
  centavos += parseInt( pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_AgenciamentoStr"].value) ) );
  if( inteiros > 0 || centavos > 0 )
    alert('O item g)AGENCIAMENTO não deverá ser incluído no valor solicitado à Petrobras');
}

function somaProjeto(frm, check)
{
  var total;
  var centavos = 0;
  var cent = 0;
  var inteiros = 0;
  var strInteiro = null;
  var strCentavo = null;

  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_Pre_Producao_PrepaStr"].value) ) );
  cent = pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_Pre_Producao_PrepaStr"].value) );
  if( cent.length == 2 && cent.substr(0, 1) == "0" )
  {
    cent = cent.substr(1, 1);
  }
  centavos += parseInt( cent );

  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_Producao_ExecucaoStr"].value) ) );
  cent = pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_Producao_ExecucaoStr"].value) );
  if( cent.length == 2 && cent.substr(0, 1) == "0" )
  {
    cent = cent.substr(1, 1);
  }
  centavos += parseInt( cent );

  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_DivulgacaoStr"].value) ) );
  cent = pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_DivulgacaoStr"].value) );
  if( cent.length == 2 && cent.substr(0, 1) == "0" )
  {
    cent = cent.substr(1, 1);
  }
  centavos += parseInt( cent );

  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_Custo_AdmStr"].value) ) );
  cent = pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_Custo_AdmStr"].value) );
  if( cent.length == 2 && cent.substr(0, 1) == "0" )
  {
    cent = cent.substr(1, 1);
  }
  centavos += parseInt( cent );

  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_Impostos_SegurosStr"].value) ) );
  cent = pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_Impostos_SegurosStr"].value) );
  if( cent.length == 2 && cent.substr(0, 1) == "0" )
  {
    cent = cent.substr(1, 1);
  }
  centavos += parseInt( cent );

  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_ElaboracaoStr"].value) ) );
  cent = pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_ElaboracaoStr"].value) );
  if( cent.length == 2 && cent.substr(0, 1) == "0" )
  {
    cent = cent.substr(1, 1);
  }
  centavos += parseInt( cent );

  inteiros += parseInt( pegaInteiros( Numero( frm["projeto.proj_Vl_Orc_AgenciamentoStr"].value) ) );
  cent = pegaCentavos( Numero( frm["projeto.proj_Vl_Orc_AgenciamentoStr"].value) );
  if( cent.length == 2 && cent.substr(0, 1) == "0" )
  {
    cent = cent.substr(1, 1);
  }
  centavos += parseInt( cent );

  strCentavo = new String( centavos );
  strInteiro = new String( inteiros );

  if ( strCentavo.length == 1 )
    strCentavo = "0" + strCentavo;

  if ( strCentavo.length > 2 )
  {
    nCentavo = strCentavo.substring( strCentavo.length - 2, strCentavo.length );
    nInteiro = strCentavo.substring( 0 , strCentavo.length -2 );

    strCentavo = nCentavo;
    inteiros += parseInt( nInteiro );
    strInteiro = new String( inteiros );
  }

  total = strInteiro + "," + strCentavo;
  frm["totalProjeto"].value = Dinheiro( total );
  frm["projeto.proj_Vl_Total_ProjetoStr"].value = Dinheiro( total );
  if( check )
  {
    total = formataTotalArtes( total );
    frm["projeto.proj_Vl_Solicitado_PetrobrasStr"].value = Dinheiro( total );
    frm["totalProjetoPorEtapa"].value = Dinheiro( total );
  }
}

function somaProjetoSimplificado(frm)
{
  var total;
  var nrMeses = parseInt( frm["projetoLiteratura.prli_Nr_MesesStr"].value );

  if( nrMeses < 6 || nrMeses > 12 )
  {
    alert("O número de meses do Projeto deve estar entre 6 e 12.");
    frm["projetoLiteratura.prli_Nr_MesesStr"].value = '';
  }
  else
  {
    total = 4000 + 3000 * nrMeses;
    total = total + ",00";
    frm["projeto.proj_Vl_Total_ProjetoStr"].value = Dinheiro( total );
    frm["projeto.proj_Vl_Solicitado_PetrobrasStr"].value = Dinheiro( total );
  }
}

function formataTotalArtes( total )
{
  total = replaceAll( total, ",", ".");
  total = total / 2;
  total = replaceAll( new String(total), ".", "," );
  if( total.indexOf(",") != -1 )
  {
    var valores = total.split(",");
    var centavos = valores[1];
    if( centavos.length > 2 )
      centavos = centavos.substring( 0 , centavos.length - 1 );

    while( centavos.length < 2 )
      centavos = centavos + "0";
    total = valores[0] + "," + centavos;
  }
  else
  {
    total = total + ",00";
  }
  return total;
}

function replaceAll(oldStr,findStr,repStr) {

  var srchNdx = 0;
  var newStr = "";

  while (oldStr.indexOf(findStr,srchNdx) != -1) {

    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));

    newStr += repStr;

    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);

  }

  newStr += oldStr.substring(srchNdx,oldStr.length);

  return newStr;

}
function verificaData(data, e)
{
    var dia = data.value.substr(0,2);
    var mes = data.value.substr(3,2);
    var ano = data.value.substr(6,4);
    var strCheck = '0123456789';
    var strData = '0123456789/';
    var msg = "";

    var whichCode = (window.Event) ? e.which : e.keyCode;

    var key = String.fromCharCode(whichCode);
    if( e.keyCode == 13 ){
      e.returnValue = false;
      return;
    }

    var tmpSaida = ""
     for(i = 0; i < data.value.length; i++ )
    {
        if (strData.indexOf(data.value.charAt(i)) != -1)
        {
            tmpSaida += data.value.charAt(i)
        }
    }

    data.value = tmpSaida

    //var tam = data.value.length;
    if ( data.value.length == 2 )         // checa o dia
    {
           if ( dia.length == 2 )
       {
           if (dia > 31)
           {
           data.value = "";
             data.focus();
             return false;
          }
          else
          {
             data.value = dia + "/";
                   data.focus();
                   return true;
                }
       }
    }
    else if ( data.value.length == 5 )    //checa o mês
    {
            if ( mes.length == 2 )
            {
               if ( mes < 1 || mes > 12 )
               {
              data.value = dia + "/" + "";
              data.focus();
              return false;
               }
               else if ( mes == 02 && dia > 29 )
               {
                    data.value = "";
                    data.focus();
                return false;
           }
           else if ( mes != 2 )
               {
                  if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 )
                  {
                 if ( dia < 1 || dia > 30 )
                 {
                 data.value = "";
                 data.focus();
                         return false;
                     }
                     else
                     {
                         data.value = dia + "/" + mes + "/";
                                data.focus();
                                return true;
                             }
                  }
                  else
                  {
                      data.value = dia + "/" + mes + "/";
                                data.focus();
                                return true;
                          }
           }
           else
           {
               data.value = dia + "/" + mes + "/";
                        data.focus();
                        return true;
                   }
        }
    }
    else if ( data.value.length == 10 || data.value.length == 8)   // checa o ano
    {
          if ( ano.length == 4 )
         {
                if ( dia > 31 )
                {
                 dia.value = "";
               data.focus();
               return false;
            }
            else if ( mes < 1 || mes > 12 )
                {
                     mes.value = "";
                   data.focus();
                   return false;
            }
                else if ( mes == 2 )
                {
                  if ( (ano%4) == 0 && (dia <  1 || dia > 29 ) )
                  {
                 data.focus();
                     return false;
                  }
                  else if ( (ano%4) != 0 && (dia < 1 || dia > 28 ) )
                  {
                    alert('Data inválida, o ano informado não &eacute; bissexto.');  // ano não &eacute; bissexto
                    data.focus();
                        return false;
                  }
                }
                else if ( mes != 2 ) //inop
                {
                  if ( mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12 )
                  {
                 if ( dia < 1 || dia > 31 )
                 {
                 alert('Data inválida.');   //  mes com 31 dias
                 data.focus();
                         return false;
                     }
                  }
                  else if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 ) //inop
                  {
                 if ( dia < 1 || dia > 30 )
                 {
                    alert('Data inválida, mês com 30 dias.');  //mes com 30 dias
                    data.focus();
                        return false;
                     }
                  }
            }
        return true;
         }
         else if ( data.value.substr(6,2) == 19 || data.value.substr(6,2) == 20 || data.value.substr(6,2) == 21 )
         {
              return true;
              //alert(data.value.substr(6,2));
         }
     return true;
    }
    //okalert(data.value.length);
    return true;
}

function Mascara(objeto, evt, mask)
{
var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var Numeros = '0123456789';
var Fixos  = '().-:/ ';
var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";

evt = (evt) ? evt : (window.event) ? window.event : "";
var value = objeto.value;
if (evt) {
 var ntecla = (evt.which) ? evt.which : evt.keyCode;
 tecla = Charset.substr(ntecla - 32, 1);
 if (ntecla < 32) return true;

 var tamanho = value.length;
 if (tamanho >= mask.length) return false;

 var pos = mask.substr(tamanho,1);
 while (Fixos.indexOf(pos) != -1) {
  value += pos;
  tamanho = value.length;
  if (tamanho >= mask.length) return false;
  pos = mask.substr(tamanho,1);
 }

 switch (pos) {
   case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
   case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
   case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
   case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
   case '*' : objeto.value = value; return true; break;
   default : return false; break;
 }
}
objeto.value = value;
return true;
}

function MaskDataCompleta(objeto, evt) {
return Mascara(objeto, evt, '##/##/#### ##:##');
}

// -----------------------------------------------------
// Verifica se possui elementos no Select
// -----------------------------------------------------
function hasOptions(obj) {

	if (obj != null && obj.options != null) {

		return true;
	}
	return false;
}


// -----------------------------------------------------
// Seleciona todos os elementos de um Select
// -----------------------------------------------------
function selectAllOptions(obj) {

	if (!hasOptions(obj)) {

		return;
	}
	for (var i = 0; i < obj.options.length; i++) {

		obj.options[i].selected = true;
	}
}

// -------------------------------------------------------------------
// Realiza a ordenacao dos elementos de um Select
// -------------------------------------------------------------------
function sortSelect(obj) {

	var o = new Array();
	if (!hasOptions(obj)) {

		return;
	}
	for (var i = 0; i < obj.options.length; i++) {

		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
	}
	if (o.length==0) {

		return;
	}

	o = o.sort(
		function(a,b) {
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			}
		);

	for (var i=0; i<o.length; i++) {

		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	}
}

// -------------------------------------------------------------------
// Realiza a ordenacao dos elementos de um Select
// -------------------------------------------------------------------
function sortSelectByValue(obj) {

	var o = new Array();
	if (!hasOptions(obj)) {

		return;
	}
	for (var i = 0; i < obj.options.length; i++) {

		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
	}
	if (o.length==0) {

		return;
	}

	o = o.sort(
		function(a,b) {
			if ((a.value+"") < (b.value+"")) { return -1; }
			if ((a.value+"") > (b.value+"")) { return 1; }
			return 0;
			}
		);

	for (var i=0; i<o.length; i++) {

		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	}
}
// -----------------------------------------------------
// Move todos os elementos de um Select para o outro
// -----------------------------------------------------
function moveAllOptions(from, to, sortable) {

	selectAllOptions(from);

	moveSelectedOptions(from, to, sortable);
}


// -----------------------------------------------------
// Move as opcoes selecionadas de um Select para o outro
// -----------------------------------------------------
function moveSelectedOptions(from, to, sortable) {

	if (!hasOptions(from)) {
		return;
	}

        var hasSelected = false;
        var projetosSelected = "";
	for (var i = 0; i < from.options.length; i++) {

		var o = from.options[i];
		if (o.selected) {
                    if( o.text.indexOf("*") == 0 )
                    {
                      hasSelected = true;
                      projetosSelected = projetosSelected + o.text + "\n";
                    }
                    else
                    {
                      if (!hasOptions(to))
                      {
                        var index = 0;
                      }
                      else
                      {
                        var index=to.options.length;
                      }
                      to.options[index] = new Option( o.text, o.value, false, false);
                    }
		}
	}

	for (var i = (from.options.length - 1); i >= 0; i--) {

		var o = from.options[i];
		if (o.selected) {
                    if( o.text.indexOf("*") != 0 )
                    {
                      from.options[i] = null;
                    }
		}
	}

        if( hasSelected )
        {
          alert('Análise já realizada na etapa, não é possível desassociar o(s) projeto(s)\n\n' + projetosSelected);
          for (var i = 0; i < from.options.length; i++) {
		from.options[i].selected = false;
	  }
          return;
        }

        if( sortable )
        {
          sortSelect(from);
          sortSelect(to);
        }
        else
        {
          sortSelectByValue(from);
          sortSelectByValue(to);
        }

	from.selectedIndex = -1;
	to.selectedIndex = -1;

}

