//função para colocar um texto padrão em algum campo texto de formulário
//quando o usuário não estiver com o foco no o texto é retirado
function textoPadraoInput( object, texto ){
    
    
    object.focus(function(){
        
        valor_campo = object.val();
        
        if( valor_campo == texto ){
            object.val("").css("font-style","normal");
        }        

    });

    
    object.blur(function(){
        valor_campo = object.val();

        if( valor_campo == "" ){
            $(this).val(texto).css("font-style","normal");
        }

    });  
}

//funcao para autocomplete das combos
(function( $ ) {
    $.widget( "ui.combobox", {
        _create: function() {
            var self = this;                
            var select = this.element,
               theWidth = select.width(),                  
               selected = select.children( ":selected" ),
               value = selected.val() ? selected.text() : "";                  
            select.hide();
            var input = $( "<input style=\"width:" + 150 + "px\">" )
                .val( value )
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: function( request, response ) {
                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                        response( select.children( "option" ).map(function() {
                            var text = $( this ).text();
                            if ( this.value && ( !request.term || matcher.test(text) ) )
                                return {
                                    label: text.replace(
                                        new RegExp(
                                            "(?![^&;]+;)(?!<[^<>]*)(" +
                                            $.ui.autocomplete.escapeRegex(request.term) +
                                            ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                        ), "<strong>$1</strong>" ),
                                    value: text,
                                    option: this
                                };
                        }) );
                    },
                    select: function( event, ui ) {
                        ui.item.option.selected = true;
                        self._trigger( "selected", event, {
                            item: ui.item.option
                        });
                    },
                    change: function( event, ui ) {
                        if ( !ui.item ) {
                            var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                                valid = false;
                            select.children( "option" ).each(function() {
                                if ( this.value.match( matcher ) ) {
                                    this.selected = valid = true;
                                    return false;
                                }
                            });
                            if ( !valid ) {
                                // remove invalid value, as it didn't match anything
                                $( this ).val( "" );
                                select.val( "" );
                                return false;
                            }
                        }
                    }
                })
                .addClass( "ui-widget ui-widget-content ui-corner-left" );
                var span = $("<span style=\" white-space: nowrap;\"></span>")
                .append(input).insertAfter( select );
            
            input.data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.label + "</a>" )
                    .appendTo( ul );
            };

            $("<div class='botao'>&nbsp;</div>")
                .attr( "tabIndex", -1 )
                .attr( "title", "Show All Items" )
                .insertAfter( input )
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s"
                    },
                    text: false
                })
                .removeClass( "ui-corner-all" )
                .addClass( "ui-corner-right ui-button-icon" )
                .click(function() {
                    // close if already visible
                    if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                        input.autocomplete( "close" );
                        return;
                    }

                    // pass empty string as value to search for, displaying all results
                    input.autocomplete( "search", "" );
                    input.focus();
                });
        }
    });
})( jQuery );

function updateTips( t ) {
    var tips = $( ".validateTips" );
    tips.text( t ).addClass( "ui-state-highlight" );

    setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
    }, 500 );
}

function checkLength( o, n, min, max ) {
    if ( o.val().length > max || o.val().length < min ) {
        o.addClass( "ui-state-error" );
        updateTips( "Tamanho do " + n + " deve ter entre " + min + " e " + max + " caracteres." );
        return false;
    } else {
        o.removeClass( "ui-state-error" );
        return true;
    }
}

function checkRegexp( o, regexp, n ) {
    if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
    } else {
        o.removeClass( "ui-state-error" );
        return true;
    }
}
function replaceAll(d, c, a) {
	var b = d;
	while (b.indexOf(c) > -1) {
		b = b.replace(c, a);
	}
	return b;
}

//testar
function validaCNPJ(b) {
	var a = b;

	a = replaceAll(replaceAll(replaceAll(a, ".", ""), "-", ""), "/", "");
	if (a.length < 14) {
		return false;
	}
	CNPJ1 = a.substr(0, 12);
	CNPJ2 = a.substr(12, 2);
	Mult = "543298765432";
	Controle = "";
	Digito = 0;
	for (j = 1; j <= 2; j++) {
		Soma = 0;
		for (i = 0; i <= 11; i++) {
			Soma = Soma + (parseInt(CNPJ1.substr(i, 1)) * parseInt(Mult.substr(i, 1)));
		}
		if (j == 2) {
			Soma = Soma + (2 * Digito);
		}
		Digito = (parseInt(Soma) * 10) % 11;
		if (Digito == 10) {
			Digito = 0;
		}
		Controle = Controle + Digito.toString();
		Mult = "654329876543";
	}
	if (Controle != CNPJ2) {
		return false;
	}
	return true;
}


function validarcpf(e) {
	   var cpf = e;
	   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	   
	   if(!filtro.test(cpf)){
	    // window.alert("CPF inválido. Tente novamente.");
		 return false;
	   }
	   
	   cpf = replaceAll(cpf, ".", "");
	   cpf = replaceAll(cpf, "-", "");
	    
	   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
		  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
		  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
		  cpf == "88888888888" || cpf == "99999999999"){
		  //window.alert("CPF inválido. Tente novamente.");
		  return false;
	   }

	   soma = 0;
	   for(i = 0; i < 9; i++)
	   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
	   resto = 11 - (soma % 11);
	   if(resto == 10 || resto == 11)
		 resto = 0;
	   if(resto != parseInt(cpf.charAt(9))){
		 //window.alert("CPF inválido. Tente novamente.");
		 return false;
	   }
	   soma = 0;
	   for(i = 0; i < 10; i ++)
		 soma += parseInt(cpf.charAt(i)) * (11 - i);
	   resto = 11 - (soma % 11);
	   if(resto == 10 || resto == 11)
		 resto = 0;
	   if(resto != parseInt(cpf.charAt(10))){
	    // window.alert("CPF inválido. Tente novamente.");
		 return false;
	   }
	   return true;
	 }

function VerifyCNPJ(a) {
	a = a.replace(/\D/g, "");
	if (parseInt(a) == 0) {
		return false;
	} else {
		g = a.length - 2;
		if (RealTestaCNPJ(a, g) == 1) {
			g = a.length - 1;
			if (RealTestaCNPJ(a, g) == 1) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}

//função para validação de email
function validarEmail( email ){
	
	if ((email.length != 0) && ((email.indexOf("@") < 1) || (email.indexOf('.') < 7)))
	{
	    return false;
	}
	return true;
}


//impede o click nos navegadores
document.onkeypress = rejeitaTecla;
document.onkeydown = rejeitaTecla;
document.oncontextmenu = alerta;

function alerta(){
	jAlert('Conteúdo do site bloqueado', 'Você não pode executar esta ação.');
	return false;
}

function rejeitaTecla(oEvent){
    var oEvent = oEvent ? oEvent : window.event;
	var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which;
	
	if(oEvent.ctrlKey && tecla == 67){ //ctrl + C
		alerta();
		tecla = 0;
		oEvent.returnValue = false;
	}
	if(oEvent.ctrlKey && tecla == 86){ //ctrl + V
		alerta();
		tecla = 0;
		oEvent.returnValue = false;
	}
}
