/* ===================================================
 * INCLUDES DAS BIBLIOTECAS EXTERNAS
 * =================================================== */

//Prototype
//document.writeln("<script src='../js/prototype.js' type='text/JavaScript'></script>");
//Script.aculo.us
//document.writeln("<script src='../js/scriptaculous.js' type='text/JavaScript'></script>");
//dhtmlgoodies_calendar
document.writeln("<script src='../js/dhtmlgoodies_calendar.js' type='text/JavaScript'></script>");


/* ===================================================
 *	ALGORITMOS GERAIS
 * =================================================== */

function contains(arr, val){
	if(val == null || arr == null || arr.length == 0) return false;
	for(var i = 0; i < arr.length; i++)
		if(arr[i] == val) return true;
	return false;
}

// limpa todos os caracteres especiais do campo solicitado
function filtrarCampo(campo){
	var s = "";
	var cp = "";
	vr = campo.value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {  
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
		 	s = s + vr.substring(i,i + 1);}
	}
	campo.value = s;
	return cp = campo.value
}

/*
 * Funcao dentro das funcoes de validacao e formatacao de CPF / CNPJ
 * Retira os seguintes caracteres da String passada como parametro:
 * '-', '/', ',', '.', '(', ')', ' '
 * 
*/
function clearSpecialChars(c){
	while((cx=c.indexOf("-"))!=-1){
		c = c.substring(0,cx)+c.substring(cx+1);
    }
	while((cx=c.indexOf("/"))!=-1){
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(","))!=-1){
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("."))!=-1){
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("("))!=-1){
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(")"))!=-1){
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(" "))!=-1){
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	return(c);
}

/*
 * Funcoes que pegam/setam a posicao do cursor
 * Parametros:
 *  - field: campo a ser validado
 *  - pos: posicao onde vai ser colocado o cursor
 *
 * USAGE: onfocus="setCaretPosition(field)" onblur="getCaretPosition(field)"
 */
function getCaretPosition(field) {
    var caretPos = 0;
    //IE support
    if (document.selection) {
        field.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -field.value.length);
        caretPos = range.text.length;
    } else
    //Firefox support
    if (field.selectionStart || field.selectionStart == '0') {
        caretPos = field.selectionStart;
    } else {
        caretPos = -100;
    }
    return caretPos;
}

function setCaretPosition (field, pos) {
    if (pos<0) return;
    //IE support
    if (field.createTextRange) {
        var range = field.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    } else
    //Firefox support
    if (field.setSelectionRange) {
        field.focus();
        field.setSelectionRange(pos, pos);
    }
}

/* ===================================================
 *	ALGORITMOS DE DATA
 * =================================================== */
 
/*
 * Formata o campo data a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USO: onkeypress="return formatDate (this,event);"
 * OBS: NÃ£o Ã© permitido "colar" uma data.
 * OBS2: Formato: dd/mm/yyyy
 * OBS3: Nao verifica validade da data, i.e. aceita sem problemas 43/12/9870
 */
function formatarData (field, event) {

    var myfield = field.value;
    var keyCode = event.keyCode;
    var charCode = event.charCode;
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var tecla = charCode ? charCode : keyCode;
    if(document.selection) {
	    var testRange = document.selection.createRange().text;
	    if((tecla>=48 && tecla<=57) && testRange.length > 0) {
	    	return true;
	    }
    }
    else if (tecla>=48 && tecla<=57 && field.selectionStart < field.selectionEnd) {
    	return false;
    }
    
    var caretPos = getCaretPosition(field);

	if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	if (myfield.length>9) {
		return false;
	}

	if (tecla==47 || (tecla>=48 && tecla<=57)) {
		if ((tecla==47 && caretPos==2) || //
			(tecla==47 && caretPos==5)) { //tecla = '/' e cursor no lugar certo
			myfield = myfield.replace(/(\/)/g,'');
	       	myfield = myfield.substring(0,2)+(caretPos==2 ? '' : '/')+ //this line: day
	       				(myfield.length>2 ? myfield.substring(2,4)+(myfield.length>4 ? (caretPos==5 ? '' : '/') : '') : '')+ //this line: month
	       				(myfield.length>4 ? myfield.substring(4,8) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos);
	       	return true;
		} else if (tecla==47 && caretPos==1) { //tecla='/' e cursor no lugar da unidade do dia
	    	myfield = myfield.replace(/(\/)/g,'');
	       	myfield = '0'+myfield.substring(0,1)+ //this line: day
	       				(myfield.length>2 ? myfield.substring(1,3)+(myfield.length<4 ? '' : '/') : '')+ //this line: month
	       				(myfield.length>3 ? myfield.substring(3,7) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos+1);
	       	return true;
		} else if (tecla==47 && caretPos==4) { //tecla='/' e cursor no lugar da unidade do mes
	    	myfield = myfield.replace(/(\/)/g,'');
	       	myfield = myfield.substring(0,2)+'/'+ //this line: day
	       				'0'+myfield.substring(2,3)+//this line: month
	       				(myfield.length>3 ? myfield.substring(3,7) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos+1);
	       	return true;
		} else if (tecla>=48 && tecla<=57 && caretPos<myfield.length) { //cursor no meio
			var indexDay = caretPos<2 ? 1 : 2;
			var indexMonth = (caretPos<5 && caretPos>=2) || indexDay==1 ? 3 : 4;
			myfield = myfield.replace(/(\/)/g,'');
			myfield = myfield.substring(0,indexDay)+(myfield.length>indexDay ? '/' : '')+
	       				(myfield.length>=indexDay ? myfield.substring(indexDay,indexMonth)+(myfield.length>indexMonth ? '/' : '') : '')+ //this line: month
	       				(myfield.length>=indexMonth ? myfield.substring(indexMonth,7) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos==2 || caretPos==5 ? caretPos+1 : caretPos);
	       	return true;
		} else if (tecla>=48 && tecla<=57) {
			myfield = myfield.replace(/(\/)/g,'');
			myfield = myfield.substring(0,2)+(myfield.length>=2 ? '/' : '')+
	       				(myfield.length>=2 ? (myfield.length<4 ? myfield.substring(2,4) : myfield.substring(2,4)+'/') : '')+ //this line: month
	       				(myfield.length>=4 ? myfield.substring(4,8) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos+1);
	       	return true;
		}
		return false;
	}
	return false;
}

/*
 * Funcao que valida uma data para ver se eh valida
 * Separador nao importa. mas a ordem eh de dd/mm/yyyy
*/
function validarData(data) {
	if (data == undefined || data == null || data == "") { return false;
	} else {
		var day, month, year;
		// verifica o formato
//		if(!(/[dd][yy][mm]/.test(padrao))) return false;
		var datePat = /^(\d{1,2})(\/|-)(\d{2})\2(\d{4})$/i;
		var matchArray = data.match(datePat);
		if (matchArray == null) return false;
		// divide a data em variaveis
		day = matchArray[1];
		month = matchArray[3];
		year = matchArray[4];
		
		if (month < 1 || month > 12) return false;
		if (day < 1 || day > 31) return false;
		if ((month==4 || month==6 || month==9 || month==11) && day==31) return false;
		// verifica ano bissexto
		if (month == 2) {
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day>29 || (day==29 && !isleap)) return false;
		}
	}
	return true; // data valida
}

/* ===================================================
 *	ALGORITMOS DE CPF
 * =================================================== */
 
/*
 * Verifica o preenchimento de um campos de CPF
 * campo vazio eh valido
 */
function validarCPF(s) {
	if (s.length == 0) return true;

	var i;
	var c;
	x = 0;
	soma = 0;
	dig1 = 0;
	dig2 = 0;
	texto = "";
	numcpf1 = "";
	numcpf = "";

	slimp = clearSpecialChars(s);

	if (slimp.length != 11)
		return false;
	else if (slimp == '00000000000' || slimp == '11111111111' || slimp == '22222222222' || slimp == '33333333333')
		return false;
	else if (slimp == '44444444444' || slimp == '55555555555' || slimp == '66666666666')
		return false;
	else if (slimp == '77777777777' || slimp == '88888888888' || slimp == '99999999999' || slimp == '12345678909')
		return false;
	else {
		for (i = 0; i < s.length; i++) {
			c = s.substring(i,i+1);
			if (/\d/.test(c)) numcpf = numcpf + c;
		}
		if (numcpf.length != 11) {
			return false;
		}

		len = numcpf.length; x = len -1;
		for (var i=0; i <= len - 3; i++) {
			y = numcpf.substring(i,i+1);
			soma = soma + ( y * x);
			x = x - 1;
			texto = texto + y;
		}
		dig1 = 11 - (soma % 11);
		if (dig1 == 10) dig1=0;
		if (dig1 == 11) dig1=0;
		numcpf1 = numcpf.substring(0,len - 2) + dig1;
		x = 11; soma=0;
		for (var i=0; i <= len - 2; i++) {
			soma = soma + (numcpf1.substring(i,i+1) * x);
			x = x - 1;
		}
		dig2= 11 - (soma % 11);
		if (dig2 == 10) dig2=0;
		if (dig2 == 11) dig2=0;
		if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
			return true;
		}
		return false;
	}
}

/*
 * Formata o campo CPF a medida que o usuario preenche os valores
 * onKeyUp="formatarCPF(this,event);"
 */
function formatarCPF(field, event) {
	if(!(/\d/.test(field.value.substring(field.value.length-1)))){
		field.value = field.value.substring(0, field.value.length-1);
		return;
	}
	if(field.value.length > 14){
		field.value = field.value.substring(0, 14);
		return;
	}
	var campo = field;
	campo.value = filtrarCampo(campo);
	var vr = campo.value;
	tam = vr.length;
	if ( tam <= 2 ){
 		campo.value = vr ;}
	if ( tam > 2 && tam <= 5 ){
		campo.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam );}
	if ( tam >= 6 && tam <= 8 ){
		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr(tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam );}
	if ( tam >= 9 && tam <= 11 ){
		campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr(tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam );}
}
 
/* ===================================================
 *  ALGORITMOS DE CNPJ
 * =================================================== */

function vcnpj( c ) {

    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, cnpj = c.value.replace(/\D+/g, '');
    digitos_iguais = 1;
   if (cnpj.length != 14)
           {
                //alert('CNPJ inválido');
                //c.focus();
                return false;
                }

    for (i = 0; i < cnpj.length - 1; i++)
          if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                {
                digitos_iguais = 0;
                break;
                }
    if (!digitos_iguais)
          {
          tamanho = cnpj.length - 2
          numeros = cnpj.substring(0,tamanho);
          digitos = cnpj.substring(tamanho);
          soma = 0;
          pos = tamanho - 7;
          for (i = tamanho; i >= 1; i--)
                {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                      pos = 9;
                }
          resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
          if (resultado != digitos.charAt(0))
{
                //alert('CNPJ inválido');
                //c.focus();
                return false;
                }

          tamanho = tamanho + 1;
          numeros = cnpj.substring(0,tamanho);
          soma = 0;
          pos = tamanho - 7;
          for (i = tamanho; i >= 1; i--)
                {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                      pos = 9;
                }
          resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
          if (resultado != digitos.charAt(1)){
                //alert('CNPJ inválido');
                //c.focus();
                return false;
                }
          else {
    // alert('CNPJ  OK !');
           return true;
           }
          }
    else{
          //alert('CNPJ inválido');
          //c.focus();
          return false;
          }
 } 

/* ===================================================
 *	ALGORITMOS DE NUMEROS
 * =================================================== */

/*
 * Funcao para validar somente letras.
 * Valida texto inteiro
 */
function validarTexto(texto, cs){
	var reg = "[\\D]";
	if(cs == null || !cs){
		reg = reg + "i";
	}
	return new RegExp(reg).test(texto);
}

/*
* Valida se o caractere digitado é um numero;
* Forma de uso: onkeypress="return validaSomenteNumeros(event);" 
*/
function validaSomenteNumeros(event) {
    
    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;

    //alert(event.keyCode);
    //alert(event.charCode);

    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    //alert(deleteKey);
    //alert(backspaceKey);
    //alert(moveKey);
    
    if (deleteKey || backspaceKey || moveKey) 
        return true;

    var tecla = charCode ? charCode : keyCode;
    
    if(tecla>=48 && tecla<=57) {
        return true;
    }
    
    return false;
}

/*
 * Valida numeros, considera virgula e ponto como v
 */
function validarNumero(field) {
	return /\d/.test(field.value);
}

/*
 * Desformata o numero, Ã© interessante usar em conjunto com formatarNumero no onFocus
 * assim quando entrar no campo fica desformatado e quando tirar do campo formata novamente.
 * Substitui a virgula por ponto parecido com o formato americano.
 * Nao faz nada caso nao seja numero
 */
function desformatarNumero(field, evento) {
	field.value = field.value.replace(/[\.]/g, "");
	field.value = field.value.replace(/[\,]/g, ".");
	if(isNaN(field.value)) return;
}

/*
 * Formata numero, baseado no formato brasileiro, melhor usado no onBlur apÃ³s usar o desformatarNumero
 * Nao faz nada caso nao seja numero
 */
function formatarNumero(field, evento) {
	if(isNaN(field.value)) return;
	var tam = field.value.length;
	var decP = field.value.lastIndexOf(".");
	var dec = ",00";
	var aux = "";
	if(decP > -1) {
		dec = "," + field.value.substring(decP+1, tam);
		aux = field.value.substring(0, decP);
	} else {
		aux = field.value;
	}

	tam = aux.length;

	if(tam > 3){
		var max = tam - 3;
		var count = 0;
		while(max > 0) {
			aux = aux.substring(0, max) + "." + aux.substring(max, tam + count);
			count = count + 1;
			max = max - 3;
		}
	}
	field.value =  aux + dec;
}

/* ===================================================
 *	ALGORITMOS DE EMAIL
 * =================================================== */
 function validarEmail(email){
	var regexp = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
	return regexp.test(email);
}
 /* ===================================================
  *	ALGORITMOS DE CALENDARIO
  * ===================================================
  * exemplo da chamada: calendario(inputField,format,buttonObj)
  * inputField = campo que tiver a data que quiser inicializar o calendario, e onde mostrara a data selecionada no calendario geralmente setada a do dia atual.
  * format = pattern  ex: yyyy/mm/dd
  * buttonObj = botao que ao clicado aparecera o calendario 
  */
 
 function calendario(inputField,format,buttonObj){
	 return displayCalendar(inputField,format,buttonObj);
 }
 
 function teste() {
	 alert('teste');
}

/*===================================================
  * ALGORITMOS DE STRINGS
  * ==================================================
  * validações básicas com strings.
  * 
  * 
 */
 /*verifica se a String passada contém números
 Esta função recebe um string e devolve 1 se se encontram caracteres numéricos e 0 se não se encontram.*/ 
 function tem_numeros(texto){
    var numeros="0123456789";
    for(i=0; i<texto.length; i++){
       if (numeros.indexOf(texto.charAt(i),0)!=-1){
          return 1;
       }
    }
    return 0;
 }
 
 //saber se um string contém um caractere que seja letra, valendo tanto as maiúsculas como minúsculas 
 function tem_letras(texto){
    var letras="abcdefghyjklmnopqrstuvwxyz"; 
    texto = texto.toLowerCase();
    for(i=0; i<texto.length; i++){
       if (letras.indexOf(texto.charAt(i),0)!=-1){
          return 1;
       }
    }
    return 0;
 }
 
 //saber se um string tem caracteres em minúsculas.
 function tem_minusculas(texto){
  var letras="abcdefghyjklmnopqrstuvwxyz"; 
    for(i=0; i<texto.length; i++){
       if (letras.indexOf(texto.charAt(i),0)!=-1){
          return 1;
       }
    }
    return 0;
 }
 
 //saber se um string tem letras maiúsculas.
 function tem_maiusculas(texto){
  var letras_mayusculas="ABCDEFGHYJKLMNOPQRSTUVWXYZ";    
    for(i=0; i<texto.length; i++){  
      if (letras_maiusculas.indexOf(texto.charAt(i),0)!=-1){
          return 1;
       }
    }
    return 0;
 }


/* ===================================================
 * ALGORITMOS DE MOEDA
 * ===================================================
 * Formata campos de valor monetario a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USAGE: onkeypress="return formatMoney (this,event);"
 */
function formatMoney (field, event) {

    var myfield = field.value;

    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var caretPos = getCaretPosition(field);

    if (deleteKey || backspaceKey || moveKey) {
        return true;
    }
    
    if (myfield.length>10) {
        return false;
    }

    var tecla = charCode ? charCode : keyCode;
    if(document.selection) {
 
        var testRange = document.selection.createRange().text;
        if((tecla>=48 && tecla<=57) && testRange.length > 0) {
            return true;
        }
    }
    else if ((tecla>=48 && tecla<=57) && field.selectionStart < field.selectionEnd) {
        return true;
    }

    if (tecla==44 || (tecla>=48 && tecla<=57)) {
        if (tecla==44 && myfield.replace(/\d/g,'').length==0 && myfield.length>0) {
            return true;
        } else if ((tecla>=48 && tecla<=57) && 
                   (myfield.length-(myfield.lastIndexOf(',')!=-1?myfield.lastIndexOf(','):100)<=2)) {
            return true;
        } else if ((tecla>=48 && tecla<=57) &&
                   (myfield.lastIndexOf(',')==-1 || caretPos<(myfield.lastIndexOf(',')+1))) {
            return true;
        }
        return false;
    }
    return false;
}

function blurDecPlaces (field, decplaces) {

    if(field.value != ""){
        var value = ''+toDotString(field.value);
        var end;
        if (value.replace(/[\.\,]/g,'').length==0) {
            field.value = '';
            return;
        }
        if (decplaces>=0) {
            var str = "" + Math.round (eval(value)*Math.pow(10,decplaces));
            while (str.length<=decplaces){
                str = "0"+str;
            }
            var decpoint = str.length - decplaces;
            if (decplaces<=0){
                end = str.substring(0,decpoint);
            } else {
                end = str.substring(0,decpoint)+","+str.substring(decpoint,str.length);
            }
        } else {
            end = value;
        }
        field.value = end;
    }
}   

function blurDecPlacesEmpty (field, decplaces) {
    
    if (field.value != "") {
        var value = '' + toDotString(field.value);
        var end;
        if (value.replace(/[\.\,]/g, '').length == 0) {
            field.value = '';
            return;
        }
        if (decplaces >= 0) {
            var str = "" + Math.round(eval(value) * Math.pow(10, decplaces));
            while (str.length <= decplaces) {
                str = "0" + str;
            }
            var decpoint = str.length - decplaces;
            if (decplaces <= 0) {
                end = str.substring(0, decpoint);
            }
            else {
                end = str.substring(0, decpoint) + "," + str.substring(decpoint, str.length);
            }
        }
        else {
            end = value;
        }
        field.value = end;
    }
}   

function toDotString (value) { //Muda um valor para somente um ponto (toFloat)

    var num = value.toString();
    var commas = /\,/g;
    num = num.replace(commas,"\.");

    var fim = "";
    if (num.lastIndexOf(".")>=0) {
        var substart = num.substr(0, num.lastIndexOf("."));
        var subend = num.substr(num.lastIndexOf("."),num.length);
        var dots = /\./g;
        substart = substart.replace(dots,"");
        fim = ""+substart+subend;
    } else {
        fim = num;
    }   
    return fim*1;
}

function toCommaString (value) { //Muda o valor para somente uma virgula (money)
    
    var num = value.toString();
    var dots = /\./g;
    num = num.replace(dots,"\,");

    var fim = "";
    if (num.lastIndexOf(",")>=0) {
        var substart = num.substr(0, num.lastIndexOf(","));
        var subend = num.substr(num.lastIndexOf(","),num.length);
        var commas = /\,/g
        substart = substart.replace(commas,"");
        fim = ""+substart+subend;
    } else {
        fim = num;
    }
    
    return fim;
}

//Recebe um campo e, caso esteja vazio, preenche com zeros
function zeroSeVazio(campo, intReal){
    if (campo.value == ''){
        if (intReal == 'int')
            document.getElementById(campo.id).value = '0'
        else
            document.getElementById(campo.id).value = '0,00';
    }
}
