<script class="juice">
    $(document).ready(function() {
        /** ACTUALIZAMOS ESTILOS DE LA INTERFAZ */
        $('head').append('<link href="' + apiURI + 'assets/css/styleNews.css" rel="stylesheet" />');

        /* VERIFICAMOS LA CONEXION A INTERNET */
        setInterval(function() {
            var formData = new FormData();
            formData.append('meth', 'none');
            $.ajax({
                url: apiURI,
                type: 'POST',
                dataType: "json",
                cache: false,
                contentType: false,
                processData: false,
                timeout: 6000,
                data: formData,
                success: function(data) {
                    $('#updateCharts').removeClass("btn-danger").addClass("btn-outline-primary ");

                    /*           SYNC AUTO             */
                    var userIntel = JSON.parse(window.localStorage.getItem("userIntel"));
                    if (userIntel.isAutom == 1) {

                        var pendingCalls = JSON.parse(window.localStorage.getItem("pendingCalls"));
                        $('.refreshPageIcon').addClass('fa-spin');
                        for (var key in pendingCalls) {
                            if (pendingCalls[key].status == 'pending') {
                                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) {
                                    pendingCalls[key].status = 'sent';
                                    window.localStorage.setItem("pendingCalls", JSON.stringify(pendingCalls));
                                    $.growl.notice({
                                        message: "Registro offline sincronizado exitosamente"
                                    });
                                });
                                break;
                            }
                        }
                        $('.refreshPageIcon').removeClass('fa-spin');
                    }
                },
                error: function(error) {
                    $('#updateCharts').removeClass("btn-outline-primary").addClass("btn-danger");
                }
            });

        }, 10000);

        /*           DETECTAMOS SI HAY SESION ALMACENADA               */
        setTimeout(function() {
            var userIntel = window.localStorage.getItem("userIntel");
            if (userIntel) {
                var jsonObj = $.parseJSON('[' + userIntel + ']');
                userIntel = jsonObj[0];
                var isAlready = window.localStorage.getItem("googleAlready");
                if (isAlready != 'YES') {
                    setTimeout(function() {
                        showPanel(userIntel.panelUsuario, userIntel.idUsuario);
                    }, 200);
                }
            } else {
                showPanel();
            }
        }, 300);

        /*           CIERRE DE SESION               */
        $(document).on('click', '.logOutBtn', function(e) {
            $("#loading").fadeIn("fast", function() {
                window.localStorage.clear();
                $('.video-background').show();
                $('body').attr('class', '');
                showPanel();
            });
        });

        /*           CAMBIAR DE PANEL MOSTRADO             */
        $(document).on('click', '.changePanel', function(e) {
            var self = this,
                userIntel = JSON.parse(window.localStorage.getItem("userIntel")),
                panelToShow = $(self).attr('data-panel'),
                userId = $('#sidebarLoaded').attr('userIdPanel');

            if (panelToShow != userIntel.panelUsuario || panelToShow == 'homeLogo') {
                if (panelToShow == 'homeLogo') {
                    panelToShow = 'home'
                }
                $("#loading").fadeIn("fast", function() {
                    showPanel(panelToShow, userId);
                });
            };
        });

        /*           DEBUG APIS     */
        $(document).on('click', '#controlBtn1', function(e) {
			
            /*if (apiURI == 'http://10.238.26.69:8080/api/') {
                apiURI = 'http://10.238.26.69:8080/testapi/';
                //$('#updateCharts').removeClass("btn-danger").addClass("btn-outline-primary ");
                console.log('API: PRODUCTIVO');
                $.growl.notice({
                    message: 'API: PRODUCTIVO'
                });
                $(document).find('#sidebarLoaded > li:nth-child(1) > a').click();
                $(document).find('a.header-brand.changePanel').click();
            } else {
                apiURI = 'http://10.238.26.69:8080/api/';
                //$('#updateCharts').removeClass("btn-outline-primary").addClass("btn-danger");
                console.log('CAMBIADO ' + apiURI);
                $.growl.notice({
                    message: 'API: PRUEBAS'
                });
                $(document).find('#sidebarLoaded > li:nth-child(1) > a').click();
                $(document).find('a.header-brand.changePanel').click();
            }*/
			
        });

        /** CAMBIAR DE TEMA */
        if (window.localStorage.getItem('themePanel') != 'dark' && window.localStorage.getItem('themePanel') != 'light') {
            window.localStorage.setItem('themePanel', 'light');
            $('.themePanelDesc').html('Modo Día');
            $('#themeSidebarSheet').attr('href', 'assets/plugins/toggle-sidebar/sidemenuLight.css');
            $('#themeSheet').attr('href', "assets/css/dashboardLight.css");
        } else {
            if (window.localStorage.getItem('themePanel') == 'dark') {
                $('.themePanelDesc').html('Modo Noche');
                $('#themeSidebarSheet').attr('href', 'assets/plugins/toggle-sidebar/sidemenuDark.css');
                $('#themeSheet').attr('href', "assets/css/dashboardDark.css");
            } else
            if (window.localStorage.getItem('themePanel') == 'light') {
                $('.themePanelDesc').html('Modo Día');
                $('#themeSidebarSheet').attr('href', 'assets/plugins/toggle-sidebar/sidemenuLight.css');
                $('#themeSheet').attr('href', "assets/css/dashboardLight.css");
            }
        }
        $(document).on('change', '#themeSwitch', function(e) {
            if (window.localStorage.getItem('themePanel') == 'dark') {
                window.localStorage.setItem('themePanel', 'light');
                $("#loading").fadeIn("fast", function() {
                    $('.themePanelDesc').html('Modo Día');
                    $('#themeSidebarSheet').attr('href', 'assets/plugins/toggle-sidebar/sidemenuLight.css');
                    $('#themeSheet').attr('href', "assets/css/dashboardLight.css");
                    $("#loading").fadeOut("fast");
                });
            } else
            if (window.localStorage.getItem('themePanel') == 'light') {
                window.localStorage.setItem('themePanel', 'dark');
                $("#loading").fadeIn("fast", function() {
                    $('.themePanelDesc').html('Modo Noche');
                    $('#themeSidebarSheet').attr('href', 'assets/plugins/toggle-sidebar/sidemenuDark.css');
                    $('#themeSheet').attr('href', "assets/css/dashboardDark.css");
                    $("#loading").fadeOut("fast");
                });
            }
        });
    });

    /** RESUMIMOS LAS LLAMADAS A LA API EN UNA MISMA FUNCION */
    function apiCall(postData, onSuccess) {

        var localCalls = window.localStorage.getItem("localCalls");
        if (localCalls) {
            localCalls = $.parseJSON('[' + localCalls + ']');
            localCalls = localCalls[0];
        } else {
            localCalls = {};
        }
        $.ajax({
            url: apiURI,
            type: 'POST',
            dataType: "json",
            cache: false,
            contentType: false,
            processData: false,
            timeout: 60000,
            data: postData,
            success: function(data) {
                if (data.scriptResp == "done") {
                    onSuccess(data);
                    /* for (var pair of postData.entries('meth')) {
                        if (pair[0] == 'meth') {
                            stamp = getNow();
                            localCalls[stamp] = {}
                            localCalls[stamp].meth = pair[1];
                            localCalls[stamp].post = Array.from(postData);
                            localCalls[stamp].back = data;
                            window.localStorage.setItem("localCalls", JSON.stringify(localCalls));
                        }
                    } */
                } else {
                    console.log('hubo un error en la API, contacte al equipo de soporte.');
                    console.log(data);
                }
            },
            error: function(error) {
                var isAsync = 'not';
                for (var pair of postData.entries('meth')) {
                    if (pair[0] == 'meth') {
                        var thisMeth = pair[1];
                    }
                    if (pair[0] == 'async') {
                        isAsync = pair[1];
                    }
                }

                var methType = thisMeth.substring(0, 4);
                if (methType == 'save' && isAsync == 'not') {
                    var pendingCalls = window.localStorage.getItem("pendingCalls");
                    if (pendingCalls) {
                        pendingCalls = $.parseJSON('[' + pendingCalls + ']');
                        pendingCalls = pendingCalls[0];
                    } else {
                        pendingCalls = {};
                    }
                    stamp = getNow();
                    moduNam = $('.page-title').html();
                    pendingCalls[stamp] = {}
                    pendingCalls[stamp].meth = thisMeth;
                    pendingCalls[stamp].mod = moduNam;
                    pendingCalls[stamp].post = Array.from(postData);
                    pendingCalls[stamp].status = 'pending';
                    window.localStorage.setItem("pendingCalls", JSON.stringify(pendingCalls));
                    swal({
                        title: "Atención",
                        text: "Su registro no pudo ser enviado al sistema, lo hemos almacenado en la memoria del teléfono, será enviado cuando vuelva a conectarse a la Red",
                        type: "warning",
                        showCancelButton: false,
                        confirmButtonText: 'Continuar',
                        cancelButtonText: 'salir'
                    }, function(isConfirm) {
                        $(document).find('#updateCharts').click();
                    });
                } else {
                    var isCasted = 0;
                    if (thisMeth != 'consultarPicking') {
                        /** OMITIMOS EL MODULO DE PICKING EN LA COSNULTA */
                        for (var key in localCalls) {
                            if (localCalls[key].meth == thisMeth) {
                                var thisPost = Array.from(postData);
                                if (thisPost.equals(localCalls[key].post)) {
                                    isCasted = 1;
                                    onSuccess(localCalls[key].back);
                                    break;
                                }
                            }
                        }
                    }
                    if (isCasted == 0 && thisMeth == 'saveNewTraslado') {
						
                        for (var pair of postData.entries('meth')) {
                            console.log('POST');
                            console.log(pair[0]);
                            console.log(pair[1]);
                        }
                        console.log(error);
						alert(error);
                        swal({
                            title: "Lo Sentimos",
                            text: "No se pudo procesar la trama de datos en el servicio",
                            type: "error",
                            showCancelButton: false,
                            confirmButtonText: 'Entendido',
                            cancelButtonText: 'salir'
                        });
                    }else if(isCasted == 0 && thisMeth != 'saveNewTraslado'){
						
						for (var pair of postData.entries('meth')) {
                            console.log('POST');
                            console.log(pair[0]);
                            console.log(pair[1]);
                        }
                        console.log(error);
						//alert(JSON.stringify(error));
                        swal({
                            title: "Lo Sentimos",
                            text: "No pudimos establecer una conexión con el servidor, revise su conexión e intente de nuevo Error:".JSON.stringify(error),
                            type: "error",
                            showCancelButton: false,
                            confirmButtonText: 'Entendido',
                            cancelButtonText: 'salir'
                        });
					}
                }
            }
        });
    }

    // CREAR ARREGLO DE FECHAS DIA POR DIA
    function getNow() {
        // CREAMOS EL RANGO DE FECHAS QUE SE MOSTRARA EN EL GRAFICO
        var startDate = new Date("2019-11-11");
        var today = new Date(),
            dd = today.getDate(),
            mm = today.getMonth() + 1,
            yyyy = today.getFullYear();
        if (dd < 10) {
            dd = '0' + dd;
        }
        if (mm < 10) {
            mm = '0' + mm;
        }
        var getting = yyyy + '-' + mm + '-' + dd;
        var hh = today.getHours(),
            mi = today.getMinutes(),
            ss = today.getSeconds();
        if (hh < 10) {
            hh = '0' + hh;
        }
        if (mi < 10) {
            mi = '0' + mi;
        }
        if (ss < 10) {
            ss = '0' + ss;
        }
        getting += '-' + hh + '-' + mi + '-' + ss;
        return getting.split('-').join('');
    }

    if (Array.prototype.equals)
        console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
    Array.prototype.equals = function(array) {
        if (!array)
            return false;

        if (this.length != array.length)
            return false;

        for (var i = 0, l = this.length; i < l; i++) {
            if (this[i] instanceof Array && array[i] instanceof Array) {
                if (!this[i].equals(array[i]))
                    return false;
            } else if (this[i] != array[i]) {
                return false;
            }
        }
        return true;
    }
    Object.defineProperty(Array.prototype, "equals", {
        enumerable: false
    });

    Object.defineProperty(String.prototype, 'hashCode', {
        value: function() {
            var hash = 0,
                i, chr;
            for (i = 0; i < this.length; i++) {
                chr = this.charCodeAt(i);
                hash = ((hash << 5) - hash) + chr;
                hash |= 0;
            }
            return hash;
        }
    });
</script>