var r='/admin/';
$(document).ready(function() {
    $("#msn-alert").css("display", "block");
    setTimeout(function(){$("#msn-alert").css("display", "none");}, 15000);
    var con=0;
    function numsn(){
        $.ajax({
            type: "POST",
            url: r+"pedido/alert-pedido.php",
            dataType: 'JSON',
            success: function(response){
            var len = response.length;
            for(var i=0; i<len; i++){
                var text = response[i].txtmsn;
                var num = response[i].numsn;
                $('#txtmsn').html(text);
                $('#txtmsn2').html(text);
                $('#numsn').html(num);
                $('#numsn2').html(num);
            }}
        });
    }

    setInterval(numsn, 30000);
    $('#departamento').on('change', function() {
        var id = $(this).val();
        $.ajax({
                url: r+'pais/municipios.php' ,
                type: "post",
                dataType: 'html',
                 data: { 'id':id},
	            success: function(data){}
        }).done(function(response) {
            $('#ciudad').html(response).slideDown(400);
            $('#localidad').html('').slideDown(400);
            $('#zona').html('').slideDown(400);
        });
    });
    $('#ciudad').on('change', function() {
        var id = $(this).val();
        $('#localidad').trigger("reset");
        $('#zona').trigger("reset");
       $.ajax({
                url: r+'pais/localidad.php' ,
                type: "post",
                dataType: 'html',
                 data: { 'id':id},
	            success: function(data){}
        }).done(function(response) {
            $('#localidad').html(response).slideDown(400);
            $('#zona').html('').slideDown(400);
        });
    });
    $('#localidad').on('change', function() {
        var id = $(this).val();
        $('#zona').trigger("reset");
       $.ajax({
                url: r+'pais/zonas.php' ,
                type: "post",
                dataType: 'html',
                 data: { 'id':id},
	            success: function(data){}
        }).done(function(response) {
            $('#zona').html(response).slideDown(400);
        });
    });
    
    $('#producto').on('change', function() {
        var id = $(this).val();
        $.ajax({
                url: r+'pedido/unidad.php' ,
                type: "post",
                dataType: 'JSON',
                 data: { 'id':id},
	            success: function(data){}
        }).done(function(response) {
                var und = response.unidad;
                var pre = response.precio;
                var present = response.present;
            $('select[name=present]').val(und);
            $('select[name=present]').trigger("chosen:updated");
            $( "input[name=precio]" ).val(pre);
            $( "input[name=precio]" ).focus().select();
            if(present<1){
                $( "#unidad" ).html(present+' KG');
            }else{
                $( "#unidad" ).html(Math.trunc(present)+' KG');
            }
        });
    });
    $('select[name=present]').on('change', function() {
        var id = $(this).val();
        $.ajax({
                url: r+'pedido/present.php' ,
                type: "post",
                dataType: 'JSON',
                 data: { 'idpresent':id},
	            success: function(data){}
        }).done(function(response) {
                var cantidad = response.cantidad;
                var unidad = response.unidad;
            $( "input[name=precio]" ).focus().select();
            if(cantidad<1){
                $( "#unidad" ).html(cantidad+' '+unidad);
            }else{
                $( "#unidad" ).html(Math.trunc(cantidad)+' '+unidad);
            }
        });
    });
});
  
$(document).ready(function() {
     // Formulario Jovenes
    var formularios = $('#formulario');
    var mensage = $('#msn-alert');
    $(formularios).submit(function(f) {
        $(mensage).slideUp(750);
        $(mensage).hide();
        f.preventDefault();
        var action = $(this).attr('action');
        var type = $(this).attr('method');
        var form = $(this);
        var formdata = false;
        if (window.FormData){
            formdata = new FormData(form[0]);
        }
        $.ajax({
            url: action,
            type: type,
        data        : formdata ? formdata : form.serialize(),
        cache       : false,
        contentType : false,
        processData : false,
	    success     : function(data, textStatus, jqXHR){
                    if (data.match('.php') != null){window.location.replace(data);}
	        }
        }).done(function(response) {
            $(mensage).html(response).slideDown(400);
            setTimeout(function(){$(mensage).html(this).slideUp(700);}, 5000);
        });
    });
    
    
    
    
    var formularios = $('#gasto');
    var mensage = $('#msn-alert');
    $("#gasto").on("submit", function() {
     var action = $(this).attr('action');
     
        f.preventDefault();
    $.ajax({
        url: action, // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data:  new FormData(this),
        type: "POST",
        success: function(data){
                    if (data.match('.php') != null){window.location.replace(data);}
	        }
        }).done(function(response) {
            $(mensage).html(response).slideDown(400);
            setTimeout(function(){$(mensage).html(this).slideUp(700);}, 5000);
        });
     });
});

// Codigo ajax formulario 
var total = 0;
var totid = 0;
var array = ['0'];
var id = '';
var pro = '';
var pre = '';
var can = '';
var bod = '';
jQuery(document).ready(function() {
    $("#anadir").on("submit", function(e){
        var idcliente= $('select[name=cliente]').val();
        var textpre= $('select[name=present] option:selected').text();
        var valpre= $('select[name=present]').val();
        var produ= $('div#producto_chosen a.chosen-single span').text();
        var pre=$("#precio").val();
        e.preventDefault();
        var formData = $(this).serialize();
        var action = $(this).attr('action');
        $.ajax({
            type: "POST",
            url: r+"pedido/producto.php",
            dataType: 'JSON',
            data: formData+'&idcliente='+idcliente,
            success: function(response){
                var len = response.length;
                for(var i=0; i<len; i++){
                    var id = response[i].rid;
                    var pro = response[i].rpro;
                    var can = response[i].rcan;
                    var iva = response[i].riva;
                    var bod = response[i].rbod;
                    var totid = response[i].rtotid;
                    if(parseInt(bod)<=parseInt(can)){
                        $("#mesage").html('<div class="alert alert-success padding" role="alert" style="background:#00ff3d;color:#dc3545"><strong>NO HAY EXISTENCIA SUFICIENTE, solo hay '+bod+' paquetes!</strong></div>').slideDown(400);
                         
                        }
                    else{
                    var idunico = id+valpre;
                    if (array.includes(idunico) != true) {
                        array.push(idunico);
                        console.log(array)
                        var tr_str = '<tr id="trow'+idunico+'">' +
                        '<td><input type="hidden" value="' + idunico + '" name="iden'+idunico+'"/><input type="hidden" value="' + id + '" name="cod'+idunico+'"/>' + pro + '</td>' +
                        '<td><input type="hidden" value="' + can + '" name="cant'+idunico+'"/>' + can + ' ' +textpre + '<input type="hidden" value="' + valpre + '" name="tipo'+idunico+'"/></td>'+
                        '<td><input  type="hidden" value="' + pre + '" name="prec'+idunico+'"/>' + moneda(pre) + '</td>' +
                        '<td><input type="hidden" value="' + iva + '" name="iva'+idunico+'"/>' + moneda(totid) + '</td>' +
                        '<td><a  title="Borrar" onclick="EliminarFila('+ totid + ',' + idunico + ');"><i class="fa text-danger fa-trash fa-2x fa-lg"></i></a></td>' +
                        '</tr>';
                        $("#tabla").append(tr_str);
                        total = total+totid;
                        $("#total").html(total);
                         $("#nada").remove();
                         
                    }else{
                        $("#mesage").html('<div class="alert alert-success padding" role="alert">Este Articulo Ya se Encentra A&ntilde;adido!</div>').slideDown(400);
                        
                    }
                }}
                $('#anadir')[0].reset();
                $('#producto').trigger("chosen:updated");
                $('#present').trigger("chosen:updated");
            }
            });setTimeout(function(){$("#mesage").html(this).slideUp(700);
                         }, 3000);
    });
    $('#cliente').on('change', function() {
        var formData = $(this).serialize();
        $.ajax({
            type: "POST",
            url: r+"pedido/anterior.php",
            dataType: 'JSON',
            data: formData,
            success: function(response){
                var memori = response.length;
                for(var i=0; i<memori; i++){
                    var boton = response[i].rbtn;
                    var modal = response[i].rmodal;
                    var code = response[i].rcode;
                }
                $("#pedanterior").html(boton);
                $("#memoria").html(modal);
                $("#code").html(code);
                $("#btnagregar").removeClass( "d-none" ).addClass( "btn-block " );
            }
        });
    });
});
// Codigo ajax formulario 
var total2 = 0;
var totid2 = 0;
var array2 = ['0'];
var id = '';
var pro = '';
var pre = '';
var can = '';
var bod = '';
jQuery(document).ready(function() {
    $("#anadir2").on("submit", function(e){
        var idcliente=document.getElementById("cliente").value;
        var pre=document.getElementById("precio").value;
        e.preventDefault();
        var formData = $(this).serialize();
        var action = $(this).attr('action');
        $.ajax({
            type: "POST",
            url: r+"pedido/producto2.php",
            dataType: 'JSON',
            data: formData+'&idcliente='+idcliente,
            success: function(response){
                var len = response.length;
                for(var i=0; i<len; i++){
                    var id = response[i].rid;
                    var pro = response[i].rpro;
                    var can = response[i].rcan;
                    var iva = response[i].riva;
                    var bod = response[i].rbod;
                    var totid2 = response[i].rtotid;
                    if(bod<=can){
                        $("#mesage").html('<div class="alert alert-success padding" role="alert" style="background:#00ff3d;color:#dc3545"><strong>NO HAY EXISTENCIA SUFICIENTE, solo hay '+bod+' paquetes!</strong></div>').slideDown(400);
                         
                        }
                    else{
                    if (array2.indexOf(id) === -1) {
                        array2.push(id);
                        var tr_str = '<tr id="trow'+id+'">' +
                        '<td><input type="hidden" value="' + id + '" name="iden'+id+'"/>' + pro + '</td>' +
                        '<td><input type="hidden" value="' + can + '" name="cant'+id+'"/>' + can + '</td>' +
                        '<td><input  type="hidden" value="' + pre + '" name="prec'+id+'"/>' + moneda(pre) + '</td>' +
                        '<td><input type="hidden" value="' + iva + '" name="iva'+id+'"/>' + moneda(totid2) + '</td>' +
                        '<td><a  title="Borrar" onclick="EliminarFila('+ totid2 + ',' + id + ');"><i class="fa text-danger fa-trash fa-2x fa-lg"></i></a></td>' +
                        '</tr>';
                        $("#tabla").append(tr_str);
                        total2 = total2+totid2;
                        $("#total2").html(total2);
                         $("#nada").remove();
                         document.getElementById("producto").value='';
                         document.getElementById("cantidad").value='';
                         document.getElementById("precio").value='';
                    } else if (array2.indexOf(id) > -1) {
                        $("#mesage").html('<div class="alert alert-success padding" role="alert">Este Articulo Ya se Encentra en el Inventario!</div>').slideDown(400);
                        
                    }
                }}$('#anadir')[0].reset();   }
            });setTimeout(function(){$("#mesage").html(this).slideUp(700);
                         }, 3000);
    });
});
 function moneda(precio){
     var valor = precio.toLocaleString('es-CO', {
      style: 'currency',
      currency: 'COP',
      maximumFractionDigits: 0,
    });
     return '$ '+valor+' COP';
 }