/*$.fn.datetimepicker.dates['es'] = {
    days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"],
    daysShort: ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sáb", "Dom"],
    daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"],
    months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
    monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
    today: "Today"
};*/


function executeFunctionByName(functionName, context /*, args */) {
    var args = Array.prototype.slice.call(arguments, 2);
    var namespaces = functionName.split(".");
    var func = namespaces.pop();
    for (var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }
    return context[func].apply(context, args);
}

$(document).ready(function(){
    llenarFomrPrimerIngreso();
   creaConf(); 
});

$('#DataContainer').on('click', '.trow', function() {
    var col = $(this).children(":first");
   var id = col.html();
   $("#formId\\:idRegi").val(id);
   consultar();
});


/*
$("input").keyup(function(){
    console.log("presionado");
});
*/
//$(this).val($(this).val().toUpperCase())

//función que cambia el contenido de los botones de componente de primefaces p:FileUpload
function cfileUpload(){
    var btnElegir = $('span.ui-button-text.ui-c:contains("Choose")').html("<i class='mdi mdi-camera'/> Elegir");
    $(btnElegir).prev('span').remove();
    var btnSubir = $('span.ui-button-text.ui-c:contains("Upload")').html("<i class='mdi mdi-cloud-upload'/> Subir");
    $(btnSubir).prev('span').remove();
    var btnSubir = $('span.ui-button-text.ui-c:contains("Cancel")').html("<i class='mdi mdi-close-circle'/> Cancelar");
    $(btnSubir).prev('span').remove();
}
function creaConf(){
    cfileUpload();
    //si el body contiene un elemento con #datatable, inicializar datatable
    if($("body #datatable").length > 0 && $("body .datatable").length === 0){
        //destruir datable
        if ( $.fn.DataTable.isDataTable('#datatable') ) {
            $('#datatable').DataTable().destroy();
        } 
        var i = 1;
         $('#datatable').each(function(){
               $(this).dataTable({
                    "autoWidth":false,
                    "bSort": (typeof $(this).attr("pt:bsort") === "undefined")?true:$(this).attr("pt:bsort")==='false'?false:true,
                    "paging":(typeof $(this).attr("pt:paging") === "undefined")?true:$(this).attr("pt:paging")==='false'?false:true,
                    "header": 'Datatables example: Customisation of the print view window'
              });
              if(!(typeof $(this).attr("pt:title") === "undefined")){
                  var titulo = $(this).parent().parent().prev('div').find(".col-sm-12.col-md-6:first-child");
                  titulo.html("<h2>"+$(this).attr("pt:title")+"</h2>");
              }
         });
    }
    
    
    if($("body .datatable").length > 0){
        //destruir datable
        if ( $.fn.DataTable.isDataTable('.datatable') ) {
            $('.datatable').DataTable().destroy();
        } 
        var i = 1;
         $('.datatable').each(function(){
               $(this).dataTable({
                    "autoWidth":false,
                    "bSort": (typeof $(this).attr("pt:bsort") === "undefined")?true:$(this).attr("pt:bsort")==='false'?false:true,
                    "paging":(typeof $(this).attr("pt:paging") === "undefined")?true:$(this).attr("pt:paging")==='false'?false:true,
                    "header": 'Datatables example: Customisation of the print view window'
              });
              if(!(typeof $(this).attr("pt:title") === "undefined")){
                  var titulo = $(this).parent().parent().prev('div').find(".col-sm-12.col-md-6:first-child");
                  titulo.html("<h2>"+$(this).attr("pt:title")+"</h2>");
              }
         });
    }
    //su el body contiene un select.select-one-menu, iniciar select-one-menu
    if($("body select.select-one-menu").length > 0){
        $('.select-one-menu').select2();
    }
    
    if($("body .clockpicker").length > 0){
        $('.clockpicker').clockpicker({
            donetext: 'Seleccionar',
            twelvehour: true,
        }).find('input').change(function() {
            //console.log(this.value);
        });
    }
    if($("body .datepicker-nv").length > 0){
        $('.datepicker-nv').each(function() {
            
            $(this).datepicker({
                autoclose: true,
                todayHighlight: true,
                format: "dd/mm/yyyy",
                language: "es",
                
                startDate: $(this).attr("startDate"),
                endDate: $(this).attr("endDate"),
                maxDate: $(this).attr("maxDate"),
                daysOfWeekDisabled: $(this).attr("daysOfWeekDisabled"),
                datesDisabled: (typeof $(this).attr("datesDisabled") === "undefined")?[]:$(this).attr("datesDisabled").split(","),
                datesEnable : $(this).attr("datesEnable")
            });
        });
    }
        
    if($("body .datepicker").length > 0){
        $('.datepicker').each(function() {
            
            $(this).datepicker({
                autoclose: true,
                todayHighlight: true,
                format: "dd/mm/yyyy",
                language: "es",
                
                startDate: $(this).attr("startDate"),
                endDate: $(this).attr("endDate"),
                maxDate: $(this).attr("maxDate"),
                daysOfWeekDisabledPar: $(this).attr("daysOfWeekDisabled"),
                datesDisabledPar: (typeof $(this).attr("datesDisabled") === "undefined")?[]:$(this).attr("datesDisabled").split(","),
                datesEnablePar : $(this).attr("datesEnable"),
                /*
                datesEnable: ['20-08-2019', '20/12/2019'],
                enableDates: ['07-12-2019', '20/12/2019']*/
                beforeShowDay : function(date) {
                    var resp = true;
                    if((typeof $(this).attr("startDate")=== "undefined")|| $(this).attr("startDate").toString()=== "-Infinity"){
                        resp = false;
                    }else{
                        var disableDaysString = (typeof $(this).attr("daysOfWeekDisabledPar") === "undefined")?"":$(this).attr("daysOfWeekDisabledPar").toString().replace("[","").replace("]","").replace("NaN,","").replace(",NaN","").replace(" ","").replace("NaN","");
                        var disableDays  = disableDaysString.split(",");
                        var day = date.getDay();
                        resp = !disableDays.includes(day.toString());
                        var datesEnableString = (typeof $(this).attr("datesEnablePar") === "undefined")?"": $(this).attr("datesEnablePar").toString().replace(" ","");
                        var datesEnable =datesEnableString.split(",");
                        if(datesEnable.includes(parseNumber((date.getDate()).toString(), 2)+"-"+parseNumber((date.getMonth()+1).toString(), 2)+"-"+parseNumber((date.getFullYear()).toString(), 4))){
                            resp = true;
                        }
                    }
                    return resp;
                }
                
               // enabledDates: $(this).attr("enabledDates")
            });
        });
//        $('.datepicker').datepicker({
//            autoclose: true,
//            todayHighlight: true,
//            format: "dd/mm/yyyy",
//            daysOfWeekDisabled: "[1,2,3,4,5]"
//        });
    }
    
    if($("body .input-daterange-datepicker").length > 0){
       moment.locale('es');
        $('.input-daterange-datepicker').daterangepicker({
            buttonClasses: ['btn', 'btn-sm'],
            applyClass: 'btn-danger',
            cancelClass: 'btn-inverse',
            language: "es",
            applyLabel :"Aceptar",
            cancelLabel : "Cancelar"
        });
        /*
        $('.input-daterange-datepicker').each(function() {
            
            $(this).datepicker({
                autoclose: true,
                todayHighlight: true,
                format: "dd/mm/yyyy",
                language: "es",
                daysOfWeekDisabled: $(this).attr("daysOfWeekDisabled"),
                //datesDisabled: ['30-08-2019'],
                datesDisabled: (typeof $(this).attr("datesDisabled") === "undefined")?[]:$(this).attr("datesDisabled").split(","),
                startDate: $(this).attr("startDate"),
                endDate: $(this).attr("endDate"),
                maxDate: $(this).attr("maxDate"),
                //datesEnable: ['20-08-2019']
                
               // enabledDates: $(this).attr("enabledDates")
            });
        });
        */
    }
    
    if($("body .input-datetimerange-datetimepicker").length > 0){
       moment.locale('es');
        $('.input-datetimerange-datetimepicker').daterangepicker({
            buttonClasses: ['btn', 'btn-sm'],
            applyClass: 'btn-danger',
            cancelClass: 'btn-inverse',
            language: "es",
            applyLabel :"Aceptar",
            cancelLabel : "Cancelar",
            /*time*/
            timePicker:true,
            format: 'DD/MM/YYYY hh:mm A',
            locale: {
                format: 'DD/MM/YYYY hh:mm A'
              },
            timePickerIncrement: 1,
            timePicker12Hour: true,
            timePickerSeconds: false
        });
        
    }
    
    
    if($("body .js-switch").length > 0){
        $("span.switchery").each(function(){
            $(this).remove();
        });
        var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
        elems.forEach(function(elem) {
          var switchery = new Switchery(elem,
            {
                color: (typeof $(elem).attr("color") === "undefined")?"#4aa9e9":$(elem).attr("color")
            });
        });
        
    }
    
    if($("body .phone-picker").length > 0){
        $(".phone-picker").each(function(){
                    $(this).intlTelInput(
                        {
                            allowExtensions: true,
                            autoFormat: false,
                            autoHideDialCode: false,
                            autoPlaceholder: false,
                            defaultCountry: "us",
                            nationalMode: false,
                            numberType: "MOBILE",
                            onlyCountries: ['us', 'ca', 'sv', 'it', 'mx', 'au'],
                            placeholderNumberType: "MOBILE",
                            preferredCountries: ['us', 'ca'],
                            preventInvalidNumbers: true//,
                            //utilsScript: "../plantilla/assets/plugins/intl-tel-input-master/build/js/utils.js']})"
                            //utilsScript: "#{resource['plantilla/assets/plugins/intl-tel-input-master/build/js/utils.js']})"
                            }
                        );
                    $(this).val($(this).val()+" ");
                });
        }
        //hacer que los inputText se pongan toUpperCase al escribir
        $('input[type=text].form-control').each(function(){
           $(this).on('blur' , function() {
                if($(this).attr("upper") === 'true'){
                    $(this).val($(this).val().toUpperCase());
                }else if($(this).attr("lower") === 'true'){
                    $(this).val($(this).val().toLowerCase());
                }
                if($(this).attr("trim") === 'true'){
                    $(this).val($.trim($(this).val()).replace(/\s/g, ''));
                }
                /*
                if($(this).attr("regex") === 'true'){
                    var VAL = $(this).val();

                    var email = new RegExp('^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$');

                    if (email.test(VAL)) {
                        console.log("validado");
                    }else{
                         console.log("no validado");
                    }
                }
               */
                
            }); 
        });
    
    
}

/*
 $('#formData\\:DataContainer').on('click','.btnNext').click(function(){
     alert("hola");
     //$('.nav-tabs >  .nav-item > .active').parent().next('li').find('a').trigger('click');
});

$('#formData\\:DataContainer').on('click','.btnPrevious').click(function(){
     alert("hola");
  //$('.nav-tabs >  .nav-item > .active').parent().prev('li').find('a').trigger('click');
});
*/




function next(){
    $('.nav-tabs >  .nav-item > .active').parent().next('li').find('a').trigger('click');
}
function back(){
    $('.nav-tabs >  .nav-item > .active').parent().prev('li').find('a').trigger('click');
}

function next(tab){
    var active = $('.nav-tabs >  .nav-item > .active');
    var next = $(active).parent().next('li').find('a');
    for(var i = 1; i< tab; i++){
       next = $(next).parent().next('li').find('a');
    }
    $(next).trigger('click');
}
function back(tab){
    var active = $('.nav-tabs >  .nav-item > .active');
    var back = $(active).parent().prev('li').find('a');
    for(var i = tab; i> 1; i--){
       back = $(back).parent().prev('li').find('a');
    }
    $(back).trigger('click');
    //$('.nav-tabs >  .nav-item > .active').parent().prev('li').find('a').trigger('click');
}

function redirect(url, time){
    setTimeout(function(){
        window.location.replace(url);
    }, time);
}
function setDMessage(tipo, titulo, cuerpo, tiempo){
    setTimeout(function(){
        setMessage(tipo, titulo, cuerpo);
    },tiempo);
}



function copiarAlPortapapeles(valor) {
  
  // Crea un campo de texto "oculto"
  var aux = document.createElement("input");

  // Asigna el contenido del elemento especificado al valor del campo
  aux.setAttribute("value", valor);

  // Añade el campo a la página
  document.body.appendChild(aux);

  // Selecciona el contenido del campo
  aux.select();

  // Copia el texto seleccionado
  document.execCommand("copy");

  // Elimina el campo de la página
  document.body.removeChild(aux);

}

function llenarFomrPrimerIngreso(){
    var url_string = window.location.href;
    if(url_string.includes('ingreso.xhtml')){
        var url = new URL(url_string);
        var user = url.searchParams.get("user");
        var pass = url.searchParams.get("pass");
        if(user!==null && pass !==null){
            $("#FormLogin\\:nomb").val(user);
            $("#FormLogin\\:llavGene").val(pass);
        }
    }
}


function parseNumber(number, size){
    while(number.toString().length < size){
        number = '0'+number;
    }
    return number;
}