function redirect(location)
{
    window.location = location;
}

function sendForm(form)
{
    document.getElementById(form).submit();
}


function sendFormAjax(form, divReturn)
{

    var options = {
        target: '#'+divReturn,   // Qual Elemento será atualizado com a Requisição
        url: form.action, // Destino das Informações do Formulário
        type: form.method, // Método utilizado na requisição
        beforeSubmit:  beforeAjaxSubmit,  // pre-submit callback
        success:       callbackAjaxSubmit  // post-submit callback
    };
    $('#'+form).ajaxSubmit(options);
    return false; // Para que o Formulário não seja enviado naturalmente
}

function replaceAll(str, de, para){
    var pos = str.indexOf(de);
    while (pos > -1){
        str = str.replace(de, para);
        pos = str.indexOf(de);
    }
    return (str);
}

function sendRequestAjaxHistory(vUrl, vData, divReturn, method){
    vData = replaceAll(vData,"undefined","");

    $.ajax({
        type: method,
        url: vUrl,
        data: vData,
        beforeSend: function(){
            beforeAjaxSubmit();
        },
        success: function(txt) {
            callbackAjaxSubmit();
            $('#'+divReturn).html(txt);
        },
        error: function(){
            alert('erro');
        }
    });
}

function sendRequestAjax(vUrl, vData, divReturn, method){
    vData = replaceAll(vData,"undefined","");

    //  HistoryDriver.addFunction('sendRequestAjaxHistory(\''+  vUrl + '\', \''+vData+'\', \''+divReturn+'\', \''+method+'\');');

    //alert(vData);
    
    $.ajax({
        type: method,
        url: vUrl,
        data: vData,
        beforeSend: function(){
            beforeAjaxSubmit();
        },
        success: function(txt) {
            callbackAjaxSubmit();
            $('#'+divReturn).html(txt);
        },
        error: function(){            
            alert('erro');
        }
    });
}


/* Antes de uma chamada Ajax executa */
function beforeAjaxSubmit() {
    $("#loadingAjax").css("display", "block");
}

/* Apos uma chamada Ajax executa */
function callbackAjaxSubmit(){
    $("#loadingAjax").css("display", "none");
}



/* Auxiliar no cadastro de Produtos */
function changeComboModelos(){
    $('#resultSearchProdutos').html();
    sendRequestAjax("produtos.php", "action=populaComboBusca&do=modelo&actionPedidos="+$('#actionPedidos').val()+"&lastIdPedidos="+$('#lastIdPedidosCad').val()+"&searchValue="+$('#searchMarcaProduto').val()+"&searchValue2="+$('#searchAplicacaoProduto').val(), "modeloComboBox", "post");
}

/* Auxiliar no cadastro de Produtos */
function changeComboProdutos(){
    $('#resultSearchProdutos').html();
    sendRequestAjax('produtos.php', 'action=populaComboBusca&do=produto&actionPedidos='+$('#actionPedidos').val()+'&lastIdPedidos='+$('#lastIdPedidosCad').val()+'&searchValue='+$('#searchMarcaProduto').val()+'&searchValue2='+$('#searchAplicacaoProduto').val()+'&searchValue3='+$('#searchModeloProduto').val(), 'resultSearchProdutos', 'post');
}





/* Validação do cadastro de Pedidos */
function validateCadPedidos(key){  
	
    if($("#codClient").val() == ""){
        alert("Campo Cliente Obrigat\u00f3rio!");
        $("#codClient").focus();
        return false;
    }
    if($("#nmClient").val() == ""){
        alert("Campo Cliente Obrigat\u00f3rio!");
        $("#nmClient").focus();
        return false;
    }

    if($("#pedido_cliente").val() == ""){
        alert("Campo Pedido Obrigat\u00f3rio!");
        $("#pedido_cliente").focus();
        return false;
    }

    var SpgtoVista = true;
    with(document.formCadPedido){
        for(var i = 0; i < pgtoVista.length; i++){
            if( pgtoVista[i].checked){
                SpgtoVista = false;
                break;
            }
        }
        if(SpgtoVista){
            alert("Campo Pagamento a Vista Obrigat\u00f3rio!");
            return false;
        }
        }

    var SpgtoAnte = true;
    with(document.formCadPedido){
        for(var i = 0; i < pgtoAnte.length; i++ ){
            if(pgtoAnte[i].checked){
                SpgtoAnte = false;
                break;
            }
        }
        if(SpgtoAnte){
            alert("Campo Pagamento Antecipado Obrigat\u00f3rio!");
            return false;
        }
        }

    if($("#dtEntregaCli").val() == ""){
        alert("Campo Data de Entrega Cliente Obrigat\u00f3rio!");
        $("#dtEntregaCli").focus();
        return false;
    }

    var Sfrete = true;
    with(document.formCadPedido){
        for(var i = 0; i < frete.length; i++ ){
            if(frete[i].checked){
                Sfrete = false;
                var freteSel = frete[i].value;
                break;
            }
        }
        if(Sfrete){
            alert("Campo Frete Obrigat\u00f3rio!");
            return false;
        }
        }
	
    if ($("input[name=frete]:checked").val() == 1) {
        if($("#trasportadora").val() == ""){
            alert("Campo Trasportadora Obrigat\u00f3rio!");
            $("#trasportadora").focus();
            return false;
        }
    }	
	
	

    var divUpdate = "";
    if(key == 'addProd'){
        document.getElementById('actionProd').value = "addProd";
        //        divUpdate = "miolo";
        divUpdate = "cadItensPedido";
    }
    else{
        document.getElementById('actionProd').value = "atualiza";
        divUpdate = "refreshMiolo";
    //        divUpdate = "cadItensPedido";
    }

    sendFormAjax('formCadPedido', divUpdate);
    return true;
}



/* Auxiliar no cadastro de Clientes */
function controlLivreComCliente(key){

    if(key == "S"){
        $("#isentIPIS").attr("checked", true);
        $("#isentICMSS").attr("checked", true);
        $("#descSuframaS").attr("checked", true);
        $("#isentIPIS").attr("readonly", true);
        $("#isentIPIN").attr("readonly", true);
        $("#isentICMSS").attr("readonly", true);
        $("#isentICMSN").attr("readonly", true);
        $("#descSuframaS").attr("readonly", true);
        $("#descSuframaN").attr("readonly", true);
    }
    if(key == "N"){
        $("#isentIPIS").attr("readonly", false);
        $("#isentIPIN").attr("readonly", false);
        $("#isentICMSS").attr("readonly", false);
        $("#isentICMSN").attr("readonly", false);
        $("#descSuframaS").attr("readonly", false);
        $("#descSuframaN").attr("readonly", false);
    }

}
/* Auxiliar no cadastro de Clientes */
function controlTipoPessoaCliente(){

    if($("#tipoPessoa").val() == "F"){
        $("#cnpj").attr("readonly", true);
        $("#inscricaoEstadual").attr("readonly", true);
        $("#cpf").attr("readonly", false);
        $("#rg").attr("readonly", false);
    }
    else{
        $("#cpf").attr("readonly", true);
        $("#rg").attr("readonly", true);
        $("#cnpj").attr("readonly", false);
        $("#inscricaoEstadual").attr("readonly", false);
    }
}

/* Remove completamente todos os caracteres especiais, acentos e espa?os*/
function removeEspecialChar(o,w){
    var r={
        'special':/[\W]/g,
        'quotes':/['\''&'\"']/g,
        'notnumbers':/[^\d]/g
    }

//    o.value = o.value.replace(r[w],'');
}

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){
            return true;
        }
    }
    else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
            return true;
        }
    }else{
        return false;
    }
}


/* Controle das Paginacoes */
function minusPage(){

    if($("#iniResult").val() == 0){
        $("#iniResult").val(0);
    }
    else{
        $("#iniResult").val($("#iniResult").val() - 25);
    }
}

/* Controle das Paginacoes */
function sumPage(){

    if($("#countResult").val() >= 25){
        $("#iniResult").val(parseInt($("#iniResult").val()) + 25);
    }
}

function hideDIV(divId) {
    $('#' + divId).hide();
}


function Pessoa(tipoPessoa){

    if(tipoPessoa == 'Juridica'){
		
        document.getElementById('inscestJ').style.display = 'table-row';
        document.getElementById('razaoJ').style.display = 'table-row';
        document.getElementById('nomeJ').style.display = 'table-row';
        document.getElementById('rgF').style.display = 'none';
        document.getElementById('nomeF').style.display = 'none';
		
        $(".tipoPessoa").attr({
            "name":"cnpj"
        });
    }	
    else {
		
        document.getElementById('inscestJ').style.display = 'none';
        document.getElementById('razaoJ').style.display = 'none';
        document.getElementById('nomeJ').style.display = 'none';
        document.getElementById('rgF').style.display = 'table-row';
        document.getElementById('nomeF').style.display = 'table-row';
		
        $(".tipoPessoa").attr({
            "name":"cpf"
        });
    }
}

function validateContato(){
    if($("#nome").val() == ""){
        alert("Campo Nome Obrigat\u00f3rio!");
        $("#nome").focus();
        return false;
    }
    if($("#endereco").val() == ""){
        alert("Campo Endere\u00E7o Obrigat\u00f3rio!");
        $("#endereco").focus();
        return false;
    }
    if($("#cidade").val() == ""){
        alert("Campo Cidade Obrigat\u00f3rio!");
        $("#cidade").focus();
        return false;
    }
    if($("#cep").val() == ""){
        alert("Campo C.E.P. Obrigat\u00f3rio!");
        $("#cep").focus();
        return false;
    }
    if($("#email").val() == ""){
        alert("Campo E-Mail Obrigat\u00f3rio!");
        $("#email").focus();
        return false;
    }
    else{
        if(!checkMail($("#email").val())){
            alert("Email Inv\u00e1lido");
            $("#email").focus();
            return false;
        }
    }
    if($("#telefone").val() == ""){
        alert("Campo Telefone Obrigat\u00f3rio!");
        $("#telefone").focus();
        return false;
    }
    if($("#assunto").val() == ""){
        alert("Campo Assunto Obrigat\u00f3rio!");
        $("#assunto").focus();
        return false;
    }
    if($("#mensagem").val() == ""){
        alert("Campo Mensagem Obrigat\u00f3rio!");
        $("#mensagem").focus();
        return false;
    }
    //var txt = document.createTextNode(" This text was added to the DIV.");
    //document.getElementById('MsgSent').appendChild(txt);
	
	
    sendFormAjax('frmContato', 'MsgSent');
    
    return true;
	
}

$(document).ready(function(){
    $(".utilizarInformacoesDeCadastro").click(function(){
        if (confirm("Atenção, nosso sistema irá começar um processo de verificação de suas informações pessoais \n\nDeseja continuar ?")) {
            console.log(this);
        }
        return false;
    });
});
