﻿var arrplan;
var c_rows;
var oTable;
var corrle = 0;
var vlObs;
var t_documento=0;
var t_efectivo = 0;
var t_total = 0;
var aTrs;
$(document).ready(function() {
    $('#txtfechavoucher').datepick({ showOn: 'button',
        buttonImageOnly: true, buttonImage: 'images/calendar.gif'
    });
    $('#txtfechacirugia').datepick({ showOn: 'button',
        buttonImageOnly: true, buttonImage: 'images/calendar.gif'
    });
    $('#txtfechadocumento').datepick({ showOn: 'button',
        buttonImageOnly: true, buttonImage: 'images/calendar.gif'
    });
    $("#btnnewdocumento").click(function(ev) {
        AddListado();
    });
    GetBancos();
    GetSucursal();
    GetMedicos();
    GetCentros();
    GetTipoDocumento();
    GetComuna();
    $("#slscentros").change(GetDetalleCentros);
    $("#btnAddVoucher").click(function(ev) {
        AddVoucher();
    });
    $("#btnBack").click(function(ev) {
        $("#divmenuvoucher").show();
        $("#divcrearvoucher").hide();
        $("#col-one").hide();
        $("#divconsultaVoucher").hide();
    });
    oTable = $('#tablelistadodocumentos').dataTable({
        "aoColumns": [
            { "bSortable": false, "sType": "numeric", "bSearchable": true },
            { "bSortable": false, "sType": "numeric", "bSearchable": true },
            { "bSortable": false, "sType": "numeric", "bSearchable": true },
            { sWidth: '100px', "bSortable": false },
            { sWidth: '100px', "bSortable": false },
            { sWidth: '100px', "bSortable": false },
            { sWidth: '150px', "bSortable": false },
            { sWidth: '100px', "bSortable": false },
            { sWidth: '50px' }

            ],
        "aaSorting": [[0, 'desc']],
        "bPaginate": false,
        "bFilter": false,
        "bAutoWidth": false,
        "bLengthChange": false,
        "sPaginationType": "full_numbers",
        "bJQueryUI": true


    });
    oTable.fnSetColumnVis(0, false);
    oTable.fnSetColumnVis(1, false);
    oTable.fnSetColumnVis(2, false);
    oTable.fnClearTable(0);
    GetIdSession();
    $("#txtrutcliente").Rut({
        digito_verificador: '#txtdigito_verificador',
        format_on: 'change',
        format: false,
        on_error: function() { jAlert('rut del cliente es incorrecto', 'Voucher', ''); $("#txtrutcliente").val(''); $("[id$=txtdigito_verificador]").val(''); $("#txtrutcliente").focus(); }
    });
    $("#txttotaldocumento").val(t_documento);
    $("#txttotalefectivo").val(t_efectivo);
    $("#txttotalvoucher").val(t_total);

    $("#txtpagoefectivo").val('0');

    $("#btncalcularefectivo").click(function(e) {
        if ($("#txtpagoefectivo").val() != '') {
            t_efectivo = parseInt($("#txtpagoefectivo").val());
            $("#txttotalefectivo").val(t_efectivo);
            SumaTotales();
        } else {
            jAlert('Por favor ingreso un numero mayor o igual a cero', 'Voucher', '');
        }
    });

    $("#txtdigito_verificador").blur(function(e) {
        VerificacionCliente();
    });

    $("#txttotalvoucher").attr("disabled", true);
    $("#txttotalefectivo").attr("disabled", true);
    $("#txttotaldocumento").attr("disabled", true);
    $("#txtvendedor").attr("disabled", true);
    $("#slssucursal").attr("disabled", true);
    $("#txtrutcentro").attr("disabled", true);
    $("#txtdireccion").attr("disabled", true);
    $("#txtcomuna").attr("disabled", true);
    $("#txtciudad").attr("disabled", true);


    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    if (dd < 10) { dd = '0' + dd }
    if (mm < 10) { mm = '0' + mm }
    $("#txtfechavoucher").val(dd + '-' + mm + '-' + yyyy);

});
function llevamaterial() {
    $("#chckllevasi").attr("checked", 'checked');
    $("#chkllevano").attr("checked", '');
}
function SumaTotales() {
    t_total = parseInt($("#txtpagoefectivo").val()) + parseInt($("#txttotaldocumento").val());
    $("#txttotalvoucher").val('');
    $("#txttotalvoucher").val(t_total);
}
function Restatotales() {
    t_total = parseInt($("#txtpagoefectivo").val()) - parseInt($("#txttotaldocumento").val());
    $("#txttotalvoucher").val('');
    $("#txttotalvoucher").val(t_total);
}
function nollevamaterial() {
    $("#chckllevasi").attr("checked", '');
    $("#chkllevano").attr("checked", 'checked');
}
function acceptNum(e) {
    tecla = (document.all) ? e.keyCode : e.which; // 2
    if (tecla == 8) return true; // 3
    patron = /\d/; // 4
    te = String.fromCharCode(tecla); // 5
    return patron.test(te); // 6

}
function VerificacionCliente() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/VerificacionCliente";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{'rut':" + $("#txtrutcliente").val() + "}",
        beforeSend: function(objeto) {
          
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $("#txtdireccionvoucher").val(obj[k].direccion);
                $("#txtclientevoucher").val(obj[k].cliente);
                $("#txtfonovoucher").val(obj[k].fono);
                $("#txtcelular").val(obj[k].celular);
                $("#slscomuna").val(obj[k].idComuna);
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;

        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}

function AddListado() {
    if ($("#slstipodoc").val() == 0) {
        jAlert('Seleccione Tipo Documento', 'Voucher', '');
    } else if ($("#slsvoucherbanco").val() == 0) {
        jAlert('Seleccione Banco', 'Voucher', '');
    } else if ($("#txtnumdocumento").val() == 0) {
        jAlert('Ingrese Documento', 'Voucher', '');
    } else if ($("#txtmontodocumento").val() == 0) {
        jAlert('Ingrese Monto', 'Voucher', '');
    } else if ($("#txtfechadocumento").val() == '') {
        jAlert('Ingrese Fecha', 'Voucher', '');
    }else{
        var rand_no = Math.floor(Math.random() * 100);
        oTable.fnAddData([
                                  corrle,
                                  $("#slstipodoc option:selected").val(),
                                  $("#slsvoucherbanco option:selected").val(),
                                  $("#slstipodoc option:selected").text(),
                                  $("#txtnumdocumento").val(),
                                  $("#slsvoucherbanco option:selected").text(),
                                  $("#txtmontodocumento").val(),
                                  $("#txtfechadocumento").val(),
                                  '<img src=\'images/close.png\' width=\'24\' height=\'24\' style=\'cursor:pointer;\' id=\'delpro_' + rand_no + '\' onclick=\'DeleteDocumento(' + rand_no + ')\'/>'

                    ]);
        corrle++;
        t_documento = parseInt(t_documento) + parseInt($("#txtmontodocumento").val());
        $("#txttotaldocumento").val('');
        $("#txttotaldocumento").val(t_documento);
        SumaTotales();
        $("#slstipodoc").val('');
        $("#slsvoucherbanco").val('');
        $("#txtnumdocumento").val('');
        $("#txtmontodocumento").val('');
        $("#txtfechadocumento").val('');
    }
}
function DeleteDocumento(value) {
    var anSelected = fnGetSelected(oTable, value);
    var iRow = oTable.fnGetPosition(anSelected[0]);
    oTable.fnDeleteRow(iRow);

}
function fnGetSelected(oTableLocal, value) {
    var aReturn = new Array();
    aTrs = oTableLocal.fnGetNodes();
    for (var i = 0; i < aTrs.length; i++) {
        if ($(aTrs[i]).find('td img#delpro_' + value).attr("id")) {
            t_documento = parseInt(t_documento) - parseInt($(aTrs[i]).find('td:eq(3)').html());
            $("#txttotaldocumento").val('');
            $("#txttotaldocumento").val(t_documento);
            Restatotales();
            aReturn.push(aTrs[i]);
        }  
    }
    return aReturn;
}
function GetBancos() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetBancos";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        beforeSend: function(objeto) {
            $('#slsvoucherbanco').children().remove();
            $('#slsvoucherbanco').append("<option value=0>Seleccione Banco</option>");
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $('#slsvoucherbanco').append("<option value=" + obj[k].idBanco + ">" + obj[k].banco + "</option>");
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;

        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}

function GetSucursal() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetSucursal";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        beforeSend: function(objeto) {
            $('#slssucursal').children().remove();
            $('#slssucursal').append("<option value=0>Seleccione Sucursal</option>");
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $('#slssucursal').append("<option value=" + obj[k].idSucursal + ">" + obj[k].sucursal + "</option>");
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;

        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}

function GetMedicos() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetMedicos";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        beforeSend: function(objeto) {
            $('#slsmedico').children().remove();
            $('#slsmedico').append("<option value=0>Seleccione Medico</option>");
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $('#slsmedico').append("<option value=" + obj[k].idMedico + ">" + obj[k].nombreMedico + "</option>");
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;
           
        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}


function GetCentros() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetCentros";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        beforeSend: function(objeto) {
            $('#slscentros').children().remove();
            $('#slscentros').append("<option value=0>Seleccione Centro</option>");
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $('#slscentros').append("<option value=" + obj[k].idCentro + ">" + obj[k].centro + "</option>");
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;

        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}

function GetDetalleCentros() {
    var select = $("#slscentros option:selected");
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetDetalleCentros";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{'rut':" + select.val() + "}",
        beforeSend: function(objeto) {
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $("#txtrutcentro").val(obj[k].rutCentro);
                $("#txtcomuna").val(obj[k].idComuna);
                $("#txtciudad").val(obj[k].idCiudad);
                $("#txtdireccion").val(obj[k].direccion);
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;

        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}

function GetTipoDocumento() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetTipoDocumento";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        beforeSend: function(objeto) {
        $('#slstipodoc').children().remove();
        $('#slstipodoc').append("<option value=0>Seleccione Tipo Documento</option>");
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $('#slstipodoc').append("<option value=" + obj[k].idTipoDocumento + ">" + obj[k].tipoDocumento + "</option>");         
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;

        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}
function GetUrl() {
    var sinde = '';
    if (window.location.port == 0) {
        sinde = "http://" + window.location.hostname + '/'
    } else {
        sinde = "http://" + window.location.hostname + ':' + window.location.port + '/HelicoVoucher/';
    }
    var vlurl = sinde;
    return vlurl;

}


function GetIdSession() {
    $.ajax({
        type: "POST",
        data: "{}",
        url: "Default.aspx/GetIdSessionVoucher",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function(msg) { $("#txtidsession").val(msg.d); }

    });
}
function AddVoucher() {
    if ($("#txtrutcliente").val() == '') {
        jAlert('Ingrese Rut Cliente ', 'Voucher', '');
    } else if ($("#txtclientevoucher").val() == '') {
        jAlert('Ingrese Nombre del Cliente ', 'Voucher', '');
    } else if ($("#slscomuna").val() == 0) {
        jAlert('Ingrese Comuna Cliente ', 'Voucher', '');
    } else if ($("#txtfonovoucher").val() == '') {
        jAlert('Ingrese Telefono Cliente ', 'Voucher', '');
    } else if ($("#txtdireccionvoucher").val() == '') {
        jAlert('Ingrese Direccion Cliente ', 'Voucher', '');
    } else if ($("#txtfechacirugia").val() == '') {
        jAlert('Ingrese Fecha Cirugía ', 'Voucher', '');
    } else if ($("#slsmedico").val() == 0) {
        jAlert('Seleccione Medico', 'Voucher', '');
    } else if ($("#slscentros").val() == 0) {
        jAlert('Seleccione Centro', 'Voucher', '');
    } else if ($("#txtpagoefectivo").val() != 0 && $("#txttotalefectivo").val() == 0 || $("#txtpagoefectivo").val() != $("#txttotalefectivo").val()) {
         jAlert('Debe Presionar Calcular Efectivo', 'Voucher', '');
    } else {
        var aReturn = new Array();
        aTrs = oTable.fnGetNodes();
        if (aTrs.length != 0 || $("#txtpagoefectivo").val() != 0) {
     
                var obj = new Object();
                obj.idUsuario = $("#txtIdUsuario").val();
                obj.idMedico = $("#slsmedico option:selected").val();
                obj.rutCliente = $("#txtrutcliente").val();
                obj.idCentro = $("#slscentros option:selected").val();
                obj.fechaVoucher = $("#txtfechavoucher").val();
                obj.fechaCirugia = $("#txtfechacirugia").val();
                obj.numeroCotizacion = $("#txtcotizacionvoucher").val();
                if ($("#chckllevasi").attr("checked")==true){
                    obj.conMaterial = 1;
                }
                if ($("#chckllevano").attr("checked") == true) {
                    obj.conMaterial = 2;
                }
                obj.observacion = $("#txtobservacionVocher").val();
                obj.identificadorSesion = $("#txtidsession").val();
                var retururl = GetUrl();
                var vlurl = retururl + "asmx/voucher.asmx/AddVoucher";
                $.ajax({
                    type: "POST",
                    url: vlurl,
                    contentType: "application/json; charset=utf-8",
                    data: "{'obj':" + JSON.stringify(obj) + "}",
                    dataType: "json",
                    success: function(msg) {

                    },
                    error: function(xhr, msg) {
                        var response = xhr.responseText;
                        alert(response.message);
                    },
                    complete: function(objeto, exito) {
                        if (exito == "success") {
                            AddEfectivo();
                            AddListadoDocumento();
                            AddCliente();
                            $("#txtestado").val('creando');
                        }
                    }
                });
            
        } else {
            jAlert('Falta Ingresar Forma de Pago', 'Voucher', '');
        }
    }
}
function AddListadoDocumento() {
    oTable.fnSetColumnVis(0, true);
    oTable.fnSetColumnVis(1, true);
    oTable.fnSetColumnVis(2, true);

    
    $("#tablelistadodocumentos tbody > tr ").each(function() {
        var obj = new Object();
        obj.numeroDocumento = $('td:eq(4)', this).html();
        obj.idTipoDocumento = $('td:eq(1)', this).html();
        obj.idSessionVoucher = $("#txtidsession").val();
        obj.idBanco = $('td:eq(2)', this).html();
        obj.monto = $('td:eq(6)', this).html();
        obj.fecha = $('td:eq(7)', this).html();
        var retururl = GetUrl();
        var vlurl = retururl + "asmx/voucher.asmx/AddDocumento";
        $.ajax({
            type: "POST",
            url: vlurl,
            contentType: "application/json; charset=utf-8",
            data: "{'obj':" + JSON.stringify(obj) + "}",
            dataType: "json",
            success: function(msg) {
            },
            error: function(xhr, msg) {
                var response = xhr.responseText;
                alert(response.message);
            },
            complete: function(objeto, exito) {
                if (exito == "success") {
                   
                }
            }
        });
    });
  
}
function AddEfectivo() {
    if ($("#txtpagoefectivo").val != '' || $("#txtpagoefectivo").val != 0) {
        var obj = new Object();
        obj.monto = $("#txtpagoefectivo").val();
        obj.idSession = $("#txtidsession").val();
        var retururl = GetUrl();
        var vlurl = retururl + "asmx/voucher.asmx/AddEfectivo";
        $.ajax({
            type: "POST",
            url: vlurl,
            contentType: "application/json; charset=utf-8",
            data: "{'obj':" + JSON.stringify(obj) + "}",
            dataType: "json",
            success: function(msg) {
            },
            error: function(xhr, msg) {
                var response = xhr.responseText;
                alert(response.message);
            },
            complete: function(objeto, exito) {
                if (exito == "success") {
                    GetIdVoucher();
                    $("#formVoucher").reset();
                    InicioFormulario();
                }
            }
        });
    } else { 
      alert("Sin pago en efectivo")
    }
}
function AddCliente() {
    var obj = new Object();
    obj.rutCliente = $("#txtrutcliente").val();
    obj.idComuna = $("#slscomuna option:selected").val();
    obj.dv = $("#txtdigito_verificador").val();
    obj.cliente = $("#txtclientevoucher").val();
    obj.direccion = $("#txtdireccionvoucher").val();
    obj.fono = $("#txtfonovoucher").val();
    obj.celular = $("#txtcelular").val();
    obj.idUsuario = $("#txtIdUsuario").val();
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/AddCliente";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        data: "{'obj':" + JSON.stringify(obj) + "}",
        dataType: "json",
        success: function(msg) {
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;
            alert(response.message);
        },
        complete: function(objeto, exito) {
            if (exito == "success") {
               
            }
        }
    });
}
function GetComuna() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetComuna";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        beforeSend: function(objeto) {
            $('#slscomuna').children().remove();
            $('#slscomuna').append("<option value=0>Seleccione Comuna</option>");
        },
        success: function(msg) {
            var obj = $.evalJSON(msg.d);
            for (var k = 0; k < obj.length; k++) {
                $('#slscomuna').append("<option value=" + obj[k].idComuna + ">" + obj[k].comuna + "</option>");
            }
        },
        error: function(xhr, msg) {
            var response = xhr.responseText;

        },
        complete: function(objeto, exito) {
            if (exito == "success") {

            }
        }

    });
}
function InicioFormulario() {
    t_documento = 0;
    t_efectivo = 0;
    t_total = 0;
    $("#txtpagoefectivo").val('0');
    oTable.fnClearTable(0);
    oTable.fnSetColumnVis(0, false);
    oTable.fnSetColumnVis(1, false);
    oTable.fnSetColumnVis(2, false);
    oTable.fnDraw();
    GetIdSession();
    IsSessionesValida();
    $("#txttotaldocumento").val(t_documento);
    $("#txttotalefectivo").val(t_efectivo);
    $("#txttotalvoucher").val(t_total);
}
function GetIdVoucher() {
    var retururl = GetUrl();
    var vlurl = retururl + "asmx/voucher.asmx/GetNumeroVoucher";
    $.ajax({
        type: "POST",
        url: vlurl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{}",
        success: function(msg) {
            jConfirm('Voucher Fue Ingresado: ' + msg.d, 'Voucher', function(r) {
                if (r == true) {
                   location.href = 'Default.aspx';
                }
            });

        },
        error: function(xhr, msg) {
            var response = xhr.responseText;
        }

    });
}
