$.fn.modal.Constructor.prototype.enforceFocus = function() {};
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
$(document).on("keydown", ":input:not(textarea)", function(event) {
    if (event.key == "Enter") {
        event.preventDefault();
    }
});

$(document).ready(function() {
    $('._language').on('click',function(){
        var language = $(this).data('language');
         $.post('/Controller/Ajax.php', {
            action: 'ajax',
            request: 'setLanguage',
            language: language
        }, function(data) {
            if (data.response){
                document.location.reload();
            }
        }, 'json');
    });
});

$(document).on('focus', '.select2', function (e) {
   if (e.originalEvent && $(this).find(".select2-selection--single").length > 0) {
   $(this).siblings('select').select2('open');  
  } 
});

$(function(){    
    $(document).on('keypress blur','input._maskDouble',function(){
        set_input_mask(this,_input_mask_double);
    });
    
    $(document).on("cut copy paste","._maskDouble",function(e) {
        e.preventDefault();
    });
    
    $("._deleteFile").on("click", function(){deleteFile(this);});
    $('._emailing').on('click',function(){ prepareEmailing(this);});
    $('._closeModalEmailing').on('click',function(){
        clearForm('emailing');
        $('.flashmessenger').html('');
        $('#modalEmailing').modal('hide');
    });
    
    $('#send_emailing').on('click',function(){emailing();});
});

function set_input_mask(o,f){  
    v_obj=o;  
    v_fun=f;  
    setTimeout("_execute_input_mask()",1);  
}  
function _execute_input_mask(){
    v_obj.value=v_fun(v_obj.value);
}  
function _input_mask_double(v){     
    var v = v.replace(/([^0-9\.]+)/g,''); 
    v = v.replace(/^[\.]/,''); 
    v = v.replace(/[\.][\.]/g,''); 
    v = v.replace(/\.(\d)(\d)(\d)/g,'.$1$2'); 
    v = v.replace(/\.(\d{1,2})\./g,'.$1'); 
    v = v.toString().split('').reverse().join('').replace(/(\d{3})/g,'$1,');    
    v = v.split('').reverse().join('').replace(/^[\,]/,''); 
    
    return v;  
}  

function _rawNumber(number){
    number = $.trim(number);
    if(number == '') return 0;
    
    return number.replace(/,/g , "");
}

$(document).ready(function() {
    $(".modal-dialog").draggable({
        handle: ".modal-header,.modal-body,.modal-footer"
    });
    
    $(".modal").on("hidden.bs.modal", function(){
        $(".modal-dialog").css({top: 0,left: 0});
    });
});

$(function(){
    $('.datatable_whit_filter_column').each( function (){
        if(!$.fn.DataTable.isDataTable('#'+this.id)) {
           setDataTable(this.id);     
        }else{
            applyFiltersOnDataTable(this.id);
        }
    });  
    
    /*Ajustar columnas cuando se activa Tab
     * Por ejemplo si hay dos tabs, las columnas de la tabla en el tab inicialmente activo se muestan bien,
     * pero cuando se hace click en otro tab, la tabla que esta en ese tab no se muestra con los width correctos en las columnas; no se muestran bien porque como estan hide, no se aplica el width */
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        $.fn.dataTable
            .tables( { visible: true, api: true } )
            .columns.adjust();
    });
    
});

function number_format(number,decimals,dec_point,thousands_sep) {
    number  = number*1;//makes sure `number` is numeric value
    var str = number.toFixed(decimals?decimals:0).toString().split('.');
    var parts = [];
    for ( var i=str[0].length; i>0; i-=3 ) {
        parts.unshift(str[0].substring(Math.max(0,i-3),i));
    }
    str[0] = parts.join(thousands_sep?thousands_sep:',');
    return str.join(dec_point?dec_point:'.');
}

function fadeOutAlert(paramTime){
    var time = 3500;
    if(paramTime){time = paramTime;
    }
  window.setTimeout(function() {
    $('.alert').slideUp('slow', function(){
        $(this).remove();
    });
  }, time);
}

function destroyDataTable(table_id){
    if ($.fn.dataTable.isDataTable( '#'+table_id )) {
        var table = $('#'+table_id).DataTable();
        table.destroy();
    } 
}

function setDataTable(tableId,paginate = false,filter = true,bInfo = false){
    $('#'+tableId).DataTable({paginate:paginate,filter:filter,aaSorting:[],bInfo:bInfo});   
    
    if($('#'+tableId).hasClass('_hideSearch')){
        $('#'+tableId+'_filter').hide();
    }
    
    applyFiltersOnDataTable(tableId);
}

function applyFiltersOnDataTable(tableId){
    $('#'+tableId).removeClass( 'display' ).addClass('table table-striped table-bordered');        
    $('#'+tableId+' tfoot th.filter').each( function () {
        var input_name = $(this).data('filtername');
        $(this).html( '<input type="text" name="filter_'+input_name+'" class="column_filter" placeholder="Buscar" style="width:100%" />' );
    } );  
    
    var table = $('#'+tableId).DataTable();
    // Apply the search
    table.columns().every( function () {
        var that = this; 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search (this.value.replace("/;/g", "|"), true, false)
                    .draw();
            }
        } );
    } );
}

function addMsgFlashmessenger(tipo,msg,messengerId){ alert(tipo+' '+msg+' '+messengerId);
    $('#msg').remove();
    $('#'+messengerId).append("<div id='msg' class='alert alert-"+tipo+"'></div>");
    var btnClose = "<button type='button' class='close' data-dismiss='alert'>&times;</button>";
    $('#msg').html(btnClose+msg);
    //fadeOutAlert();
}
function submit(formName){ 
    $('form[name='+formName+']').submit();
}

function clearForm(formName){
    $('form[name='+formName+']').trigger('reset');
    $('form[name='+formName+']').find('.has-error').removeClass("has-error");
    $('form[name='+formName+']').find('.has-success').removeClass("has-success");
    $('form[name='+formName+']').find('.form-control-feedback').remove();
    $('select').trigger('change');
}

function _getTranslation(msj,callback){
    $.post('/Controller/Ajax.php', {
        action: 'ajax',
        request: 'getTranslation',
        msj:msj
            }, function(data) {
                if(callback){callback(data.translation);}                
            }, 'json');
}

function _alert(msg,callbackOk){
    $.alert({ 
        title:"<i class='fa fa-info-circle'></i> Mensaje", 
        content:msg,
        columnClass: 'col-md-6 col-md-offset-3',
        buttons: {   
            ok: {
                text: "OK",
                btnClass: 'btn-default',
                keys: ['enter'],
                action: function(){
                     callbackOk();
                }
            }
        }                      
    });     
}

function confirmDelete(msg,link){  
    $.confirm({
            theme: 'material',
            columnClass: 'col-md-6 col-md-offset-3',
            icon: 'fa fa-trash',
            title: 'Eliminar registro',
            content: msg,
            buttons:{                
                cancel: {
                    text:'No',
                    btnClass: 'btn-default col-md-4 pull-right',
                    action: function(){
                       $(this).remove();
                    }
                },
                confirm: {
                    text: 'Si ',
                    btnClass: 'btn-primary col-md-4 pull-right',
                    action: function(){
                       document.location = link;
                    }
                }
            }
        });        
        return false;
}

function deleteRegistry(msg,callback){     
     $.confirm({
            theme: 'material',
            columnClass: 'col-md-6 col-md-offset-3',
            icon: 'fa fa-trash',
            title: _getTranslation('Eliminar registro'),
            content: msg,
            buttons:{                
                cancel: {
                    text:'No',
                    btnClass: 'btn-default col-md-4 pull-right',
                    action: function(){
                       $(this).remove();
                    }
                },
                confirm: {
                    text: 'Si ',
                    btnClass: 'btn-primary col-md-4 pull-right',
                    action: function(){
                        callback();
                    }
                }
            }
        });
        return null;
}

function confirmAction(operation,callback){
    $.confirm({
        title: 'Confirmar operacion !',
        icon: 'fa fa-key',
        content: '' +
        '<form action="" class="formName">' +
        '<div class="form-group">' +
        '<label>Ingresa clave para confirmar operacion.</label>' +
        '<input id="master_key" type="password" placeholder="Clave" class="name form-control" required />' +
        '</div>' +
        '</form>',
        buttons: {
            formSubmit: {
                text: 'Submit',
                btnClass: 'btn-blue _confirmAction',
                action: function () {
                    $.post('/Controller/Ajax.php', {
                        action: 'ajax',
                        request: 'confirmAction',
                        operation: operation,
                        masterKey: $('#master_key').val()
                    }, function(data) {
                        if (data.response){
                            callback();
                        }else{                            
                            $('.flashmessenger').html(data.msg); 
                            return false;
                        }     
                    }, 'json');
                }
            },
            cancel: function () {
                //close
            }
        },
        onContentReady: function(){
            $('#master_key').focus();
            $('#master_key').on('keydown',function(e){
                var keycode = e.keyCode || e.which;
                if(keycode === 13) {
                  e.preventDefault();
                  $('._confirmAction').trigger('click');
                }
            });
        }
    });
}

function specialTemplateSelect(){
    $('select._selectWith2Rows').each(function(){
        switch(this.id){
            case 'shipping_address':
                $('#shipping_address').select2({templateResult:_formatShippingAddress,templateSelection:_formatShippingAddress});
                break;
        }
        
        var container = $(this).next('.select2-container');
        container.addClass('_selectWith2Rows');
    });   
}

function _formatShippingAddress (shippingAddress) {
    if(shippingAddress.id !== ''){
        var item = shippingAddress.text;
        item = item.split('{*}');

        var $item = $("<span style='display:block'>"+item[0]+"</span><span>"+item[1]+"</span>");

        return $item ;  
    }    
};

/* EMAILING*/
function prepareEmailing(operation){   
    var operation_name = $(operation).data('operationname');
    var operation_id = $(operation).data('operationid');
    $('#operation_id').val(operation_id);
    $('#operation_name').val(operation_name);
    
     $.post('/Controller/Ajax.php', {
        action: 'emailing',
        request: 'getDataOperation',
        operation_name:operation_name,
        operation_id:operation_id
    }, function(data) {
        if (data.response){ 
            $('#to').val(data.to);
            $('#subject').val(data.subject);
            $('#message').val(data.messageMail);
            $('._attachments').html(data.attachments);
            
            $('#modalEmailing').modal('show');
        }
    }, 'json');
}

function emailing(){
    var options = $('form[name=emailing]').serializeArray();
    var attachmentFiles = $('._attachementForEmail').serializeArray();
    $.post('/Controller/Ajax.php', {
        action: 'emailing',
        request: 'emailing',
        options:options,
        attachmentFiles:attachmentFiles
    }, function(data) {
        if (data.response){ 
            clearForm('emailing');
            $('#modalEmailing').modal('hide');
        }
        
        $('.flashmessenger').html(data.msg);
        
    }, 'json');
}
/* END EMAILING BOL*/

/* VENDORS */

function setDataToEditVendor(id){
    $.post('/Controller/Proveedor.php', {
    action: 'ajax',
    request: 'getDataToEdit',
    id: id
    }, function(data) {
        if (data.response){     
            for (var name in data.vendorData) {
                $('form[name=vendor] #'+name).val(data.vendorData[name]);
            }                      
            $('select').trigger('change');   
            $('#modalAddVendor').modal('show');
        }
    }, 'json');
}
    
function deleteVendor(id){     
    var title = '';
    var content = '';
    var comfirmText = ''
    _getTranslation('Eliminar registro',function(translation){
        title  = translation;
        
        _getTranslation('Desea eliminar este proveedor ?',function(translation){
        content  = translation;
        
            _getTranslation('Si',function(translation){
                comfirmText  = translation; 

                 $.confirm({
                    theme: 'material',
                    columnClass: 'col-md-6 col-md-offset-3',
                    icon: 'fa fa-trash',
                    title: title,
                    content: content,
                    buttons:{                
                        cancel: {
                            text:'No',
                            btnClass: 'btn-default col-md-4 pull-right',
                            action: function(){
                               $(this).remove();
                            }
                        },
                        confirm: {
                            text: comfirmText,
                            btnClass: 'btn-primary col-md-4 pull-right',
                            action: function(){
                                $.post('/Controller/Proveedor.php', {
                                    action: 'ajax',
                                    request: 'deleteVendor',
                                    id: id
                                    }, function(data) {
                                        if (data.response){     
                                             document.location.href = 'Proveedor.php';
                                        }
                                    }, 'json');                       
                            }
                        }
                    }
                });
                 return null;
            });
           
        });
    });  
}

/* END VENDORS */

/* USERS */

function setDataToEditUser(id){
    $.post('/Controller/Usuario.php', {
    action: 'ajax',
    request: 'getDataToEdit',
    id: id
    }, function(data) {
        if (data.response){     
            for (var name in data.userData) {
                $('form[name=user] #'+name).val(data.userData[name]);
            }                      
            $('select').trigger('change');   
            $('#modalAddUser').modal('show');
        }
    }, 'json');
}
    
function deleteUser(id){     
    var title = '';
    var content = '';
    var comfirmText = ''
    _getTranslation('Cancelar registro',function(translation){
        title  = translation;
        
        _getTranslation('Desea cancelar este usuario ?',function(translation){
        content  = translation;
        
            _getTranslation('Si',function(translation){
                comfirmText  = translation; 

                 $.confirm({
                    theme: 'material',
                    columnClass: 'col-md-6 col-md-offset-3',
                    icon: 'fa fa-trash',
                    title: title,
                    content: content,
                    buttons:{                
                        cancel: {
                            text:'No',
                            btnClass: 'btn-default col-md-4 pull-right',
                            action: function(){
                               $(this).remove();
                            }
                        },
                        confirm: {
                            text: comfirmText,
                            btnClass: 'btn-primary col-md-4 pull-right',
                            action: function(){
                                $.post('/Controller/Usuario.php', {
                                    action: 'ajax',
                                    request: 'deleteUser',
                                    id: id
                                    }, function(data) {
                                        if (data.response){     
                                             document.location.href = 'Usuario.php';
                                        }
                                    }, 'json');                       
                            }
                        }
                    }
                });
                 return null;
            });
           
        });
    });  
}

/* END PURCHASE */

/* PURCHASES */

function setDataToEditPurchase(id){
    $.post('/Controller/Compra.php', {
    action: 'ajax',
    request: 'getDataToEdit',
    id: id
    }, function(data) {
        if (data.response){     
            for (var name in data.purchaseData) {
                $('form[name=purchase] #'+name).val(data.purchaseData[name]);
            }                      
            $('select').trigger('change');   
            $('#modalAddPurchase').modal('show');
        }
    }, 'json');
}
    
function deletePurchase(id){     
    var title = '';
    var content = '';
    var comfirmText = ''
    _getTranslation('Cancelar registro',function(translation){
        title  = translation;
        
        _getTranslation('Desea cancelar esta compra ?',function(translation){
        content  = translation;
        
            _getTranslation('Si',function(translation){
                comfirmText  = translation; 

                 $.confirm({
                    theme: 'material',
                    columnClass: 'col-md-6 col-md-offset-3',
                    icon: 'fa fa-trash',
                    title: title,
                    content: content,
                    buttons:{                
                        cancel: {
                            text:'No',
                            btnClass: 'btn-default col-md-4 pull-right',
                            action: function(){
                               $(this).remove();
                            }
                        },
                        confirm: {
                            text: comfirmText,
                            btnClass: 'btn-primary col-md-4 pull-right',
                            action: function(){
                                $.post('/Controller/Compra.php', {
                                    action: 'ajax',
                                    request: 'deletePurchase',
                                    id: id
                                    }, function(data) {
                                        if (data.response){     
                                             document.location.href = 'Compra.php';
                                        }
                                    }, 'json');                       
                            }
                        }
                    }
                });
                 return null;
            });
           
        });
    });  
}

/* END USER */

/* PAGOS */
function getListFacturasProveedores(){    
    var proveedor = $('#proveedor').val();
    $.post('/Controller/Pago.php', {
        action: 'ajax',
        request: 'getListFacturasByProveedor',
        proveedor: proveedor
    }, function(data) {
        if (data.response){
            $("#listFacturasProveedores").html(data.listFacturas);
        }
    }, 'json');
    setSumPagos();
}

function addInvoiceToPayment(trId){ 
    /*
    var montoTotalPago = $('#monto').val();
    if(montoTotalPago.trim() === ''){
         _getTranslation('Antes de seleccionar Facturas, ingresa el monto del pago.',function(msj){$.alert({content:msj,title:"<i class='fa fa-info-circle'></i> Mensaje", columnClass: 'col-md-6 col-md-offset-3'});});        
         $('#monto').focus();
     }
    */
    var pagos = $(".ammountPymt").serializeArray();  
    var sumPagos = 0;
    $.each(pagos,function(i,pago){
        if($.trim(pago.value) !== ''){
          sumPagos = parseFloat(sumPagos) + parseFloat(pago.value);
        }      
    });
  
    /*if(montoTotalPago > sumPagos){  */
        $.post('/Controller/Pago.php', {
            action: 'ajax',
            request: 'addInvoiceToPayment',
            idFactura: trId,
            //montoTotalPago: montoTotalPago,
            sumPagos: sumPagos
        }, function(data) {
            if (data.response){
                $("#listFacturasAPagar").append(data.factura);
                $('#addInvoice_'+trId).hide();
                setSumPagos();
            }
        }, 'json'); 
   // }        
}

function deleteInvoiceFromPayment(trId){
    $('#pago['+trId+']').remove();
    $('#deleteInvoice_'+trId).remove();
    $('#addInvoice_'+trId).show();
    setSumPagos();
}

function setSumPagos(){
    var pagos = $(".ammountPymt").serializeArray();  
    var sumPagos = 0;
    
    $.each(pagos,function(i,pago){
        if($.trim(pago.value) !== ''){
          sumPagos = parseFloat(sumPagos) + parseFloat(pago.value);
        }      
    });    
    
    var checkAmmountDecimal = sumPagos.toFixed(2);
    $('#suma_de_pagos').val(checkAmmountDecimal);
    $('#monto').val(checkAmmountDecimal);
    sumPagos = "$"+checkAmmountDecimal.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    $('.sumPagos').html(sumPagos);
    $('#label_suma_pagos').html(sumPagos);
    
    
}

function limpiarFacturasAPagarPorCambioMonto(){
    var monto_original = $('#monto_original').val();
    $.confirm({
            theme: 'material',
            columnClass: 'col-md-6 col-md-offset-3',
            icon: 'fa fa-refresh',
            title: 'Cambiar monto de pago',
            content: 'Si cambia el monto de pago, se cancelaran las facturas seleccionadas hasta ahora. Desea continuar ?',
            buttons:{                
                cancel: {
                    text:'No',
                    btnClass: 'btn-default col-md-4 pull-right',
                    action: function(){                       
                       $('#monto').val(monto_original);
                       $('#monto_original').val(monto_original);
                       setLabelMonto(monto_original);
                       $(this).remove();
                    }
                },
                confirm: {
                    text: 'Si ',
                    btnClass: 'btn-primary col-md-4 pull-right',
                    action: function(){                        
                         $("#listFacturasAPagar").html('');
                         getListFacturasProveedores();                    
                     }
                }
            }
        });
}

function setLabelMonto(monto){
    var monto = parseFloat(monto);
    $('#label_monto_pago').html('$'+monto.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}

/* END */

/* REPORTS */
function setFilterReport(report,callback){
    var reportName = $(report).data('reportname');
    $('#reporte').val(reportName);
    
    $.post('/Controller/Reportes.php',{
        action: 'ajax',
        request: 'getFiltersReport',
        report: reportName
    },function(data){
        if(data.response){
            $('#filtersArea').html(data.filters);
            $('select').select2();            
            $("#fechaInicio,#fechaFin").datetimepicker({format: 'DD/MM/YYYY'});
            $('#modalFiltroReportes').modal('show');
            
            if(callback){callback();}
        }
    },'json');
}
/* END REPORTS*/