function mudaCombosMes(acao, tipo){
   var myAjax = new Ajax.Request( "/TransparenciaPara/ordembanc.do?acao=" + acao, 
   {method: 'POST', parameters: "trimestre=0",onComplete: mudaComboMes(tipo)} );
}

function mudaCombosTrimestre(acao, tipo){
   var myAjax = new Ajax.Request( "/TransparenciaPara/ordembanc.do?acao=" + acao, 
   {method: 'POST', parameters: "mes=0",onComplete: mudaComboTrimestre(tipo)} );
}

function hoje(){
	var mydate=new Date()
	var year=mydate.getYear()
	if (year < 1000)
		year+=1900
		var day=mydate.getDay()
		var month=mydate.getMonth()
		var daym=mydate.getDate()
	if (daym<10)
		daym="0"+daym
		var dayarray=new Array("Domingo","Segunda-feira","Terça-feira","Quarta-feira","Quinta-feira","Sexta-feira","Sábado")
		var montharray=new Array("Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro")
	
	document.write("<small><font color='ff0000' face='Arial' size='2'><b>"+dayarray[day]+", "+daym+" de "+montharray[month]+" de  "+year+".</b></font></small>")
}

function mudaComboTrimestre(tipo){
  if ( tipo == "area" ){
    document.formArea.trimestre.value="0"
    document.formArea.trimestre.text="Selecione&nbsp;&nbsp;"
  } else if ( tipo == "orgao" ){
    document.formOrgao.trimestre.value="0"
    document.formOrgao.trimestre.text="Selecione&nbsp;&nbsp;"
  } else if ( tipo == "ug" ){
    document.formUg.trimestre.value="0"
    document.formUg.trimestre.text="Selecione&nbsp;&nbsp;"
  }  
}

function mudaComboMes(tipo){
  if ( tipo == "area" ){
	document.formArea.mes.value="0"
	document.formArea.mes.text="Selecione&nbsp;&nbsp;"
  } else if ( tipo == "orgao" ){
	document.formOrgao.mes.value="0"
	document.formOrgao.mes.text="Selecione&nbsp;&nbsp;"
  } else if ( tipo == "ug" ){
	document.formUg.mes.value="0"
	document.formUg.mes.text="Selecione&nbsp;&nbsp;"
  } 
}

function selecionaAPC(idApc, NomeApc){
	document.forms[0].idapc.value = idApc;
	document.forms[0].nome.value = NomeApc;
	focus=document.forms[0].nome.value;
}

function confirmaUsuarios(senha, confirmacao) {
   if (document.forms[0].idgrupo.value == ""){  
   		alert("Campo Grupo é requerido !");
   } else {
     if (document.forms[0].login.value == "") {
     	alert("Campo Login é requerido !");
     } else {     
	     if (document.forms[0].senha.value == "") {
	     	alert("Campo Senha é requerido !");
	     } else {   		
		   if (senha != confirmacao){
	   			alert("Confirmação da senha inválida !");   		
		   } else {
			 	document.forms[0].submit();
		   }
		 }  
	 }
   }	
}

function checaAPC(action){
	if(document.forms[0].idgrupo.value == '4'){
		document.forms[0].action=action+'?apc=1';
  		document.forms[0].submit();
	} else {
		document.forms[0].action=action;
  		document.forms[0].submit();	
	}
}

function pesquisarAPCs(){
  if (document.forms[0].elements["chave"].value != ''){
	  document.forms[0].action=action+'?pesquisar=1';      
      document.forms[0].submit();
  }else{
     alert("Digite uma chave de pesquisa !");
  }
}

function pesquisarChaveApcUsuario(AlterarExcluir) {
  if (document.forms[1].elements["chave"].value != ''){
      document.forms[1].elements["idarea"].value = document.forms[0].elements["idarea"].value;
      document.forms[1].elements["matricula"].value = document.forms[0].elements["matricula"].value;
      document.forms[1].elements["cargo"].value = document.forms[0].elements["cargo"].value;
      document.forms[1].elements["telefones"].value = document.forms[0].elements["telefones"].value;
      document.forms[1].elements["email"].value = document.forms[0].elements["email"].value;
      if (AlterarExcluir == "INSERIR"){      
    	  document.forms[1].elements["login"].value = document.forms[0].elements["login"].value;
	      document.forms[1].elements["senha"].value = document.forms[0].elements["senha"].value;
	  }	
      document.forms[1].elements["ativo"].value = document.forms[0].elements["ativo"].value;
      document.forms[1].action="/siscon/Usuario/action.do?dispatch=consultarApc&acao=" + AlterarExcluir;
      document.forms[1].submit();
  }else{
     alert("Digite uma chave de pesquisa !");
  }
}

function pesquisarChave(){
  if (document.forms[0].elements["chave"].value != ''){
      document.forms[0].submit();
  }else{
     alert("Digite uma chave de pesquisa !");
  }
}

function onSobreEscrever(event) {
  if (!event.target.checked)
    return;
    
  var selected = false;

  for (var i = 0; i < event.target.form.elements["recomendacoesVinculadas"].length; i++) {
    var objCheckbox = event.target.form.elements["recomendacoesVinculadas"][i];

    if (objCheckbox.checked) {
      selected = true;
      break;
    }
  }
  
  if (! selected) {
    event.target.checked = false;
    alert("Por favor, selecione algum vínculo antes.");
    return;
  }
  
  if (! confirm("Isso irá remover **TODOS** os vínculos atuais e substituí-los por estes que você selecionou.")) {
    event.target.checked = false;
    /* Cancela o evento */
    event.cancelBubble = true;
    if (event.stopPropagation)
      event.stopPropagation();  
  }
}

function toggleCheckboxes(objCheckbox) {
  var parentFormElements = objCheckbox.form.elements;

  for (var element in parentFormElements) {
    var curElement = objCheckbox.form[element];
    if (curElement instanceof HTMLInputElement) {
      if (curElement != objCheckbox) {
        curElement.checked = false;
      }
    }
  }
}

function teste(args){ 
 var p=args;
 if (p != null){
	window.location.href="/siscon/Ra/editar.do?acao=situacoesRa#" + p; 	
	} 
}

function confirmarReset(texto, url) {
  if (document.forms[0].gerarsenha.value = "S"){
	confirmar(texto, '/siscon/Usuario/action.do?dispatch=resetarSenha');   
  } else {		  
	document.forms[0].submit();
  }
}


function confirmar(texto, url) {
  if (confirm(texto)) {
    window.location.href=url;
  }
}
  function confirmaGerarSenha(t) {
  if (confirm(t)) {
    document.forms[0].submit();
  }
}

function remover(texto, url){ 
 var p=url;
 if (url != null){
    if (confirm(texto)){
	    window.location.href=url; 	
    }                       	  
 } 
}

function removerOrientacaoRa(aCaminho){ 
 var p=aCaminho;
 if (aCaminho != null){
    if (confirm('remover o vinculo com o Ra?')){
	    window.location.href=aCaminho; 	
    }                       	  
 } 
}


// progress bar para área de texto //
function textCounter(field,counter,maxlimit,linecounter) {

	// text width//
	var fieldWidth =  parseInt(field.style.width);
	var charcnt    = field.value.length;        

	// trim the extra text
	if (charcnt > maxlimit) { 
		field.value = field.value.substring(0, maxlimit);
	}
	else { 

		// progress bar percentage
		var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;
		document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";

		// color correction on style from CCFFF -> CC0000
		setcolor(document.getElementById(counter),percentage,"background-color");
	}	
}

function setcolor(obj,percentage,prop){
	obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";

}

// Selecionar todos os checks
var checkflag = "false";
function check(field) {
 if (checkflag == "false") {
  for (i = 0; i <= field.length-1; i++) {
   field[i].checked = true;
  }
   checkflag = "true";
   return "Desmarcar todas"; 
 }else {
   for (i = 0; i <= field.length-1; i++) {
     field[i].checked = false; 
   }
  checkflag = "false";
  return "Selecionar todas"; }
}
// Verifica se todos os checks estão marcados
function analisarChecks(field){
  alert("tamanho: " + field.length);
  if(field.length > 0){
     for (i = 0; i <= field.length-1; i++) {
      if (field[i].checked == true){
        checkflag = "true";
      }
    }
    if(checkflag == "true"){
       document.forms[0].submit();
    }else{
       alert("É necessario marcar pelo menos uma Orientação!");
    }
  }else{
       alert("Não Existe Orientação vinculada a essa Situação!");
  }
}
// 
var wFlag = "false";
function analisarChecksW(form){
  for (i = 0; i<= form.length-1;i++){
  	if (form[i].name == "recomendacoesRaVinculadas"){
		if (form[i].checked){
			wFlag = "true";
		} else if (form[i+1].checked){
			form[i].checked = true;
			wFlag = "true";
		}	
  	}
  }
  if(wFlag == "true"){
     document.forms[0].submit();
  }else{
     alert("É necessario marcar pelo menos uma Orientação !");
  }  
}

// 
var Valida = "false";
function analisarChecksSacSi(form){
  for (i = 0; i<= form.length-1;i++){
  	if (form[i].name == "recomendacoesSacSi"){
		if (form[i].checked){
			Valida = "true";
		}	
  	}
  }
  if(Valida == "true"){
     document.forms[0].submit();
  }else{
     alert("É necessario marcar pelo menos uma Recomendação !");
  }  
}

// Metodo para limpar todos os campos do formulario de aluno
function limparAluno(){
 document.forms["alunoForm"].elements["nmAluno"].value='';
 document.forms["alunoForm"].elements["nascimento"].value='';
 document.forms["alunoForm"].elements["endereco"].value='';
 document.forms["alunoForm"].elements["complemento"].value='';
 document.forms["alunoForm"].elements["fone01"].value='';
 document.forms["alunoForm"].elements["fone02"].value='';
 document.forms["alunoForm"].elements["fone03"].value='';
 document.forms["alunoForm"].elements["email"].value='';
 document.forms["alunoForm"].elements["nmPai"].value='';
 document.forms["alunoForm"].elements["nmMae"].value='';
 document.forms["alunoForm"].elements["rg"].value='';
 document.forms["alunoForm"].elements["cpf"].value='';
 document.forms["alunoForm"].elements["serie"].value='';
  
}

function MascaraCEP (formato, keypress, objeto)
	{
	campo = eval (objeto);
	if (formato=='CEP')
		{
		caracteres = '01234567890';
		separacoes = 1;
		separacao1 = '-';
		conjuntos = 2;
		conjunto1 = 5;
		conjunto2 = 3;
		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length < 
		(conjunto1 + conjunto2 + 1))
			{
			if (campo.value.length == conjunto1) 
			   campo.value = campo.value + separacao1;
			}
		else 
			event.returnValue = false;
		}
	}


//Metodo para trocar a action de um form e submete-lo
function mudar(action){
  document.forms[0].action=action;
  document.forms[0].submit();
}

function fecharPop(pop){
  var fechar=pop;
  if (fechar != null){
     alert('Situação vinculada com sucesso!');
     if (navigator.appName.indexOf("Microsoft") !=-1){

        self.opener.document.refresh;
     }
     
     if(navigator.appName.indexOf("Firefox") !=-1 || navigator.appName.indexOf("Netscape") !=-1){
        if (window.opener && !window.opener.closed){
           window.opener.document.location.reload();
        }
     }
     window.close();       
  }
}

function findDescCheck(action){
	if (document.forms[0].elements["recNaoVinculadas"].checked != false 	
	 || document.forms[0].elements["recVinculadas"].checked != false){
    	if (document.forms[0].elements["recNaoVinculadas"].checked == false 
    	 && document.forms[0].elements["recVinculadas"].checked == true){
  			document.forms[0].action=action;
  			document.forms[0].submit();
    	}else{
      		if (document.forms[0].elements["descricao"].value != ''){
  				document.forms[0].action=action;
  				document.forms[0].submit();
      		}else{
     			alert("digite um texto para a Consulta!");
    		}
  		}
  	}else{
		alert("É obrigatorio selecionar um filtro !");
  	}
}

function alterar(){
  if (document.forms[0].elements["descricao"].value != ''){
      document.forms[0].submit();
  }else{
     alert("digite um texto para o filtro!");
  }
}

function checarOrgao(){
	if (document.forms[0].elements["orgaoId"].value == '0') {
		alert("É necessário selecionar o órgão.");
	} else if ('0' == document.forms[0].elements["ugId"].value) {
		alert("É necessário selecionar uma unidade gestora.");
	} else {
		document.forms[0].submit();
	}
}

function pesquisarNome(){
  if (document.forms[0].elements["nome"].value != ''){
      document.forms[0].submit();
  }else{
     alert("digite um texto para o filtro!");
  }
}

function pesquisar(campo){
  if (document.forms[0].elements[campo].value != ''){
      document.forms[0].submit();
  }else{
     alert("digite um texto para o filtro!");
  }
}



function pesquisarSigla(){
  if (document.forms[0].elements["sigla"].value != ''){
      document.forms[0].submit();
  }else{
     alert("digite um texto para o filtro!");
  }
}




//Metodo que direciona para uma determinada action
function set(target) {
	document.forms[0].dispatch.value=target;
}

function pesquisarDirecionandoAction(){
      document.forms[0].submit();
}

//"Netscape"
//"Microsoft Internet Explorer"
//"Microsoft"
function abreJanelaCentro(pagina, nome, w, h, scroll) {
 var winl = (screen.width - w) / 2; 
 var wint = (screen.height - h) / 2;
 winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable';
 if (navigator.appName.indexOf("Microsoft") !=-1){
   window.showModalDialog(pagina,nome,'dialogHeight: '+h+'px;dialogTop: '+wint+'px; dialogLeft: '+winl+'px; dialogWidth: '+w+'px; edge: raised; center: Yes; help: no; resizable: yes; status: yes;');
   //window.showModalDialog(pagina,nome,'dialogHeight: '+h+';dialogTop: '+wint+'; dialogLeft: '+winl+'; dialogWidth: '+w+'; edge: Sunken; center: Yes; help: no; resizable: yes; status: No;');
 }
 if(navigator.appName.indexOf("Netscape") !=-1){
    if (parseInt(navigator.appVersion) >= 0) { 
       win = window.open(pagina, nome, winprops);
       win.window.focus(); 
    }
 }
 if(navigator.appName.indexOf("Firefox") !=-1){
    if (parseInt(navigator.appVersion) >= 0) { 
      win = window.open(pagina, nome, winprops);
      win.window.focus(); 
    }
 }
}

  function load(path){
     var str = '<%=request.getAttribute("popup")%>';
     if (str=='sim') {
       alert('Registro salvo com sucesso!');
      if (window.opener && !window.opener.closed)
     //window.opener.history.go( 0 );
      window.opener.document.location=path;
        window.close();       
     }
    }
function maskHora(hora) {

  var result = '';

  if (hora.length==2) {
  
    if (hora.substr(0,1) == '0' || hora.substr(0,1) == '1')

      result = hora + ':';
	
	else if (hora.substr(0,1) == '2' && (hora.substr(1,1) == '1' || hora.substr(1,1) == '2' || hora.substr(1,1) == '3'))
	
      result = hora + ':';
	  
	else 
	
	  result = hora.substr(0,1);
	  
  } else if (hora.length==4) {
  
    verifList = "0,1,2,3,4,5";
  
    if (verifList.indexOf(hora.substr(3,1))!=-1) 
	
	  result = hora;
	  
	else
	  
	  result = hora.substr(0,3);
	
  } else if (hora.length==5) {
	
	  result = hora;
		
  } else {

    for (i=0;i<hora.length;i++) {

      if (result.length==2) {

        result = result + ':';

      }

      if (hora.substr(i,1)!=':') {

        result = result + hora.substr(i,1);

      }

    }

  }
  hora=result;
}
function formataData(obj) {
    var data = '';
    data = data + obj.value;

    if (data.length == 2) {
        data = data + '/';
        obj.value = data;
    }
    if (data.length == 5) {
        data = data + '/';
        obj.value = data;
    }
    if (data.length == 10) {
	obj.value = data;
    }
}
function formataHora(obj) {
    var data = '';
    data = data + obj.value;

    if (data.length == 2) {
        data = data + ':';
        obj.value = data;
    }
    if (data.length == 5) {
        data = data + ':';
        obj.value = data;
    }
    if (data.length == 7) {
	obj.value = data;
    }
}

function ApenasNum(strParm) {
	strParm = String(strParm);
	var chrPrt = "0";
	var strRet = "";
	var j=0;
	for (var i=0; i < strParm.length; i++) {
		chrPrt = strParm.substring(i, i+1);
		if ( chrPrt.match(/\d/) ) {
			if (j==0) {
				strRet = chrPrt;
				j=1;
			}	else {
				strRet = strRet.concat(chrPrt);
			}
		}
	}
	return strRet;
}
function ApenasNumeros(obj) {
	aux= obj.value;
	obj.value =aux.toUpperCase();
	var chrvalid = '0123456789';
	if(chrvalid.indexOf(obj.value)==-1) {
	  obj.value='';
	}
}
function ApenasPFJ(obj) {
	aux= obj.value;
	obj.value =aux.toUpperCase();
	var chrvalid = 'FJP';
	if(chrvalid.indexOf(obj.value)==-1) {
	  obj.value='';
	}
}
function Nota(obj) {
   	var str = obj.value;
   	var aux = '123456789.,';
	for (i=0;i<str.length;i++) {
	  alert(str);
	   if (aux.indexOf(str[i])!=-1) {
	      if (str[i]==',')
	         str[i] = '.';
	   }
	   else {
		  str[i] = '';
	   }
	}
	alert(str);
	obj.value = str;	
}

function formataNome(obj) {
	aux = obj.value;
	obj.value = aux.toUpperCase();
}
function formataEmail(obj) {
	aux = obj.value;
	obj.value = aux.toLowerCase();
}

function formataCPF(obj) {
    var cpf = '';
    cpf = cpf + obj.value;

    if (cpf.length == 3) {
        cpf = cpf + '.';
        obj.value = cpf;
    }
    if (cpf.length == 7) {
        cpf = cpf + '.';
        obj.value = cpf;
    }
    if (cpf.length == 11) {
        cpf = cpf + '-';
        obj.value = cpf;
    }
    if (cpf.length == 14) {
	obj.value = cpf;
    }
}
function formataCEP(obj) {
    var cep = '';
    cep = cep + obj.value;

    if (cep.length == 2) {
        cep = cep + '.';
        obj.value = cep;
    }
    if (cep.length == 6) {
        cep = cep + '-';
        obj.value = cep;
    }
    if (cep.length == 10) {
	obj.value = cep;
    }
}

function Limpar(valor, validos) {
	// retira caracteres invalidos da string
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) {
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0) {
			result += aux;
		}
	}
	return result;
}

function formataValor(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = Telefone_Remove_Format(campo.value);
	tam = vr.length;
	
	if (tam < tammax && tecla != 8) {
		tam = vr.length + 1 ;
	}

	if (tecla == 8 ) {
		tam = tam - 1 ;
	}

	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) {
		if ( tam <= 2 ) {
			campo.value = vr ;
		}
		if ( (tam > 2) && (tam <= 5) ) {
			campo.value = vr.substr( 0, tam - 2 ) + '.' + vr.substr( tam - 2, tam ) ;
		}
		if ( (tam >= 6) && (tam <= 8) ) {
			campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '.'+ vr.substr( tam - 2, tam ) ;
		}
		if ( (tam >= 9) && (tam <= 11) ) {
			campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ;
		}
		if ( (tam >= 12) && (tam <= 14) ) {
			campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ;
		}
		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 ) + '.' + vr.substr( tam - 2, tam ) ;
		}
	}

}

function formataTelefone(Campo, e) {
    var key = '';
    var len = 0;
    var strCheck = '0123456789';
    var aux = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    
    if (whichCode == 13 || whichCode == 8 || whichCode == 0)
    {
        return true;  // Enter backspace ou FN qualquer um que n?o seja alfa numerico
    }
    key = String.fromCharCode(whichCode);
    if (strCheck.indexOf(key) == -1){
        return false;  //N?O E VALIDO
    }
    
    aux =  Telefone_Remove_Format(Campo.value);
    
    len = aux.length;
    if(len>=10)
    {
        return false;    //impede de digitar um telefone maior que 10
    }
    aux += key;
    
    Campo.value = Telefone_Mont_Format(aux);
    return false;
}

function  Telefone_Mont_Format(Telefone)
{
    var aux = len = '';
    
    len = Telefone.length;
    if(len<=9)
    {
        tmp = 5;
    }
    else
    {
        tmp = 6;
    }
    
    aux = '';
    for(i = 0; i < len; i++) {

        if(i==0)
        {
            aux = '(';
        }
        aux += Telefone.charAt(i);
        if(i+1==2)
        {
            aux += ')';
        }
        
        if(i+1==tmp)
        {
            aux += '-';
        }
    }
    return aux ;
}

function  Telefone_Remove_Format(Telefone)
{
    var strCheck = '0123456789';
    var len = i = aux = '';
    len = Telefone.length;
    for(i = 0; i < len; i++)
    {
        if (strCheck.indexOf(Telefone.charAt(i))!=-1)
        {
            aux += Telefone.charAt(i);
        }
    }
    return aux;
}
function tryNumberFormat(obj){
	obj.value = new NumberFormat(obj.value).toFormatted();
}
 
function NumberFormat(num, inputDecimal)
{
	// constants
	this.COMMA = ',';
	this.PERIOD = '.';
	this.DASH = '-'; // v1.5.0 - new - used internally
	this.LEFT_PAREN = '('; // v1.5.0 - new - used internally
	this.RIGHT_PAREN = ')'; // v1.5.0 - new - used internally
	this.LEFT_OUTSIDE = 0; // v1.5.0 - new - currency
	this.LEFT_INSIDE = 1;  // v1.5.0 - new - currency
	this.RIGHT_INSIDE = 2;  // v1.5.0 - new - currency
	this.RIGHT_OUTSIDE = 3;  // v1.5.0 - new - currency
	this.LEFT_DASH = 0; // v1.5.0 - new - negative
	this.RIGHT_DASH = 1; // v1.5.0 - new - negative
	this.PARENTHESIS = 2; // v1.5.0 - new - negative
	this.NO_ROUNDING = -1 // v1.5.1 - new

	// member variables
	this.num;
	this.numOriginal;
	this.hasSeparators = false;  // v1.5.0 - new
	this.separatorValue;  // v1.5.0 - new
	this.inputDecimalValue; // v1.5.0 - new
	this.decimalValue;  // v1.5.0 - new
	this.negativeFormat; // v1.5.0 - new
	this.negativeRed; // v1.5.0 - new
	this.hasCurrency;  // v1.5.0 - modified
	this.currencyPosition;  // v1.5.0 - new
	this.currencyValue;  // v1.5.0 - modified
	this.places;
	this.roundToPlaces; // v1.5.1 - new

	// external methods
	this.setNumber = setNumberNF;
	this.toUnformatted = toUnformattedNF;
	this.setInputDecimal = setInputDecimalNF; // v1.5.0 - new
	this.setSeparators = setSeparatorsNF; // v1.5.0 - new - for separators and decimals
	this.setCommas = setCommasNF;
	this.setNegativeFormat = setNegativeFormatNF; // v1.5.0 - new
	this.setNegativeRed = setNegativeRedNF; // v1.5.0 - new
	this.setCurrency = setCurrencyNF;
	this.setCurrencyPrefix = setCurrencyPrefixNF;
	this.setCurrencyValue = setCurrencyValueNF; // v1.5.0 - new - setCurrencyPrefix uses this
	this.setCurrencyPosition = setCurrencyPositionNF; // v1.5.0 - new - setCurrencyPrefix uses this
	this.setPlaces = setPlacesNF;
	this.toFormatted = toFormattedNF;
	this.toPercentage = toPercentageNF;
	this.getOriginal = getOriginalNF;
	this.moveDecimalRight = moveDecimalRightNF;
	this.moveDecimalLeft = moveDecimalLeftNF;

	// internal methods
	this.getRounded = getRoundedNF;
	this.preserveZeros = preserveZerosNF;
	this.justNumber = justNumberNF;
	this.expandExponential = expandExponentialNF;
	this.getZeros = getZerosNF;
	this.moveDecimalAsString = moveDecimalAsStringNF;
	this.moveDecimal = moveDecimalNF;

	// setup defaults
	if (inputDecimal == null) {
		this.setNumber(num, this.PERIOD);
	} else {
		this.setNumber(num, inputDecimal); // v.1.5.1 - new
	}
	this.setCommas(true);
	this.setNegativeFormat(this.LEFT_DASH); // v1.5.0 - new
	this.setNegativeRed(false); // v1.5.0 - new
	this.setCurrency(false); // v1.5.1 - false by default
	this.setCurrencyPrefix('R$');
	this.setPlaces(2);
}

/*
 * setInputDecimal
 * val - The decimal value for the input.
 *
 * v1.5.0 - new
 */
function setInputDecimalNF(val)
{
	this.inputDecimalValue = val;
}

/*
 * setNumber - Sets the number
 * num - The number to be formatted
 * inputDecimal - (Optional) The decimal character for the input
 *  Also refer to setInputDecimal
 * 
 * If there is a non-period decimal format for the input,
 * setInputDecimal should be called before calling setNumber.
 *
 * v1.5.0 - modified
 */
function setNumberNF(num, inputDecimal)
{
	if (inputDecimal != null) {
		this.setInputDecimal(inputDecimal); // v.1.5.1 - new
	}
	
	this.numOriginal = num;
	this.num = this.justNumber(num);
}

/*
 * toUnformatted - Returns the number as just a number.
 * If the original value was '100,000', then this method will return the number 100000
 * v1.0.2 - Modified comments, because this method no longer returns the original value.
 */
function toUnformattedNF()
{
	return (this.num);
}

/*
 * getOriginal - Returns the number as it was passed in, which may include non-number characters.
 * This function is new in v1.0.2
 */
function getOriginalNF()
{
	return (this.numOriginal);
}

/*
 * setNegativeFormat - How to format a negative number.
 * 
 * format - The format. Use one of the following constants.
 * LEFT_DASH   example: -1000
 * RIGHT_DASH  example: 1000-
 * PARENTHESIS example: (1000)
 *
 * v1.5.0 - new
 */
function setNegativeFormatNF(format)
{
	this.negativeFormat = format;
}

/*
 * setNegativeRed - Format the number red if it's negative.
 * 
 * isRed - true, to format the number red if negative, black if positive;
 *  false, for it to always be black font.
 *
 * v1.5.0 - new
 */
function setNegativeRedNF(isRed)
{
	this.negativeRed = isRed;
}

/*
 * setSeparators - One purpose of this method is to set a
 *  switch that indicates if there should be separators between groups of numbers.
 *  Also, can use it to set the values for the separator and decimal.
 *  For example, in the value 1,000.00
 *   The comma (,) is the separator and the period (.) is the decimal.
 *
 * Both separator or decimal are not required.
 * The separator and decimal cannot be the same value. If they are, decimal with be changed.
 * Can use the following constants (via the instantiated object) for separator or decimal:
 *  COMMA
 *  PERIOD
 * 
 * isC - true, if there should be separators; false, if there should be no separators
 * separator - the value of the separator.
 * decimal - the value of the decimal.
 *
 * v1.5.0 - new
 */
function setSeparatorsNF(isC, separator, decimal)
{
	this.hasSeparators = isC;
	
	// Make sure a separator was passed in
	if (separator == null) separator = this.COMMA;
	
	// Make sure a decimal was passed in
	if (decimal == null) decimal = this.PERIOD;
	
	// Additionally, make sure the values aren't the same.
	//  When the separator and decimal both are periods, make the decimal a comma.
	//  When the separator and decimal both are any other value, make the decimal a period.
	if (separator == decimal) {
		this.decimalValue = (decimal == this.PERIOD) ? this.COMMA : this.PERIOD;
	} else {
		this.decimalValue = decimal;
	}
	
	// Since the decimal value changes if decimal and separator are the same,
	// the separator value can keep its setting.
	this.separatorValue = separator;
}

/*
 * setCommas - Sets a switch that indicates if there should be commas.
 * The separator value is set to a comma and the decimal value is set to a period.
 * isC - true, if the number should be formatted with separators (commas); false, if no separators
 *
 * v1.5.0 - modified
 */
function setCommasNF(isC)
{
	this.setSeparators(isC, this.COMMA, this.PERIOD);
}

/*
 * setCurrency - Sets a switch that indicates if should be displayed as currency
 * isC - true, if should be currency; false, if not currency
 */
function setCurrencyNF(isC)
{
	this.hasCurrency = isC;
}

/*
 * setCurrencyPrefix - Sets the symbol for currency.
 * val - The symbol
 */
function setCurrencyValueNF(val)
{
	this.currencyValue = val;
}

/*
 * setCurrencyPrefix - Sets the symbol for currency.
 * The symbol will show up on the left of the numbers and outside a negative sign.
 * cp - The symbol
 *
 * v1.5.0 - modified - This now calls setCurrencyValue and setCurrencyPosition(this.LEFT_OUTSIDE)
 */
function setCurrencyPrefixNF(cp)
{
	this.setCurrencyValue(cp);
	this.setCurrencyPosition(this.LEFT_OUTSIDE);
}

/*
 * setCurrencyPosition - Sets the position for currency,
 *  which includes position relative to the numbers and negative sign.
 * cp - The position. Use one of the following constants.
 *  This method does not automatically put the negative sign at the left or right.
 *  They are left by default, and would need to be set right with setNegativeFormat.
 *	LEFT_OUTSIDE  example: $-1.00
 *	LEFT_INSIDE   example: -$1.00
 *	RIGHT_INSIDE  example: 1.00$-
 *	RIGHT_OUTSIDE example: 1.00-$
 *
 * v1.5.0 - new
 */
function setCurrencyPositionNF(cp)
{
	this.currencyPosition = cp
}

/*
 * setPlaces - Sets the precision of decimal places
 * p - The number of places.
 *  -1 or the constant NO_ROUNDING turns off rounding to a set number of places.
 *  Any other number of places less than or equal to zero is considered zero.
 *
 * v1.5.1 - modified
 */
function setPlacesNF(p)
{
	this.roundToPlaces = !(p == this.NO_ROUNDING); // v1.5.1
	this.places = (p < 0) ? 0 : p; // v1.5.1 - Don't leave negatives.
}

/*
 * toFormatted - Returns the number formatted according to the settings (a string)
 *
 * v1.5.0 - modified
 * v1.5.1 - modified
 */
function toFormattedNF()
{	
	var pos;
	var nNum = this.num; // v1.0.1 - number as a number
	var nStr;            // v1.0.1 - number as a string
	var splitString = new Array(2);   // v1.5.0
	
	// round decimal places - modified v1.5.1
	// Note: Take away negative temporarily with Math.abs
	if (this.roundToPlaces) {
		nNum = this.getRounded(nNum);
		nStr = this.preserveZeros(Math.abs(nNum)); // this step makes nNum into a string. v1.0.1 Math.abs
	} else {
		nStr = this.expandExponential(Math.abs(nNum)); // expandExponential is called in preserveZeros, so call it here too
	}

	// the separator and decimal values have to be different
	// this is enforced in justNumber
	if (nStr.indexOf(this.PERIOD) == -1) {
		splitString[0] = nStr;
		splitString[1] = '';
	} else {
		splitString = nStr.split(this.PERIOD, 2);
	}

	// separators
	if (this.hasSeparators) {
		pos = splitString[0].length;
		while (pos > 0) {
			pos -= 3;
			if (pos <= 0) break;

			splitString[0] = splitString[0].substring(0,pos)
				+ this.separatorValue
				+ splitString[0].substring(pos, splitString[0].length);
		}
	}
	
	// decimal
	if (splitString[1].length > 0) {
		nStr = splitString[0] + this.decimalValue + splitString[1];
	} else {
		nStr = splitString[0];
	}
	
	// negative and currency
	// $[c0] -[n0] $[c1] -[n1] #.#[nStr] -[n2] $[c2] -[n3] $[c3]
	var c0 = '';
	var n0 = '';
	var c1 = '';
	var n1 = '';
	var n2 = '';
	var c2 = '';
	var n3 = '';
	var c3 = '';
	var negSignL = (this.negativeFormat == this.PARENTHESIS) ? this.LEFT_PAREN : this.DASH;
	var negSignR = (this.negativeFormat == this.PARENTHESIS) ? this.RIGHT_PAREN : this.DASH;
		
	if (this.currencyPosition == this.LEFT_OUTSIDE) {
		// add currency sign in front, outside of any negative. example: $-1.00	
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c0 = this.currencyValue;
	} else if (this.currencyPosition == this.LEFT_INSIDE) {
		// add currency sign in front, inside of any negative. example: -$1.00
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c1 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_INSIDE) {
		// add currency sign at the end, inside of any negative. example: 1.00$-
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c2 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_OUTSIDE) {
		// add currency sign at the end, outside of any negative. example: 1.00-$
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c3 = this.currencyValue;
	}

	nStr = c0 + n0 + c1 + n1 + nStr + n2 + c2 + n3 + c3;
	
	// negative red
	if (this.negativeRed && nNum < 0) {
		nStr = '<font color="red">' + nStr + '</font>';
	}

	return (nStr);
}

/*
 * toPercentage - Format the current number as a percentage.
 * This is separate from most of the regular formatting settings.
 * The exception is the number of decimal places.
 * If a number is 0.123 it will be formatted as 12.3%
 *
 * !! This is an initial version, so it doesn't use many settings.
 * !! should use some of the formatting settings that toFormatted uses.
 * !! probably won't want to use settings like currency.
 *
 * v1.5.0 - new
 */
function toPercentageNF()
{
	nNum = this.num * 100;
	
	// round decimal places
	nNum = this.getRounded(nNum);
	
	return nNum + '%';
}

/*
 * Return concatenated zeros as a string. Used to pad a number.
 * It might be extra if already have many decimal places
 * but is needed if the number doesn't have enough decimals. 
 */
function getZerosNF(places)
{
		var extraZ = '';
		var i;
		for (i=0; i<places; i++) {
			extraZ += '0';
		}
		return extraZ;
}

/*
 * Takes a number that JavaScript expresses in notational format
 * and makes it the full number (as a string).
 * e.g. Makes -1e-21 into -0.000000000000000000001
 *
 * If the value passed in is not a number (as determined by isNaN),
 * this function just returns the original value.
 *
 * Exponential number formats can include 1e21 1e+21 1e-21
 *  where 1e21 and 1e+21 are the same thing.
 *
 * If an exponential number is evaluated by JavaScript,
 * it will change 12.34e-9 to 1.234e-8,
 * which is a benefit to this method, because
 * it prevents extra zeros that occur for certain numbers
 * when using moveDecimalAsString
 *
 * Returns a string.
 *
 * v1.5.1 - new
 */
function expandExponentialNF(origVal)
{
	if (isNaN(origVal)) return origVal;
	
	var newVal = parseFloat(origVal) + ''; // parseFloat to let JavaScript evaluate number
	var eLoc = newVal.toLowerCase().indexOf('e');

	if (eLoc != -1) {
		var plusLoc = newVal.toLowerCase().indexOf('+');
		var negLoc = newVal.toLowerCase().indexOf('-', eLoc); // search for - after the e
		var justNumber = newVal.substring(0, eLoc);
		
		if (negLoc != -1) {
			// shift decimal to the left
			var places = newVal.substring(negLoc + 1, newVal.length);
			justNumber = this.moveDecimalAsString(justNumber, true, parseInt(places));
		} else {
			// shift decimal to the right
			// Check if there's a plus sign, and if not refer to where the e is.
			// This is to account for either formatting 1e21 or 1e+21
			if (plusLoc == -1) plusLoc = eLoc;
			var places = newVal.substring(plusLoc + 1, newVal.length);
			justNumber = this.moveDecimalAsString(justNumber, false, parseInt(places));
		}
		
		newVal = justNumber;
	}

	return newVal;
} 

/*
 * Move decimal right.
 * Returns a number.
 *
 * v1.5.1 - new
 */
function moveDecimalRightNF(val, places)
{
	var newVal = '';
	
	if (places == null) {
		newVal = this.moveDecimal(val, false);
	} else {
		newVal = this.moveDecimal(val, false, places);
	}
	
	return newVal;
}

/*
 * Move decimal left.
 * Returns a number.
 *
 * v1.5.1 - new
 */
function moveDecimalLeftNF(val, places)
{
	var newVal = '';
	
	if (places == null) {
		newVal = this.moveDecimal(val, true);
	} else {
		newVal = this.moveDecimal(val, true, places);
	}
	
	return newVal;
}

/*
 * moveDecimalAsString
 * This is used by moveDecimal, and does not run parseFloat on the return value.
 * 
 * Normally a decimal place is moved by multiplying by powers of 10
 * Multiplication and division in JavaScript can result in floating point limitations.
 * So use this method to move a decimal place left or right.
 *
 * Parameters:
 * val - The value to be shifted. Can be a number or a string,
 *  but don't include special characters. It should evaluate to a number.
 * left - If true, then move decimal left. If false, move right.
 * places - (optional) If not included, then use the objects this.places
 *  The purpose is so this method can be used independent of the state of the object.
 *
 * The regular expresions:
 * re1
 * Pad with zeros in case there aren't enough numbers to cover the spaces shift.
 * A left shift pads to the left, and a right shift pads to the right.
 * Can't just concatenate. There might be a negative sign or the value could be an exponential.
 *
 * re2
 * Switch the decimal.
 * Need the first [0-9]+ to force the search to start rightmost.
 * The \.? and [0-9]{} criteria are the pieces that will be switched
 *
 * Other notes:
 * This method works on exponential numbers, e.g. 1.7e-12
 * because the regular expressions only modify the number and decimal parts.
 *
 * Mozilla can't handle [0-9]{0} in the regular expression.
 *  Fix: Since nothing changes when the decimal is shifted zero places, return the original value.
 *
 * IE is incorrect if exponential ends in .
 *  e.g. -8500000000000000000000. should be -8.5e+21
 *  IE counts it as -8.5e+22
 *	Fix: Replace trailing period, if there is one, using replace(/\.$/, '').
 *
 * Netscape 4.74 and 6.1 cannot handle '$1' + extraZ in a replace. It replaces with nothing.
 *  The concatenation of $1 and a zero might be interpreted as $10, which is not valid.
 *  However, it can handle extraZ + '$1' in the replace, so the if(left) logic is ok.
 *  Fix: Use the parenthesized substring match properties, e.g. RegExp.$1, after calling re1.test(newVal)
 *  
 * Netscape 4.74 cannot handle a leading - in the string being searched for the re2 expressions.
 *  e.g. /([0-9]*)(\.?)([0-9]{2})/ should match everything in -100.00 except the -
 *  but it matches nothing using Netscape 4.74.
 *  It might be a combination of the * ? special characters.
 *  Fix: (-?) was added to each of the re2 expressions to look for - one or zero times.
 *
 * Returns a string.
 *
 * v1.5.1 - new
 */
function moveDecimalAsStringNF(val, left, places)
{
	var spaces = (arguments.length < 3) ? this.places : places;
	if (spaces <= 0) return val; // to avoid Mozilla limitation
			
	var newVal = val + '';
	var extraZ = this.getZeros(spaces);
	var re1 = new RegExp('([0-9.]+)');
	if (left) {
		newVal = newVal.replace(re1, extraZ + '$1');
		var re2 = new RegExp('(-?)([0-9]*)([0-9]{' + spaces + '})(\\.?)');		
		newVal = newVal.replace(re2, '$1$2.$3');
	} else {
		if (re1.test(newVal)) {
			newVal = RegExp.leftContext + RegExp.$1 + extraZ + RegExp.rightContext;
		}
		var re2 = new RegExp('(-?)([0-9]*)(\\.?)([0-9]{' + spaces + '})');
		newVal = newVal.replace(re2, '$1$2$4.');
	}
	newVal = newVal.replace(/\.$/, ''); // to avoid IE flaw
	
	return newVal;
}

/*
 * moveDecimal
 * Refer to notes in moveDecimalAsString
 * parseFloat is called here to clear away the padded zeros.
 *
 * Returns a number.
 *
 * v1.5.1 - new
 */
function moveDecimalNF(val, left, places)
{
	var newVal = '';
	
	if (places == null) {
		newVal = this.moveDecimalAsString(val, left);
	} else {
		newVal = this.moveDecimalAsString(val, left, places);
	}
	
	return parseFloat(newVal);
}

/*
 * getRounded - Used internally to round a value
 * val - The number to be rounded
 * 
 *  To round to a certain decimal precision,
 *  all that should need to be done is
 *  multiply by a power of 10, round, then divide by the same power of 10.
 *  However, occasional numbers don't get exact results in most browsers.
 *  e.g. 0.295 multiplied by 10 yields 2.9499999999999997 instead of 2.95
 *  Instead of adjusting the incorrect multiplication,
 *  this function uses string manipulation to shift the decimal.
 *
 * Returns a number.
 *
 * v1.5.1 - modified
 */
function getRoundedNF(val)
{
	val = this.moveDecimalRight(val);
	val = Math.round(val);
	val = this.moveDecimalLeft(val);
	
	return val;
}

/*
 * preserveZeros - Used internally to make the number a string
 * 	that preserves zeros at the end of the number
 * val - The number
 */
function preserveZerosNF(val)
{
	var i;

	// make a string - to preserve the zeros at the end
	val = this.expandExponential(val);
	
	if (this.places <= 0) return val; // leave now. no zeros are necessary - v1.0.1 less than or equal
	
	var decimalPos = val.indexOf('.');
	if (decimalPos == -1) {
		val += '.';
		for (i=0; i<this.places; i++) {
			val += '0';
		}
	} else {
		var actualDecimals = (val.length - 1) - decimalPos;
		var difference = this.places - actualDecimals;
		for (i=0; i<difference; i++) {
			val += '0';
		}
	}
	
	return val;
}

/*
 * justNumber - Used internally to parse the value into a floating point number.
 * Replace all characters that are not 0-9, a decimal point, or a negative sign.
 *
 *  A number can be entered using special notation.
 *  For example, the following is a valid number: 0.0314E+2
 *
 * v1.0.2 - new
 * v1.5.0 - modified
 * v1.5.1 - modified
 */
function justNumberNF(val)
{
	newVal = val + '';
	
	var isPercentage = false;
	
	// check for percentage
	// v1.5.0
	if (newVal.indexOf('%') != -1) {
		newVal = newVal.replace(/\%/g, '');
		isPercentage = true; // mark a flag
	}
		
	// Replace everything but digits - + ( ) e
	var re = new RegExp('[^\\' + this.inputDecimalValue + '\\d\\-\\+\\(\\)e]', 'g');		
	newVal = newVal.replace(re, '');
	// Replace the first decimal with a period and the rest with blank
	// The regular expression will only break if a special character
	//  is used as the inputDecimalValue
	//  e.g. \ but not .
	// By calling test, it will fill RegExp.leftContext et al
	// The leftContext is what's to the left of the first match
	// Search again in what's in the rightContext
	var tempRe = new RegExp('[' + this.inputDecimalValue + ']', 'g');
	if (tempRe.test(newVal)) {
		newVal = RegExp.leftContext + this.PERIOD + RegExp.rightContext.replace(tempRe, '');
	}
	
	// If negative, get it in -n format
	if (newVal.charAt(newVal.length - 1) == this.DASH ) {
		newVal = newVal.substring(0, newVal.length - 1);
		newVal = '-' + newVal;
	}
	else if (newVal.charAt(0) == this.LEFT_PAREN
	 && newVal.charAt(newVal.length - 1) == this.RIGHT_PAREN) {
		newVal = newVal.substring(1, newVal.length - 1);
		newVal = '-' + newVal;
	}
	
	newVal = parseFloat(newVal);
	
	if (!isFinite(newVal)) {
		newVal = 0;
  }
	
	// now that it's a number, adjust for percentage, if applicable.
  // example. if the number was formatted 24%, then move decimal left to get 0.24
  // v1.5.0 - updated v1.5.1
  if (isPercentage) {
  	newVal = this.moveDecimalLeft(newVal, 2);
  }
		
	return newVal;
}

//-->