<commit_before>angular.module('starter.controllers', [])
        .controller('AppCtrl', function ($scope, $localStorage, $location, pushService) {

            $scope.logOut = function () {
                $localStorage.$reset();
                $location.url('/login');
            };

            pushService.register().then(
                    function (result) {
                        console.log("Registrado en PushService: " + result);

                    },
                    function (err) {
                        console.log("Ocurrio un error al registrar en pushService: " + err);
                    });

        })

        .controller('MascotasCtrl', function ($scope, $http, config, $localStorage, $ionicLoading) {

            $scope.lista = [];
            LeerDatos(function () {
                console.log("Leer datos normal");
            });
            $scope.Actualizar = function () {
                $scope.lista = [];
                console.log("leyendo");
                LeerDatos(function () {
                    console.log("Datos Actualizados");
                });
            };
            $scope.Actualizar_Pull = function () {
                $scope.lista = [];
                console.log("Pull");
                LeerDatos(function () {
                    $scope.$broadcast('scroll.refreshComplete');
                });
            };
            function LeerDatos(callback) {
                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
                console.log("entro");
                $scope.ruta_img = config.ruta_mascota;
                url = config.apiurl + 'mismascotas/' + $localStorage.id_usuario + '/' + 0;
                console.log(url);
                $http.get(url)
                        .success(function (data) {
                            $scope.lista = data;
                            $ionicLoading.hide();
                            callback();
                        });

            }

        })

        .controller('SingleMascotaCtrl', function ($scope, $stateParams, config, $http, $ionicLoading, $localStorage, Camera) {
            $ionicLoading.show({
                content: 'Loading',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });

            $scope.mascota = {};
            url = config.apiurl + 'pet/' + $stateParams.mascotaId + '/' + $localStorage.id_usuario;
            console.log(url);
            $http.get(url)
                    .success(function (data) {
                        $scope.mascota = data[0];
                        if ($scope.mascota.imagen !== null) {
                            $scope.mascota.imagen = config.ruta_mascota + $scope.mascota.imagen;
                        }
                        $ionicLoading.hide();
                    });
            $scope.TakePhoto = function () {

                var options = {
                    correctOrientation: true,
                    quality: 50,
                    encodingType: 0     // 0=JPG 1=PNG
                };
                Camera.getPicture(options).then(onSuccess, onFail);
            };
            var onSuccess = function (FILE_URI) {
                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
                console.log(FILE_URI);
                $scope.mascota.imagen = FILE_URI;
                $scope.$apply();
                send();

            };
            var onFail = function (e) {
                console.log("On fail " + e);
                $ionicLoading.hide();
            }
            function send() {
                var myImg = $scope.mascota.imagen;
                var options = new FileUploadOptions();
                options.fileKey = "file";
                options.fileName = myImg.substr(myImg.lastIndexOf('/') + 1);
                options.mimeType = "image/jpeg";
                options.chunkedMode = false;
                var params = {};
                params.id = $scope.mascota.id;
                params.tipo = "m";
                options.params = params;
                var ft = new FileTransfer();
                ft.upload(myImg, encodeURI("http://webapi.petpharm.net/uploadImage.php"), win, fail, options);
            }

            function win(r) {
                console.log("Code = " + r.responseCode);
                console.log("Response = " + r.response);
                console.log("Sent = " + r.bytesSent);
                $ionicLoading.hide();
            }
            function fail(error) {
                console.log("An error has occurred: Code = " + error.code);
                $ionicLoading.hide();
            }
        })

        .controller('MascotahcCtrl', function ($scope, $stateParams, $ionicLoading, $http, config, $ionicModal) {
            $scope.datos = [];
            $scope.mascotaId = $stateParams.mascotaId;
            $ionicModal.fromTemplateUrl('templates/modal.html', {
                scope: $scope,
                animation: 'slide-in-up'
            }).then(function (modal) {
                $scope.modal = modal;
            });
            $scope.open = function (detalle, fecha) {
                $scope.titulo = fecha;
                $scope.detalle = detalle;
                $scope.modal.show();
            };
            $scope.open2 = function (detalle, fecha) {
                $scope.titulo = fecha;
                $scope.detalle = "";
                separador = "";
                for (i = 0; i < detalle.length; i++) {
                    $scope.detalle += separador + "" + (detalle[i].tipo === "a" ? "Motivo consulta: " : "Diagnostico: ") + "";
                    $scope.detalle += detalle[i].desc;
                    separador = "

";
                }

                $scope.modal.show();
            };
            $scope.closeModal = function () {
                $scope.modal.hide();
            };

            $scope.Actualizar = function () {
                $scope.datos = [];
                console.log("leyendo");
                Consulta(function () {
                    console.log("Datos Actualizados");
                });
            };
            $scope.Actualizar_Pull = function () {
                $scope.datos = [];
                console.log("Pull");
                Consulta(function () {
                    $scope.$broadcast('scroll.refreshComplete');
                });
            };
            Consulta(function () {
                console.log("Datos leidos");
            });
            function Consulta(callback) {
                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
                url = config.apiurl + 'hc/' + $stateParams.mascotaId + '/0';
                console.log(url);
                $http.get(url)
                        .success(function (data) {
                            for (var i = 0; i < data.length; i++) {
                                $scope.datos[i] = {};
                                $scope.datos[i].fecha = data[i].fecha;
                                $scope.datos[i].detalles = [];
                                detalles = data[i].detalles.split(":");
                                for (var j = 0; j < detalles.length; j++) {
                                    var det = detalles[j].split(",");
                                    $scope.datos[i].detalles[j] = {
                                        tipo: det[0],
                                        desc: det[1]
                                    }
                                }
                            }
                            // $scope.datos = data;
                            $ionicLoading.hide();
                            callback();
                        });
            }
        })

        .controller('VeterinariosCtrl', function ($scope, $stateParams) {
            $scope.lista = [
                {nombre: 'Veterinario 1', clinica: 'Clinica 1', id: 1},
                {nombre: 'Veterinario 2', clinica: 'Clinica 2', id: 2},
                {nombre: 'Veterinario 3', clinica: 'Clinica 1', id: 3},
                {nombre: 'Veterinario 4', clinica: 'Clinica 3', id: 4},
                {nombre: 'Veterinario 5', clinica: 'Clinica 4', id: 5},
                {nombre: 'Veterinario 6', clinica: 'Clinica 2', id: 6}
            ];
        })

        .controller('SingleVeterinarioCtrl', function ($scope, $stateParams, $http, $ionicLoading, config) {
            $scope.mascotaId = $stateParams.mascotaId;
            $scope.veterinarioId = $stateParams.veterinarioId;
            $ionicLoading.show({
                content: 'Loading',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            $scope.$on("$stateChangeSuccess", function () {
                $scope.map = {
                    center: {
                        lat: -33.865143,
                        lng: 151.209900,
                        zoom: 16
                    },
                    defaults: {
                        scrollWheelZoom: false,
                        zoomControl: false,
                        dragging: false,
                        tileLayer: "http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png"
                    },
                    markers: {
                        osloMarker: {
                            lat: -33.865143,
                            lng: 151.209900,
                            focus: true,
                            draggable: false,
                            icon: {
                                iconUrl: 'img/ppp.png',
                                iconSize: [100, 107] // size of the icon

                            }
                        }
                    }
                };
                $http.get(config.apiurl + 'vet/' + $stateParams.mascotaId + '/0')
                        .success(function (data) {
                            $scope.vet = data[0];
                            $ionicLoading.hide();
                        });
            });

        })

        .controller('PerfilCtrl', function ($scope, $http, $localStorage, $ionicLoading, config, Camera) {
            $scope.perfil = {};
            $ionicLoading.show({
                content: 'Loading',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            var url = config.apiurl + 'my/' + $localStorage.id_usuario + '/0';
            console.log(url);
            $http.get(url)
                    .success(function (data) {
                        $scope.perfil = data[0];
                        if ($scope.perfil.imagen !== null) {
                            $scope.perfil.imagen = config.ruta_perfil + $scope.perfil.imagen;
                        }
                        $ionicLoading.hide();
                    });

            $scope.TakePhoto = function () {

                var options = {
                    correctOrientation: true,
                    quality: 50,
                    encodingType: 0     // 0=JPG 1=PNG
                };
                Camera.getPicture(options).then(onSuccess, onFail);
            };
            var onSuccess = function (FILE_URI) {
                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
                console.log(FILE_URI);
                $scope.perfil.imagen = FILE_URI;
                $scope.$apply();
                send();

            };
            var onFail = function (e) {
                console.log("On fail " + e);
                $ionicLoading.hide();
            }
            function send() {
                var myImg = $scope.perfil.imagen;
                var options = new FileUploadOptions();
                options.fileKey = "file";
                options.fileName = myImg.substr(myImg.lastIndexOf('/') + 1);
                options.mimeType = "image/jpeg";
                options.chunkedMode = false;
                var params = {};
                params.id = $localStorage.id_usuario;
                params.tipo = "d";
                options.params = params;
                var ft = new FileTransfer();
                ft.upload(myImg, encodeURI("http://webapi.petpharm.net/uploadImage.php"), win, fail, options);
            }

            function win(r) {
                console.log("Code = " + r.responseCode);
                console.log("Response = " + r.response);
                console.log("Sent = " + r.bytesSent);
                $ionicLoading.hide();
            }
            function fail(error) {
                console.log("An error has occurred: Code = " + error.code);
                $ionicLoading.hide();
            }
        })

        .controller('PuntosCtrl', function ($scope, $cordovaGeolocation, $ionicLoading, LocationsService) {

            $scope.lista = [];
            function WIAM() {
                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
                $cordovaGeolocation
                        .getCurrentPosition()
                        .then(function (position) {
                            $scope.map.center.lat = position.coords.latitude;
                            $scope.map.center.lng = position.coords.longitude;
                            $scope.map.center.zoom = 15;
                            $scope.map.markers.now = {
                                lat: position.coords.latitude,
                                lng: position.coords.longitude,
                                message: "Tu estas aqui",
                                focus: true,
                                draggable: false
                            };
                            $ionicLoading.hide();

                        }, function (err) {
                            $ionicLoading.hide();

                            // error
                            console.log("Location error!");
                            console.log(err);
                        });

            }
            $scope.$on("$stateChangeSuccess", function () {

                $scope.puntos = LocationsService.savedLocations;
                $scope.locate = function () {
                    WIAM();
                };
                $scope.map = {
                    center: {
                        lat: -33.865143,
                        lng: 151.209900,
                        zoom: 16,
                    },
                    defaults: {
                        scrollWheelZoom: false,
                        tileLayer: "http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
                    },
                    markers: $scope.puntos,
                };
                WIAM();
            });

        })

        .controller('LoginCtrl', function ($scope, $state, $localStorage, AuthService,
                $ionicLoading) {
            console.log("LLego al login");
            if ($localStorage.username) {
                $state.go("app.gps");
            }
            $localStorage.$reset();

            $scope.loginData = {};
            var userdata = $scope.loginData;

            if (userdata.password === "") {
                $scope.ShowError = false;
            }
            $scope.doLogin = function () {
                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });
                var userdata = $scope.loginData;
                AuthService.Login(userdata.username, userdata.password, function (response) {
                    $scope.loginData.password = "";
                    if (response.result) {
                        $localStorage.username = response.username;
                        $localStorage.id_usuario = response.id_usuario;
                        $ionicLoading.hide();
                        $state.go("app.gps");

                    } else {
                        $ionicLoading.hide();
                        $scope.ShowError = true;
                        $scope.Error = response.data;
                    }
                });

            };

        });
<commit_msg>otra prueba<commit_after>angular.module('starter.controllers', [])
        .controller('AppCtrl', function ($scope, $localStorage, $location, pushService,$ionicPlatform) {

            $scope.logOut = function () {
                $localStorage.$reset();
                $location.url('/login');
            };
            $ionicPlatform.ready(function () {
                pushService.register().then(
                        function (result) {
                            console.log("Registrado en PushService: " + result);

                        },
                        function (err) {
                            console.log("Ocurrio un error al registrar en pushService: " + err);
                        });

            });

        })

                .controller('MascotasCtrl', function ($scope, $http, config, $localStorage, $ionicLoading) {

                    $scope.lista = [];
                    LeerDatos(function () {
                        console.log("Leer datos normal");
                    });
                    $scope.Actualizar = function () {
                        $scope.lista = [];
                        console.log("leyendo");
                        LeerDatos(function () {
                            console.log("Datos Actualizados");
                        });
                    };
                    $scope.Actualizar_Pull = function () {
                        $scope.lista = [];
                        console.log("Pull");
                        LeerDatos(function () {
                            $scope.$broadcast('scroll.refreshComplete');
                        });
                    };
                    function LeerDatos(callback) {
                        $ionicLoading.show({
                            content: 'Loading',
                            animation: 'fade-in',
                            showBackdrop: true,
                            maxWidth: 200,
                            showDelay: 0
                        });
                        console.log("entro");
                        $scope.ruta_img = config.ruta_mascota;
                        url = config.apiurl + 'mismascotas/' + $localStorage.id_usuario + '/' + 0;
                        console.log(url);
                        $http.get(url)
                                .success(function (data) {
                                    $scope.lista = data;
                                    $ionicLoading.hide();
                                    callback();
                                });

                    }

                })

                .controller('SingleMascotaCtrl', function ($scope, $stateParams, config, $http, $ionicLoading, $localStorage, Camera) {
                    $ionicLoading.show({
                        content: 'Loading',
                        animation: 'fade-in',
                        showBackdrop: true,
                        maxWidth: 200,
                        showDelay: 0
                    });

                    $scope.mascota = {};
                    url = config.apiurl + 'pet/' + $stateParams.mascotaId + '/' + $localStorage.id_usuario;
                    console.log(url);
                    $http.get(url)
                            .success(function (data) {
                                $scope.mascota = data[0];
                                if ($scope.mascota.imagen !== null) {
                                    $scope.mascota.imagen = config.ruta_mascota + $scope.mascota.imagen;
                                }
                                $ionicLoading.hide();
                            });
                    $scope.TakePhoto = function () {

                        var options = {
                            correctOrientation: true,
                            quality: 50,
                            encodingType: 0     // 0=JPG 1=PNG
                        };
                        Camera.getPicture(options).then(onSuccess, onFail);
                    };
                    var onSuccess = function (FILE_URI) {
                        $ionicLoading.show({
                            content: 'Loading',
                            animation: 'fade-in',
                            showBackdrop: true,
                            maxWidth: 200,
                            showDelay: 0
                        });
                        console.log(FILE_URI);
                        $scope.mascota.imagen = FILE_URI;
                        $scope.$apply();
                        send();

                    };
                    var onFail = function (e) {
                        console.log("On fail " + e);
                        $ionicLoading.hide();
                    }
                    function send() {
                        var myImg = $scope.mascota.imagen;
                        var options = new FileUploadOptions();
                        options.fileKey = "file";
                        options.fileName = myImg.substr(myImg.lastIndexOf('/') + 1);
                        options.mimeType = "image/jpeg";
                        options.chunkedMode = false;
                        var params = {};
                        params.id = $scope.mascota.id;
                        params.tipo = "m";
                        options.params = params;
                        var ft = new FileTransfer();
                        ft.upload(myImg, encodeURI("http://webapi.petpharm.net/uploadImage.php"), win, fail, options);
                    }

                    function win(r) {
                        console.log("Code = " + r.responseCode);
                        console.log("Response = " + r.response);
                        console.log("Sent = " + r.bytesSent);
                        $ionicLoading.hide();
                    }
                    function fail(error) {
                        console.log("An error has occurred: Code = " + error.code);
                        $ionicLoading.hide();
                    }
                })

                .controller('MascotahcCtrl', function ($scope, $stateParams, $ionicLoading, $http, config, $ionicModal) {
                    $scope.datos = [];
                    $scope.mascotaId = $stateParams.mascotaId;
                    $ionicModal.fromTemplateUrl('templates/modal.html', {
                        scope: $scope,
                        animation: 'slide-in-up'
                    }).then(function (modal) {
                        $scope.modal = modal;
                    });
                    $scope.open = function (detalle, fecha) {
                        $scope.titulo = fecha;
                        $scope.detalle = detalle;
                        $scope.modal.show();
                    };
                    $scope.open2 = function (detalle, fecha) {
                        $scope.titulo = fecha;
                        $scope.detalle = "";
                        separador = "";
                        for (i = 0; i < detalle.length; i++) {
                            $scope.detalle += separador + "" + (detalle[i].tipo === "a" ? "Motivo consulta: " : "Diagnostico: ") + "";
                            $scope.detalle += detalle[i].desc;
                            separador = "

";
                        }

                        $scope.modal.show();
                    };
                    $scope.closeModal = function () {
                        $scope.modal.hide();
                    };

                    $scope.Actualizar = function () {
                        $scope.datos = [];
                        console.log("leyendo");
                        Consulta(function () {
                            console.log("Datos Actualizados");
                        });
                    };
                    $scope.Actualizar_Pull = function () {
                        $scope.datos = [];
                        console.log("Pull");
                        Consulta(function () {
                            $scope.$broadcast('scroll.refreshComplete');
                        });
                    };
                    Consulta(function () {
                        console.log("Datos leidos");
                    });
                    function Consulta(callback) {
                        $ionicLoading.show({
                            content: 'Loading',
                            animation: 'fade-in',
                            showBackdrop: true,
                            maxWidth: 200,
                            showDelay: 0
                        });
                        url = config.apiurl + 'hc/' + $stateParams.mascotaId + '/0';
                        console.log(url);
                        $http.get(url)
                                .success(function (data) {
                                    for (var i = 0; i < data.length; i++) {
                                        $scope.datos[i] = {};
                                        $scope.datos[i].fecha = data[i].fecha;
                                        $scope.datos[i].detalles = [];
                                        detalles = data[i].detalles.split(":");
                                        for (var j = 0; j < detalles.length; j++) {
                                            var det = detalles[j].split(",");
                                            $scope.datos[i].detalles[j] = {
                                                tipo: det[0],
                                                desc: det[1]
                                            }
                                        }
                                    }
                                    // $scope.datos = data;
                                    $ionicLoading.hide();
                                    callback();
                                });
                    }
                })

                .controller('VeterinariosCtrl', function ($scope, $stateParams) {
                    $scope.lista = [
                        {nombre: 'Veterinario 1', clinica: 'Clinica 1', id: 1},
                        {nombre: 'Veterinario 2', clinica: 'Clinica 2', id: 2},
                        {nombre: 'Veterinario 3', clinica: 'Clinica 1', id: 3},
                        {nombre: 'Veterinario 4', clinica: 'Clinica 3', id: 4},
                        {nombre: 'Veterinario 5', clinica: 'Clinica 4', id: 5},
                        {nombre: 'Veterinario 6', clinica: 'Clinica 2', id: 6}
                    ];
                })

                .controller('SingleVeterinarioCtrl', function ($scope, $stateParams, $http, $ionicLoading, config) {
                    $scope.mascotaId = $stateParams.mascotaId;
                    $scope.veterinarioId = $stateParams.veterinarioId;
                    $ionicLoading.show({
                        content: 'Loading',
                        animation: 'fade-in',
                        showBackdrop: true,
                        maxWidth: 200,
                        showDelay: 0
                    });
                    $scope.$on("$stateChangeSuccess", function () {
                        $scope.map = {
                            center: {
                                lat: -33.865143,
                                lng: 151.209900,
                                zoom: 16
                            },
                            defaults: {
                                scrollWheelZoom: false,
                                zoomControl: false,
                                dragging: false,
                                tileLayer: "http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png"
                            },
                            markers: {
                                osloMarker: {
                                    lat: -33.865143,
                                    lng: 151.209900,
                                    focus: true,
                                    draggable: false,
                                    icon: {
                                        iconUrl: 'img/ppp.png',
                                        iconSize: [100, 107] // size of the icon

                                    }
                                }
                            }
                        };
                        $http.get(config.apiurl + 'vet/' + $stateParams.mascotaId + '/0')
                                .success(function (data) {
                                    $scope.vet = data[0];
                                    $ionicLoading.hide();
                                });
                    });

                })

                .controller('PerfilCtrl', function ($scope, $http, $localStorage, $ionicLoading, config, Camera) {
                    $scope.perfil = {};
                    $ionicLoading.show({
                        content: 'Loading',
                        animation: 'fade-in',
                        showBackdrop: true,
                        maxWidth: 200,
                        showDelay: 0
                    });
                    var url = config.apiurl + 'my/' + $localStorage.id_usuario + '/0';
                    console.log(url);
                    $http.get(url)
                            .success(function (data) {
                                $scope.perfil = data[0];
                                if ($scope.perfil.imagen !== null) {
                                    $scope.perfil.imagen = config.ruta_perfil + $scope.perfil.imagen;
                                }
                                $ionicLoading.hide();
                            });

                    $scope.TakePhoto = function () {

                        var options = {
                            correctOrientation: true,
                            quality: 50,
                            encodingType: 0     // 0=JPG 1=PNG
                        };
                        Camera.getPicture(options).then(onSuccess, onFail);
                    };
                    var onSuccess = function (FILE_URI) {
                        $ionicLoading.show({
                            content: 'Loading',
                            animation: 'fade-in',
                            showBackdrop: true,
                            maxWidth: 200,
                            showDelay: 0
                        });
                        console.log(FILE_URI);
                        $scope.perfil.imagen = FILE_URI;
                        $scope.$apply();
                        send();

                    };
                    var onFail = function (e) {
                        console.log("On fail " + e);
                        $ionicLoading.hide();
                    }
                    function send() {
                        var myImg = $scope.perfil.imagen;
                        var options = new FileUploadOptions();
                        options.fileKey = "file";
                        options.fileName = myImg.substr(myImg.lastIndexOf('/') + 1);
                        options.mimeType = "image/jpeg";
                        options.chunkedMode = false;
                        var params = {};
                        params.id = $localStorage.id_usuario;
                        params.tipo = "d";
                        options.params = params;
                        var ft = new FileTransfer();
                        ft.upload(myImg, encodeURI("http://webapi.petpharm.net/uploadImage.php"), win, fail, options);
                    }

                    function win(r) {
                        console.log("Code = " + r.responseCode);
                        console.log("Response = " + r.response);
                        console.log("Sent = " + r.bytesSent);
                        $ionicLoading.hide();
                    }
                    function fail(error) {
                        console.log("An error has occurred: Code = " + error.code);
                        $ionicLoading.hide();
                    }
                })

                .controller('PuntosCtrl', function ($scope, $cordovaGeolocation, $ionicLoading, LocationsService) {

                    $scope.lista = [];
                    function WIAM() {
                        $ionicLoading.show({
                            content: 'Loading',
                            animation: 'fade-in',
                            showBackdrop: true,
                            maxWidth: 200,
                            showDelay: 0
                        });
                        $cordovaGeolocation
                                .getCurrentPosition()
                                .then(function (position) {
                                    $scope.map.center.lat = position.coords.latitude;
                                    $scope.map.center.lng = position.coords.longitude;
                                    $scope.map.center.zoom = 15;
                                    $scope.map.markers.now = {
                                        lat: position.coords.latitude,
                                        lng: position.coords.longitude,
                                        message: "Tu estas aqui",
                                        focus: true,
                                        draggable: false
                                    };
                                    $ionicLoading.hide();

                                }, function (err) {
                                    $ionicLoading.hide();

                                    // error
                                    console.log("Location error!");
                                    console.log(err);
                                });

                    }
                    $scope.$on("$stateChangeSuccess", function () {

                        $scope.puntos = LocationsService.savedLocations;
                        $scope.locate = function () {
                            WIAM();
                        };
                        $scope.map = {
                            center: {
                                lat: -33.865143,
                                lng: 151.209900,
                                zoom: 16,
                            },
                            defaults: {
                                scrollWheelZoom: false,
                                tileLayer: "http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
                            },
                            markers: $scope.puntos,
                        };
                        WIAM();
                    });

                })

                .controller('LoginCtrl', function ($scope, $state, $localStorage, AuthService,
                        $ionicLoading) {
                    console.log("LLego al login");
                    if ($localStorage.username) {
                        $state.go("app.gps");
                    }
                    $localStorage.$reset();

                    $scope.loginData = {};
                    var userdata = $scope.loginData;

                    if (userdata.password === "") {
                        $scope.ShowError = false;
                    }
                    $scope.doLogin = function () {
                        $ionicLoading.show({
                            content: 'Loading',
                            animation: 'fade-in',
                            showBackdrop: true,
                            maxWidth: 200,
                            showDelay: 0
                        });
                        var userdata = $scope.loginData;
                        AuthService.Login(userdata.username, userdata.password, function (response) {
                            $scope.loginData.password = "";
                            if (response.result) {
                                $localStorage.username = response.username;
                                $localStorage.id_usuario = response.id_usuario;
                                $ionicLoading.hide();
                                $state.go("app.gps");

                            } else {
                                $ionicLoading.hide();
                                $scope.ShowError = true;
                                $scope.Error = response.data;
                            }
                        });

                    };

                });
<|endoftext|>


<commit_before>import localforage from 'localforage';
import Vue from 'vue'
import Vuex from 'vuex'
import SpotifyWebApi from 'spotify-web-api-js'

import App from './App.vue'

Vue.use(Vuex);

var store = new Vuex.Store({
  state: {
    loggedIn: false
  },
  mutations: {
    LOGGED_IN (state) {
      state.loggedIn = true;
    },
    LOGGED_OUT (state) {
      state.loggedIn = false;
    }
  },
  // learned_that::actions recieve a context object exposing same methods on store instance
  actions: {
    logOut(context) {
      localforage.clear()
      .then(() => {
        context.commit('LOGGED_OUT');
      })
      .catch((err) => console.error(err));
    }
  }
})

var spotify = new SpotifyWebApi();

Object.defineProperty(Vue.prototype, '$spotify', {value: spotify});

localforage.config({
  name: 'sortzzi'
});

window.vm = new Vue({
  el: '#app',
  store,
  render: h => h(App)
});

<commit_msg>Add simple track cart state management to Vuex store.<commit_after>import localforage from 'localforage';
import Vue from 'vue'
import Vuex from 'vuex'
import SpotifyWebApi from 'spotify-web-api-js'

import App from './App.vue'

Vue.use(Vuex);

var store = new Vuex.Store({
  state: {
    loggedIn: false,
    trackCart: []
  },
  mutations: {
    LOGGED_IN (state) {
      state.loggedIn = true;
    },
    LOGGED_OUT (state) {
      state.loggedIn = false;
    },
    ADD_TO_TRACK_CART (state, payload) {
      if(!state.trackCart.includes(payload) && payload != undefined)
        state.trackCart.push(payload);
    },
    REMOVE_FROM_TRACK_CART(state, payload){
      if(state.trackCart.includes(payload))
        state.trackCart = state.trackCart.filter(item => item != payload);
    },
  },
  // learned_that::actions recieve a context object exposing same methods on store instance
  actions: {
    logOut(context) {
      localforage.clear()
      .then(() => {
        context.commit('LOGGED_OUT');
      })
      .catch((err) => console.error(err));
    }
  }
})

var spotify = new SpotifyWebApi();

Object.defineProperty(Vue.prototype, '$spotify', {value: spotify});

localforage.config({
  name: 'sortzzi'
});

window.vm = new Vue({
  el: '#app',
  store,
  render: h => h(App)
});

<|endoftext|>


<commit_before>'use strict';

/**
 * Compute a `display` property regarding of access display
 * configuration.
 */
module.exports = function display(ctx) {
  ctx.data = ctx.data.filter(function (item) {
    var displayItemAccess = ctx.display.access.indexOf(item.access) !== -1;
    var isAlias = item.alias;
    var displayAlias = ctx.display.alias;

    return displayItemAccess && !(isAlias && !displayAlias);
  });
};
<commit_msg>Ensure `display.access` is defined before testing - Refs SassDoc/sassdoc-theme-default#27<commit_after>'use strict';

/**
 * Compute a `display` property in regards of `display.access`
 * configuration.
 */
module.exports = function display(ctx) {
  ctx.data = ctx.data.filter(function (item) {
    var displayItemAccess = ctx.display.access ? (ctx.display.access.indexOf(item.access) !== -1) : false;
    var isAlias = item.alias;
    var displayAlias = ctx.display.alias;

    return displayItemAccess && !(isAlias && !displayAlias);
  });
};
<|endoftext|>


<commit_before>app.directive('appSocialMedia', function () {

    var template = '' + //'
Redes
' +
    '
' +
        '
' +
            '

' +
        '
' +
        '
' +
            'Tweets by CB1939Canarias ' +
        '
' +
    '
';

    return {
        restrict: 'E',
        scope: false,
        template: template
    };
});
<commit_msg>added pusher in social media<commit_after>app.directive('appSocialMedia', function () {

    var template = '' + //'
Redes
' +
    '
' +
        '
' +
            '

' +
        '
' +
        '

' +
        '
' +
            'Tweets by CB1939Canarias ' +
        '
' +
    '
';

    return {
        restrict: 'E',
        scope: false,
        template: template
    };
});
<|endoftext|>


<commit_before>import buildHierarchy from './buildHierarchy';
import createVisualization from './createVisualization';

const draggingClass = 'chart--dragging';
const chartArea = document.getElementById('Chart');
const demoLink = document.getElementById('demo');
var fileInput;

// initialize
{
    let a = 5;
    a++;
    chartArea.addEventListener('dragover', onDragOver);
    chartArea.addEventListener('dragenter', onDragEnter);
    chartArea.addEventListener('dragleave', onDragLeave);
    chartArea.addEventListener('drop', onDrop);
    chartArea.addEventListener('click', uploadClickListener);

    fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.className = 'hiddenFileInput';
    fileInput.addEventListener('change', onFileChange);
    document.body.appendChild(fileInput);

    demoLink.addEventListener('click', loadDemo);
}

function onDragOver(ev) {
    ev.preventDefault();
}

function onDragEnter(ev) {
    chartArea.classList.add(draggingClass);
}

function onDragLeave(ev) {
    chartArea.classList.remove(draggingClass);
}

function onDrop(ev) {
    ev.preventDefault();

    var file = ev.dataTransfer.files[0];

    var reader = new FileReader();
    reader.onload = loadEv => {
        chartArea.classList.remove(draggingClass);
        handleFileUpload(reader.result);
    };

    reader.readAsText(file);
}

function onFileChange(ev) {
    var fr = new FileReader();
    fr.onloadend = evt => {
        if (evt.target.readyState === FileReader.DONE) {
            handleFileUpload(fr.result);
        }
    };

    fr.readAsText(ev.target.files[0]);
}

function handleFileUpload(jsonText) {
    var json = JSON.parse(jsonText);

    chartArea.classList.remove('chart--needsUpload');
    chartArea.removeEventListener('click', uploadClickListener);

    if (demoLink.parentNode) {
        demoLink.parentNode.removeChild(demoLink);
    }

    createVisualization(buildHierarchy(json), '#Chart');
}

function uploadClickListener(ev) {
    fileInput.click();
}

function loadDemo(ev) {
    var request = new XMLHttpRequest();
    request.open('GET', 'test/stats-demo.json', true);

    request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
            handleFileUpload(request.response);
        }
    };

    request.send();
}
<commit_msg>removed leftover code<commit_after>import buildHierarchy from './buildHierarchy';
import createVisualization from './createVisualization';

const draggingClass = 'chart--dragging';
const chartArea = document.getElementById('Chart');
const demoLink = document.getElementById('demo');
var fileInput;

// initialize
{
    chartArea.addEventListener('dragover', onDragOver);
    chartArea.addEventListener('dragenter', onDragEnter);
    chartArea.addEventListener('dragleave', onDragLeave);
    chartArea.addEventListener('drop', onDrop);
    chartArea.addEventListener('click', uploadClickListener);

    fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.className = 'hiddenFileInput';
    fileInput.addEventListener('change', onFileChange);
    document.body.appendChild(fileInput);

    demoLink.addEventListener('click', loadDemo);
}

function onDragOver(ev) {
    ev.preventDefault();
}

function onDragEnter(ev) {
    chartArea.classList.add(draggingClass);
}

function onDragLeave(ev) {
    chartArea.classList.remove(draggingClass);
}

function onDrop(ev) {
    ev.preventDefault();

    var file = ev.dataTransfer.files[0];

    var reader = new FileReader();
    reader.onload = loadEv => {
        chartArea.classList.remove(draggingClass);
        handleFileUpload(reader.result);
    };

    reader.readAsText(file);
}

function onFileChange(ev) {
    var fr = new FileReader();
    fr.onloadend = evt => {
        if (evt.target.readyState === FileReader.DONE) {
            handleFileUpload(fr.result);
        }
    };

    fr.readAsText(ev.target.files[0]);
}

function handleFileUpload(jsonText) {
    var json = JSON.parse(jsonText);

    chartArea.classList.remove('chart--needsUpload');
    chartArea.removeEventListener('click', uploadClickListener);

    if (demoLink.parentNode) {
        demoLink.parentNode.removeChild(demoLink);
    }

    createVisualization(buildHierarchy(json), '#Chart');
}

function uploadClickListener(ev) {
    fileInput.click();
}

function loadDemo(ev) {
    var request = new XMLHttpRequest();
    request.open('GET', 'test/stats-demo.json', true);

    request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
            handleFileUpload(request.response);
        }
    };

    request.send();
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.ui',
  name: 'MultiChoiceView',

  extendsModel: 'foam.ui.View',

  documentation: 'A View for selecting a set of keys from an array of choices or from a DAO.',

  properties: [
    {
      name: 'prop',
      hidden: true
    },
    {
      name:  'choices',
      type:  'Array[StringField]',
      documentation: 'Array of [value, text] choices.  Simple String values will be upgraded to [value, value]. Can also be a map, in which case this becomes a [key, value] map in enumeration order.',
      defaultValue: [],
      preSet: function(_, a) {
        // If a is a map, instead of an array, we make [key, value] pairs.
        if ( typeof a === 'object' && ! Array.isArray(a) ) {
          var out = [];
          for ( var key in a ) {
            if ( a.hasOwnProperty(key) )
              out.push([key, a[key]]);
          }
          return out;
        }

        a = a.clone();
        // Upgrade single values to [value, value]
        for ( var i = 0 ; i < a.length ; i++ )
          if ( ! Array.isArray(a[i]) )
            a[i] = [a[i], a[i]];
        return a;
      },

      postSet: function(_, choices) {
        var set = this.data;
        var newSet = {};

        for ( var i = 0 ; i < choices.length ; i++ ) {
          var key = choices[i][0];

          if ( set[key] ) newSet[key] = set[key];
        }

        if ( Object.keys(set) !== Object.keys(newSet) ) this.data = newSet;

        this.updateHTML();
      }
    },
    {
      model_: 'FunctionProperty',
      name: 'objToChoice',
      help: 'A Function which adapts an object from the DAO to a [key, value, ...] choice.'
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      onDAOUpdate: 'onDAOUpdate'
    },
    {
      name: 'name',
      type: 'String',
      defaultValue: 'field'
    },
    {
      name: 'helpText',
      type: 'String',
      defaultValue: undefined
    },
    {
      name: 'size',
      type: 'int',
      defaultValue: 1
    }
  ],

  listeners: [
    {
      name: 'onValueChange',
      code: function() {
        console.log('********* args: ', arguments);
      }
    },
    {
      name: 'onDAOUpdate',
      isMerged: 100,
      code: function() {
        this.dao.select(MAP(this.objToChoice))(function(map) {
          // console.log('***** Update Choices ', map.arg2, this.choices);
          this.choices = map.arg2;
        }.bind(this));
      }
    }
  ],

  templates: [
    function toHTML() {/*
<select id="%%id" name="%%name" size="%%size"><% this.toInnerHTML(out); %></select>*/},
    function toInnerHTML() {/*
<% var set = this.data %>
<% if ( this.helpText ) { %>
<option disabled="disabled"><%= escapeHTML(this.helpText) %></option>
<% } %>
<% this.choices.forEach(function(choice) {
  var id = this.nextID(); %>
 <option id="<%= id %>" <% if ( set[choice[0]] ) { %>selected<% } %> value="<%= i %>"><%= escapeHTML(choice[1].toString()) %></option>
<% } %>
*/}
  ],

  methods: {
    initHTML: function() {
      this.SUPER();
      this.onDAOUpdate();
    }
  }
});
<commit_msg>Bug fixes and CSS for MultiChoiceView.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.ui',
  name: 'MultiChoiceView',

  extendsModel: 'foam.ui.View',

  documentation: 'A View for selecting a set of keys from an array of choices or from a DAO.',

  properties: [
    {
      name: 'prop',
      hidden: true
    },
    {
      name:  'choices',
      type:  'Array[StringField]',
      documentation: 'Array of [value, text] choices.  Simple String values will be upgraded to [value, value]. Can also be a map, in which case this becomes a [key, value] map in enumeration order.',
      defaultValue: [],
      preSet: function(_, a) {
        // If a is a map, instead of an array, we make [key, value] pairs.
        if ( typeof a === 'object' && ! Array.isArray(a) ) {
          var out = [];
          for ( var key in a ) {
            if ( a.hasOwnProperty(key) )
              out.push([key, a[key]]);
          }
          return out;
        }

        a = a.clone();
        // Upgrade single values to [value, value]
        for ( var i = 0 ; i < a.length ; i++ )
          if ( ! Array.isArray(a[i]) )
            a[i] = [a[i], a[i]];
        return a;
      },

      postSet: function(_, choices) {
        var set = this.data;
        var newSet = {};

        for ( var i = 0 ; i < choices.length ; i++ ) {
          var key = choices[i][0];

          if ( set[key] ) newSet[key] = set[key];
        }

        if ( Object.keys(set) !== Object.keys(newSet) ) this.data = newSet;

        this.updateHTML();
      }
    },
    {
      model_: 'FunctionProperty',
      name: 'objToChoice',
      help: 'A Function which adapts an object from the DAO to a [key, value, ...] choice.'
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      onDAOUpdate: 'onDAOUpdate'
    },
    {
      name: 'name',
      type: 'String',
      defaultValue: 'field'
    },
    {
      name: 'helpText',
      type: 'String',
      defaultValue: undefined
    },
    {
      name: 'size',
      type: 'int',
      defaultValue: 1
    }
  ],

  listeners: [
    {
      name: 'onValueChange',
      code: function() {
        console.log('********* args: ', arguments);
      }
    },
    {
      name: 'onDAOUpdate',
      isMerged: 100,
      code: function() {
        this.dao.select(MAP(this.objToChoice))(function(map) {
          // console.log('***** Update Choices ', map.arg2, this.choices);
          this.choices = map.arg2;
        }.bind(this));
      }
    }
  ],

  templates: [
    function CSS() {/*
      .multi-choice-view {
        overflow: auto;
        margin-right: 6px;
      }
    */},
    function toHTML() {/*
<select class="multi-choice-view" id="%%id" name="%%name" size="%%size" multiple><% this.toInnerHTML(out); %></select>*/},
    function toInnerHTML() {/*
<% var set = this.data %>
<% if ( this.helpText ) { %>
<option disabled="disabled"><%= escapeHTML(this.helpText) %></option>
<% } %>
<% this.choices.forEach(function(choice) {
  var id = self.nextID(); %>
 <option id="<%= id %>" <% if ( set[choice[0]] ) { %>selected<% } %> value="<%= i %>"><%= escapeHTML(choice[1].toString()) %></option>
<% }); %>
*/}
  ],

  methods: {
    initHTML: function() {
      this.SUPER();
      this.onDAOUpdate();
    }
  }
});
<|endoftext|>


<commit_before>import {Events, Styler, UICorePlugin, template} from 'clappr'
import pluginHtml from './public/playback-rate-selector.html'
import pluginStyle from './public/style.scss'

const DEFAULT_PLAYBACK_RATES = [
  {value: 0.5, label: '0.5x'},
  {value: 0.75, label: '0.75x'},
  {value: 1, label: 'Normal'},
  {value: 1.5, label: '1.5x'},
  {value: 2, label: '2x'}
]

const DEFAULT_PLAYBACK_RATE = 1
const DEFAULT_PLAYBACK_RATE_SUFFIX = 'x' // Used by getTitle method

export default class PlaybackRatePlugin extends UICorePlugin {
  get name() { return 'playback_rate' }
  get template() { return template(pluginHtml) }

  get attributes() {
    return {
      'class': this.name,
      'data-playback-rate-select': ''
    }
  }

  get events() {
    return {
      'click [data-playback-rate-select]': 'onRateSelect',
      'click [data-playback-rate-button]': 'onShowMenu'
    }
  }

  get container() {
    return this.core.activeContainer
      ? this.core.activeContainer
      : this.core.mediaControl.container
  }

  get playback() {
    return this.core.activePlayback
      ? this.core.activePlayback
      : this.core.getCurrentPlayback()
  }

  bindEvents() {
    if (Events.CORE_ACTIVE_CONTAINER_CHANGED)
      this.listenTo(this.core, Events.CORE_ACTIVE_CONTAINER_CHANGED, this.reload)
    else
      this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.reload)

    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.render)
    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_HIDE, this.hideContextMenu)
  }

  getExternalInterface() {
    return {
      getPlaybackRate: this.getSelectedRate,
      setPlaybackRate: this.setSelectedRate
    }
  }

  reload() {
    this.stopListening()
    // Ensure it stop listening before rebind events (avoid duplicate events)
    process.nextTick(() => {
      this.bindEvents()
    })
  }

  shouldRender() {
    return this.container && (
      this.playback.tagName === 'video'
      || this.playback.tagName === 'audio'
    )
  }

  render() {
    if (! this.shouldRender())
      return this

    const cfg = this.core.options.playbackRateConfig || {}
    this.playbackRates = cfg.options || DEFAULT_PLAYBACK_RATES
    this.selectedRate = cfg.defaultValue || DEFAULT_PLAYBACK_RATE
    this.rateSuffix = cfg.rateSuffix || DEFAULT_PLAYBACK_RATE_SUFFIX

    let t = template(pluginHtml)
    let html = t({playbackRates: this.playbackRates, title: this.getTitle()})
    this.$el.html(html)

    let style = Styler.getStyleFor(pluginStyle, {baseUrl: this.core.options.baseUrl})
    this.$el.append(style)

    this.core.mediaControl.$('.media-control-right-panel').append(this.el)
    this.updateText()

    return this
  }

  onRateSelect(event) {
    event.stopPropagation()
    let rate = event.target.dataset.playbackRateSelect // data-playback-rate-select
    this.setSelectedRate(rate)
    this.toggleContextMenu()
    return false
  }

  onShowMenu() {
    this.toggleContextMenu()
  }

  toggleContextMenu() {
    this.$('.playback_rate ul').toggle()
  }

  hideContextMenu() {
    this.$('.playback_rate ul').hide()
  }

  toNumber(value) {
    value = Number(value)
    // Fallback to default playback rate if cannot be converted
    return isNaN(value) ? DEFAULT_PLAYBACK_RATE : value
  }

  setSelectedRate(rate) {
    rate = this.toNumber(rate)
    this.playback.el.playbackRate = rate
    this.selectedRate = rate
    this.updateText()
  }

  getSelectedRate() {
    return this.selectedRate
  }

  setActiveListItem(rateValue) {
    this.$('a').removeClass('active')
    this.$(`a[data-playback-rate-select="${rateValue}"]`).addClass('active')
  }

  buttonElement() {
    return this.$('.playback_rate button')
  }

  getTitle() {
    let rate = this.selectedRate

    for (const i in this.playbackRates) {
      if (this.playbackRates[i].value == rate)
        return this.playbackRates[i].label
    }

    // Unknown rate formatted title
    return rate + this.rateSuffix
  }

  updateText() {
    this.buttonElement().text(this.getTitle())
    this.setActiveListItem(this.selectedRate)
  }
}
<commit_msg>fix: remove serial event rebind<commit_after>import {Events, Styler, UICorePlugin, template} from 'clappr'
import pluginHtml from './public/playback-rate-selector.html'
import pluginStyle from './public/style.scss'

const DEFAULT_PLAYBACK_RATES = [
  {value: 0.5, label: '0.5x'},
  {value: 0.75, label: '0.75x'},
  {value: 1, label: 'Normal'},
  {value: 1.5, label: '1.5x'},
  {value: 2, label: '2x'}
]

const DEFAULT_PLAYBACK_RATE = 1
const DEFAULT_PLAYBACK_RATE_SUFFIX = 'x' // Used by getTitle method

export default class PlaybackRatePlugin extends UICorePlugin {
  get name() { return 'playback_rate' }
  get template() { return template(pluginHtml) }

  get attributes() {
    return {
      'class': this.name,
      'data-playback-rate-select': ''
    }
  }

  get events() {
    return {
      'click [data-playback-rate-select]': 'onRateSelect',
      'click [data-playback-rate-button]': 'onShowMenu'
    }
  }

  get container() {
    return this.core.activeContainer
      ? this.core.activeContainer
      : this.core.mediaControl.container
  }

  get playback() {
    return this.core.activePlayback
      ? this.core.activePlayback
      : this.core.getCurrentPlayback()
  }

  bindEvents() {
    if (Events.CORE_ACTIVE_CONTAINER_CHANGED)
      this.listenTo(this.core, Events.CORE_ACTIVE_CONTAINER_CHANGED, this.reload)
    else
      this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.reload)

    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.render)
    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_HIDE, this.hideContextMenu)
  }

  getExternalInterface() {
    return {
      getPlaybackRate: this.getSelectedRate,
      setPlaybackRate: this.setSelectedRate
    }
  }

  reload() {
    this.stopListening()
    this.bindEvents()
  }

  shouldRender() {
    return this.container && (
      this.playback.tagName === 'video'
      || this.playback.tagName === 'audio'
    )
  }

  render() {
    if (! this.shouldRender())
      return this

    const cfg = this.core.options.playbackRateConfig || {}
    this.playbackRates = cfg.options || DEFAULT_PLAYBACK_RATES
    this.selectedRate = cfg.defaultValue || DEFAULT_PLAYBACK_RATE
    this.rateSuffix = cfg.rateSuffix || DEFAULT_PLAYBACK_RATE_SUFFIX

    let t = template(pluginHtml)
    let html = t({playbackRates: this.playbackRates, title: this.getTitle()})
    this.$el.html(html)

    let style = Styler.getStyleFor(pluginStyle, {baseUrl: this.core.options.baseUrl})
    this.$el.append(style)

    this.core.mediaControl.$('.media-control-right-panel').append(this.el)
    this.updateText()

    return this
  }

  onRateSelect(event) {
    event.stopPropagation()
    let rate = event.target.dataset.playbackRateSelect // data-playback-rate-select
    this.setSelectedRate(rate)
    this.toggleContextMenu()
    return false
  }

  onShowMenu() {
    this.toggleContextMenu()
  }

  toggleContextMenu() {
    this.$('.playback_rate ul').toggle()
  }

  hideContextMenu() {
    this.$('.playback_rate ul').hide()
  }

  toNumber(value) {
    value = Number(value)
    // Fallback to default playback rate if cannot be converted
    return isNaN(value) ? DEFAULT_PLAYBACK_RATE : value
  }

  setSelectedRate(rate) {
    rate = this.toNumber(rate)
    this.playback.el.playbackRate = rate
    this.selectedRate = rate
    this.updateText()
  }

  getSelectedRate() {
    return this.selectedRate
  }

  setActiveListItem(rateValue) {
    this.$('a').removeClass('active')
    this.$(`a[data-playback-rate-select="${rateValue}"]`).addClass('active')
  }

  buttonElement() {
    return this.$('.playback_rate button')
  }

  getTitle() {
    let rate = this.selectedRate

    for (const i in this.playbackRates) {
      if (this.playbackRates[i].value == rate)
        return this.playbackRates[i].label
    }

    // Unknown rate formatted title
    return rate + this.rateSuffix
  }

  updateText() {
    this.buttonElement().text(this.getTitle())
    this.setActiveListItem(this.selectedRate)
  }
}
<|endoftext|>


<commit_before>/*
 * jQuery File Upload Image Preview & Resize Plugin 1.5.0
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2013, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, DataView, Blob, Uint8Array */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'load-image',
            'load-image-meta',
            'load-image-exif',
            'load-image-ios',
            'canvas-to-blob',
            './jquery.fileupload-process'
        ], factory);
    } else {
        // Browser globals:
        factory(
            window.jQuery,
            window.loadImage
        );
    }
}(function ($, loadImage) {
    'use strict';

    // Prepend to the default processQueue:
    $.blueimp.fileupload.prototype.options.processQueue.unshift(
        {
            action: 'loadImageMetaData',
            disableImageHead: '@',
            disableExif: '@',
            disableExifThumbnail: '@',
            disableExifSub: '@',
            disableExifGps: '@',
            disabled: '@disableImageMetaDataLoad'
        },
        {
            action: 'loadImage',
            // Use the action as prefix for the "@" options:
            prefix: true,
            fileTypes: '@',
            maxFileSize: '@',
            noRevoke: '@',
            disabled: '@disableImageLoad'
        },
        {
            action: 'resizeImage',
            // Use "image" as prefix for the "@" options:
            prefix: 'image',
            maxWidth: '@',
            maxHeight: '@',
            minWidth: '@',
            minHeight: '@',
            crop: '@',
            orientation: '@',
            forceResize: '@',
            disabled: '@disableImageResize'
        },
        {
            action: 'saveImage',
            quality: '@imageQuality',
            disabled: '@disableImageResize'
        },
        {
            action: 'saveImageMetaData',
            disabled: '@disableImageMetaDataSave'
        },
        {
            action: 'resizeImage',
            // Use "preview" as prefix for the "@" options:
            prefix: 'preview',
            maxWidth: '@',
            maxHeight: '@',
            minWidth: '@',
            minHeight: '@',
            crop: '@',
            orientation: '@',
            thumbnail: '@',
            canvas: '@',
            disabled: '@disableImagePreview'
        },
        {
            action: 'setImage',
            name: '@imagePreviewName',
            disabled: '@disableImagePreview'
        }
    );

    // The File Upload Resize plugin extends the fileupload widget
    // with image resize functionality:
    $.widget('blueimp.fileupload', $.blueimp.fileupload, {

        options: {
            // The regular expression for the types of images to load:
            // matched against the file type:
            loadImageFileTypes: /^image\/(gif|jpeg|png)$/,
            // The maximum file size of images to load:
            loadImageMaxFileSize: 10000000, // 10MB
            // The maximum width of resized images:
            imageMaxWidth: 1920,
            // The maximum height of resized images:
            imageMaxHeight: 1080,
            // Defines the image orientation (1-8) or takes the orientation
            // value from Exif data if set to true:
            imageOrientation: false,
            // Define if resized images should be cropped or only scaled:
            imageCrop: false,
            // Disable the resize image functionality by default:
            disableImageResize: true,
            // The maximum width of the preview images:
            previewMaxWidth: 80,
            // The maximum height of the preview images:
            previewMaxHeight: 80,
            // Defines the preview orientation (1-8) or takes the orientation
            // value from Exif data if set to true:
            previewOrientation: true,
            // Create the preview using the Exif data thumbnail:
            previewThumbnail: true,
            // Define if preview images should be cropped or only scaled:
            previewCrop: false,
            // Define if preview images should be resized as canvas elements:
            previewCanvas: true
        },

        processActions: {

            // Loads the image given via data.files and data.index
            // as img element, if the browser supports the File API.
            // Accepts the options fileTypes (regular expression)
            // and maxFileSize (integer) to limit the files to load:
            loadImage: function (data, options) {
                if (options.disabled) {
                    return data;
                }
                var that = this,
                    file = data.files[data.index],
                    dfd = $.Deferred();
                if (($.type(options.maxFileSize) === 'number' &&
                            file.size > options.maxFileSize) ||
                        (options.fileTypes &&
                            !options.fileTypes.test(file.type)) ||
                        !loadImage(
                            file,
                            function (img) {
                                if (img.src) {
                                    data.img = img;
                                }
                                dfd.resolveWith(that, [data]);
                            },
                            options
                        )) {
                    return data;
                }
                return dfd.promise();
            },

            // Resizes the image given as data.canvas or data.img
            // and updates data.canvas or data.img with the resized image.
            // Also stores the resized image as preview property.
            // Accepts the options maxWidth, maxHeight, minWidth,
            // minHeight, canvas and crop:
            resizeImage: function (data, options) {
                if (options.disabled || !(data.canvas || data.img)) {
                    return data;
                }
                options = $.extend({canvas: true}, options);
                var that = this,
                    dfd = $.Deferred(),
                    img = (options.canvas && data.canvas) || data.img,
                    resolve = function (newImg) {
                        if (newImg && (newImg.width !== img.width ||
                                newImg.height !== img.height ||
                                options.forceResize)) {
                            data[newImg.getContext ? 'canvas' : 'img'] = newImg;
                        }
                        data.preview = newImg;
                        dfd.resolveWith(that, [data]);
                    },
                    thumbnail;
                if (data.exif) {
                    if (options.orientation === true) {
                        options.orientation = data.exif.get('Orientation');
                    }
                    if (options.thumbnail) {
                        thumbnail = data.exif.get('Thumbnail');
                        if (thumbnail) {
                            loadImage(thumbnail, resolve, options);
                            return dfd.promise();
                        }
                    }
                }
                if (img) {
                    resolve(loadImage.scale(img, options));
                    return dfd.promise();
                }
                return data;
            },

            // Saves the processed image given as data.canvas
            // inplace at data.index of data.files:
            saveImage: function (data, options) {
                if (!data.canvas || options.disabled) {
                    return data;
                }
                var that = this,
                    file = data.files[data.index],
                    dfd = $.Deferred();
                if (data.canvas.toBlob) {
                    data.canvas.toBlob(function (blob) {
                        if (!blob.name) {
                            if (file.type === blob.type) {
                                blob.name = file.name;
                            } else if (file.name) {
                                blob.name = file.name.replace(
                                    /\..+$/,
                                    '.' + blob.type.substr(6)
                                );
                            }
                        }
                        // Store the created blob at the position
                        // of the original file in the files list:
                        data.files[data.index] = blob;
                        dfd.resolveWith(that, [data]);
                    }, file.type, options.quality);
                } else {
                    return data;
                }
                return dfd.promise();
            },

            loadImageMetaData: function (data, options) {
                if (options.disabled) {
                    return data;
                }
                var that = this,
                    dfd = $.Deferred();
                loadImage.parseMetaData(data.files[data.index], function (result) {
                    $.extend(data, result);
                    dfd.resolveWith(that, [data]);
                }, options);
                return dfd.promise();
            },

            saveImageMetaData: function (data, options) {
                if (!(data.imageHead && data.canvas &&
                        data.canvas.toBlob && !options.disabled)) {
                    return data;
                }
                var file = data.files[data.index],
                    blob = new Blob([
                        data.imageHead,
                        // Resized images always have a head size of 20 bytes,
                        // including the JPEG marker and a minimal JFIF header:
                        this._blobSlice.call(file, 20)
                    ], {type: file.type});
                blob.name = file.name;
                data.files[data.index] = blob;
                return data;
            },

            // Sets the resized version of the image as a property of the
            // file object, must be called after "saveImage":
            setImage: function (data, options) {
                if (data.preview && !options.disabled) {
                    data.files[data.index][options.name || 'preview'] = data.preview;
                }
                return data;
            }

        }

    });

}));
<commit_msg>Added imageType option to force the type for the image saved from canvas.<commit_after>/*
 * jQuery File Upload Image Preview & Resize Plugin 1.6.0
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2013, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, DataView, Blob, Uint8Array */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'load-image',
            'load-image-meta',
            'load-image-exif',
            'load-image-ios',
            'canvas-to-blob',
            './jquery.fileupload-process'
        ], factory);
    } else {
        // Browser globals:
        factory(
            window.jQuery,
            window.loadImage
        );
    }
}(function ($, loadImage) {
    'use strict';

    // Prepend to the default processQueue:
    $.blueimp.fileupload.prototype.options.processQueue.unshift(
        {
            action: 'loadImageMetaData',
            disableImageHead: '@',
            disableExif: '@',
            disableExifThumbnail: '@',
            disableExifSub: '@',
            disableExifGps: '@',
            disabled: '@disableImageMetaDataLoad'
        },
        {
            action: 'loadImage',
            // Use the action as prefix for the "@" options:
            prefix: true,
            fileTypes: '@',
            maxFileSize: '@',
            noRevoke: '@',
            disabled: '@disableImageLoad'
        },
        {
            action: 'resizeImage',
            // Use "image" as prefix for the "@" options:
            prefix: 'image',
            maxWidth: '@',
            maxHeight: '@',
            minWidth: '@',
            minHeight: '@',
            crop: '@',
            orientation: '@',
            forceResize: '@',
            disabled: '@disableImageResize'
        },
        {
            action: 'saveImage',
            quality: '@imageQuality',
            type: '@imageType',
            disabled: '@disableImageResize'
        },
        {
            action: 'saveImageMetaData',
            disabled: '@disableImageMetaDataSave'
        },
        {
            action: 'resizeImage',
            // Use "preview" as prefix for the "@" options:
            prefix: 'preview',
            maxWidth: '@',
            maxHeight: '@',
            minWidth: '@',
            minHeight: '@',
            crop: '@',
            orientation: '@',
            thumbnail: '@',
            canvas: '@',
            disabled: '@disableImagePreview'
        },
        {
            action: 'setImage',
            name: '@imagePreviewName',
            disabled: '@disableImagePreview'
        }
    );

    // The File Upload Resize plugin extends the fileupload widget
    // with image resize functionality:
    $.widget('blueimp.fileupload', $.blueimp.fileupload, {

        options: {
            // The regular expression for the types of images to load:
            // matched against the file type:
            loadImageFileTypes: /^image\/(gif|jpeg|png)$/,
            // The maximum file size of images to load:
            loadImageMaxFileSize: 10000000, // 10MB
            // The maximum width of resized images:
            imageMaxWidth: 1920,
            // The maximum height of resized images:
            imageMaxHeight: 1080,
            // Defines the image orientation (1-8) or takes the orientation
            // value from Exif data if set to true:
            imageOrientation: false,
            // Define if resized images should be cropped or only scaled:
            imageCrop: false,
            // Disable the resize image functionality by default:
            disableImageResize: true,
            // The maximum width of the preview images:
            previewMaxWidth: 80,
            // The maximum height of the preview images:
            previewMaxHeight: 80,
            // Defines the preview orientation (1-8) or takes the orientation
            // value from Exif data if set to true:
            previewOrientation: true,
            // Create the preview using the Exif data thumbnail:
            previewThumbnail: true,
            // Define if preview images should be cropped or only scaled:
            previewCrop: false,
            // Define if preview images should be resized as canvas elements:
            previewCanvas: true
        },

        processActions: {

            // Loads the image given via data.files and data.index
            // as img element, if the browser supports the File API.
            // Accepts the options fileTypes (regular expression)
            // and maxFileSize (integer) to limit the files to load:
            loadImage: function (data, options) {
                if (options.disabled) {
                    return data;
                }
                var that = this,
                    file = data.files[data.index],
                    dfd = $.Deferred();
                if (($.type(options.maxFileSize) === 'number' &&
                            file.size > options.maxFileSize) ||
                        (options.fileTypes &&
                            !options.fileTypes.test(file.type)) ||
                        !loadImage(
                            file,
                            function (img) {
                                if (img.src) {
                                    data.img = img;
                                }
                                dfd.resolveWith(that, [data]);
                            },
                            options
                        )) {
                    return data;
                }
                return dfd.promise();
            },

            // Resizes the image given as data.canvas or data.img
            // and updates data.canvas or data.img with the resized image.
            // Also stores the resized image as preview property.
            // Accepts the options maxWidth, maxHeight, minWidth,
            // minHeight, canvas and crop:
            resizeImage: function (data, options) {
                if (options.disabled || !(data.canvas || data.img)) {
                    return data;
                }
                options = $.extend({canvas: true}, options);
                var that = this,
                    dfd = $.Deferred(),
                    img = (options.canvas && data.canvas) || data.img,
                    resolve = function (newImg) {
                        if (newImg && (newImg.width !== img.width ||
                                newImg.height !== img.height ||
                                options.forceResize)) {
                            data[newImg.getContext ? 'canvas' : 'img'] = newImg;
                        }
                        data.preview = newImg;
                        dfd.resolveWith(that, [data]);
                    },
                    thumbnail;
                if (data.exif) {
                    if (options.orientation === true) {
                        options.orientation = data.exif.get('Orientation');
                    }
                    if (options.thumbnail) {
                        thumbnail = data.exif.get('Thumbnail');
                        if (thumbnail) {
                            loadImage(thumbnail, resolve, options);
                            return dfd.promise();
                        }
                    }
                }
                if (img) {
                    resolve(loadImage.scale(img, options));
                    return dfd.promise();
                }
                return data;
            },

            // Saves the processed image given as data.canvas
            // inplace at data.index of data.files:
            saveImage: function (data, options) {
                if (!data.canvas || options.disabled) {
                    return data;
                }
                var that = this,
                    file = data.files[data.index],
                    dfd = $.Deferred();
                if (data.canvas.toBlob) {
                    data.canvas.toBlob(
                        function (blob) {
                            if (!blob.name) {
                                if (file.type === blob.type) {
                                    blob.name = file.name;
                                } else if (file.name) {
                                    blob.name = file.name.replace(
                                        /\..+$/,
                                        '.' + blob.type.substr(6)
                                    );
                                }
                            }
                            // Don't restore invalid meta data:
                            if (file.type !== blob.type) {
                                delete data.imageHead;
                            }
                            // Store the created blob at the position
                            // of the original file in the files list:
                            data.files[data.index] = blob;
                            dfd.resolveWith(that, [data]);
                        },
                        options.type || file.type,
                        options.quality
                    );
                } else {
                    return data;
                }
                return dfd.promise();
            },

            loadImageMetaData: function (data, options) {
                if (options.disabled) {
                    return data;
                }
                var that = this,
                    dfd = $.Deferred();
                loadImage.parseMetaData(data.files[data.index], function (result) {
                    $.extend(data, result);
                    dfd.resolveWith(that, [data]);
                }, options);
                return dfd.promise();
            },

            saveImageMetaData: function (data, options) {
                if (!(data.imageHead && data.canvas &&
                        data.canvas.toBlob && !options.disabled)) {
                    return data;
                }
                var file = data.files[data.index],
                    blob = new Blob([
                        data.imageHead,
                        // Resized images always have a head size of 20 bytes,
                        // including the JPEG marker and a minimal JFIF header:
                        this._blobSlice.call(file, 20)
                    ], {type: file.type});
                blob.name = file.name;
                data.files[data.index] = blob;
                return data;
            },

            // Sets the resized version of the image as a property of the
            // file object, must be called after "saveImage":
            setImage: function (data, options) {
                if (data.preview && !options.disabled) {
                    data.files[data.index][options.name || 'preview'] = data.preview;
                }
                return data;
            }

        }

    });

}));
<|endoftext|>


<commit_before>import Vue from 'vue'
import VueRouter from 'vue-router'
import { sync } from 'vuex-router-sync'

Vue.use(VueRouter)
import App from './App'
import Vuex from 'vuex'
Vue.use(Vuex)

import vuexI18n from 'vuex-i18n'

require('es6-promise').polyfill()

/**
* you can add your module here
*/
let store = new Vuex.Store({
  modules: {
    i18n: vuexI18n.store
  }
})

store.registerModule('vux', {
  state: {
    demoScrollTop: 0,
    isLoading: false,
    direction: 'forward'
  },
  mutations: {
    updateDemoPosition (state, payload) {
      state.demoScrollTop = payload.top
    },
    updateLoadingStatus (state, payload) {
      state.isLoading = payload.isLoading
    },
    updateDirection (state, payload) {
      state.direction = payload.direction
    }
  },
  actions: {
    updateDemoPosition ({commit}, top) {
      commit({type: 'updateDemoPosition', top: top})
    }
  }
})

Vue.use(vuexI18n.plugin, store)

// plugins
import { LocalePlugin, DevicePlugin, ToastPlugin, AlertPlugin, ConfirmPlugin, LoadingPlugin, WechatPlugin, AjaxPlugin, AppPlugin } from 'vux'
Vue.use(DevicePlugin)
Vue.use(ToastPlugin)
Vue.use(AlertPlugin)
Vue.use(ConfirmPlugin)
Vue.use(LoadingPlugin)
Vue.use(WechatPlugin)
Vue.use(AjaxPlugin)
Vue.use(LocalePlugin)

// test
if (process.env.platform === 'app') {
  Vue.use(AppPlugin, store)
}

const wx = Vue.wechat
const http = Vue.http

/**
* -------------------------- 微信分享 ----------------------
* 请不要直接复制下面代码
*/

if (process.env.NODE_ENV === 'production') {
  wx.ready(() => {
    console.log('wechat ready')
    wx.onMenuShareAppMessage({
      title: 'VUX', // 分享标题
      desc: '基于 WeUI 和 Vue 的移动端 UI 组件库',
      link: 'https://vux.li?x-page=wechat_share_message',
      imgUrl: 'https://static.vux.li/logo_520.png'
    })

    wx.onMenuShareTimeline({
      title: 'VUX', // 分享标题
      desc: '基于 WeUI 和 Vue 的移动端 UI 组件库',
      link: 'https://vux.li?x-page=wechat_share_timeline',
      imgUrl: 'https://static.vux.li/logo_520.png'
    })
  })

  const permissions = JSON.stringify(['onMenuShareTimeline', 'onMenuShareAppMessage'])
  const url = document.location.href
  http.post('https://vux.li/jssdk?url=' + encodeURIComponent(url.split('#')[0]) + '&jsApiList=' + permissions).then(res => {
    wx.config(res.data.data)
  })
}

import objectAssign from 'object-assign'

const vuxLocales = require('json-loader!yaml-loader!vux/src/locales/all.yml')
const componentsLocales = require('json-loader!yaml-loader!src/locales/components.yml')
const globalLocales = require('json-loader!yaml-loader!src/locales/global_locales.yml') || {en: {}, 'zh-CN': {}}

const finalLocales = {
  'en': objectAssign(vuxLocales['en'], componentsLocales['en'], globalLocales['en']),
  'zh-CN': objectAssign(vuxLocales['zh-CN'], componentsLocales['zh-CN'], globalLocales['zh-CN'])
}

for (let i in finalLocales) {
  Vue.i18n.add(i, finalLocales[i])
}

const nowLocale = Vue.locale.get()
if (/zh/.test(nowLocale)) {
  Vue.i18n.set('zh-CN')
} else {
  Vue.i18n.set('en')
}

const FastClick = require('fastclick')
FastClick.attach(document.body)

// The following line will be replaced with by vux-loader with routes in ./demo_list.json
const routes = []

const router = new VueRouter({
  routes
})

sync(store, router)

// simple history management
const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)

router.beforeEach(function (to, from, next) {
  store.commit('updateLoadingStatus', {isLoading: true})

  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)

  if (toIndex) {
    if (toIndex > fromIndex || !fromIndex || (toIndex === '0' && fromIndex === '0')) {
      store.commit('updateDirection', {direction: 'forward'})
    } else {
      store.commit('updateDirection', {direction: 'reverse'})
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit('updateDirection', {direction: 'forward'})
  }

  if (/\/http/.test(to.path)) {
    let url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})

router.afterEach(function (to) {
  store.commit('updateLoadingStatus', {isLoading: false})
  if (process.env.NODE_ENV === 'production') {
    ga && ga('set', 'page', to.fullPath)
    ga && ga('send', 'pageview')
  }
})

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')
<commit_msg>Demo: Fix scrolling direction bug<commit_after>import Vue from 'vue'
import VueRouter from 'vue-router'
import { sync } from 'vuex-router-sync'

Vue.use(VueRouter)
import App from './App'
import Vuex from 'vuex'
Vue.use(Vuex)

import vuexI18n from 'vuex-i18n'

require('es6-promise').polyfill()

/**
* you can add your module here
*/
let store = new Vuex.Store({
  modules: {
    i18n: vuexI18n.store
  }
})

store.registerModule('vux', {
  state: {
    demoScrollTop: 0,
    isLoading: false,
    direction: 'forward'
  },
  mutations: {
    updateDemoPosition (state, payload) {
      state.demoScrollTop = payload.top
    },
    updateLoadingStatus (state, payload) {
      state.isLoading = payload.isLoading
    },
    updateDirection (state, payload) {
      state.direction = payload.direction
    }
  },
  actions: {
    updateDemoPosition ({commit}, top) {
      commit({type: 'updateDemoPosition', top: top})
    }
  }
})

Vue.use(vuexI18n.plugin, store)

// plugins
import { LocalePlugin, DevicePlugin, ToastPlugin, AlertPlugin, ConfirmPlugin, LoadingPlugin, WechatPlugin, AjaxPlugin, AppPlugin } from 'vux'
Vue.use(DevicePlugin)
Vue.use(ToastPlugin)
Vue.use(AlertPlugin)
Vue.use(ConfirmPlugin)
Vue.use(LoadingPlugin)
Vue.use(WechatPlugin)
Vue.use(AjaxPlugin)
Vue.use(LocalePlugin)

// test
if (process.env.platform === 'app') {
  Vue.use(AppPlugin, store)
}

const wx = Vue.wechat
const http = Vue.http

/**
* -------------------------- 微信分享 ----------------------
* 请不要直接复制下面代码
*/

if (process.env.NODE_ENV === 'production') {
  wx.ready(() => {
    console.log('wechat ready')
    wx.onMenuShareAppMessage({
      title: 'VUX', // 分享标题
      desc: '基于 WeUI 和 Vue 的移动端 UI 组件库',
      link: 'https://vux.li?x-page=wechat_share_message',
      imgUrl: 'https://static.vux.li/logo_520.png'
    })

    wx.onMenuShareTimeline({
      title: 'VUX', // 分享标题
      desc: '基于 WeUI 和 Vue 的移动端 UI 组件库',
      link: 'https://vux.li?x-page=wechat_share_timeline',
      imgUrl: 'https://static.vux.li/logo_520.png'
    })
  })

  const permissions = JSON.stringify(['onMenuShareTimeline', 'onMenuShareAppMessage'])
  const url = document.location.href
  http.post('https://vux.li/jssdk?url=' + encodeURIComponent(url.split('#')[0]) + '&jsApiList=' + permissions).then(res => {
    wx.config(res.data.data)
  })
}

import objectAssign from 'object-assign'

const vuxLocales = require('json-loader!yaml-loader!vux/src/locales/all.yml')
const componentsLocales = require('json-loader!yaml-loader!src/locales/components.yml')
const globalLocales = require('json-loader!yaml-loader!src/locales/global_locales.yml') || {en: {}, 'zh-CN': {}}

const finalLocales = {
  'en': objectAssign(vuxLocales['en'], componentsLocales['en'], globalLocales['en']),
  'zh-CN': objectAssign(vuxLocales['zh-CN'], componentsLocales['zh-CN'], globalLocales['zh-CN'])
}

for (let i in finalLocales) {
  Vue.i18n.add(i, finalLocales[i])
}

const nowLocale = Vue.locale.get()
if (/zh/.test(nowLocale)) {
  Vue.i18n.set('zh-CN')
} else {
  Vue.i18n.set('en')
}

const FastClick = require('fastclick')
FastClick.attach(document.body)

// The following line will be replaced with by vux-loader with routes in ./demo_list.json
const routes = []

const router = new VueRouter({
  routes
})

sync(store, router)

// simple history management
const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)

router.beforeEach(function (to, from, next) {
  store.commit('updateLoadingStatus', {isLoading: true})

  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)

  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit('updateDirection', {direction: 'forward'})
    } else {
      store.commit('updateDirection', {direction: 'reverse'})
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit('updateDirection', {direction: 'forward'})
  }

  if (/\/http/.test(to.path)) {
    let url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})

router.afterEach(function (to) {
  store.commit('updateLoadingStatus', {isLoading: false})
  if (process.env.NODE_ENV === 'production') {
    ga && ga('set', 'page', to.fullPath)
    ga && ga('send', 'pageview')
  }
})

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')
<|endoftext|>