/*
 *******************************************************************
 * Arquivo:     funcoes.js
 * Data:        30 de maio de 2006.
 * Copyright:   IEL-GO Todos os Direitos Reservados
 *******************************************************************
*/
      function sleep(millisecondi) {
	      var now = new Date();
	      var exitTime = now.getTime() + millisecondi;
  
	      while(true){
		      now = new Date();
		      if(now.getTime() > exitTime) return;
	      }
      }

/********************************************************************
	FUN??O USADA PARA INSERIR UM CURSO
********************************************************************/
function cursoAdd(m1 , m2){
	 var m1len = m1.length;
	 for ( i=0; i<m1len ; i++) {
		 if (m1.options[i].selected == true ) {
			 m2len = m2.length;
			 m2.options[m2len] = new Option(m1.options[i].text, m1.options[i].value, false, false);
		 }
        }

	for ( i = (m1len -1); i>=0; i--){
        if (m1.options[i].selected == true ) {
            m1.options[i] = null;
        }
    }
    m2.focus();
    m2.click();
}

/********************************************************************
	FUN??O USADA PARA EXCLUIR UM CURSO
********************************************************************/
function cursoRetirar(m1 , m2){
	    var m2len = m2.length ;
        for ( i=0; i<m2len ; i++){
            if (m2.options[i].selected == true ) {
                m1len = m1.length;
                m1.options[m1len]= new Option(m2.options[i].text, m2.options[i].value, false, false);
            }
        }
        for ( i=(m2len-1); i>=0; i--) {
            if (m2.options[i].selected == true ) {
                m2.options[i] = null;
            }
        }
}

/*
 * Descri??o:   Abre o documento Ficha Roteiro em uma jenala popup.
 * Param:       URL da Ficha roteiro.
 * Autor:       Vin?cius R. do Amaral
 */
function mostraFichaRoteiro(url) {

    popURL  = url;
    popNAME = "Ficha_Roteiro";
    popPROP = "scrollbars,status,width=600,left=" + (screen.width/2 - 600/2) + ",height=600,top=" + (screen.height/2 - 600/2);

    window.open(popURL, popNAME, popPROP);
}

/*
 * Descri??o:   Abre o documento de contrato de uma pessoa em uma jenala popup.
 * Param:       URL do contrato da empresa.
 * Autor:       DivC?sar Soares
 */
function mostraConvenio(url) {
    popURL  = url;
    popNAME = "CONTRATO";
    popPROP = "scrollbars,status,width=650,left=" + (screen.width/2 - 650/2) + ",height=650,top=" + (screen.height/2 - 650/2);

    window.open(popURL, popNAME, popPROP);
}

/*
 * Fun??o para retirar os espa?os em branco no inicio e fim da string.
 * Autor:   DivC?sar Soares
 */
function trim(str) {

    while (str.charAt(0) == " ")
    str = str.substr(1,str.length -1);

    while (str.charAt(str.length-1) == " ")
    str = str.substr(0,str.length-1);

    return str;
}

/*
 */
 function Trim(str){return str.replace(/^\s+|\s+$/g,"");}

/*
 * Funcao utilizada para adicionar zeros na hora
 * revis?o: Divino C?sar Soares
 * @author Raphael Adrien
 * @param textField
 */
function addZeroHora(obj){
	tamanho 	= obj.value.length;

	if(tamanho == 1) {
		obj.value = "0" + obj.value + ":00";
	}
	else if(tamanho == 2){
		obj.value = obj.value + ":00";
	} 
	else if (tamanho == 3) {
		obj.value = obj.value + "00";
	}
	else if (tamanho == 4) {
		obj.value = obj.value + "0";
	}
}


/*
 * Abre a tela principal do atendimento online.
 * 
 * Autor: Vinicios R. Amaral
 * Data:  xxxxxxxxxxxxxxxxxxxxxx
 */
//function horarioAtendimento(){              
//    day = new Date();
//    hr = day.getHours();
//    if ((hr >= 0) && (hr <=5)){
//    t = "frmAvisoAtendimento.jsp";}
//    if ((hr >= 6) && (hr <=11)){
//    t = "frmIdentificaChat.jsp";}
//    if ((hr >= 12) && (hr <=18)){
//    t = "frmIdentificaChat.jsp";}
//    if ((hr >= 18) && (hr <=23)){
//    t = "frmAvisoAtendimento.jsp";}
//    window.open("/interagy/cadastros/"+t, "TELA_DE_ATENDIMENTO", "width=451,height=575,status=yes");
//}


/*
 * Pergunta ao usu?rio se deseja realmente cancelar o cadastro da oferta de vaga, se confirmar, redireciona para  atela de login
 * caso contr?rio n?o faz nada.
 *
 * Autor: DivC?sar Soares
 * Data : 19 de maio de 2006.
 */
//function cancelarOfertarVaga() {
//    
//    goTo("", "Deseja realmente cancelar a oferta de vaga?", "SVEmpresaCT?modulo=empresa&acao=iniciar");
//}

/*
 * Pergunta ao usu?rio se deseja realmente cancelar o seu pr?-cadastro, se confirmar, redireciona para a tela de login
 * caso contr?rio na? faz nada.
 *
 * Autor: Divino C?sar Soares L.
 * Data:   11 de maio de 2006.
 */
function cancelarPreCadastroEscola(OPERADOR) {
    /*
     * verifica se ? um operador que esta cadastrando, se for deve ser redirecionado para outra p?gina e n?o a de login.
     */

	//alert(OPERADOR);

    if (OPERADOR) {
        url = "./AdministradorSV?modulo=admPreCadastroEscola";
    }
    else {
        url = "./cadastros/composer.jsp?redirecionamento=/cadastros/escola/index.jsp";
    }
	
	//alert(url);
    //url = url;

    goTo("", "Deseja realmente cancelar o cadastro?", url);
}

/*
 * Redireciona o location principal do browser para o URL especificado nos parametros.
 * se alerta for diferente de vazio, mostra o alerta primeiro, se o confirma for diferente de vazio
 * primeiro pede a confirma??o.
 *
 * Author: Divino C?sar Soares L.
 * Date:   11 de Maio de 2006
 */
function goTo(alerta, confirma, url) {

    if (alerta != "") {
        alert(alerta);
    }

    if (confirma != "") {
        if (! confirm(confirma)) {
            return ;
        }
    }
    
    self.location = url;
}


/*
 * @Author: Divino C?sar
 * @Date:   28 de mar?o de 2006
 * seleciona o tem de um radio group que foi indicado no parametro.
 *
 */
function selectRadioItem(item, valor) {
    for (i=0; i<item.length; i++) {
        if (item[i].value == valor) {
            item[i].checked = true;
            item[i].disabled = false;
            return ;
        }
    }
}

/*
 * @Author: Divino C?sar
 * @Date:   27 de mar?o de 2006
 * seleciona o tem de um checkbox que foi indicado no parametro.
 *
 */
function selectItemCombo(combo, valor) {
    for (i=0; i<combo.length; i++) {
        if (combo.options[i].value == valor) {
            combo.options[i].selected = true;
            return ;
        }
    }
}

//Variaveis para saber tamanho da tela 
//Utilizado no padrao de consultas

var screenHeight = screen.height;
var screenWidth  = screen.width;

/********************************************************************
	FUN??O USADA PARA FORMATAR MENUS.
********************************************************************/

var isDHTML = 0;
var isID = 0;
var isAll = 0;
var isLayers = 0;

if (document.getElementById) {isID = 1; isDHTML = 1;}
else {
if (document.all) {isAll = 1; isDHTML = 1;}
else {
browserVersion = parseInt(navigator.appVersion);
if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {isLayers = 1; isDHTML = 1;}
}}

//function findDOM(objectID,withStyle) {
//	if (withStyle == 1) {
//		if (isID) { return (document.getElementById(objectID).style) ; }
//		else { 
//			if (isAll) { return (document.all[objectID].style); }
//		else {
//			if (isLayers) { return (document.layers[objectID]); }
//		};}
//	}
//	else {
//		if (isID) { return (document.getElementById(objectID)) ; }
//		else { 
//			if (isAll) { return (document.all[objectID]); }
//		else {
//			if (isLayers) { return (document.layers[objectID]); }
//		};}
//	}
//}

//function toggleClamShellMenu(objectID) {
//	if (isAll || isID) {
//		domStyle = findDOM(objectID,1);
//		if (domStyle.display =='block')  domStyle.display='none';
//		else domStyle.display='block';
//	}
//	else {
//		destination = objectID + '.html';
//		self.location = destination;
//	}
//	return;
//}


/********************************************************************
	FUN??O USADA PARA FORMATAR CONSULTAS/PESQUISAS.
********************************************************************/
 

//function tableruler()
//{
//	if (document.getElementById && document.createTextNode)
//	{
//		var tables=document.getElementsByTagName('table');
//		for (var i=0;i<tables.length;i++)
//		{
//			if(tables[i].className=='ruler')
//			{
//				var trs=tables[i].getElementsByTagName('tr');
//				for(var j=0;j<trs.length;j++)
//				{
//					if(trs[j].parentNode.nodeName=='TBODY')
//					{
//						trs[j].onmouseover=function(){this.className='ruled';return false}
//						trs[j].onmouseout=function(){this.className='';return false}
//					}
//				}
//			}
//		}
//	}
//}

//function sortTable(col, tableToSort, ncol)
//  {
//    var iCurCell   = col;
//    var totalRows  = tableToSort.rows.length;
//    var colArray   = new Array();
//    var oldIndex01 = new Array();
//    var oldIndex02 = new Array();
//    var oldIndex03 = new Array();
//    var oldIndex04 = new Array();
//    var oldIndex05 = new Array();
//    var oldImage01 = new Array();
    
//    var i;
//    var k;

//    for (i=0; i < totalRows; i++)
//      {

//        if(i < 10) {

//           k = '00' + i;

//        }

//        if(i >= 10 && i < 99) {

//           k = '0' + i;

//        }

//        if(i >= 100 && i <999 ) {

//           k = i;

//        }

//        colArray  [i] = tableToSort.cells(iCurCell).innerText + k;
//        oldImage01[i] = document.figura[i].src;

//        if(col == 0) {

//           oldIndex01[i] = tableToSort.cells(iCurCell+1).innerText;

//           if(ncol > 4) {

//              oldIndex02[i] = tableToSort.cells(iCurCell+2).innerText;
 
//           }

//        }
//        else if(col == 1) {
//           oldIndex01[i] = tableToSort.cells(iCurCell-1).innerText;

//           if(ncol > 4) {

//              oldIndex02[i] = tableToSort.cells(iCurCell+1).innerText;

//           }

//        }
//        else if(col == 2) {
//           oldIndex01[i] = tableToSort.cells(iCurCell-2).innerText;
//           oldIndex02[i] = tableToSort.cells(iCurCell-1).innerText;
//        }
//        else if(col == 3) {
//           oldIndex01[i] = tableToSort.cells(iCurCell-3).innerText;
//           oldIndex02[i] = tableToSort.cells(iCurCell-2).innerText;
//           oldIndex03[i] = tableToSort.cells(iCurCell-1).innerText;
//        }
//        else if(col == 4) {
//           oldIndex01[i] = tableToSort.cells(iCurCell-4).innerText;
//           oldIndex02[i] = tableToSort.cells(iCurCell-3).innerText;
//           oldIndex03[i] = tableToSort.cells(iCurCell-2).innerText;
//           oldIndex04[i] = tableToSort.cells(iCurCell-1).innerText;
//        }
//        else if(col == 5) {
//           oldIndex01[i] = tableToSort.cells(iCurCell-5).innerText;
//           oldIndex02[i] = tableToSort.cells(iCurCell-4).innerText;
//           oldIndex03[i] = tableToSort.cells(iCurCell-3).innerText;
//           oldIndex04[i] = tableToSort.cells(iCurCell-2).innerText;
//           oldIndex05[i] = tableToSort.cells(iCurCell-1).innerText;
//        }
//        iCurCell    = iCurCell + tableToSort.cols;
//      }
//
//      colArray.sort();

//      for (i=0; i < totalRows; i++)
//        {
//          k = colArray[i].substr(colArray[i].length - 3, 3) * 1;
//          document.figura[i].src = oldImage01[k];
//          if(col == 0) {
//             tableToSort.rows(i).cells(col).innerHTML   = colArray[i].substr(0, colArray[i].length - 3);

//             if(ncol > 3) {

//                tableToSort.rows(i).cells(col+1).innerHTML = oldIndex01[k];

//             }

//             if(ncol > 4) {

//                tableToSort.rows(i).cells(col+2).innerHTML = oldIndex02[k];

//             }

//          }
//          else if(col == 1) {
//             tableToSort.rows(i).cells(col-1).innerHTML = oldIndex01[k];
//             tableToSort.rows(i).cells(col).innerHTML   = colArray[i].substr(0, colArray[i].length - 3);

//             if(ncol > 4) {

//                tableToSort.rows(i).cells(col+1).innerHTML = oldIndex02[k];
 
//             }
 
//          }
//          else if(col == 2) {
//             tableToSort.rows(i).cells(col-2).innerHTML = oldIndex01[k];
//             tableToSort.rows(i).cells(col-1).innerHTML = oldIndex02[k];
//             tableToSort.rows(i).cells(col).innerHTML   = colArray[i].substr(0, colArray[i].length - 3);
//          }
//          else if(col == 3) {
//             tableToSort.rows(i).cells(col-3).innerHTML = oldIndex01[k];
//             tableToSort.rows(i).cells(col-2).innerHTML = oldIndex02[k];
//             tableToSort.rows(i).cells(col-1).innerHTML = oldIndex03[k];
//             tableToSort.rows(i).cells(col).innerHTML   = colArray[i].substr(0, colArray[i].length - 3);
//          }
//          else if(col == 4) {
//             tableToSort.rows(i).cells(col-4).innerHTML = oldIndex01[k];
//             tableToSort.rows(i).cells(col-3).innerHTML = oldIndex02[k];
//             tableToSort.rows(i).cells(col-2).innerHTML = oldIndex03[k];
//             tableToSort.rows(i).cells(col-1).innerHTML = oldIndex04[k];
//             tableToSort.rows(i).cells(col).innerHTML   = colArray[i].substr(0, colArray[i].length - 3);
//          }
//          else if(col == 5) {
//             tableToSort.rows(i).cells(col-5).innerHTML = oldIndex01[k];
//             tableToSort.rows(i).cells(col-4).innerHTML = oldIndex02[k];
//             tableToSort.rows(i).cells(col-3).innerHTML = oldIndex03[k];
//             tableToSort.rows(i).cells(col-2).innerHTML = oldIndex04[k];
//             tableToSort.rows(i).cells(col-1).innerHTML = oldIndex05[k];
//             tableToSort.rows(i).cells(col).innerHTML   = colArray[i].substr(0, colArray[i].length - 3);
//          }
//        }
//      }


/********************************************************************
	FUN??O USADA PARA RETORNAR APENAS N?MERO INTEIROS
********************************************************************/
function Tecla(e){
	if (document.all) // Internet Explorer
		var tecla = e.keyCode;
	else if((document.layers) || (document.getElementById)) // Nestcape ou Mozilla
		var tecla = e.which;

	if (tecla != 8){
		return ((tecla > 47) && (tecla < 58)); // numeros de 0 a 9
	}else { // Outros caracteres...
		return true;
        }
}

/********************************************************************
	FUN??O USADA PARA - FORMATAR CAMPOS
********************************************************************/
function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all) 
	 // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	else if((document.layers) || (document.getElementById)) 
	 // Netscape ou Mozilla
		nTecla = evtKeyPress.which;
	
    if(nTecla==8) return true;
	sValue = objForm[strField].value;

	// Limpa todos os caracteres de formata??o que
	// j? estiverem no campo.
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( " ", "" );
	sValue = sValue.toString().replace( " ", "" );
	fldLen = sValue.length;
	mskLen = sMask.length;

	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;

	while (i <= mskLen) {
		bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

		if (bolMask) {
			sCod += sMask.charAt(i);
			mskLen++; }
		else {
			sCod += sValue.charAt(nCount);
			nCount++;
		}

		i++;
	}

        if (sCod != null && sCod != "") {
            objForm[strField].value = sCod;
        }

	if (nTecla != 8) { // backspace
		if (sMask.charAt(i-1) == "9") { // apenas n?meros...
			return ((nTecla > 47) && (nTecla < 58)); } // n?meros de 0 a 9
		else { // qualquer caracter...
			return true;
		}
	}
	else {
		return true;
	}
}

validadorCPF                = new Object;
validadorCPF.message        = '';
validadorCPF.getMessage     = function() { return this.message; }
validadorCPF.tiraMascara    = function(cpf) {cpf = cpf.replace (".","");cpf = cpf.replace (".","");cpf = cpf.replace ("-","");cpf.replace ("/","");return cpf;}
/**
* metodo para validar o CPF
*/
validadorCPF.validar = function( cpf ) {

    // Verifica se o campo tem menos de 11 digitos
    if (cpf == '') {
        this.message    = 'O CPF deve ser informado.';
        return false;
    }
    
    cpf = cpf.replace (".","");
    cpf = cpf.replace (".","");
    cpf = cpf.replace ("-","");

    // Verifica cpf fantasmas
    if (cpf == '00000000000' ||  cpf == '11111111111' ||
        cpf == '22222222222' ||  cpf == '33333333333' ||
        cpf == '44444444444' ||  cpf == '55555555555' ||
        cpf == '66666666666' ||  cpf == '77777777777' ||
        cpf == '88888888888' ||  cpf == '99999999999' ||
        cpf == '00000000190') {
        
        this.message    = 'CPF inválido.';
        return false;
   }
    // Aqui come?a a checagem do CPF
    var POSICAO, I, SOMA, DV, DV_INFORMADO;
    var DIGITO = new Array(10);
    
    DV_INFORMADO = cpf.substr(9, 2); // Retira os dois ?ltimos d?gitos do n?mero informado
    
    // Desmembra o n?mero do CPF na array DIGITO
    for (I=0; I<=8; I++) {
        DIGITO[I] = cpf.substr( I, 1);
    }

    // Calcula o valor do 10? d?gito da verifica??o
    POSICAO = 10;
    SOMA = 0;
    for (I=0; I<=8; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[9] = SOMA % 11;
    if (DIGITO[9] < 2) {
        DIGITO[9] = 0;
    }
    else{
        DIGITO[9] = 11 - DIGITO[9];
    }

    // Calcula o valor do 11? d?gito da verifica??o
    POSICAO = 11;
    SOMA = 0;
    for (I=0; I<=9; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[10] = SOMA % 11;
    if (DIGITO[10] < 2) {
        DIGITO[10] = 0;
    }
    else {
        DIGITO[10] = 11 - DIGITO[10];
    }

    // Verifica se os valores dos d?gitos verificadores conferem
    DV = DIGITO[9] * 10 + DIGITO[10];
    if (DV != DV_INFORMADO) {
        this.message    = 'Dígito do CPF inválido.';
        return false;
    } 

    return true;
}

/********************************************************************
	FUN??O USADA PARA VERIFICAR O CPF DIGITADO
********************************************************************/
function Verifica_CPF(obj) {
var CPF = obj.value; // Recebe o valor digitado no campo
// Verifica se o campo tem menos de 11 digitos
if (CPF == '') {
  alert('O CPF deve ser informado!');
  obj.focus();
  return false;
   }

//if (CPF.length != 14) {
  //alert('O N?mero do CPF est? incompleto!');
  //obj.focus();
  //return false;
   //}

CPF = CPF.replace (".","");
CPF = CPF.replace (".","");
CPF = CPF.replace ("-","");

// Verifica cpf fantasmas
if (CPF == '00000000000' ||
    CPF == '11111111111' ||
    CPF == '22222222222' ||
    CPF == '33333333333' ||
    CPF == '44444444444' ||
    CPF == '55555555555' ||
    CPF == '66666666666' ||
    CPF == '77777777777' ||
    CPF == '88888888888' ||
    CPF == '99999999999' ||
    CPF == '00000000190' 
	) {
  		alert('CPF inválido!!');
  		obj.focus();
  		return false;
   }

// Aqui come?a a checagem do CPF
var POSICAO, I, SOMA, DV, DV_INFORMADO;
var DIGITO = new Array(10);
DV_INFORMADO = CPF.substr(9, 2); // Retira os dois ?ltimos d?gitos do n?mero informado

// Desmembra o n?mero do CPF na array DIGITO
for (I=0; I<=8; I++) {
  DIGITO[I] = CPF.substr( I, 1);
}

// Calcula o valor do 10? d?gito da verifica??o
POSICAO = 10;
SOMA = 0;
   for (I=0; I<=8; I++) {
      SOMA = SOMA + DIGITO[I] * POSICAO;
      POSICAO = POSICAO - 1;
   }
DIGITO[9] = SOMA % 11;
   if (DIGITO[9] < 2) {
        DIGITO[9] = 0;
}
   else{
       DIGITO[9] = 11 - DIGITO[9];
}

// Calcula o valor do 11? d?gito da verifica??o
POSICAO = 11;
SOMA = 0;
   for (I=0; I<=9; I++) {
      SOMA = SOMA + DIGITO[I] * POSICAO;
      POSICAO = POSICAO - 1;
   }
DIGITO[10] = SOMA % 11;
   if (DIGITO[10] < 2) {
        DIGITO[10] = 0;
   }
   else {
        DIGITO[10] = 11 - DIGITO[10];
   }

// Verifica se os valores dos d?gitos verificadores conferem
DV = DIGITO[9] * 10 + DIGITO[10];
   if (DV != DV_INFORMADO) {
      //alert('CPF inv?lido!!');
      obj.focus();
      obj.value = '';
      return false;
   } 
}


/*
 * @Author: Raphael Adrien
 * @Date:   19 de abril de 2006
 * Verifica se o cnpj e valido e retorna a mensagem.
 *
 */
validadorCNPJ               = new Object;
validadorCNPJ.message       = '';
validadorCNPJ.getMessage     = function() { return this.message; }
validadorCNPJ.tiraMascara    = function() {cpf = cpf.replace (".","");cpf = cpf.replace (".","");cpf = cpf.replace ("-","");cpf.replace ("/","");return cpf;}
validadorCNPJ.validar = function( CNPJ ) {
	this.message = new String;
	if (CNPJ.length < 18) this.message = "É necessario preencher corretamente o número do CNPJ! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (this.message.length == 0) this.message = "É necessário preencher corretamente o número do CNPJ! \n\n";
	}
	
	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4){
       x = CNPJ.substring(0,2);
       x += CNPJ. substring (3,6);
       x += CNPJ. substring (7,10);
       x += CNPJ. substring (11,15);
       x += CNPJ. substring (16,18);
       CNPJ = x;
	} else {
       CNPJ = CNPJ. replace (".","");
       CNPJ = CNPJ. replace (".","");
       CNPJ = CNPJ. replace ("-","");
       CNPJ = CNPJ. replace ("/","");
	}

   var nonNumbers = /\D/;
   if (nonNumbers.test(CNPJ)) this.message = "A verificação de CNPJ suporta apenas números! \n\n";
   var a = [];
   var b = new Number;
   var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];

  	for (i=0; i<12; i++){
	    a[i] = CNPJ.charAt(i);
   		b += a[i] * c[i+1];
	}

	if ((x = b % 11) < 2) { 
		a[12] = 0 
	} 
	else { 
		a[12] = 11-x 
	}
	
    b = 0;
    for (y=0; y<13; y++) {
           b += (a[y] * c[y]);
    }
   
    if ((x = b % 11) < 2) { 
    	a[13] = 0; 
    } 
    else { 
    	a[13] = 11-x; 
   	}

   if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
           this.message ="É necessário preencher corretamente o número do CNPJ!";
   }

   if (this.message.length > 0){
           return false;
   } 
   
   
   return true;

}

/********************************************************************
	FUN??O USADA PARA VERIFICAR O CNPJ DIGITADO
********************************************************************/
function validaCNPJ(strCNPJ) {
	 var CNPJ = strCNPJ.value;

     if (CNPJ == '') {
	   return;
	 }

	 erro = new String;
	 if (CNPJ.length =! 18) {
		alert("É necessario preencher corretamente o número do CNPJ!");
		strCNPJ.value = '';
                strCNPJ.focus(); 
                return false;
	 }
	 
	 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		 if (erro.length == 0) {
			 alert("É necessario preencher corretamente o número do CNPJ!");
                	 strCNPJ.value = '';
        		 strCNPJ.focus(); 
                         return false;
		 }
	 }
	 //substituir os caracteres que n?o s?o n?meros
	 if(document.layers && parseInt(navigator.appVersion) == 4){
		   x = CNPJ.substring(0,2);
		   x += CNPJ. substring (3,6);
		   x += CNPJ. substring (7,10);
		   x += CNPJ. substring (11,15);
		   x += CNPJ. substring (16,18);
		   CNPJ = x; 
     } else {
		   CNPJ = CNPJ.replace (".","");
		   CNPJ = CNPJ.replace (".","");
		   CNPJ = CNPJ.replace ("-","");
		   CNPJ = CNPJ.replace ("/","");
     }
     var nonNumbers = /\D/;
     if (nonNumbers.test(CNPJ)) {
		 alert("A verificação de CNPJ suporta apenas números!");
		 strCNPJ.value = '';
		 strCNPJ.focus(); 
                 return false;
	 }
     var a = [];
     var b = new Number;
     var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
     for (i=0; i<12; i++){
		   a[i] = CNPJ.charAt(i);
		   b += a[i] * c[i+1];
     }
     if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
     b = 0;
     for (y=0; y<13; y++) {
		   b += (a[y] * c[y]); 
     }
     if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
     if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                  alert("CNPJ inválido!");
		  strCNPJ.value = '';
		  strCNPJ.focus(); 
                  return false;
     }

     return true;
}

/********************************************************************
	FUN??O USADA PARA RETORNAR CAMPOS DIGITADOS NUMEROS E DATAS
********************************************************************/
function formata(objCampo,intTipo,intTamanho){ 
	//objCampo   = campo a ser formatado 
	//intTipo = 2 -> n?mero; intTipo = 3 -> data; 
	//intTamanho = Quantidade de caracteres que o campo poder? aceitar 
	 
	//verifica tecla pressionada 
	var str=objCampo.value 
	 
	//Tamanho m?ximo permitido 
	if (str.length>intTamanho-1){ 
		return false 
	} 
	 
	//Verifica o intTipo para barrar caracteres inv?lidos 
	switch (intTipo) 
	{ 
		
		case 2: //n?meros 
			if (window.event.keyCode>=48 && window.event.keyCode<=57){ 
				return true 
			} 
		case 3: //Data 
			if (window.event.keyCode<48 || window.event.keyCode>57){ 
				return false 
			} 
			if (str.length==2){ 
				objCampo.value = objCampo.value + '/' 
				return true 
			} 
			if (str.length==5){ 
				objCampo.value = objCampo.value + '/' 
				return true 
			} 
			return true 
		default: 
			return false 
	} 
 
	return false 
} 
	 
/*
 * @Author: Raphael Adrien
 * @Date:   19 de abril de 2006
 * Verifica se o cnpj e valido e retorna a mensagem.
 *
 */
validadorEMAIL               = new Object;
validadorEMAIL.message       = '';
validadorEMAIL.getMessage     = function() { return this.message; }

validadorEMAIL.validar = function( email ) {

        if (email == ""){
            return false;
	}
	else if (email.indexOf("@") == -1 ||
			email.indexOf("@.") != -1 ||
			email.indexOf(" ") != -1 ||
			email.indexOf("'") != -1 ||
			email.indexOf("\"") != -1 ||
			email.indexOf(";") != -1 ||
			email.indexOf(",") != -1 ||
			email.indexOf("{") != -1 ||
			email.indexOf("}") != -1 ||
			email.indexOf("[") != -1 ||
			email.indexOf("]") != -1 ||
			email.indexOf(">") != -1 ||
			email.indexOf("<") != -1 ||
			email.indexOf("|") != -1 ||
			email.indexOf("?") != -1 ||
			email.length < 10 ){
			this.message = "Informe o e-mail corretamente.";
			return false;
	}
	return true;
}






/********************************************************************
	FUN??O USADA PARA VALIDAR UM E-MAIL DIGITADO.
********************************************************************/
function verificaEmail(obj) {
var sValue;
sValue = obj.value;

if (sValue == "") { return ; }

if (sValue.indexOf("@") == -1 ||
			sValue.indexOf("@.") != -1 ||
			sValue.indexOf(" ") != -1 ||
			sValue.indexOf("'") != -1 ||
			sValue.indexOf("\"") != -1 ||
			sValue.indexOf(";") != -1 ||
			sValue.indexOf(",") != -1 ||
			sValue.indexOf("{") != -1 ||
			sValue.indexOf("}") != -1 ||
			sValue.indexOf("[") != -1 ||
			sValue.indexOf("]") != -1 ||
			sValue.indexOf(">") != -1 ||
			sValue.indexOf("<") != -1 ||
			sValue.indexOf("|") != -1 ||
			sValue.indexOf("?") != -1 ||
			sValue.length < 10 ){
			alert("Informe corretamente o e-mail!");
			obj.focus();
	}
	
	obj.value = obj.value.toLowerCase(); 
}

/********************************************************************
	FUN??O USADA PARA MINIMIZAR UMA STRING DIGITADA.
********************************************************************/
function minuscula(frmObj) {
	frmObj.value = frmObj.value.toLowerCase();
}

/********************************************************************
	FUN??O USADA PARA MAXIMIZAR UMA STRING DIGITADA.
********************************************************************/
 function maiuscula(frmObj) {
	frmObj.value = frmObj.value.toUpperCase();
}

/********************************************************************
	FUN??O USADA PARA FAZER UMA SAUDA??O AO USUARIO. DATA COMPLETA
********************************************************************/
function saudacao(){

	var dataHora, xHora, xDia, dia, mes, ano, txtSaudacao, dataAtual;
	dataHora = new Date();
	xHora = dataHora.getHours();
	
	if (xHora >= 0 && xHora < 12) {txtSaudacao = "Bom Dia!"}
	if (xHora >= 12 && xHora < 18) {txtSaudacao = "Boa Tarde!"}
	if (xHora >= 18 && xHora < 23) {txtSaudacao = "Boa Noite!"}
	
	xDia = dataHora.getDay();
	diaSemana = new Array(7);
	diaSemana[0] = "Domingo";
	diaSemana[1] = "Segunda-feira";
	diaSemana[2] = "Terça-feira";
	diaSemana[3] = "Quarta-feira";
	diaSemana[4] = "Quinta-feira";
	diaSemana[5] = "Sexta-feira";
	diaSemana[6] = "Sábado";
	dia = dataHora.getDate();
	mes = dataHora.getMonth();
	mesDoAno = Array(12);
	mesDoAno[0] = "janeiro";
	mesDoAno[1] = "fevereiro";
	mesDoAno[2] = "março";
	mesDoAno[3] = "abril";
	mesDoAno[4] = "maio";
	mesDoAno[5] = "junho";
	mesDoAno[6] = "julho";
	mesDoAno[7] = "agosto";
	mesDoAno[8] = "setembro";
	mesDoAno[9] = "outubro";
	mesDoAno[10] = "novembro";
	mesDoAno[11] = "dezembro";
	ano = dataHora.getFullYear();
	dataAtual = txtSaudacao + " " + diaSemana[xDia] + ", " + dia + " de " + mesDoAno[mes] + " de " + ano;
	document.write(dataAtual);
}

/********************************************************************
	FUN??O USADA PARA FAZER UMA SAUDA??O AO USUARIO. DATA RESUMIDA
********************************************************************/
function dataResumida(){

	var dataHora, dia, mes, ano, dataAtual;
	dataHora = new Date();
	
	dia = dataHora.getDate();
	if (dia < 10){dia = "0"+dia;} 
	mes = dataHora.getMonth() + 1;
	if (mes < 10){mes = "0"+mes;}
	ano = dataHora.getFullYear();
	dataAtual = dia + "/" + mes + "/" + ano;
	document.write(dataAtual);
}

/********************************************************************
	FUN??O USADA PARA INSERIR UM CURSO NA LISTA.
********************************************************************/
function moveOver(cboOri1, cboOri2, listDes1, listDes2)  
{
	var isNew = true;
	var boxLength = listDes1.length;
	var selectedItem = cboOri1.selectedIndex;
	if (selectedItem == -1){
		alert('O Curso deve ser Selecionado!');
		isNew = false;
	}else{
		var selectedText = cboOri1.options[selectedItem].text;
		var selectedValue = cboOri1.options[selectedItem].value;
	}

	var selectedItemNivel = cboOri2.selectedIndex;
	var selectedTextNivel = cboOri2.options[selectedItemNivel].text;
	var selectedValueNivel = cboOri2.options[selectedItemNivel].value;
	var i;
	if (boxLength != 0) {
		for (i = 0; i < boxLength; i++) {
			thisitem = listDes1.options[i].text;
			thisitemNivel = listDes2.options[i].text;
			if ((thisitem == selectedText) && (thisitemNivel == selectedTextNivel)) {
				alert('Curso ' + thisitem + ' Nível ' + thisitemNivel + ' já foi selecionado.');
				isNew = false;
				break;
			}
	   }
	} 
	if (isNew) {
		newoption = new Option(selectedText, selectedValue, false, false);
		newnivel =  new Option(selectedTextNivel, selectedValueNivel, false, false);
		listDes1.options[boxLength] = newoption;
		listDes2.options[boxLength] = newnivel;
	}
		cboOri1.selectedIndex=-1;
		cboOri2.selectedIndex=-1;
}

/********************************************************************
	FUN??O USADA PARA REMOVER UM CURSO NA LISTA.
********************************************************************/
function removeMe(listDes1, listDes2) {
	var boxLength = listDes1.length;
	question = confirm("Deseja realmente excluir este item?");
	if (question != "0"){
		for (i = 0; i < boxLength; i++) {
			if (listDes1.options[i].selected) {
				listDes1.options[i] = null;
				listDes2.options[i] = null;
				break;				
		   }	
		}
	}
}

/********************************************************************
	FUN??O USADA PARA INSERIR ITENS DE UMA LISTA EM OUTRA
********************************************************************/
function moveCurso(cboOri1, listDes1)  
{
	var isNew = true;
	var boxLength = listDes1.length;
	var selectedItem = cboOri1.selectedIndex;
	if (selectedItem == -1){
		alert('Um item deve ser Selecionado!');
		isNew = false;
	}else{
		var selectedText = cboOri1.options[selectedItem].text;
		var selectedValue = cboOri1.options[selectedItem].value;
	}

	var i;
	if (boxLength != 0) {
		for (i = 0; i < boxLength; i++) {
			thisitem = listDes1.options[i].text;
			if (thisitem == selectedText) {
				alert('O item ' + thisitem + ' já foi selecionado.');
				isNew = false;
				break;
			}
	   }
	} 
	if (isNew) {
		newoption = new Option(selectedText, selectedValue, false, false);
		listDes1.options[boxLength] = newoption;
	}
		cboOri1.selectedIndex=-1;
}



/********************************************************************
	FUN??O USADA PARA REMOVER UM ITEM DE UMA LISTA
********************************************************************/
function removeCurso(listDes1) {
	var boxLength = listDes1.length;
	question = confirm("Deseja realmente excluir este item?");
	if (question != "0"){
		for (i = 0; i < boxLength; i++) {
			if (listDes1.options[i].selected) {
				listDes1.options[i] = null;
				break;				
		   }	
		}
	}
}


/*
 * Remover itens selecionados, da lista passada como parametro
 * Autor: DivC?sar Soares
 */
function removeItens(lista) {

    /* N?o podemos usar direto length, por que ela vai sendo diminuida a medida que setamos os itens para null */
    i = lista.length-1;

    if (lista.selectedIndex >= 0) {
        for (; i >= 0; i-- ) {
            if (lista.options[i].selected) {
                if (confirm("Deseja realmente \"" + lista.options[i].text + "\" da lista?")) {
                    lista.options[i] = null;
                }
            }
        }
    }
}


/*
 * Move somente os itens selecionados de uma lista, para outra.
 * Autor: DivC?sar Soares
 */
function moveItens(cboOri1, listDes1) { 

    for (i = 0; i < cboOri1.length; i++) {

        if (cboOri1.options[i].selected) {
            var isNew = true;
            var boxLength = listDes1.length;

            if (i == -1){
                    alert('Um item deve ser Selecionado!');
                    isNew = false;
            }
            else{
                    var selectedText = cboOri1.options[i].text;
                    var selectedValue = cboOri1.options[i].value;
            }

            var i2;
            if (boxLength != 0) {
                    for (i2 = 0; i2 < boxLength; i2++) {
                            thisitem = listDes1.options[i2].text;
                            if (thisitem == selectedText) {
                                    isNew = false;
                                    break;
                            }
               }
            } 
            if (isNew) {
                    newoption = new Option(selectedText, selectedValue, false, false);
                    listDes1.options[boxLength] = newoption;
            }

            cboOri1.options[i].selected = false;
        }
    }                
}

/********************************************************************
	FUN??O USADA PARA REMOVER UMA ATIVIDADE NA LISTA.
********************************************************************/
function removeAtividade(listDes1) {
	var boxLength = listDes1.length;
	question = confirm("Deseja realmente excluir a Atividade?");
	if (question != "0"){
		for (i = 0; i < boxLength; i++) {
			if (listDes1.options[i].selected) {
				listDes1.options[i] = null;
				break;
		   }	
		}
	}
}

/********************************************************************
	FUN??O USADA PARA MOSTRAR OS CURSOS NA LISTA.
********************************************************************/
function saveMe(listDes1, listDes2) {
	var strValues = "";
	var strValuesNivel = "";
	var boxLength = listDes1.length;
	var count = 0;
	if (boxLength != 0) {
		for (i = 0; i < boxLength; i++) {
			if (count == 0) {
				strValues = listDes1.options[i].value;
				strValuesNivel = listDes2.options[i].value;
			}
			else {
				strValues = strValues + "," + listDes1.options[i].value;
				strValuesNivel = strValuesNivel + "," + listDes2.options[i].value;
			}	
			count++;
	   }
	}
	if (strValues.length == 0) {
		alert("Você deve selecionar algum curso.");
	}
	else {
		alert("Código dos itens selecionados:\r\n" + strValues);
	   }
}

/********************************************************************
	FUN??O USADA PARA INSERIR UM CURSO DIGITADO PELO USUARIO.
********************************************************************/
function inserirCurso(cboOri1, cboOri2, listDes1, listDes2)  
{
	var isNew = true;
	var boxLength = listDes1.length;
	var selectedItem = cboOri1.value;
	if (selectedItem == ''){
		alert('O Curso deve ser Informado!');
		isNew = false;
	}else{
		var selectedText = selectedItem;
		var selectedValue = 1;
	}

	var selectedItemNivel = cboOri2.selectedIndex;
	var selectedTextNivel = cboOri2.options[selectedItemNivel].text;
	var selectedValueNivel = cboOri2.options[selectedItemNivel].value;
	var i;
	if (boxLength != 0) {
		for (i = 0; i < boxLength; i++) {
			thisitem = listDes1.options[i].text;
			thisitemNivel = listDes2.options[i].text;
			if ((thisitem == selectedText) && (thisitemNivel == selectedTextNivel)) {
				alert('Curso ' + thisitem + ' Nível ' + thisitemNivel + ' já foi selecionado.');
                            isNew = false;
				break;
			}
	   }
	} 
	if (isNew) {
		newoption = new Option(selectedText, selectedValue, false, false);
		newnivel =  new Option(selectedTextNivel, selectedValueNivel, false, false);
		listDes1.options[boxLength] = newoption;
		listDes2.options[boxLength] = newnivel;
	}
		cboOri1.value = '';
		cboOri2.selectedIndex=-1;
		cboOri1.focus();
}

/********************************************************************
	FUN??O USADA PARA INSERIR UMA ATIVIDADE DIGITADA PELO USUARIO.
********************************************************************/
function inserirAtividade(cboOri1, listDes1)  
{
	var isNew = true;
	var boxLength = listDes1.length;
	var selectedItem = cboOri1.value;
	if (selectedItem == ''){
		alert('Um item deve ser Informado!');
		isNew = false;
	}else{
		var selectedText = selectedItem;
		var selectedValue = 1;
	}

	var i;
	if (boxLength != 0) {
		for (i = 0; i < boxLength; i++) {
			thisitem = listDes1.options[i].text;
			if (thisitem == selectedText) {
				alert('O item ' + thisitem  + ' já foi selecionado.');
				isNew = false;
				break;
			}
	   }
	} 
	if (isNew) {
		newoption = new Option(selectedText, selectedValue, false, false);
		listDes1.options[boxLength] = newoption;
	}
		cboOri1.value = '';
		cboOri1.focus();
}

/********************************************************************
	FUN??O USADA PARA INSERIR UM IDIOMA SELECIONADO E O SEU NIVEL.
********************************************************************/
function inserirIdioma(cboOri1, listDes1)  
{
	var isNew = true;
	var boxLength = listDes1.length;
	var selectedItem = cboOri1.selectedIndex;
	if (selectedItem == -1){
		alert('Um item deve ser Selecionado!');
		isNew = false;
	}else{
		var selectedText = cboOri1.options[selectedItem].text;
		var selectedValue = cboOri1.options[selectedItem].value;
	}

	var i;
	if (boxLength != 0) {
		for (i = 0; i < boxLength; i++) {
			thisitem = listDes1.options[i].text;
			if (thisitem == selectedText) {
				alert('O item ' + thisitem + ' já foi selecionado.');
				isNew = false;
				break;
			}
	   }
	} 
	if (isNew) {
		newoption = new Option(selectedText, selectedValue, false, false);
		listDes1.options[boxLength] = newoption;
	}
		cboOri1.selectedIndex=-1;
}


/********************************************************************
	FUN??O USADA PARA INSERIR OP??ES DE UMA LISTA EM OUTRA
********************************************************************/
function curso1add(m1 , m2){
	var m1len 	= m1.length;
	var i 		= 0;
	var m2len 	= m2.length;	
	if (m1.selectedIndex >= 0) { i = m1.selectedIndex; } else { return false; }
			 
	for(d=0; d<m2len; d++) { 
		if (m2.options[d].value == m1.options[i].value) {
			alert("O item (" + m1.options[i].text + ") já foi adicionado.");
			return false;
		}
	}

	m2.options[m2len] = new Option(m1.options[i].text, m1.options[i].value, false, false);	// insere o item na ?ltima posi??o
	m1.options[i] = null;

	// verifica se o auxilio transporte está adicionado
	m2len 	= m2.length;

	for(x=0; x<m2len; x++) { 
		if (m2.options[x].value == '18' ) {
			document.getElementById('fieldAuxilioTransporte').style.display	= '';
			document.getElementById('valorAuxilioTransporte').style.display	= '';
		}
	}
}

/********************************************************************
	FUN??O USADA PARA EXCLUIR UM CURSO
********************************************************************/
function curso1retirar(m1 , m2){
	var m2len = m2.length;
	var i	  = 0;
    var m1len = m1.length;
    if (m2.selectedIndex >= 0) { i = m2.selectedIndex; } else { return false; }

	for(d=0; d<m1len; d++) { 
		if (m1.options[d].value == m2.options[i].value) {
			m2.options[i] = null;
			return false;
		}
	}
	if(m2.options[i].value != 18 || document.getElementById('estagioObrigatorio').value == 'S'  ){
		m1.options[m1len] = new Option(m2.options[i].text, m2.options[i].value, false, false);

		if(m2.options[i].value == 18){
			document.getElementById('fieldAuxilioTransporte').style.display	= 'none';
			document.getElementById('valorAuxilioTransporte').style.display	= 'none';
		}

		m2.options[i] = null;
	}
}

/********************************************************************
	FUN??O USADA PARA ABRIR JANELAS
********************************************************************/

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

/********************************************************************
	FUN??O USADA PARA ABRIR JANELA DE CANCELAMENTO DE CADASTRO
********************************************************************/

function abrirJanelaCancelar(theURL,winName,features,abrirJanela) { //v2.0
	if (abrirJanela == 1){
		window.open(theURL,winName,features);
	}
}

/********************************************************************
	FUN??O USADA PARA ABRIR O HELP
********************************************************************/

function abreHelp(campo){
      	campo.style.visibility = 'visible';
} 

/********************************************************************
	FUN??O USADA PARA FECHAR O HELP
********************************************************************/
        
function fechaHelp(campo){
    campo.style.visibility = 'hidden';
}



/********************************************************************
	FUN??O USADA PARA ADICIONAR ZERO AO NUMERO DO DDD
********************************************************************/
function adicionaZero(obj){
    var sValue;
    sValue = obj.value;

    if (sValue != "" && sValue != null && sValue != " " && sValue != "0"){
            if (sValue.length < 2)
                    sValue = "00"+sValue;
            else if (sValue.length < 3)
                    sValue = "0"+sValue;
            else if(sValue.length < 1)
                    sValue = "0"+sValue;
    }else{
        sValue = "";
    }
    obj.value = sValue;
}



/**********************************************
 * Autor:           Divino C?sar S. L
 * Descri??o:       Mostra ou esconde o div de instru??es para preenchimento de um campo
 * Data:            20-03-2006
 **********************************************/
function displayHelp(objeto, etype) {

    /** Captura o objeto div que ira mostrar a mensagem */
    oDiv    = objeto.parentNode;

    /* Mostrar ou esconder o texto */
    if (oDiv) {    

        if (etype == 'focus') {
            span                 = document.createElement('span');
            span.id              = 'span_' + objeto.name;
            span.className       = 'span_help';
            span.innerHTML       = objeto.title;           

            oDiv.appendChild( span );
        }
        else {
            span                 = document.getElementById( 'span_' + objeto.name );
            oDiv.removeChild( span );
        }
    }

}


function setHelpsForms(formulario) {

    with (formulario) {
        for (i=0; i<elements.length; i++) {
            var element = elements[i];

            if (element.title != null && element.title != undefined) {
            
	            YAHOO.util.Event.addListener(element, "focus", displayHelp);  
				YAHOO.util.Event.addListener(element, "blur", displayHelp);  

            }
        }
    }

}






/*###########################################################
# Autor     : Fabricio Camargo Faria
# Descri??o : M?todo para limpar o formul?rio
###########################################################*/
function limparForm(form) {
    for( i = 0; form.elements.length; i++ ) {
        element     = form.elements[i];
        if(element.type != "submit" && element.type != "button") {
            element.value   = '';
        }
    }
}

/********************************************************
* Autor     : Fabricio Camargo Faria
* Descri??o : M?todo para adicionar zero(s) nos ddd's
* Modo usar : dever ser adicionado ao evento onblur 
*             do input. Ex: onBlur="maskDdd(this);"
********************************************************/
function maskDdd(element) {
    if(element.value.length==0)
        element.value   = '';
    else if(element.value.length==1)
        element.value   = '00' + element.value;
    else if(element.value.length==2)
        element.value   = '0' + element.value;
}

/********************************************************
* Autor     : Fabricio Camargo Faria
* Descri??o : Encontra a Posi??o X do elemento
* Modo usar : Passa o elemento html
********************************************************/
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}
/********************************************************
* Autor     : Fabricio Camargo Faria
* Descri??o : Encontra a Posi??o Y do elemento
* Modo usar : Passa o elemento html
********************************************************/

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/********************************************************
* Autor     : Fabricio Camargo Faria
* Descri??o : Mostra mensagem alterando todos os br para \n
* Modo usar : passa o texto que ser? mostrado
********************************************************/
function showMessage(text) {
    msg = replaceAll(text, "&lt;br/&gt;", "\n");
    alert(msg);
}

/**
 * @param strChk      String to be cleaned
 * @param strFind     String to replace
 * @param strReplace  String to insert
 * @return            String without unwanted characters/strings
 */
function replaceAll(strChk, strFind, strReplace) {
  var strOut = strChk;
  while (strOut.indexOf(strFind) > -1) {
    strOut = strOut.replace(strFind, strReplace);
  }
  return strOut;
}

/********************************************************
* Autor     : Vinicius R. do Amaral
* Descri??o : Formato moeda
* Modo usar : onKeydown="Formata(this,20,event,2)"
********************************************************/
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; 
} 

//Formata n?mero tipo moeda usando o evento onKeyDown 
function FormataMoeda(campo,tammax,teclapres,decimal) { 
var tecla = teclapres.keyCode; 
vr = Limpar(campo.value,"0123456789"); 
tam = vr.length; 
dec=decimal 

    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 <= dec ) 
        { campo.value = vr ; } 

        if ( (tam > dec) && (tam <= 5) ){ 
        campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; } 
        if ( (tam >= 6) && (tam <= 8) ){ 
        campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, 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 - dec, 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 - dec, 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 ) ;} 
    } 
    else {
        return false;
    }
}

/****************************************************
* Autor : Fabricio Camargo Faria
* Data  : 09/05/2006
*
* fun??o para restringir a quantidade de op??es marcadas
* dentro de um select multiple
* Parametro
*   select: Element select
*   max: n?mero m?ximo de itens seleciodados
****************************************************/
function maxSelected( select, max ) {    
    selected    = 0;
    for( i = 0; i < select.options.length; i++ ) {
        if( select.options.item( i ).selected ) {
            selected++;

            if( max < selected ) 
                select.options.item( i ).selected = false;
        }
    }
}

/**************************************
* Autor : Fabricio Camargo Faria
* Data  : 15/05/2006
*
* fun??o para habilitar ou desabilitar o readonly de formul?rios ou
* inputs
***************************************/
function ReadOnly( object, readonly ) {
    if( object.tagName == 'FORM' ) this.readonly_form( object, readonly );
    else if( object.tagName == 'INPUT' ) this.readonly_element( object, readonly );
}

ReadOnly.prototype.readonly_element = function( object, readonly ) {
    if( object.type == 'radio' )
        object.disabled = readonly;
    else
        object.readOnly = readonly;
}

ReadOnly.prototype.readonly_form = function( object, readonly ) {
    for( i = 0; i < object.elements.length; i++ )
        this.readonly_element( object.elements.item(i), readonly );
}

/**************************************
* Autor : Vin?cius R. do Amaral
* Data  : 24/07/2006
*
* Fun??o para formatar a data do dia 
***************************************/
function WriteDate(){
        hoje = new Date()
        dia = hoje.getDate()
        dias = hoje.getDay()
        mes = hoje.getMonth()
        ano = hoje.getYear()
        if (ano < 2000)
                ano = 1900 + ano
        function CriaArray (n) {
        this.length = n }
        NomeDia = new CriaArray(7)
        NomeDia[0] = "Domingo"
        NomeDia[1] = "Segunda"
        NomeDia[2] = "Terça"
        NomeDia[3] = "Quarta"
        NomeDia[4] = "Quinta"
        NomeDia[5] = "Sexta"
        NomeDia[6] = "Sábado"
        NomeMes = new CriaArray(12)
        NomeMes[0] = "janeiro"
        NomeMes[1] = "fevereiro"
        NomeMes[2] = "mar?o"
        NomeMes[3] = "abril"
        NomeMes[4] = "maio"
        NomeMes[5] = "junho"
        NomeMes[6] = "julho"
        NomeMes[7] = "agosto"
        NomeMes[8] = "setembro"
        NomeMes[9] = "outubro"
        NomeMes[10] = "novembro"
        NomeMes[11] = "dezembro"

	document.write (NomeDia[dias]+", " + dia + " de " + NomeMes[mes] + " de "  + ano)
}

/**
 * Fun??o criada para setar os valores obtidos pelo cpf do usuario.
 * @author Divino Cesar
 * @author Raphael Adrien
 * @param  form
 * @param  Object rDados - Objeto de pessoa
 */
 function setaValores( form, retData){
 	 var dia = '';
 	 var mes = '';
 	 var ano = '';
 	 
	 if (retData != null && (retData instanceof Object)) {
		 // Bloqueia todos os campos que a pessoa n?o pode alterar
		 statusFormPessoa(true, form);
		
		form.idPessoa.value 		= retData.pessoa.idPessoa;
		form.nome.value 			= retData.pessoa.nome;

		if( retData.pessoa.dataNascimento != null ){
			dia	= retData.pessoa.dataNascimento.getDate();
			mes = retData.pessoa.dataNascimento.getMonth()+1;
			ano = retData.pessoa.dataNascimento.getFullYear();
	
			if ( dia < 10 ){
				dia	= '0'+dia;
			}
	
			if (mes < 10){
				mes = '0'+mes;
			}		
	
			form.dataNascimento.value	= dia+"/"+mes+"/"+ano;
		}

		//form.dataNascimento.value	= retData.pessoa.dataNascimento.getDate() + "/" 
		//												+ (retData.pessoa.dataNascimento.getMonth()+1) + "/"
		//												+ retData.pessoa.dataNascimento.getFullYear();


		selectRadioItem(form.sexo, retData.pessoa.sexo);
		
		if (retData.pessoa.residencial != null){
			form.ddd1.value			= retData.pessoa.residencial.ddd;
			if (form.fone1){
				form.fone1.value		= retData.pessoa.residencial.telefone;
			} else {
				form.fone1.value		= retData.pessoa.residencial.telefone;
			}
		}

		if (retData.pessoa.comercial != null) {
			form.ddd2.value			= retData.pessoa.comercial.ddd;
			if (form.fone2){
				form.fone2.value		= retData.pessoa.comercial.telefone;
			} else {
				form.fone2.value		= retData.pessoa.comercial.telefone;
			}
		}

		if (retData.pessoa.celular != null) {	
			form.ddd3.value			= retData.pessoa.celular.ddd;
			if (form.fone3){
				form.fone3.value		= retData.pessoa.celular.telefone;
			} else {
				form.fone3.value		= retData.pessoa.celular.telefone;
			}
		}

		if(retData.email != null ){
			form.email.value			= retData.email;
		}

		//Verifica se o form contem os campos de endere?o
		if( form.idEndereco != null ){
			//Verifica se o objeto contem o endere?o da pessoa
			if (retData.pessoa.enderecos != null && retData.pessoa.enderecos[0] != null) {
				form.idEndereco.value	= retData.pessoa.enderecos[0].idEndereco;
				form.status.value		= retData.pessoa.enderecos[0].status;
				form.cep.value			= retData.pessoa.enderecos[0].cep;
				form.uf.value			= retData.pessoa.enderecos[0].uf;
				form.cidade.value		= retData.pessoa.enderecos[0].cidade;
				form.bairro.value		= retData.pessoa.enderecos[0].bairro;
				form.logradouro.value	= retData.pessoa.enderecos[0].logradouro;
				form.complemento.value	= retData.pessoa.enderecos[0].complemento;
			}
		}
	}
	else {
			
			statusFormPessoa(false, form);

			form.idPessoa.value 		= "0";
			form.nome.value 			= "";
			form.dataNascimento.value	= "";
			selectRadioItem(form.sexo, "M");
			form.ddd1.value			= "";
			if (form.fone1){
				form.fone1.value		= "";
			} else {
				form.fone1.value		= "";
			}
			form.ddd2.value			= "";
			if (form.fone2){
				form.fone2.value		= "";
			} else {
				form.fone2.value = '';
			}
			form.ddd3.value			= "";
			if (form.fone3){
				form.fone3.value		= "";
			} else {
				form.fone3.value		= "";
			}
			form.email.value			= "";
			
			//Verifica se o form contem o endere?o
			if( form.idEndereco != null ) {
				form.idEndereco.value		= "0";
				form.status.value			= "";
				form.cep.value				= "";
				form.uf.value				= "";
				form.cidade.value			= "";
				form.bairro.value			= "";
				form.logradouro.value		= "";
				form.complemento.value		= "";
			}
			
			
		}
 }
 
/**
 * Fun??o utilizada para bloquear o formul?rio
 * @author Divino Cesar
 * @author Raphael Adrien
 * @param status - vari?vel boolean
 * @param elemento form - form que deve ser bloqueado
 */ 
function statusFormPessoa(status, form){
		form.idPessoa.readOnly = status;
		form.nome.readOnly = status;
		form.dataNascimento.readOnly = status;
		form.sexo[0].readOnly = status;
		form.sexo[1].readOnly = status;
		form.ddd1.readOnly = status;
		form.fone1.readOnly = status;
		form.ddd2.readOnly = status;
		form.fone2.readOnly = status;
		form.ddd3.readOnly = status;
		if (form.fone3){
			form.fone3.readOnly = status;
		} else {
			form.fone3.readOnly = status;
		}
		//form.email.readOnly = status;
}

/**
 * Fun??o criada para formatar as strings para adicionar a tabela nas telas do sistema
 * @author Raphael Adrien
 * @param tamanho - vari?vel que define o tamanho maximo do campo na tela
 * @param texto - texto a ser adicionado na tela
 * @return texto - texto formatado para a tela
 */
 function formatTextoTable(tamanho, texto){
 	
 	if(texto.length > tamanho){
 		texto	= texto.substring(0, tamanho-3) + "...";
 	}
 	
 	return texto;
 }






////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
//////// NOVAS FUN??ES, DEPOIS QUE TODO O SISTEMA FOR ALTERADO O LAYOUT RETIRAR AS ACIMA ///////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////

// Retorna a string com a quantidade de caracteres especificada, completa os caracteres
// utilizando o caractere informado no parametro.
function strPadLeft(entrada, tamanho, caractere) {

	var dif = tamanho - entrada.length;

	for (i=1; i<=dif; i++) {
		entrada = caractere + entrada;
	}

	return entrada;
}

// Funcao para retirar os espacos em branco no inicio e fim da string.
function strTrim(str) {

    while (str.charAt(0) == " ")
    str = str.substr(1,str.length -1);

    while (str.charAt(str.length-1) == " ")
    str = str.substr(0,str.length-1);

    return str;
}

// Transforma string para minusculo
function strToLower(frmObj) {
	frmObj.value = frmObj.value.toLowerCase();
}

// Transforma string para maiusculo
function strToUpper(frmObj) {
	frmObj.value = frmObj.value.toUpperCase();
}

// Substitui todas as ocorrencias da do segundo parametro pelo valor do segundo
// a pesquisa ? feita no primeiro parametro.
function strReplaceAll(strChk, strFind, strReplace) {
	var strOut = strChk;
  
  	while (strOut.indexOf(strFind) > -1) {
    	strOut = strOut.replace(strFind, strReplace);
  	}
  	
  	return strOut;
}

// Retorna o nome do estado por estenso tendo como entrada a sigla do mesmo
function strTraduzEstado(sigla) {

	switch(sigla) {
		case 'AC':
			return "ACRE";
		case 'BA':
			return "BAHIA";
		case 'CE':
			return "CEARÁ";
		case 'DF':
			return "DISTRITO FEDERAL";
		case 'ES':
			return "ESPIRITO SANTO";
		case 'GO':
			return "GOIÁS";
		case 'MA':
			return "MARANHÃO";
		case 'AM':
			return "AMAZONAS";
		case 'RR':
			return "RORAIMA";
		case 'RN':
			return "RIO GRANDE DO NORTE";
		case 'RO':
			return "RONDÔNIA";
		case 'TO':
			return "TOCANTINS";
		case 'RS':
			return "RIO GRANDE DO SUL";
		case 'RJ':
			return "RIO DE JANEIRO";
		case 'SP':
			return "SÃO PAULO";
		case 'SC':
			return "SANTA CATARINA";
		case 'PR':
			return "PARANÁ";
		case 'PA':
			return "PARÁ";
		case 'AL':
			return "ALAGOAS";
		case 'SE':
			return "SERGIPE";
		case 'PB':
			return "PARAÍBA";
		case 'AP':
			return "AMAPÁ";
		case 'PI':
			return "PIAUÍ";
		case 'MS':
			return "MATO GROSSO DO SUL";
		case 'MT':
			return "MATO GROSSO";
		case 'MG':
			return "MINAS GERAIS";
		case 'PE':
			return "PERNAMBUCO";
	}	
}

// Funcao utilizada para adicionar zeros na hora. Transforma um valor no formato x em xx:xx
// Raphael Adrien
function timeAddZeroHora(obj){
	tamanho 	= obj.value.length;

	if(tamanho == 1) {
		obj.value = "0" + obj.value + ":00";
	}
	else if(tamanho == 2){
		obj.value = obj.value + ":00";
	} 
	else if (tamanho == 3) {
		obj.value = obj.value + "00";
	}
	else if (tamanho == 4) {
		obj.value = obj.value + "0";
	}
}

// seleciona o tem de um radio group que foi indicado no parametro.
function formSelectRadioItem(item, valor) {
	
	// Locura!!! se item.length == 1, ent?o ele retorna undefined....
	if (item.length != undefined) {
	    for (i=0; i<item.length; i++) {
	        if (item[i].value == valor) {
	            item[i].checked = true;
	            item[i].disabled = false;
	            return ;
	        }
	    }
    }
    else {
    	if (item.value == valor) {
    		item.checked = true;
    	}
    }
}

// seleciona o tem de um checkbox que foi indicado no parametro.
function formSelectItemCombo(combo, valor) {

    for (i=0; i<combo.length; i++) {
        if (combo.options[i].value == valor) {
            combo.options[i].selected = true;
            return ;
        }
    }
}

// Metodo para limpar o formulario
function formLimpar(form) {
    for( i = 0; form.elements.length; i++ ) {
        element     = form.elements[i];
        
        if(element.type != "submit" && element.type != "button") {
			element.value   = '';
        }
    }
}


function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

var free = new Array(8, 9, 37, 38, 39, 40, 46)
var ctrl = new Array(86, 67, 88, 90)

function hasIn(array, value) {
	for (var i=0; i<array.length; i++) {
		if (array[i] == value) {
			return true;
		}
	}
	
	return false;
}


function maskApenasInteiros(v) {

	return v.replace(/\D/g,"")
}

//-----------------------------------------------------
//Funcao: MascaraMoeda
//Sinopse: Mascara de preenchimento de moeda
//Parametro:
//   objTextBox : Objeto (TextBox)
//   SeparadorMilesimo : Caracter separador de mil?simos
//   SeparadorDecimal : Caracter separador de decimais
//   e : Evento
//USO: onKeyPress="return(maskMoeda(this,'.',',',event))" 
//Retorno: Booleano
//Autor: Vinicius R. do Amaral
//Data Cria??o: 21/11/2006
//-----------------------------------------------------
function maskMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
	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 ((whichCode == 13) || (whichCode == 8) || (whichCode == 0))  return true;
    key = String.fromCharCode(whichCode); // Valor para o c?digo da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inv?lida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

// Formata um campo data
function maskDate(v) {
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{2})(\d)/,"$1/$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	v=v.replace(/(\d{2})(\d)/,"$1/$2")       //Coloca um ponto entre o terceiro e o quarto dígitos

	return v
}

// Formata um campo cep
function maskCep(v) {
    v=v.replace(/\D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2") //Esse é tão fácil que não merece explicações
    v=v.replace(/(\d{3})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações

    return v
}

// Formata um campo cpf
function maskCpf(v) {
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

// Formata um campo CNPJ
function maskCnpj(v) {
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    
    return v
}

// Formata um campo telefone
function maskTelefone(v) {
    v=v.replace(/\D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{4})(\d)/,"$1-$2") //Esse tb é tão fácil que não merece explicações

    return v
}

/**
 *Não usar esta função para as novas implementações usar a somenteStrings. 
 * @param campo
 * @return
 */
function maskApenasStrings(campo) {

	// Se a tecla CTRL esta pressionada e ao mesmo tempo o v
	if (window.event.ctrlLeft) {
		if ( hasIn(ctrl, window.event.keyCode) ) { return true; }
	}

	// permite strings
	if (window.event.keyCode>=48 && window.event.keyCode<=57){ 
		return false;
	} 
}

/**
 * Desenvolvido para substituir a função maskApenasStrings, pois esta é apenas 
 * compativel com ie sendo que a aceitaStrings é compativel tanto para ie, nestcape, mozila, crome.
 * @param campo - objeto 
 * @param eve - evento que foi disparado
 * @return
 * Tony Christopher
 */
function somenteStrings(campo, eve) {
	var keyCode;
	if (document.all) // Internet Explorer
		keyCode = eve.keyCode;
	else if((document.layers) || (document.getElementById)) // Nestcape ou Mozilla
		keyCode = eve.which;
	
	// return false qdo numeros
	if (keyCode>= 96 && keyCode<= 105){ 
		return false;
	}
	return true;
}

// Formata um campo onde hora deve ser entrada
function maskHora(v) {
    v=v.replace(/\D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1:$2") //Esse tb é tão fácil que não merece explicações

    return v
}

// Valida??o do CPF informado
function validaCpf(obj) {

	var CPF = obj.value; // Recebe o valor digitado no campo

	// Verifica se o campo tem menos de 11 digitos
	if (CPF == "") {
  		alert("Por favor, informe corretamente seu CPF!");
 	 	obj.focus();
  		return false;
   	}

	//if (CPF.length != 14) {
  		//alert("Por favor, informe corretamente seu CPF!");
  		//obj.focus();
  		//return false;
   	//}

	CPF = CPF.replace (".","");
	CPF = CPF.replace (".","");
	CPF = CPF.replace ("-","");

	// DEIXA PASSAR O CPF GERAL
	if (CPF == '00000000190' ) {
  		return true;
    }

	// Verifica cpf fantasmas
	if (CPF == '00000000000' || CPF == '11111111111' || CPF == '22222222222' || CPF == '33333333333' || CPF == '44444444444' ||
    	CPF == '55555555555' || CPF == '66666666666' || CPF == '77777777777' || CPF == '88888888888' || CPF == '99999999999') {
  		alert('CPF inválido!!');
  		obj.focus();
  		return false;
   }

	// Aqui come?a a checagem do CPF
	var POSICAO, I, SOMA, DV, DV_INFORMADO;
	var DIGITO = new Array(10);
	DV_INFORMADO = CPF.substr(9, 2); // Retira os dois ?ltimos d?gitos do n?mero informado

	// Desmembra o n?mero do CPF na array DIGITO
	for (I=0; I<=8; I++) {
  		DIGITO[I] = CPF.substr( I, 1);
	}

	// Calcula o valor do 10? d?gito da verifica??o
	POSICAO = 10;
	SOMA = 0;
   	for (I=0; I<=8; I++) {
		SOMA = SOMA + DIGITO[I] * POSICAO;
      	POSICAO = POSICAO - 1;
   	}

	DIGITO[9] = SOMA % 11;
   	if (DIGITO[9] < 2) {
    	DIGITO[9] = 0;
	}
   	else {
		DIGITO[9] = 11 - DIGITO[9];
	}

	// Calcula o valor do 11? d?gito da verifica??o
	POSICAO = 11;
	SOMA = 0;
   	for (I=0; I<=9; I++) {
    	SOMA = SOMA + DIGITO[I] * POSICAO;
      	POSICAO = POSICAO - 1;
   	}

	DIGITO[10] = SOMA % 11;
   	if (DIGITO[10] < 2) {
    	DIGITO[10] = 0;
   	}
   	else {
    	DIGITO[10] = 11 - DIGITO[10];
   	}

	// Verifica se os valores dos d?gitos verificadores conferem
	DV = DIGITO[9] * 10 + DIGITO[10];
   	if (DV != DV_INFORMADO) {
    	alert('CPF inválido');
      	obj.focus();
      	// A pedido do paulo galeno
      	//obj.value = '';
      	return false;
   	} 
   	
   	return true;
}

// Valida a Carga hora informada
function validaHora(objHoraFormatada, strHoraMaxima){
	var strHoraFormatada = objHoraFormatada.value;

	if (strHoraFormatada==""){
		return false;
	}

	if( strHoraFormatada.length != 5){
		return false;
	}

	var strHora = parseInt(strHoraFormatada.substring(0,2),10);
	var strMinuto = parseInt(strHoraFormatada.substring(3,5),10);

	if (parseInt(strHora) >= strHoraMaxima && parseInt(strMinuto) > 0){
		return false;
	}
	else if(parseInt(strMinuto) > 59){
		return false;
	}
	else return true;
}

//function validaTeste(horaFormatada){
//	//alert(converteHoraFormatadaEmDecimal(cargaHoraria.value));
//	//alert(cargaHoraria.value);
//	var cargaHorariaDecimal = converteHoraFormatadaEmDecimal(horaFormatada.value);
////	alert('Carga horária decimal: '+cargaHorariaDecimal);
////	alert('Comparação: '+(cargaHorariaDecimal > 30));
//	validaHora(horaFormatada, 30);
//	//alert(horaFormatada.value+' em decimal fica '+cargaHorariaDecimal+' e formatada novamente fica '+converteHoraDecimalEmFormatada(cargaHorariaDecimal));
//}

// Converte Hora Decimal para Hora Formatada
function converteHoraDecimalEmFormatada(objHoraDecimal){
	var strHoraDecimal = String(objHoraDecimal);
	var strHora = "";
	
	if (strHoraDecimal.indexOf('.') > 0) 
		strHora = strHoraDecimal.substring(0,strHoraDecimal.indexOf('.'));
	else 
		strHora = String(strHoraDecimal);

	var strMinuto = String(Math.round((objHoraDecimal % parseInt(strHora))*60));
	
	if (Number(strMinuto) >= 60){
		strHora = String(Number(strHora)+1);
		strMinuto = String(Number(strMinuto) - 60);
	}
	
	if (strHora.length == 1) strHora = '0' + strHora;
	if (strMinuto.length == 1) strMinuto = '0' + strMinuto;	
	return (strHora+':'+strMinuto);
}

// Converte Hora Formatada em Decimal
function converteHoraFormatadaEmDecimal(objHoraFormatada){
	var strHora = objHoraFormatada
	
	if (strHora==""){
		alert('Hora inválida.');
		return 0; 
	}
	
	var intHora = parseInt(strHora.substring(0,2),10); 
	var intMinuto = parseInt(strHora.substring(3,5),10);

	return (intHora + (intMinuto / 60));
}

// Converte Hora Formatada em Exterso
function converteHoraFormatadaExtenso(objHoraFormatada){
	var strHora = objHoraFormatada
	
	if (strHora==""){
		alert('Erro ao converter Hora Formatada para Exterso. Hora vazia.')		
	}
	var intHora = parseInt(strHora.substring(0,2),10); 
	var intMinuto = parseInt(strHora.substring(3,5),10);
	var retorno = String(intHora) + ' horas';
	
	if (intMinuto > 0){
		retorno += ' e '+String(intMinuto)+' minutos';
	}
	
	return retorno;
}
// Valida a data informada
function validaData(objCampo){ 
	
	//verifica se uma deterimnada data ? v?lida ou n?o 
	var strData = objCampo.value 
	
	if (strData==""){ 
		return false; 
	} 
	
	var intDia = parseInt(strData.substring(0,2),10); 
	var intMes = parseInt(strData.substring(3,5),10); 
	var intAno = parseInt(strData.substring(6,10),10); 
	 
	if (intDia <= 31 && intMes <=12 && intAno >= 1000){ 
	  if (strData.substring(0,1)=='0' && strData.substring(1,2) != '0' || strData.substring(0,1)!='0'){ 
		if (strData.substring(2,3)=="/"){ 
		  if (strData.substring(3,4)=='0' && strData.substring(4,5)!='0' || strData.substring(3,4)!='0'){ 
			if (strData.substring(5,6)=="/"){ 
			  if (strData.substring(6,7)== '0' || strData.substring(6,7)=='' && strData.substring(7,8)!='0'){ 
				window.alert("Data inválida!"); 
				return false; 
			  } 
			  else { 
				if (intMes == 2){ 
				  if ((intDia > 0 ) && (intDia <= 29)){ 
					 if (intDia == 29){ 
						if ((intAno % 4) == 0){ 
						  return true; 
						} 
						else { 
						  window.alert("Data inválida!"); 
						  return false; 
						} 
					 } 
				  } 
				  else { 
				    window.alert("Data inválida!"); 
					return false; 
				  } 
				} 
				if ((intMes == 4)||(intMes == 6)||(intMes == 9)||(intMes ==11)){ 
				  if ((intDia > 0 ) && (intDia <= 30)){ 
					return true; 
				  } 
				  else{ 
					window.alert("Data inválida!"); 
					return false; 
				  } 
				} 
				if ((intMes == 1)||(intMes == 3)||(intMes == 5)||(intMes ==7)||(intMes ==8)||(intMes == 10)||(intMes == 12)) { 
				  if ((intDia > 0) && (intDia <= 31)) { 
					return true; 
				  } 
				  else{ 
					window.alert("Data inválida!"); 
					return false; 
				  } 
				} 
			  } 
			} 
			else{ 
			  window.alert("Data inválida!"); 
			  return false; 
			} 
		  } 
		  else{ 
			window.alert("Data inválida!"); 
			return false; 
		  } 
		} 
		else{ 
		  window.alert("Data inválida!"); 
		  return false; 
		} 
	  } 
	  else{ 
		window.alert("Data inválida!"); 
		return false; 
	  } 
	} 
	else { 
	  window.alert("Data inválida!"); 
	  return false; 
	} 

	return true; 
} 

function validaEmail(campo) {

	var email = campo.value;
	var ponto_mail = email.indexOf('.', '0');
	var arroba_mail = email.indexOf('@', '0');
	var last_ponto = email.lastIndexOf('.');
	var caracs_especiais = new Array('/', '*', '+', '=', '`', '[', ']', ';', ',', '\\', '?', '|', ':', '{', '}', ')', '(', '&', '^', '%', '$', '#', '!', '~', '\"', '\'', ' ');
	
	for (cont=0; cont<=caracs_especiais.length; cont++) {
		if (email.indexOf(caracs_especiais[cont], '0') != -1) {
			alert("Por gentileza, informe um e-mail valido!");
			campo.focus();
			return false;
		}
	}		
	
	if (!email || (last_ponto < arroba_mail))	// verificamos se o e-email esta branco,
	{										    // e se o arroba esta no lugar correto
		alert("Por gentileza, preencha seu e-mail corretamente!");
		campo.focus();
		return false;
	}
	else										// e-mail nao esta em branco, e o arroba no lugar certo
	{			
		if ((last_ponto+1) == email.length)			// v se o ponto nao e' o ultimo caractere
		{
			alert("Por gentileza, informe corretamente seu e-mail!");
			campo.focus();
			return false;		
		}
	
		if ((arroba_mail == -1) || (ponto_mail == -1))		// se nao tem o arroba no e-mail, ou o ponto
		{
			alert("Por gentileza, informe corretamente seu e-mail!");
			campo.focus();
			return false;
		}
		else									// se tem arroba ou ponto no email...
		{
			if (((arroba_mail+1) == (ponto_mail)) || ((arroba_mail-1) == (ponto_mail)))
			{
				alert("Por gentileza, informe corretamente seu e-mail!");
				campo.focus();
				return false;
			}
		}
	}

	return true;
}

function validaDDD(campo) {

	campo.value = trim(campo.value);

	if (campo.value.length == 2) {
		campo.value = "0" + campo.value;
	}
	else if (campo.value.length == 1) {
		campo.value = "00" + campo.value;	
	}
}

/**
 * Função curada para formatar o cpf
 */
function formataCpf( cpf ){
	var auxCpf;
	cpf = noFormatCpf( cpf );
	
	auxCpf	= cpf.substr(0,3) + ".";
	auxCpf += cpf.substr(3,3) + ".";
	auxCpf += cpf.substr(6,3) + "-";
	auxCpf += cpf.substr(9,3);
	
	return auxCpf;
}

/**
 * Função criada para retirar a formatação de um campo cpf
 */
function noFormatCpf( cpf ){
	cpf	= cpf.replace(".","");
	cpf = cpf.replace(".","");
	cpf = cpf.replace("-","");
	
	return cpf;
}

/**
* Função responsavel por tirar os espaços
*/
function Trim(str){
	return str.replace(/^\s+|\s+$/g,"");
}

function avisoCefet(documento, escola){
	if (escola == null){
		escola = 'CEFET';
	} else if (escola == 'UNITINS'){
		escola = ' da '+ escola;
	} else if (escola == 'IFG'){
		escola = ' do '+ escola;
	}
	if(documento == "TCE"){
		alert("Alunos "+escola+" deverão entrar em Contato no IEL (Fone: 3216-0319) para receber as informações necessárias e  imprimir o TCE, conforme  procedimentos internos "+ escola +".");
	}else if(documento == "ficha"){
		alert("Alunos " + escola + " deverão entrar em Contato no IEL (Fone: 3216-0319) para receber as informações necessárias e imprimir o Plano de Atividades, conforme procedimentos internos "+ escola +".");
	}
}

/**
 * Verify if the field is a valid Date.
 */
function validDate(vfield){
	var diaStr, mesStr, anoStr
	var diaInt, mesInt, anoInt
	var tam, sep1, sep2, verAno
	
	tam = vfield.value.length;

	sep1 = parseInt(vfield.value.indexOf("/", 0));

	if (sep1<0){
		alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
		return false;
	}

	sep2 = parseInt(vfield.value.indexOf("/", sep1+1))

	if (sep2<5){
		alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
		return false;
	}

	verAno = tam-sep2;

	if(verAno < 5 ){
		alert("As datas devem ser preenchidas utilizando 4 dígitos para informar o Ano (ex.: DD/MM/AAAA)!");
		return false;
	}

	diaStr = vfield.value.substring(0, sep1);

	if(diaStr.substring(0, 1) == "0")
		diaStr = diaStr.substring(1, 2);

	if (isInt(diaStr)){
		mesStr = vfield.value.substring(sep1+1, sep2);

		if(mesStr.substring(0, 1) == "0")
			mesStr = mesStr.substring(1, 2);

		if (isInt(mesStr)){
			anoStr = vfield.value.substring(sep2+1, tam);

			if (isInt(anoStr)){
				diaInt = parseInt(diaStr);
				mesInt = parseInt(mesStr);
				anoInt = parseInt(anoStr);
	
				if ((diaInt <= 0) || (diaInt > 31)){
					alert("O dia informado não é válido!");
					return false;
				}
	
				if ((mesInt <= 0) || (mesInt > 12)){
					alert("O mês informado não é válido!");
					return false;
				}
	
				if ((mesInt == 4) || (mesInt == 6) || (mesInt == 9) || (mesInt == 11)){
					if( diaInt > 30){
						alert("O mês informado não possui mais de 30 dias!");
						return false;
					}
				}
	
				if (mesInt == 2){
					if ((anoInt % 4 == 0) && ( (anoInt % 100 != 0) || (anoInt % 400 == 0))){
						if (diaInt > 29){
							alert("O mês informado não possui mais de 29 dias!");
							return false;
						}
					} else {
						if(diaInt > 28){
							alert("O mês informado não possui mais de 28 dias!");
							return false;
						}
					}
					return true;
				}
				return true;
			} else {
				alert("Data inválida");
				return false;
			}
		} else{
			alert("Data inválida");
			return false;
		}
	} else {
		alert("Data inválida");
		return false;
	}
}

/** função verifica se um número inteiro.*/
function isInt(number) {
    if (isNaN(number)) {
        return false;
    }
    var myMod = number % 1;
    if (myMod == 0) {
        return true;
    } else {
        return false;
    }
}

/** Converte a data no formato MM/dd/yyyy usada para o contrutor do objeto do tipo new Date()
 * strData = '21/12/2008';
 * Exemplo: new Date(convertDateMMDDYYYY(strData, '/'));
 * */
function convertDateMMDDYYYY(data, delimitador) {
	var dataArray = data.split(delimitador);
	var dia = dataArray[1];
	var mes = dataArray[0];
	var ano = dataArray[2];
	var dataFormatada = dia + delimitador + mes + delimitador + ano;
	return dataFormatada;
}

/**
 * Valida um Período de data para saber se a dataInicial é maior que a data final.
 * Exemplo: if (!periodoValido(inputDataInicial, inputDataFinal)){alert(<mensagem de retorno>); return false;}
 * */	
function periodoValido(objDataInicial, objDataFinal) {
	try{
		if ((objDataInicial.value != '') && (objDataFinal.value == '') || (objDataFinal == null)) {
			throw new Error('Coloque também um valor para a Data Final!');
		}
		if ((objDataFinal.value != "") && (objDataInicial.value == "") || (objDataInicial == null)) {
			throw new Error('Coloque também um valor para a Data Inicial!');
		}
		if (!validDate(objDataInicial)){return false;}
		if (!validDate(objDataFinal)){return false;}
		
		var dtIni = new Date(convertDateMMDDYYYY(objDataInicial.value, "/"));
		var dtFin = new Date(convertDateMMDDYYYY(objDataFinal.value, "/"));
		if (dtFin < dtIni) {
			return false;
	    } 
	   	return true;
	}catch(err){
		alert(err.message);
		return false;
	}		
}

/**
 * Função que abre um popup
 * Tony Christopher
 */
function abrePopup(window, url) {

    var popURL  = url;
    var popNAME = 'Ficha_Roteiro';
    var popPROP = 'scrollbars,status,width='+screen.width+',left=' + (screen.width/2 - 600/2) + ',height='+screen.width+',top=' + (screen.height/2 - 600/2);

    window.open(popURL, popNAME, popPROP);
}

/**************************************************************
 * Objeto validação de formulário. 
 **************************************************************/
validaFrm                = new Object;
validaFrm.message        = '';
validaFrm.emptyMessage   = function(){this.message = ''; document.getElementById('divErro').style.display = 'none'; }
validaFrm.showMessage    = function(){if (!document.getElementById('divErro')){alert('Tag divErro não existe no formulário!');return false;}document.getElementById('divErro').style.display = '';document.getElementById('divErro').innerHTML = this.getMessage(); window.scroll(250,250);return true;}
validaFrm.addMessage     = function(erro){this.message += '<img src="'+URL_+'/img/v2_formAcoes/btn_alertaMsg.gif" alt="Alerta"/>&nbsp;'+erro+'<br />';}
validaFrm.getMessage     = function() { return this.message; }
validaFrm.isMessage     = function() {if(this.message == '') {return false;}else{return true;}}
validaFrm.validar = function (frm){
    this.message = '';
    //listar os inputs
    try{
    for (var i = 0; i < frm.elements.length; i++){
    	if (frm.elements[i].getAttribute('validate')){
    		frm.elements[i].className = '';
    		// Tipo Obrigatório
        	if ((frm.elements[i].getAttribute('validate') == 'request') || (frm.elements[i].getAttribute('validate') == 'request-cpf')
        	       || (frm.elements[i].getAttribute('validate') == 'request-cnpj') || (frm.elements[i].getAttribute('validate') == 'request-email')
        	       || (frm.elements[i].getAttribute('validate') == 'request-data')){
                if (frm.elements[i].value == ''){
                    frm.elements[i].className = 'alerta'; 
                	if (frm.elements[i].title.length == 0){
                        this.addMessage('O campo '+frm.elements[i].name+', deve ser informado!');
                    } else {
                        this.addMessage(frm.elements[i].title);
                    }
                }
        	}
        	if (Trim(frm.elements[i].value).length > 0){
		    	//-- Tipo CPF ou CNPJ
		    	if ((frm.elements[i].getAttribute('validate') == 'cpf') || (frm.elements[i].getAttribute('validate') == 'request-cpf')){
	                if (!validadorCPF.validar(frm.elements[i].value)){
	                    validaFrm.addMessage(validadorCPF.getMessage());
	                    frm.elements[i].className = 'alerta';
	                }
		    	} else if ((frm.elements[i].getAttribute('validate') == 'cnpj') || (frm.elements[i].getAttribute('validate') == 'request-cnpj')){
	                if (!validadorCNPJ.validar(frm.elements[i].value)){
	                    validaFrm.addMessage(validadorCNPJ.getMessage());
	                    frm.elements[i].className = 'alerta';
	                }
		    	}
	            //-- Tipo Email
	            if ((frm.elements[i].getAttribute('validate') == 'email') || (frm.elements[i].getAttribute('validate') == 'request-email')){
	    			if (!this.validarEmail(frm.elements[i].value)){
	    				frm.elements[i].className = 'alerta';
	    			}
	            }
	            //-- Tipo Data
	            if ((frm.elements[i].getAttribute('validate') == 'data') || (frm.elements[i].getAttribute('validate') == 'request-data')){
            		if (!this.validaData(frm.elements[i].value)){
            			frm.elements[i].className = 'alerta';
            		}
	            }

        	}
    	} // fim teste validate
    }// fim for
    }catch(err){
    	alert(err.message);
    }
    if (this.isMessage()){
        this.showMessage();
        return false;
    }
    document.getElementById('divErro').style.display = 'none';
    return true;
}	
validaFrm.validarEmail = function (email){
    var ponto_mail = email.indexOf('.', '0');
    var arroba_mail = email.indexOf('@', '0');
    var last_ponto = email.lastIndexOf('.');
    var caracs_especiais = new Array('/', '*', '+', '=', '`', '[', ']', ';', ',', '\\', '?', '|', ':', '{', '}', ')', '(', '&', '^', '%', '$', '#', '!', '~', '\"', '\'', ' ');
    
   
    for (cont=0; cont<=caracs_especiais.length; cont++) {
        if (email.indexOf(caracs_especiais[cont], '0') != -1) {
            this.addMessage("Por gentileza, informe um e-mail valido!");
            return false;
        }
    }       
    
    if (!email || (last_ponto < arroba_mail)){   // verificamos se o e-email esta branco, e se o arroba esta no lugar correto
        this.addMessage("Por gentileza, preencha seu e-mail corretamente!");
        return false;
    } else {                                        // e-mail nao esta em branco, e o arroba no lugar certo
        if ((last_ponto+1) == email.length){         // v se o ponto nao e' o ultimo caractere
            this.addMessage("Por gentileza, informe corretamente seu e-mail!");
            return false;       
        }
        if ((arroba_mail == -1) || (ponto_mail == -1)){      // se nao tem o arroba no e-mail, ou o ponto
            this.addMessage("Por gentileza, informe corretamente seu e-mail!");
            return false;
        } else {                                    // se tem arroba ou ponto no email...
            if (((arroba_mail+1) == (ponto_mail)) || ((arroba_mail-1) == (ponto_mail))) {
                this.addMessage("Por gentileza, informe corretamente seu e-mail!");
                return false;
            }
        }
    }
    return true;
}

validaFrm.validaData = function (strData){
	if (strData==""){ 
		this.addMessage('Data deve ser informada!');
		return false; 
	} 
	
	var intDia = parseInt(strData.substring(0,2),10); 
	var intMes = parseInt(strData.substring(3,5),10); 
	var intAno = parseInt(strData.substring(6,10),10); 

    if (intDia <= 31 && intMes <=12 && intAno >= 1000){ 
      if (strData.substring(0,1)=='0' && strData.substring(1,2) != '0' || strData.substring(0,1)!='0'){ 
        if (strData.substring(2,3)=="/"){ 
          if (strData.substring(3,4)=='0' && strData.substring(4,5)!='0' || strData.substring(3,4)!='0'){ 
            if (strData.substring(5,6)=="/"){ 
              if (strData.substring(6,7)== '0' || strData.substring(6,7)=='' && strData.substring(7,8)!='0'){ 
                this.addMessage("Data inválida!");
                return false; 
              } 
              else { 
                if (intMes == 2){ 
                  if ((intDia > 0 ) && (intDia <= 29)){ 
                     if (intDia == 29){ 
                        if ((intAno % 4) == 0){ 
                          return true; 
                        } 
                        else { 
                          this.addMessage("Data inválida!"); 
                          return false; 
                        } 
                     } 
                  } 
                  else { 
                    this.addMessage("Data inválida!"); 
                    return false; 
                  } 
                } 
                if ((intMes == 4)||(intMes == 6)||(intMes == 9)||(intMes ==11)){ 
                  if ((intDia > 0 ) && (intDia <= 30)){ 
                    return true; 
                  } 
                  else{ 
                    this.addMessage("Data inválida!"); 
                    return false; 
                  } 
                } 
                if ((intMes == 1)||(intMes == 3)||(intMes == 5)||(intMes ==7)||(intMes ==8)||(intMes == 10)||(intMes == 12)) { 
                  if ((intDia > 0) && (intDia <= 31)) { 
                    return true; 
                  } 
                  else{ 
                    this.addMessage("Data inválida!"); 
                    return false; 
                  } 
                } 
              } 
            } 
            else{ 
              this.addMessage("Data inválida!"); 
              return false; 
            } 
          } 
          else{ 
            this.addMessage("Data inválida!"); 
            return false; 
          } 
        } 
        else{ 
          this.addMessage("Data inválida!"); 
          return false; 
        } 
      } 
      else{ 
        this.addMessage("Data inválida!"); 
        return false; 
      } 
    } 
    else { 
      this.addMessage("Data inválida!"); 
      return false; 
    } 

    return true; 
} 

function direcionarPagina(url){
    window.location = url;	
}

//Funcoes para alterar o tamanho da fonte
var min=11;
var max=18;
function increaseId(nomeTagPai, nomeTagFilho) {
   var p = document.getElementById(nomeTagPai).childNodes;
	for(var i = 0;i < p.length;i++) {
		if (p[i].name == nomeTagFilho){
		  if(p[i].style.fontSize) {
		     var s = parseInt(p[i].style.fontSize.replace("px",""));
		  } else {
		     var s = 12;
		  }
		  if(s!=max) {
		     s += 1;
		  }
		  p[i].style.fontSize = s+"px"
		}
	}
}

function decreaseId(nameTagPai, nomeTagFilho) {
    var p = document.getElementById(nameTagPai).childNodes;
    for(var i=0;i<p.length;i++) {
        if (p[i].name == nomeTagFilho){
            if(p[i].style.fontSize) {
                var s = parseInt(p[i].style.fontSize.replace("px",""));
            } else {
                var s = 12;
            }
            if(s!=min) {
                s -= 1;
            }
            p[i].style.fontSize = s+"px"
        }
    }   
}

function increase(tagName) {
   var p = document.getElementsByName(tagName);
    for(var i = 0;i < p.length;i++) {
          if(p[i].style.fontSize) {
             var s = parseInt(p[i].style.fontSize.replace("px",""));
          } else {
             var s = 12;
          }
          if(s!=max) {
             s += 1;
          }
          p[i].style.fontSize = s+"px"
    }
}

function decrease(tagName) {
    var p = document.getElementsByName(tagName);
    for(var i=0;i<p.length;i++) {
            if(p[i].style.fontSize) {
                var s = parseInt(p[i].style.fontSize.replace("px",""));
            } else {
                var s = 12;
            }
            if(s!=min) {
                s -= 1;
            }
            p[i].style.fontSize = s+"px"
    }   
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function getSelectedRadio(obj){
	for (var i = 0; i < obj.length;i++){
	   if (obj[i].checked){
            return obj[i].value;	   	
	   }
	}
	return '';
}

/**
 * Funções para manipulação de cookies
 * 
 * */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

var win = null;
function NewWindow(mypage,myname,w,h,scroll,pos){
	if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
	if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;
	}else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
	settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
	win = window.open(mypage,myname,settings);
}

function calcPeriodoHoras(periodoEntrada, periodoSaida, calculaHora){
	   var minuto = 60000;
	   var hora = minuto * 60; 
		var dia = hora * 24;
		var horarioVerao = 0;
				   
       // ajusta o horario de cada objeto Date
   var dt1 = new Date();
   var dt2 = new Date();
   var partes1 = periodoEntrada.value.split(":");
   var partes2 = periodoSaida.value.split(":");
       
   dt1.setHours(partes1[0]);
   dt1.setMinutes(partes1[1]);
   dt1.setSeconds(0);
   dt2.setHours(partes2[0]);
   dt2.setMinutes(partes2[1]);
   dt2.setSeconds(0);
       
       // determina o fuso horário de cada objeto Date
   var fh1 = dt1.getTimezoneOffset();
   var fh2 = dt2.getTimezoneOffset(); 
       
       // retira a diferença do horário de verão
   var dif = Math.abs(dt2.getTime() - dt1.getTime());
   if (calculaHora) {
      return parseInt(dif / hora);
   } else {
 	   return Math.ceil((dif % hora)/minuto);
   }
}
