//*********************************************************************************************

//Funcao para posiciar o combo no valor desejado
function PosicionarCombo(nameObj, Valor){
		
	for (i=0; i< nameObj.length; i++) {
			
		if(nameObj.options[i].value == Valor){
			nameObj.options[i].selected = true;
		}
		else{
			nameObj.options[i].selected = false;
		}
			
	}			
}		

//*********************************************************************************************

//Funcao para formatar data de DD/MM/YYYY(Formulario) para YYYY/MM/DD(MySql) 
function FormatDateSQL(strData){
	if (strData.length == 10){
		return(strData.split("/")[2] + "/" + strData.split("/")[1] + "/" + strData.split("/")[0]);
	}
	else{
		return("0000/00/00");
	}	
}

//*********************************************************************************************

//Funcao para formatar data de YYYY/MM/DD(MySql) para DD/MM/YYYY(Formulario) 
function FormatDateFormulario(strData){
	if (strData == "0000/00/00"){
		return(strData.split("/")[0] + "/" + strData.split("/")[1] + "/" + strData.split("/")[2]);
	}
	else{
		return("");
	}	
}

//*********************************************************************************************

//Retornar o "Default" quando valor nulo
function NaoNulo(strValor, strDefault){
	if (strValor.length == 0){
		return(strDefault);
	}
	else{
		return(strValor);
	}	
}

//*********************************************************************************************

//Formata valor para ser passado ao MySql
function ValorMySQL(strValor){
	
	strValor = removeCaracter(strValor, ".");
	strValor = strValor.replace(',', '.');
	
	return(strValor);
		
}

//*********************************************************************************************

function ValidaCPF(theCPF){
	
	theCPF.value = theCPF.value.replace(/\D/g,"")
	
  	if (theCPF.value == "")
  	{
	  	return true;
	}
  
	if (((theCPF.value.length == 11) && (theCPF.value == 11111111111) || (theCPF.value == 22222222222) || (theCPF.value == 33333333333) || (theCPF.value == 44444444444) || (theCPF.value == 55555555555) || (theCPF.value == 66666666666) || (theCPF.value == 77777777777) || (theCPF.value == 88888888888) || (theCPF.value == 99999999999) || (theCPF.value == 00000000000)))
  	{
    	return false;
  	}

  	if (!((theCPF.value.length == 11) || (theCPF.value.length == 14)))
  	{
    	return false;
  	}

  	var checkOK = "0123456789";
  	var checkStr = theCPF.value;
  	var allValid = true;
  	var allNum = "";
  	for (i = 0;  i < checkStr.length;  i++)
  	{
	    ch = checkStr.charAt(i);
	    
	    for (j = 0;  j < checkOK.length;  j++)
	    
    	  	if (ch == checkOK.charAt(j))
	        	break;
	    	if (j == checkOK.length)
    		{
      			allValid = false;
      			break;
    		}
    	allNum += ch;
  	}
  	if (!allValid)
  	{
    	return false;
  	}

  	var chkVal = allNum;
  	var prsVal = parseFloat(allNum);
  	if (chkVal != "" && !(prsVal > "0"))
  	{
    	return false;
  	}

	if (theCPF.value.length == 11)
	{
  		var tot = 0;
	
  		for (i = 2;  i <= 10;  i++)
    		tot += i * parseInt(checkStr.charAt(10 - i));
		
  		if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(9)))
  		{
    		return false;
		}
  
  		tot = 0;
  
  		for (i = 2;  i <= 11;  i++)
    		tot += i * parseInt(checkStr.charAt(11 - i));

  		if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(10)))
  		{
    		return false;
  		}
	}
	else
	{
  		var tot  = 0;
  		var peso = 2;
  
  		for (i = 0;  i <= 11;  i++)
  		{
    		tot += peso * parseInt(checkStr.charAt(11 - i));
    		peso++;
    		if (peso == 10)
    		{
        		peso = 2;
    		}
  		}

  		if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(12)))
  		{
    		return false;
  		}
  
  		tot  = 0;
  		peso = 2;
  
  		for (i = 0;  i <= 12;  i++)
  		{
    		tot += peso * parseInt(checkStr.charAt(12 - i));
    		peso++;
    		if (peso == 10)
			{
				peso = 2;
			}
	  	}

  		if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(13)))
  		{
    		return false;
  		}
	}
  
	return true;
	} 

//*********************************************************************************************

//Funcao para criticar CNPJ
function ValidaCNPJ(strCNPJ) {
	
	var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
	var dig1= new Number;
	var dig2= new Number;

	exp = /\.|\-|\//g
	strCNPJ = strCNPJ.toString().replace(exp, ""); 
	var digito = new Number(eval(strCNPJ.charAt(12)+strCNPJ.charAt(13)));
    
	for(i = 0; i<valida.length; i++){
        dig1 += (i>0? (strCNPJ.charAt(i-1)*valida[i]):0);    
    	dig2 += strCNPJ.charAt(i)*valida[i];    
	}
	
	dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
	dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
    	
	if(((dig1*10)+dig2) != digito){
		return false;
	}else{
		return true;
	}               
}
    
//*********************************************************************************************

//Funcao para criticar DATA
function ValidaData(strData){

	var err = 0
	var valid = "0123456789/"
	var ok = "yes";
	var temp;
	
	for (var i=0; i< strData.length; i++) {
 		temp = "" + strData.substring(i, i+1);
 		if (valid.indexOf(temp) == "-1") err = 1;
	}

	if (strData.length != 10) err=1
	
	b = strData.substring(3, 5)		// month
	c = strData.substring(2, 3)		// '/'
	d = strData.substring(0, 2)		// day 
	e = strData.substring(5, 6)		// '/'
	f = strData.substring(6, 10)	// year

	if (b<1 || b>12) err = 1
	if (c != '/') err = 1
	if (d<1 || d>31) err = 1
	if (e != '/') err = 1
	if (f<1850 || f>2050) err = 1
	if (b==4 || b==6 || b==9 || b==11){
			if (d==31) err=1
	}

	if (b==2){

		var g=parseInt(f/4)
			
		if (isNaN(g)) {
				err=1 
		}

		if (d>29) err=1
		if (d==29 && ((f/4)!=parseInt(f/4))) err=1
	}

	if (err==1) {
		return false;
	}
	else{
		return true;
	}
} 


//*********************************************************************************************
//                             MASCARA DE DADOS
//*********************************************************************************************

//Mascarar dados no formulario
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(soNumeros(v_obj.value))
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g, "($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(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
}

function mvalor(v){
	v=v.replace(/\D/g,"") 					//Remove tudo o que não é dígito
	v=v.replace(/(\d)(\d{8})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos
	v=v.replace(/(\d)(\d{5})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos
	v=v.replace(/(\d)(\d{2})$/,"$1,$2") 	//Coloca ponto antes dos 2 últimos digitos
return v
}

function rg(v){
	v=v.replace(/\D/g,"") 					//Remove tudo o que não é dígito
	v=v.replace(/(\d)(\d{9})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos
	v=v.replace(/(\d)(\d{6})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos
	v=v.replace(/(\d)(\d{3})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos	
return v
}

function svalor(v){
	v=v.replace(/\D/g,"") 					//Remove tudo o que não é dígito
	v=v.replace(/(\d)(\d{9})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos
	v=v.replace(/(\d)(\d{6})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos
	v=v.replace(/(\d)(\d{3})$/,"$1.$2") 	//Coloca ponto antes dos 2 últimos digitos
return v
}

function cep(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{3})(\d)/,"$1-$2")      //Coloca um hífen depois do bloco de quatro dígitos
    return v
}


function hora(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    
    return v
}

function mreferencia(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    
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

function mdata(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)/,"$1/$2")    			//Coloca hífen entre o quarto e o quinto dígitos
    return v
}

//*********************************************************************************************

























//*********************************************************************************************
//								NAO ESTAO SENDO UTILIZADAS
//*********************************************************************************************








// --------------------------------------------------------------------------------------------------
// cbo = Objeto que vai ser preenchido
// valor = valor para preencher o combo
// descricao = texto para preencher o combo
function PreencheCombo(cbo, valor, texto) {
	var itemJaExiste = false;

	for (i = 0; i < cbo.options.length ; i++) {
		cbovalue = cbo.options[i].value;

		if (cbovalue == valor) {
			itemJaExiste = true;
			break;
		}
	}
	
	if (!itemJaExiste) {
		cbo.options[cbo.length] = new Option(texto, valor, false, true);
	}
}

// --------------------------------------------------------------------------------------------------
// cbo = Objeto combo que vai ter o ítem excluido
// valor = valor para preencher o combo
function RemoveCombo(cbo, valor) {
	for (i = 0; i < cbo.options.length ; i++) {
		cbovalue = cbo.options[i].value;

		if (cbovalue == valor) {
			cbo.options.remove(i);
		}
	}
}

function FormataData(Campo,teclapres) {
	var tecla = teclapres.keyCode;	
	var vr = Campo.value;	
	vr = window.event.srcElement.value;	
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );	
	tam = vr.length;    
	if (vr.length == (Campo.maxLength)) {
		return;
	}
	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
		{
			window.event.srcElement.value = vr.substr( 0, 2  ) + '/' + vr.substr( 2, tam );
		}
		if ( tam >= 5 && tam <= 10 )
		{
			window.event.srcElement.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); 
		}
	}
}

function FormataHora(Campo,teclapres) {
	var tecla = teclapres.keyCode;
	var vr = Campo.value;
	vr = window.event.srcElement.value;
	vr = vr.replace( ":", "" );
	tam = vr.length;    
	if (vr.length == (Campo.maxLength)) {
		return;
	}
	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
		{
			window.event.srcElement.value = vr.substr( 0, 2  ) + ':' + vr.substr( 2, tam );
		}
	}
}

function FecharForm(strNivel){
	var dtNow = new Date();			
		
	window.location = strNivel + 'areatrabalho.aspx?dt='
}

function DigitaNumero(oObj){

	var i;
	var strTexto = oObj.value;
	var intKeyCode = event.keyCode;
	var strKey = event.keyChar;
	
	//virgula deixa passar
	if (intKeyCode == 44 ) {		
		return;
	}	

	if (! (intKeyCode >= 48 && intKeyCode <= 57)) {
		event.keyCode = 0;
		return(false);
	}	
	
}
// ------------------------------------------------------------------------------------------------------
function LeapYear(intYear) {
   if (intYear % 100 == 0) {
      if (intYear % 400 == 0) { return true; }
   }
   else {
      if ((intYear % 4) == 0) { return true; }
   }
   
   return false;
}

// ------------------------------------------------------------------------------------------------------
function Repetir(strTexto, lngQtd){

	var strAux = "";
	var i;
	
	for (i = 1; i <= lngQtd; i++){
		strAux += strTexto;
	}
	
	return(strAux);

}


// --------------------------------------------------------------------------------------------------
function jsMensagem(sMsg) {	
	if (sMsg != '') {
		aMss = sMsg.split('<br>');
		if (aMss.length > 1) {
			sMsg = '';
			for (i=0; i<aMss.length; i++) {
				sMsg = sMsg + aMss[i] + '\n';
			}
		}
		alert(sMsg);
	}
}
//-----------------------marcar todos-----------------------------------
function selecionar_todas(retorno){
		
	formulario=document.frm;
		
	if(retorno==true){
		for(i=0;i<formulario.length;i++){
			if(formulario.elements[i].type=="checkbox" && formulario.elements[i].name!="todas"){
				if(formulario.elements[i].checked==false){
	  				formulario.elements[i].checked=true;
	   			}
			}
		}
	} else {
		for(i=0;i<formulario.length;i++){
			if(formulario.elements[i].type=="checkbox" && formulario.elements[i].name!="todas"){
				if(formulario.elements[i].checked==true){
			  		formulario.elements[i].checked=false;
				}
			}
		}
	}
}
//---------------------------------------------------------------------

function FormataCampo(Campo,teclapres,mascara){
//pegando o tamanho do texto da caixa de texto com delay de -1 no event
//ou seja o caractere que foi digitado não será contado.
strtext = Campo.value
tamtext = strtext.length
//pegando o tamanho da mascara
tammask = mascara.length
//criando um array para guardar cada caractere da máscara
arrmask = new Array(tammask)
//jogando os caracteres para o vetor
for (var i = 0 ; i < tammask; i++){
arrmask[i] = mascara.slice(i,i+1)
}
//alert (teclapres.keyCode)
//começando o trabalho sujo
if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){
if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)){
Organiza_Casa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)
}
else{
Detona_Event(Campo,strtext)
}
}
else{//Aqui funcionaria a mascara para números mas eu ainda não implementei
if ((arrmask[tamtext] == "A")) {
charupper = event.valueOf()
//charupper = charupper.toUpperCase()
Detona_Event(Campo,strtext)
masktext = strtext + charupper
Campo.value = masktext
}
}
}
function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){
	if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){
		separador = arrpos
		masktext = strtext + separador
		Campo.value = masktext
	}
}
function Detona_Event(Campo,strtext){
	event.returnValue = false
	if (strtext != "") {
		Campo.value = strtext
	}
}

//--------------------------------------------------------

function removeCaracter(str, sub) {
	i = str.indexOf(sub);
   	r = "";
   	if (i == -1) return str;
   	r += str.substring(0,i) + removeCaracter(str.substring(i + sub.length), sub);
   	return r;
}
