<script class='controller'>
    setTimeout(function() {

        /*           ACTUALIZAR CONTADORES               */
        $(document).off('click', "#updateCharts");
        $(document).on('click', '#updateCharts', function(e) {
            var userIntel = JSON.parse(window.localStorage.getItem("userIntel")),
                panelToShow = userIntel.panelUsuario,
                userId = $('#sidebarLoaded').attr('userIdPanel');
            $("#loading").fadeIn("fast", function() {
                showPanel(panelToShow, userId);
            });
        });

        /** CUANDO INICIA EL MODULO CARGAMOS LAS PRIMERAS TARJETAS */
        $('.anim1').velocity("transition.slideUpBigIn", {
            stagger: 250,
            complete: function() {
                listPending();

                /*           SYNC AUTO             */
                var userIntel = JSON.parse(window.localStorage.getItem("userIntel"));
                if (userIntel.isAutom == 1) {
                    $(document).find('.isAutom').click();
                }
                $(document).off('change', ".isAutom");
                $(document).on('change', '.isAutom', function(e) {
                    if ($('.isAutom').prop('checked')) {
                        userIntel.isAutom = 1;
                        window.localStorage.setItem("userIntel", JSON.stringify(userIntel));
                    } else {
                        userIntel.isAutom = 0;
                        window.localStorage.setItem("userIntel", JSON.stringify(userIntel));
                    }
                });
            }
        });


        /*           OPCIONES DE SYNC             */
        $(document).off('click', ".thisSyncCall");
        $(document).on('click', '.thisSyncCall', function(e) {
            var thisKey = $(this).find('.key').html();
            var status = $(this).find('.status').html();
            var operIs = $(this).find('.operacion').html();
            var operWas = $('.oper span').html();
            if (operIs != operWas) {

                $('.animOpts').slideUp('fast', function() {
                    $('.oper span').html(operIs);
                    $('.oper .selectedKey').html(thisKey);
                    if (status == 'pending') {
                        $(document).find("#syncThisCall").show();
                    } else {
                        $(document).find("#syncThisCall").hide();
                    }
                    $('.animOpts').slideDown('fast', function() {
                        console.log('listo');
                    });
                });
            } else {
                $('.animOpts').slideUp('fast');
                $('.oper span, .selectedKey').html('');
            }
        });


        /*           ENVIAR SYNC INDIVIDUAL             */
        $(document).off('click', "#syncThisCall");
        $(document).on('click', '#syncThisCall', function(e) {
            var pendingCalls = JSON.parse(window.localStorage.getItem("pendingCalls")),
                thisKey = $('.selectedKey').html();

            $('.refreshPageIcon').addClass('fa-spin');
            for (var key in pendingCalls) {

                if (key == thisKey) {
                    console.log(pendingCalls[key]);
                    var formData = new FormData();
                    for (var key2 in pendingCalls[key].post) {
                        var string = pendingCalls[key].post[key2][1];
                        var validate = '1';
                        if (validate == '[') {
                            var value = string.substring(1, string.length - 1);
                        } else {
                            var value = string;
                        }
                        formData.append(pendingCalls[key].post[key2][0], value);
                    }
                    formData.append('async', 'isAsync');
                    formData.append('now', getNow());
                    apiCall(formData, function(data) {
                        console.log(data);
                        pendingCalls[key].status = 'sent';
                        console.log(pendingCalls);
                        window.localStorage.setItem("pendingCalls", JSON.stringify(pendingCalls));
                        listPending();
                        swal({
                            title: "Felicitaciones",
                            text: "Su Registro ha sido sincronizado exitosamente.",
                            type: "success",
                            showCancelButton: false,
                            confirmButtonText: 'Entendido',
                            cancelButtonText: 'salir'
                        });
                        $('.refreshPageIcon').removeClass('fa-spin');
                    });
                    break;
                }
            }
        });


    }, 10000);

    function listPending() {
        var pendingCalls = window.localStorage.getItem("pendingCalls");
        if (pendingCalls) {
            pendingCalls = $.parseJSON('[' + pendingCalls + ']');
            pendingCalls = pendingCalls[0];

            $('.listadoSync tbody').html('');
            for (var key in pendingCalls) {
                console.log(pendingCalls[key]);

                var fecha = key.substring(0, 4);
                fecha += '-' + key.substring(4, 6);
                fecha += '-' + key.substring(6, 8);
                fecha += ' ' + key.substring(8, 10);
                fecha += ':' + key.substring(10, 12);
                fecha += ':' + key.substring(12, 14);

                if (pendingCalls[key].status == 'pending') {
                    var estado = '<span style="font-size: 34px;" class=""><i class="fa fa-exclamation-triangle fa-x4"></i></span>';
                    var estadoCol = 'btn-danger';
                } else {
                    var estado = '<span style="font-size: 34px;" class=""><i class="fa fa-check fa-x4"></i></span>';
                    var estadoCol = 'btn-success';
                }
                $('.listadoSync tbody').append(' <tr class="thisSyncCall">' +
                    '<td class="offscreen key" data-valtype="fecha">' + key + '</td>' +
                    '<td class="fecha" data-valtype="fecha">' + fecha + '</td>' +
                    '<td class="modulo" data-valtype="modulo">' + pendingCalls[key].mod + '</td> ' +
                    '<td class="operacion" data-valtype="operacion">' + pendingCalls[key].mod.hashCode() + '</td> ' +
                    '<td style="text-align: center;" class="estado ' + estadoCol + '" data-valtype="estado">' + estado + '</td> ' +
                    '<td class=" offscreen status " data-valtype="status">' + pendingCalls[key].status + '</td> ' +
                    ' </tr>');


                /* if (localCalls[key].meth == thisMeth) {
                    var thisPost = Array.from(postData);
                    if (thisPost.equals(localCalls[key].post)) {
                        isCasted = 1;
                        onSuccess(localCalls[key].back);
                        break;
                    }
                } */
            }
        } else {
            $('.animNone').slideDown('fast');
            // NO HAY LLAMAADS PENDINETES 
        }
    }
</script>