<commit_before>(function ( $ ) {
    var PLUGIN_IDENTIFIER = 'ytLoad';
    var settings;
    var ajaxError;

    function injectProgressBar() {
        var $progressBar = $('#'+settings.progressBarId);

        if ($progressBar.length == 0) {
            $('body').append('

');
            $progressBar = $('#'+settings.progressBarId);
        }

        return $progressBar;
    }

    function completeProgressBar() {
        var $progressBar = $('#'+settings.progressBarId);

        $progressBar.remove();
        settings.onComplete();
    }

    var methods = {
        init: function(options) {
            ajaxError = false;

            settings = $.extend({
                registerAjaxHandlers: true,
                startPercentage: 30,
                startDuration: null,
                completeDuration: 100,
                fadeDelay: 200,
                fadeDuration: 200,
                progressBarId: PLUGIN_IDENTIFIER,
                onStart: function() { },
                onComplete: function() { },
                onError: function() { }
            }, options);

            if(settings.registerAjaxHandlers) {
                $(document).on('ajaxStart.'+PLUGIN_IDENTIFIER, function() {
                    methods.start();
                });

                $(document).on('ajaxComplete.'+PLUGIN_IDENTIFIER, function() {
                    if($.active < 2) {
                        methods.complete();
                    }
                });

                $(document).on('ajaxError.'+PLUGIN_IDENTIFIER, function() {
                    methods.error();
                });
            }
        },

        start: function() {
            var $progressBar = injectProgressBar();
            ajaxError = false;

            methods.setProgress(settings.startPercentage, settings.startDuration);
            settings.onStart();
        },

        complete: function() {
            var $progressBar = injectProgressBar();
            methods.setProgress(100, settings.completeDuration, function() {
                $progressBar.delay(settings.fadeDelay);
                $progressBar.fadeOut({
                    duration: settings.fadeDuration
                });
            });
        },

        setProgress: function(progress, duration, finished) {
            var $progressBar = injectProgressBar();
            if(!duration) {
                duration = progress * 5;
            }
            var width = (101 / 100) * progress;
            width = Math.round(width * 100) / 100;

            if(width > 99) {
                // TODO: Bug in jquery.transit? Further research needed to submit bug report.
                var doubleCompleteHack = false;
            }

            $progressBar.transit({
                width: width+'%',
                duration: duration,
                complete: function() {
                    if(width > 99) {
                        if(doubleCompleteHack == true) {
                            completeProgressBar();
                        }
                        doubleCompleteHack = true;
                    }
                    if(finished) {
                        finished();
                    }
                }
            });
        },

        error: function() {
            var $progressBar = $('#'+settings.progressBarId);
            $progressBar.addClass('error');

            settings.onError();
        },

        destroy: function() {
            if(settings.registerAjaxHandlers) {
                $(document).off('ajaxStart.'+PLUGIN_IDENTIFIER);
                $(document).off('ajaxComplete.'+PLUGIN_IDENTIFIER);
                $(document).off('ajaxError.'+PLUGIN_IDENTIFIER);
            }
            var $progressBar = $('#'+settings.progressBarId);

            if ($progressBar.length == 0) {
                $progressBar.remove();
            }
        }
    };

    $.ytLoad = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.'+PLUGIN_IDENTIFIER );
        }
    };
}( jQuery ));<commit_msg>'remove' now also removes existing progressBar elements.<commit_after>(function ( $ ) {
    var PLUGIN_IDENTIFIER = 'ytLoad';
    var settings;
    var ajaxError;

    function injectProgressBar() {
        var $progressBar = $('#'+settings.progressBarId);

        if ($progressBar.length == 0) {
            $('body').append('

');
            $progressBar = $('#'+settings.progressBarId);
        }

        return $progressBar;
    }

    function completeProgressBar() {
        var $progressBar = $('#'+settings.progressBarId);

        $progressBar.remove();
        settings.onComplete();
    }

    var methods = {
        init: function(options) {
            ajaxError = false;

            settings = $.extend({
                registerAjaxHandlers: true,
                startPercentage: 30,
                startDuration: null,
                completeDuration: 100,
                fadeDelay: 200,
                fadeDuration: 200,
                progressBarId: PLUGIN_IDENTIFIER,
                onStart: function() { },
                onComplete: function() { },
                onError: function() { }
            }, options);

            if(settings.registerAjaxHandlers) {
                $(document).on('ajaxStart.'+PLUGIN_IDENTIFIER, function() {
                    methods.start();
                });

                $(document).on('ajaxComplete.'+PLUGIN_IDENTIFIER, function() {
                    if($.active < 2) {
                        methods.complete();
                    }
                });

                $(document).on('ajaxError.'+PLUGIN_IDENTIFIER, function() {
                    methods.error();
                });
            }
        },

        start: function() {
            var $progressBar = injectProgressBar();
            ajaxError = false;

            methods.setProgress(settings.startPercentage, settings.startDuration);
            settings.onStart();
        },

        complete: function() {
            var $progressBar = injectProgressBar();
            methods.setProgress(100, settings.completeDuration, function() {
                $progressBar.delay(settings.fadeDelay);
                $progressBar.fadeOut({
                    duration: settings.fadeDuration
                });
            });
        },

        setProgress: function(progress, duration, finished) {
            var $progressBar = injectProgressBar();
            if(!duration) {
                duration = progress * 5;
            }
            var width = (101 / 100) * progress;
            width = Math.round(width * 100) / 100;

            if(width > 99) {
                // TODO: Bug in jquery.transit? Further research needed to submit bug report.
                var doubleCompleteHack = false;
            }

            $progressBar.transit({
                width: width+'%',
                duration: duration,
                complete: function() {
                    if(width > 99) {
                        if(doubleCompleteHack == true) {
                            completeProgressBar();
                        }
                        doubleCompleteHack = true;
                    }
                    if(finished) {
                        finished();
                    }
                }
            });
        },

        error: function() {
            var $progressBar = $('#'+settings.progressBarId);
            $progressBar.addClass('error');

            settings.onError();
        },

        destroy: function() {
            if(settings.registerAjaxHandlers) {
                $(document).off('ajaxStart.'+PLUGIN_IDENTIFIER);
                $(document).off('ajaxComplete.'+PLUGIN_IDENTIFIER);
                $(document).off('ajaxError.'+PLUGIN_IDENTIFIER);
            }
            var $progressBar = $('#'+settings.progressBarId);

            if ($progressBar.length != 0) {
                $progressBar.remove();
            }
        }
    };

    $.ytLoad = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.'+PLUGIN_IDENTIFIER );
        }
    };
}( jQuery ));<|endoftext|>


<commit_before>angular.module('appControllers').controller('GPSCtrl', GPSCtrl); // get the main module contollers set
GPSCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$interval']; // Inject my dependencies

// create our controller function with all necessary logic
function GPSCtrl($rootScope, $scope, $state, $http, $interval) {
    $scope.$parent.helppage = 'plates/gps-help.html';
    $scope.data_list = [];
    $scope.isHidden = false;

    function connect($scope) {
        if (($scope === undefined) || ($scope === null))
            return; // we are getting called once after clicking away from the gps page

        if (($scope.socket === undefined) || ($scope.socket === null)) {
            socket = new WebSocket(URL_GPS_WS);
            $scope.socket = socket; // store socket in scope for enter/exit usage
        }

        $scope.ConnectState = "Disconnected";

        socket.onopen = function (msg) {
            // $scope.ConnectStyle = "label-success";
            $scope.ConnectState = "Connected";
        };

        socket.onclose = function (msg) {
            // $scope.ConnectStyle = "label-danger";
            $scope.ConnectState = "Disconnected";
            $scope.$apply();
            delete $scope.socket;
            setTimeout(function() {connect($scope);}, 1000);
        };

        socket.onerror = function (msg) {
            // $scope.ConnectStyle = "label-danger";
            $scope.ConnectState = "Error";
            resetSituation();
            $scope.$apply();
        };

        socket.onmessage = function (msg) {
            loadSituation(msg.data);
            $scope.$apply(); // trigger any needed refreshing of data
        };
    }

    var situation = {};
    var display_area_size = -1;

    var statusGPS = document.getElementById("status-gps"),
        statusIMU = document.getElementById("status-imu"),
        statusBMP = document.getElementById("status-bmp"),
        statusLog = document.getElementById("status-logging"),
        statusCal = document.getElementById("status-calibrating");

    function sizeMap() {
        var width = 0;
        var el = document.getElementById("map_display").parentElement;
        width = el.offsetWidth; // was  (- (2 * el.offsetLeft))
        if (width !== display_area_size) {
            display_area_size = width;
            $scope.map_width = width;
            $scope.map_height = width;
        }
        return width;
    }

    function setGeoReferenceMap(la, lo) {
        // Mercator projection
        // var map = "img/world.png";
        var map_width = 2530;
        var map_height = 1603;
        var map_zero_x = 1192;
        var map_zero_y = 1124;
        var font_size = 18; // size of font used for marker

        sizeMap();
        var div_width = $scope.map_width;
        var div_height = $scope.map_height;

        // longitude: just scale and shift
        var x = (map_width * (180 + lo) / 360) - (map_width/2 - map_zero_x); // longitude_shift;

        // latitude: using the Mercator projection
        la_rad = la * Math.PI / 180; // convert from degrees to radians
        merc_n = Math.log(Math.tan((la_rad / 2) + (Math.PI / 4))); // do the Mercator projection (w/ equator of 2pi units)
        var y = (map_height / 2) - (map_width * merc_n / (2 * Math.PI)) - (map_height/2 - map_zero_y); // fit it to our map

        // dot = '

';
        //
        $scope.map_pos_x = map_width - Math.round(x - (div_width / 2));
        $scope.map_pos_y = map_height - Math.round(y - (div_height / 2));

        $scope.map_mark_x = Math.round((div_width - (font_size * 0.85)) / 2);
        $scope.map_mark_y = Math.round((div_height - font_size) / 2);
    }

    function loadSituation(data) { // mySituation
        situation = angular.fromJson(data);
        // consider using angular.extend()
        $scope.raw_data = angular.toJson(data, true); // makes it pretty

        $scope.Satellites = situation.GPSSatellites;
        $scope.GPS_satellites_tracked = situation.GPSSatellitesTracked;
        $scope.GPS_satellites_seen = situation.GPSSatellitesSeen;
        $scope.Quality = situation.GPSFixQuality;

        var solutionText = "No Fix";
        if (situation.GPSFixQuality === 2) {
            solutionText = "GPS + SBAS (WAAS / EGNOS)";
        } else if (situation.GPSFixQuality === 1) {
            solutionText = "3D GPS"
        }
        $scope.SolutionText = solutionText;

        $scope.gps_horizontal_accuracy = situation.GPSHorizontalAccuracy.toFixed(1);
        $scope.gps_vertical_accuracy = (situation.GPSVerticalAccuracy*3.2808).toFixed(1); // accuracy is in meters, need to display in ft

        // NACp should be an integer value in the range of 0 .. 11
        // var accuracies = ["≥ 10 NM", "< 10 NM", "< 4 NM", "< 2 NM", "< 1 NM", "< 0.5 NM", "< 0.3 NM", "< 0.1 NM", "< 100 m", "< 30 m", "< 10 m", "< 3 m"];
        // $scope.gps_horizontal_accuracy = accuracies[status.NACp];
        // "LastFixLocalTime":"2015-10-11T16:47:03.523085162Z"

        $scope.gps_lat = situation.GPSLatitude.toFixed(5); // result is string
        $scope.gps_lon = situation.GPSLongitude.toFixed(5); // result is string
        $scope.gps_alt = situation.GPSAltitudeMSL.toFixed(1);
        $scope.gps_track = situation.GPSTrueCourse.toFixed(1);
        $scope.gps_speed = situation.GPSGroundSpeed.toFixed(1);
        $scope.gps_vert_speed = situation.GPSVerticalSpeed.toFixed(1);

        // "LastGroundTrackTime":"0001-01-01T00:00:00Z"

        /* not currently used
            $scope.ahrs_temp = status.Temp;
        */
        $scope.press_time = Date.parse(situation.BaroLastMeasurementTime);
        $scope.gps_time = Date.parse(situation.GPSLastGPSTimeStratuxTime);
        if ($scope.gps_time - $scope.press_time < 1000) {
            $scope.ahrs_alt = Math.round(situation.BaroPressureAltitude.toFixed(0));
        } else {
            $scope.ahrs_alt = "---";
        }

        $scope.ahrs_heading = Math.round(situation.AHRSGyroHeading.toFixed(0));
        // pitch and roll are in degrees
        $scope.ahrs_pitch = situation.AHRSPitch.toFixed(1);
        $scope.ahrs_roll = situation.AHRSRoll.toFixed(1);
        $scope.ahrs_slip_skid = situation.AHRSSlipSkid.toFixed(1);
        ahrs.update(situation.AHRSPitch, situation.AHRSRoll, situation.AHRSGyroHeading, situation.AHRSSlipSkid);

        $scope.ahrs_heading_mag = situation.AHRSMagHeading.toFixed(0);
        $scope.ahrs_gload = situation.AHRSGLoad.toFixed(2);
        gMeter.update(situation.AHRSGLoad);

        if (situation.AHRSTurnRate> 0.25) {
            $scope.ahrs_turn_rate = (60/situation.AHRSTurnRate).toFixed(1); // minutes/turn
        } else {
            $scope.ahrs_turn_rate = '\u221e';
        }
        if (situation.AHRSStatus & 0x01) {
            statusGPS.classList.remove("off");
            statusGPS.classList.add("on");
        } else {
            statusGPS.classList.add("off");
            statusGPS.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x02) {
            if (statusIMU.classList.contains("off")) {
                setTimeout(gMeter.reset(), 1000);
            }
            statusIMU.classList.remove("off");
            statusIMU.classList.add("on");
        } else {
            statusIMU.classList.add("off");
            statusIMU.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x04) {
            statusBMP.classList.remove("off");
            statusBMP.classList.add("on");
        } else {
            statusBMP.classList.add("off");
            statusBMP.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x10) {
            statusLog.classList.remove("off");
            statusLog.classList.add("on");
        } else {
            statusLog.classList.add("off");
            statusLog.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x08) {
            statusCal.classList.add("blink");
            statusCal.classList.remove("on");
            statusCal.innerText = "Caging";
        } else {
            statusCal.classList.remove("blink");
            statusCal.classList.add("on");
            statusCal.innerText = "Ready";
        }
        // "LastAttitudeTime":"2015-10-11T16:47:03.534615187Z"

        setGeoReferenceMap(situation.GPSLatitude, situation.GPSLongitude);
    }

    function resetSituation() { // mySituation
        $scope.raw_data = "error getting gps / ahrs status";
        $scope.ahrs_heading = "---";
        $scope.ahrs_pitch = "--";
        $scope.ahrs_roll = "--";
        $scope.ahrs_slip_skid = "--";
        $scope.ahrs_heading_mag = "---";
        $scope.ahrs_turn_rate = "--";
        $scope.ahrs_gload = "--";
        statusGPS.classList.add("off");
        statusGPS.classList.remove("on");
        statusIMU.classList.add("off");
        statusIMU.classList.remove("on");
        statusBMP.classList.add("off");
        statusBMP.classList.remove("on");
        statusLog.classList.add("off");
        statusLog.classList.remove("on");
        statusCal.classList.add("off");
        statusCal.classList.remove("on");
        statusCal.innerText = "Error";
    }

    function getSatellites() {
        // Simple GET request example (note: response is asynchronous)
        $http.get(URL_SATELLITES_GET).
        then(function (response) {
            loadSatellites(response.data);
        }, function (response) {
            $scope.raw_data = "error getting satellite data";
        });
    }

    function setSatellite(obj, new_satellite) {
        new_satellite.SatelliteNMEA = obj.SatelliteNMEA;
        new_satellite.SatelliteID = obj.SatelliteID;     // Formatted code indicating source and PRN code. e.g. S138==WAAS satellite 138, G2==GPS satellites 2
        new_satellite.Elevation = obj.Elevation;        // Angle above local horizon, -xx to +90
        new_satellite.Azimuth = obj.Azimuth;         // Bearing (degrees true), 0-359
        new_satellite.Signal = obj.Signal;          // Signal strength, 0 - 99; -99 indicates no reception
        new_satellite.InSolution = obj.InSolution;   // is this satellite in the position solution
    }

    function loadSatellites(satellites) {
        if (($scope === undefined) || ($scope === null))
            return; // we are getting called once after clicking away from the status page

        $scope.raw_data = angular.toJson(satellites, true);

        $scope.data_list.length = 0; // clear array
        // we need to use an array so AngularJS can perform sorting; it also means we need to loop to find a tower in the towers set
        for (var key in satellites) {
            //if (satellites[key].Messages_last_minute > 0) {
            var new_satellite = {};
            setSatellite(satellites[key], new_satellite);
            $scope.data_list.push(new_satellite); // add to start of array
            //}
        }
        // $scope.$apply();
    }

    // refresh satellite info once each second (aka polling)
    var updateSatellites = $interval(getSatellites, 1000, 0, false);

    $state.get('gps').onEnter = function () {
        // everything gets handled correctly by the controller
    };

    $state.get('gps').onExit = function () {
        if (($scope.socket !== undefined) && ($scope.socket !== null)) {
            $scope.socket.close();
            $scope.socket = null;
        }
        // stop polling for gps/ahrs status
        $interval.cancel(updateSatellites);
    };

    // GPS/AHRS Controller tasks go here
    var ahrs = new AHRSRenderer("ahrs_display");

    $scope.hideClick = function() {
        $scope.isHidden = !$scope.isHidden;
        var disp = "block";
        if ($scope.isHidden) {
            disp = "none";
        }
        var hiders = document.querySelectorAll(".hider");

        for (var i=0; i < hiders.length; i++) {
            hiders[i].style.display = disp;
        }
    };

    $scope.AHRSCage = function() {
        if (!$scope.IsCaging()) {
            $http.post(URL_AHRS_CAGE).then(function (response) {
                // do nothing
            }, function (response) {
                // do nothing
            });
        }
    };

    $scope.IsCaging = function() {
        var caging = statusCal.innerText === "Caging";
        if (caging) {
            ahrs.turn_off("Calibrating. Fly straight and do not move sensor.");
        } else {
            ahrs.turn_on();
        }
        return caging;
    };

    var gMeter = new GMeterRenderer("gMeter_display", 4.4, -1.76);

    // GPS Controller tasks
    connect($scope); // connect - opens a socket and listens for messages
}
<commit_msg>Only report turn tate < 10 min/turn on web UI.<commit_after>angular.module('appControllers').controller('GPSCtrl', GPSCtrl); // get the main module contollers set
GPSCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$interval']; // Inject my dependencies

// create our controller function with all necessary logic
function GPSCtrl($rootScope, $scope, $state, $http, $interval) {
    $scope.$parent.helppage = 'plates/gps-help.html';
    $scope.data_list = [];
    $scope.isHidden = false;

    function connect($scope) {
        if (($scope === undefined) || ($scope === null))
            return; // we are getting called once after clicking away from the gps page

        if (($scope.socket === undefined) || ($scope.socket === null)) {
            socket = new WebSocket(URL_GPS_WS);
            $scope.socket = socket; // store socket in scope for enter/exit usage
        }

        $scope.ConnectState = "Disconnected";

        socket.onopen = function (msg) {
            // $scope.ConnectStyle = "label-success";
            $scope.ConnectState = "Connected";
        };

        socket.onclose = function (msg) {
            // $scope.ConnectStyle = "label-danger";
            $scope.ConnectState = "Disconnected";
            $scope.$apply();
            delete $scope.socket;
            setTimeout(function() {connect($scope);}, 1000);
        };

        socket.onerror = function (msg) {
            // $scope.ConnectStyle = "label-danger";
            $scope.ConnectState = "Error";
            resetSituation();
            $scope.$apply();
        };

        socket.onmessage = function (msg) {
            loadSituation(msg.data);
            $scope.$apply(); // trigger any needed refreshing of data
        };
    }

    var situation = {};
    var display_area_size = -1;

    var statusGPS = document.getElementById("status-gps"),
        statusIMU = document.getElementById("status-imu"),
        statusBMP = document.getElementById("status-bmp"),
        statusLog = document.getElementById("status-logging"),
        statusCal = document.getElementById("status-calibrating");

    function sizeMap() {
        var width = 0;
        var el = document.getElementById("map_display").parentElement;
        width = el.offsetWidth; // was  (- (2 * el.offsetLeft))
        if (width !== display_area_size) {
            display_area_size = width;
            $scope.map_width = width;
            $scope.map_height = width;
        }
        return width;
    }

    function setGeoReferenceMap(la, lo) {
        // Mercator projection
        // var map = "img/world.png";
        var map_width = 2530;
        var map_height = 1603;
        var map_zero_x = 1192;
        var map_zero_y = 1124;
        var font_size = 18; // size of font used for marker

        sizeMap();
        var div_width = $scope.map_width;
        var div_height = $scope.map_height;

        // longitude: just scale and shift
        var x = (map_width * (180 + lo) / 360) - (map_width/2 - map_zero_x); // longitude_shift;

        // latitude: using the Mercator projection
        la_rad = la * Math.PI / 180; // convert from degrees to radians
        merc_n = Math.log(Math.tan((la_rad / 2) + (Math.PI / 4))); // do the Mercator projection (w/ equator of 2pi units)
        var y = (map_height / 2) - (map_width * merc_n / (2 * Math.PI)) - (map_height/2 - map_zero_y); // fit it to our map

        // dot = '

';
        //
        $scope.map_pos_x = map_width - Math.round(x - (div_width / 2));
        $scope.map_pos_y = map_height - Math.round(y - (div_height / 2));

        $scope.map_mark_x = Math.round((div_width - (font_size * 0.85)) / 2);
        $scope.map_mark_y = Math.round((div_height - font_size) / 2);
    }

    function loadSituation(data) { // mySituation
        situation = angular.fromJson(data);
        // consider using angular.extend()
        $scope.raw_data = angular.toJson(data, true); // makes it pretty

        $scope.Satellites = situation.GPSSatellites;
        $scope.GPS_satellites_tracked = situation.GPSSatellitesTracked;
        $scope.GPS_satellites_seen = situation.GPSSatellitesSeen;
        $scope.Quality = situation.GPSFixQuality;

        var solutionText = "No Fix";
        if (situation.GPSFixQuality === 2) {
            solutionText = "GPS + SBAS (WAAS / EGNOS)";
        } else if (situation.GPSFixQuality === 1) {
            solutionText = "3D GPS"
        }
        $scope.SolutionText = solutionText;

        $scope.gps_horizontal_accuracy = situation.GPSHorizontalAccuracy.toFixed(1);
        $scope.gps_vertical_accuracy = (situation.GPSVerticalAccuracy*3.2808).toFixed(1); // accuracy is in meters, need to display in ft

        // NACp should be an integer value in the range of 0 .. 11
        // var accuracies = ["≥ 10 NM", "< 10 NM", "< 4 NM", "< 2 NM", "< 1 NM", "< 0.5 NM", "< 0.3 NM", "< 0.1 NM", "< 100 m", "< 30 m", "< 10 m", "< 3 m"];
        // $scope.gps_horizontal_accuracy = accuracies[status.NACp];
        // "LastFixLocalTime":"2015-10-11T16:47:03.523085162Z"

        $scope.gps_lat = situation.GPSLatitude.toFixed(5); // result is string
        $scope.gps_lon = situation.GPSLongitude.toFixed(5); // result is string
        $scope.gps_alt = situation.GPSAltitudeMSL.toFixed(1);
        $scope.gps_track = situation.GPSTrueCourse.toFixed(1);
        $scope.gps_speed = situation.GPSGroundSpeed.toFixed(1);
        $scope.gps_vert_speed = situation.GPSVerticalSpeed.toFixed(1);

        // "LastGroundTrackTime":"0001-01-01T00:00:00Z"

        /* not currently used
            $scope.ahrs_temp = status.Temp;
        */
        $scope.press_time = Date.parse(situation.BaroLastMeasurementTime);
        $scope.gps_time = Date.parse(situation.GPSLastGPSTimeStratuxTime);
        if ($scope.gps_time - $scope.press_time < 1000) {
            $scope.ahrs_alt = Math.round(situation.BaroPressureAltitude.toFixed(0));
        } else {
            $scope.ahrs_alt = "---";
        }

        $scope.ahrs_heading = Math.round(situation.AHRSGyroHeading.toFixed(0));
        // pitch and roll are in degrees
        $scope.ahrs_pitch = situation.AHRSPitch.toFixed(1);
        $scope.ahrs_roll = situation.AHRSRoll.toFixed(1);
        $scope.ahrs_slip_skid = situation.AHRSSlipSkid.toFixed(1);
        ahrs.update(situation.AHRSPitch, situation.AHRSRoll, situation.AHRSGyroHeading, situation.AHRSSlipSkid);

        $scope.ahrs_heading_mag = situation.AHRSMagHeading.toFixed(0);
        $scope.ahrs_gload = situation.AHRSGLoad.toFixed(2);
        gMeter.update(situation.AHRSGLoad);

        if (situation.AHRSTurnRate> 0.6031) {
            $scope.ahrs_turn_rate = (6/situation.AHRSTurnRate).toFixed(1); // minutes/turn
        } else {
            $scope.ahrs_turn_rate = '\u221e';
        }
        if (situation.AHRSStatus & 0x01) {
            statusGPS.classList.remove("off");
            statusGPS.classList.add("on");
        } else {
            statusGPS.classList.add("off");
            statusGPS.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x02) {
            if (statusIMU.classList.contains("off")) {
                setTimeout(gMeter.reset(), 1000);
            }
            statusIMU.classList.remove("off");
            statusIMU.classList.add("on");
        } else {
            statusIMU.classList.add("off");
            statusIMU.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x04) {
            statusBMP.classList.remove("off");
            statusBMP.classList.add("on");
        } else {
            statusBMP.classList.add("off");
            statusBMP.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x10) {
            statusLog.classList.remove("off");
            statusLog.classList.add("on");
        } else {
            statusLog.classList.add("off");
            statusLog.classList.remove("on");
        }
        if (situation.AHRSStatus & 0x08) {
            statusCal.classList.add("blink");
            statusCal.classList.remove("on");
            statusCal.innerText = "Caging";
        } else {
            statusCal.classList.remove("blink");
            statusCal.classList.add("on");
            statusCal.innerText = "Ready";
        }
        // "LastAttitudeTime":"2015-10-11T16:47:03.534615187Z"

        setGeoReferenceMap(situation.GPSLatitude, situation.GPSLongitude);
    }

    function resetSituation() { // mySituation
        $scope.raw_data = "error getting gps / ahrs status";
        $scope.ahrs_heading = "---";
        $scope.ahrs_pitch = "--";
        $scope.ahrs_roll = "--";
        $scope.ahrs_slip_skid = "--";
        $scope.ahrs_heading_mag = "---";
        $scope.ahrs_turn_rate = "--";
        $scope.ahrs_gload = "--";
        statusGPS.classList.add("off");
        statusGPS.classList.remove("on");
        statusIMU.classList.add("off");
        statusIMU.classList.remove("on");
        statusBMP.classList.add("off");
        statusBMP.classList.remove("on");
        statusLog.classList.add("off");
        statusLog.classList.remove("on");
        statusCal.classList.add("off");
        statusCal.classList.remove("on");
        statusCal.innerText = "Error";
    }

    function getSatellites() {
        // Simple GET request example (note: response is asynchronous)
        $http.get(URL_SATELLITES_GET).
        then(function (response) {
            loadSatellites(response.data);
        }, function (response) {
            $scope.raw_data = "error getting satellite data";
        });
    }

    function setSatellite(obj, new_satellite) {
        new_satellite.SatelliteNMEA = obj.SatelliteNMEA;
        new_satellite.SatelliteID = obj.SatelliteID;     // Formatted code indicating source and PRN code. e.g. S138==WAAS satellite 138, G2==GPS satellites 2
        new_satellite.Elevation = obj.Elevation;        // Angle above local horizon, -xx to +90
        new_satellite.Azimuth = obj.Azimuth;         // Bearing (degrees true), 0-359
        new_satellite.Signal = obj.Signal;          // Signal strength, 0 - 99; -99 indicates no reception
        new_satellite.InSolution = obj.InSolution;   // is this satellite in the position solution
    }

    function loadSatellites(satellites) {
        if (($scope === undefined) || ($scope === null))
            return; // we are getting called once after clicking away from the status page

        $scope.raw_data = angular.toJson(satellites, true);

        $scope.data_list.length = 0; // clear array
        // we need to use an array so AngularJS can perform sorting; it also means we need to loop to find a tower in the towers set
        for (var key in satellites) {
            //if (satellites[key].Messages_last_minute > 0) {
            var new_satellite = {};
            setSatellite(satellites[key], new_satellite);
            $scope.data_list.push(new_satellite); // add to start of array
            //}
        }
        // $scope.$apply();
    }

    // refresh satellite info once each second (aka polling)
    var updateSatellites = $interval(getSatellites, 1000, 0, false);

    $state.get('gps').onEnter = function () {
        // everything gets handled correctly by the controller
    };

    $state.get('gps').onExit = function () {
        if (($scope.socket !== undefined) && ($scope.socket !== null)) {
            $scope.socket.close();
            $scope.socket = null;
        }
        // stop polling for gps/ahrs status
        $interval.cancel(updateSatellites);
    };

    // GPS/AHRS Controller tasks go here
    var ahrs = new AHRSRenderer("ahrs_display");

    $scope.hideClick = function() {
        $scope.isHidden = !$scope.isHidden;
        var disp = "block";
        if ($scope.isHidden) {
            disp = "none";
        }
        var hiders = document.querySelectorAll(".hider");

        for (var i=0; i < hiders.length; i++) {
            hiders[i].style.display = disp;
        }
    };

    $scope.AHRSCage = function() {
        if (!$scope.IsCaging()) {
            $http.post(URL_AHRS_CAGE).then(function (response) {
                // do nothing
            }, function (response) {
                // do nothing
            });
        }
    };

    $scope.IsCaging = function() {
        var caging = statusCal.innerText === "Caging";
        if (caging) {
            ahrs.turn_off("Calibrating. Fly straight and do not move sensor.");
        } else {
            ahrs.turn_on();
        }
        return caging;
    };

    var gMeter = new GMeterRenderer("gMeter_display", 4.4, -1.76);

    // GPS Controller tasks
    connect($scope); // connect - opens a socket and listens for messages
}
<|endoftext|>


<commit_before>var picsTaken = 0;
var entries = [];

/* execute immediately on load */
reloadEntries();

function getPhoto(data) {
    $('#camera-photo').attr('src', "data:image/jpeg;base64," + data);
}

function getPhotoError () {
    $('#error-output').append('
error capturing photo
');
}

function getPosition (position) {
    var longitude = position.coords.latitude;
    var latitude = position.coords.longitude;
    $('#gis-location').html("GIS coordinates: " + longitude + ", " + latitude);
}

function getPositionError (error) {
    $('#error-output').append('
' + error.message + '
');
}

$('button.camera-control').click(function () {
	++picsTaken;
   	$('#pics-taken').html(picsTaken + " pictures have been taken");
    if (navigator.camera) {
    	var options = {
    		quality: 60,
    		destinationType: Camera.DestinationType.DATA_URL,
    		sourceType: 1,
    		encodingType: 0
    	};
    	navigator.camera.getPicture(getPhoto, getPhotoError, options);
        navigator.geolocation.getCurrentPosition(getPosition, getPositionError);
        $('#error-output').append('
just attempted geolocation
');
    }
});

$('button.save').click(function () {
    entries.append(makeEntry());
    saveEntries();
});

function makeEntry () {
    var currentPhoto = $('#camera-photo').attr('src');
    var currentGisLocation = $('#gis-location').html();
    var currentDescription = $('#description').val();

    var entry = {
        "photo" : currentPhoto,
        "gisLocation" : currentGisLocation,
        "description" : currentDescription
    };
    return entry;
}

function reloadEntries () {
    if (Modernizr.localstorage) {
        if (localStorage["entries"] != null) {
            entries = JSON.parse(localStorage["entries"]);
        }
    }
}

function saveEntries () {
    if (Modernizr.localstorage) {
        localStorage.clear();
            localStorage["entries"] = JSON.stringify(entries);
    }
}
<commit_msg>Tweaks to get geolocation working<commit_after>var picsTaken = 0;
var entries = [];

/* execute immediately on load */
reloadEntries();

function getPhoto(data) {
    $('#camera-photo').attr('src', "data:image/jpeg;base64," + data);
}

function getPhotoError () {
    $('#error-output').append('
error capturing photo
');
}

function getPosition (position) {
    $('#gis-location').html("hello");
    var longitude = position.coords.latitude;
    var latitude = position.coords.longitude;
    $('#gis-location').html("GIS coordinates: " + longitude + ", " + latitude);
}

function getPositionError (error) {
    $('#error-output').append('
' + error.message + '
');
}

$('button.camera-control').click(function () {
	++picsTaken;
   	$('#pics-taken').html(picsTaken + " pictures have been taken");
    if (navigator.camera) {
    	var options = {
    		quality: 60,
    		destinationType: Camera.DestinationType.DATA_URL,
    		sourceType: 1,
    		encodingType: 0
    	};
    	navigator.camera.getPicture(getPhoto, getPhotoError, options);
        navigator.geolocation.getCurrentPosition(getPosition, getPositionError);
    }
});

$('button.save').click(function () {
    entries.append(makeEntry());
    saveEntries();
});

function makeEntry () {
    var currentPhoto = $('#camera-photo').attr('src');
    var currentGisLocation = $('#gis-location').html();
    var currentDescription = $('#description').val();

    var entry = {
        "photo" : currentPhoto,
        "gisLocation" : currentGisLocation,
        "description" : currentDescription
    };
    return entry;
}

function reloadEntries () {
    if (Modernizr.localstorage) {
        if (localStorage["entries"] != null) {
            entries = JSON.parse(localStorage["entries"]);
        }
    }
}

function saveEntries () {
    if (Modernizr.localstorage) {
        localStorage.clear();
            localStorage["entries"] = JSON.stringify(entries);
    }
}
<|endoftext|>


<commit_before>/**
 * Created by Nightpaws on 04/03/2016.
 */
//General requirements
var q = require('q');
var deferred = q.defer();
var config = require('../../../config');

//Database logging components
var messageModel = require('../../models/message.model');
var mongoose = require('mongoose');

//External posting requirements
var Twit = require('twit');
var facebook = require('tiny-facebook-wrapper');

//Twitter accounts for Twit
var first = new Twit({
    consumer_key: config.twitter.first.consumer_key,
    consumer_secret: config.twitter.first.consumer_secret,
    access_token: config.twitter.first.access_token_key,
    access_token_secret: config.twitter.first.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var second = new Twit({
    consumer_key: config.twitter.second.consumer_key,
    consumer_secret: config.twitter.second.consumer_secret,
    access_token: config.twitter.second.access_token_key,
    access_token_secret: config.twitter.second.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var third = new Twit({
    consumer_key: config.twitter.third.consumer_key,
    consumer_secret: config.twitter.third.consumer_secret,
    access_token: config.twitter.third.access_token_key,
    access_token_secret: config.twitter.third.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fourth = new Twit({
    consumer_key: config.twitter.fourth.consumer_key,
    consumer_secret: config.twitter.fourth.consumer_secret,
    access_token: config.twitter.fourth.access_token_key,
    access_token_secret: config.twitter.fourth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fifth = new Twit({
    consumer_key: config.twitter.fifth.consumer_key,
    consumer_secret: config.twitter.fifth.consumer_secret,
    access_token: config.twitter.fifth.access_token_key,
    access_token_secret: config.twitter.fifth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var phd = new Twit({
    consumer_key: config.twitter.phd.consumer_key,
    consumer_secret: config.twitter.phd.consumer_secret,
    access_token: config.twitter.phd.access_token_key,
    access_token_secret: config.twitter.phd.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

//Access Token for Facebook
var accessToken1 = config.facebook.accessToken1;
var accessToken2 = config.facebook.accessToken2;
var accessToken3 = config.facebook.accessToken3;
var accessToken4 = config.facebook.accessToken4;
var accessToken5 = config.facebook.accessToken5;
var accessTokenPhD = config.facebook.accessTokenPhD;

var accounts = {
    submit: function (subject, message, recipients, sender) {

        //Initialise variables needed for submissions
        var q = require('q');
        var deferred = q.defer();
        var one, two, three, four, five, six;
        var s1 = true, s2 = true, s3 = true, s4 = true, s5 = true, s6 = true;

        one = recipients[0];
        two = recipients[1];
        three = recipients[2];
        four = recipients[3];
        five = recipients[4];
        six = recipients[5];

        //Message posting attempted! Log to database
        var msg = new messageModel({
            uid: sender,
            subject: subject,
            message: message,
            year: {
                first: recipients[0],
                second: recipients[1],
                third: recipients[2],
                fourth: recipients[3],
                fifth: recipients[4],
                phd: recipients[5]
            }
        });

        msg.save(function (err) {

            if (err) {

                if (err.code === 11000)
                    deferred.reject('Post flooding detected');
                else
                    deferred.reject('Error posting message');

            } else {
                var wallpost;
                //if message content isn't null
                if (message != null) {
                    var t = subject + "\n\n" + message;
                    wallpost = t;

                    //if subject is long
                    if (subject.length > 100)
                        subject = subject.substring(0, subject.length - 40);
                } else {
                    //if message content is null
                    wallpost = subject;
                }

                //Perform submissions to Social Media
                if (one) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year1 + '/feed', accessToken1, {message: wallpost}, function (error, res) {
                        if (error) {
                            s1 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        if(message!=null) {
                            //If post with contents
                            first.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                        else{
                            //else if subject/tweet only
                            first.post('statuses/update', {status: subject })
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                    });

                }
                if (two) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year2 + '/feed', accessToken2, {message: wallpost}, function (error, res) {
                        if (error) {
                            s2 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        second.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s2 = false;
                                console.log(err);
                            });
                    });

                }
                if (three) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year3 + '/feed', accessToken3, {message: wallpost}, function (error, res) {
                        if (error) {
                            s3 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        third.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s3 = false;
                                console.log(err);
                            });
                    });

                }
                if (four) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year4 + '/feed', accessToken4, {message: wallpost}, function (error, res) {
                        if (error) {
                            s4 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fourth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s4 = false;
                                console.log(err);
                            });
                    });

                }
                if (five) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year5 + '/feed', accessToken5, {message: wallpost}, function (error, res) {
                        if (error) {
                            s5 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fifth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s5 = false;
                                console.log(err);
                            });
                    });

                }
                if (six) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_yearPhD + '/feed', accessTokenPhD, {message: wallpost}, function (error, res) {
                        if (error) {
                            s6 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        phd.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s6 = false;
                                console.log(err);
                            });
                    });

                }
            }
        });

        var successState = [s1, s2, s3, s4, s5, s6];
        deferred.resolve(successState);

        return deferred.promise;
    }

};
module.exports = accounts;<commit_msg>added debug lines to find missing link<commit_after>/**
 * Created by Nightpaws on 04/03/2016.
 */
//General requirements
var q = require('q');
var deferred = q.defer();
var config = require('../../../config');

//Database logging components
var messageModel = require('../../models/message.model');
var mongoose = require('mongoose');

//External posting requirements
var Twit = require('twit');
var facebook = require('tiny-facebook-wrapper');

//Twitter accounts for Twit
var first = new Twit({
    consumer_key: config.twitter.first.consumer_key,
    consumer_secret: config.twitter.first.consumer_secret,
    access_token: config.twitter.first.access_token_key,
    access_token_secret: config.twitter.first.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var second = new Twit({
    consumer_key: config.twitter.second.consumer_key,
    consumer_secret: config.twitter.second.consumer_secret,
    access_token: config.twitter.second.access_token_key,
    access_token_secret: config.twitter.second.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var third = new Twit({
    consumer_key: config.twitter.third.consumer_key,
    consumer_secret: config.twitter.third.consumer_secret,
    access_token: config.twitter.third.access_token_key,
    access_token_secret: config.twitter.third.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fourth = new Twit({
    consumer_key: config.twitter.fourth.consumer_key,
    consumer_secret: config.twitter.fourth.consumer_secret,
    access_token: config.twitter.fourth.access_token_key,
    access_token_secret: config.twitter.fourth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fifth = new Twit({
    consumer_key: config.twitter.fifth.consumer_key,
    consumer_secret: config.twitter.fifth.consumer_secret,
    access_token: config.twitter.fifth.access_token_key,
    access_token_secret: config.twitter.fifth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var phd = new Twit({
    consumer_key: config.twitter.phd.consumer_key,
    consumer_secret: config.twitter.phd.consumer_secret,
    access_token: config.twitter.phd.access_token_key,
    access_token_secret: config.twitter.phd.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

//Access Token for Facebook
var accessToken1 = config.facebook.accessToken1;
var accessToken2 = config.facebook.accessToken2;
var accessToken3 = config.facebook.accessToken3;
var accessToken4 = config.facebook.accessToken4;
var accessToken5 = config.facebook.accessToken5;
var accessTokenPhD = config.facebook.accessTokenPhD;

var accounts = {
    submit: function (subject, message, recipients, sender) {

        //Initialise variables needed for submissions
        var q = require('q');
        var deferred = q.defer();
        var one, two, three, four, five, six;
        var s1 = true, s2 = true, s3 = true, s4 = true, s5 = true, s6 = true;

        one = recipients[0];
        two = recipients[1];
        three = recipients[2];
        four = recipients[3];
        five = recipients[4];
        six = recipients[5];

        //Message posting attempted! Log to database
        var msg = new messageModel({
            uid: sender,
            subject: subject,
            message: message,
            year: {
                first: recipients[0],
                second: recipients[1],
                third: recipients[2],
                fourth: recipients[3],
                fifth: recipients[4],
                phd: recipients[5]
            }
        });

        msg.save(function (err) {

            if (err) {

                if (err.code === 11000)
                    deferred.reject('Post flooding detected');
                else
                    deferred.reject('Error posting message');

            } else {
                var wallpost;

                console.log("DEBUG CODE =========");
                console.log("===subject: "+subject);
                console.log("===message: "+message);

                //if message content isn't null
                if (message != null) {
                    var t = subject + "\n\n" + message;
                    wallpost = t;

                    //if subject is long
                    if (subject.length > 100)
                        subject = subject.substring(0, subject.length - 40);
                } else {
                    //if message content is null
                    wallpost = subject;
                }

                //Perform submissions to Social Media
                if (one) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year1 + '/feed', accessToken1, {message: wallpost}, function (error, res) {
                        if (error) {
                            s1 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        if(message!=null) {
                            //If post with contents
                            first.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                        else{
                            //else if subject/tweet only
                            first.post('statuses/update', {status: subject })
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                    });

                }
                if (two) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year2 + '/feed', accessToken2, {message: wallpost}, function (error, res) {
                        if (error) {
                            s2 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        second.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s2 = false;
                                console.log(err);
                            });
                    });

                }
                if (three) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year3 + '/feed', accessToken3, {message: wallpost}, function (error, res) {
                        if (error) {
                            s3 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        third.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s3 = false;
                                console.log(err);
                            });
                    });

                }
                if (four) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year4 + '/feed', accessToken4, {message: wallpost}, function (error, res) {
                        if (error) {
                            s4 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fourth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s4 = false;
                                console.log(err);
                            });
                    });

                }
                if (five) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year5 + '/feed', accessToken5, {message: wallpost}, function (error, res) {
                        if (error) {
                            s5 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fifth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s5 = false;
                                console.log(err);
                            });
                    });

                }
                if (six) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_yearPhD + '/feed', accessTokenPhD, {message: wallpost}, function (error, res) {
                        if (error) {
                            s6 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        phd.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s6 = false;
                                console.log(err);
                            });
                    });

                }
            }
        });

        var successState = [s1, s2, s3, s4, s5, s6];
        deferred.resolve(successState);

        return deferred.promise;
    }

};
module.exports = accounts;<|endoftext|>


<commit_before>/* eslint-env babel-eslint, node, mocha */

const { itBoth, run } = require('./database_base')
const helpers = require('../src/database/helpers')
const expect = require('chai').expect
const moment = require('moment')
const { randomTableName } = require('./_util')

run('helpers', () => {
  describe('createTableIfNotExists', () => {
    itBoth('Creates if not exists', knex => {
      const randomName = randomTableName('tmp_rnd_')

      return helpers(knex)
        .createTableIfNotExists(randomName, table => {
          table.increments('id')
        })
        .then(() => knex.schema.hasTable(randomName))
        .then(has => expect(has).to.equal(true))
    })

    itBoth("Doesn't throw if already exists", knex => {
      const randomName = randomTableName('tmp_rnd_')

      return helpers(knex)
        .createTableIfNotExists(randomName, table => {
          table.increments('id')
        })
        .then(() => knex.schema.hasTable(randomName))
        .then(has => expect(has).to.equal(true))
        .then(() =>
          helpers(knex).createTableIfNotExists(randomName, table => {
            table.increments('id')
          })
        )
    })
  })

  describe('date', () => {
    itBoth('now works', (knex, sampleTable) => {
      knex(sampleTable)
        .insert({ tTimestamp: helpers(knex).date.now() })
        .then(() => knex(sampleTable).select('*'))
        .then(rows => {
          const delta = moment().diff(moment(rows[0].tTimestamp), 'milliseconds')
          expect(delta).to.be.below(250)
        })
    })

    itBoth('format works', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() => knex(sampleTable).select('*'))
        .then(rows => {
          const delta = moment(rows[1].tTimestamp).diff(moment(rows[0].tTimestamp), 'hours')
          expect(delta).to.be.within(23, 24)
        })
    })

    itBoth('isBefore works (col < exp)', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )
      const between = helpers(knex).date.format(
        moment()
          .add(1, 'hour')
          .toDate()
      )

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isBefore('tTimestamp', between))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(1)
        })
    })

    itBoth('isBefore works (col < date)', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )
      const between = moment()
        .add(1, 'hour')
        .toDate()

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isBefore('tTimestamp', between))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(1)
        })
    })

    itBoth('isAfter works (col < date)', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )
      const between = moment()
        .add(1, 'hour')
        .toDate()

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isAfter('tTimestamp', between))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(2)
        })
    })

    itBoth('isBetween works', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isBetween('tTimestamp', now, later))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(2)
        })
    })

    itBoth('isSameDay works', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const laterToday = helpers(knex).date.format(
        moment()
          .add(1, 'hours')
          .toDate()
      )
      const tomorrow = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )

      return knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: laterToday }))
        .then(() => knex(sampleTable).insert({ tTimestamp: tomorrow }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isSameDay('tTimestamp', now))
            .select('*')
        )
        .then(rows => {
          return expect(rows.length).to.equal(2)
        })
    })
  })
})
<commit_msg>fix(tests): fixed isSameDay test<commit_after>/* eslint-env babel-eslint, node, mocha */

const { itBoth, run } = require('./database_base')
const helpers = require('../src/database/helpers')
const expect = require('chai').expect
const moment = require('moment')
const { randomTableName } = require('./_util')

run('helpers', () => {
  describe('createTableIfNotExists', () => {
    itBoth('Creates if not exists', knex => {
      const randomName = randomTableName('tmp_rnd_')

      return helpers(knex)
        .createTableIfNotExists(randomName, table => {
          table.increments('id')
        })
        .then(() => knex.schema.hasTable(randomName))
        .then(has => expect(has).to.equal(true))
    })

    itBoth("Doesn't throw if already exists", knex => {
      const randomName = randomTableName('tmp_rnd_')

      return helpers(knex)
        .createTableIfNotExists(randomName, table => {
          table.increments('id')
        })
        .then(() => knex.schema.hasTable(randomName))
        .then(has => expect(has).to.equal(true))
        .then(() =>
          helpers(knex).createTableIfNotExists(randomName, table => {
            table.increments('id')
          })
        )
    })
  })

  describe('date', () => {
    itBoth('now works', (knex, sampleTable) => {
      knex(sampleTable)
        .insert({ tTimestamp: helpers(knex).date.now() })
        .then(() => knex(sampleTable).select('*'))
        .then(rows => {
          const delta = moment().diff(moment(rows[0].tTimestamp), 'milliseconds')
          expect(delta).to.be.below(250)
        })
    })

    itBoth('format works', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() => knex(sampleTable).select('*'))
        .then(rows => {
          const delta = moment(rows[1].tTimestamp).diff(moment(rows[0].tTimestamp), 'hours')
          expect(delta).to.be.within(23, 24)
        })
    })

    itBoth('isBefore works (col < exp)', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )
      const between = helpers(knex).date.format(
        moment()
          .add(1, 'hour')
          .toDate()
      )

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isBefore('tTimestamp', between))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(1)
        })
    })

    itBoth('isBefore works (col < date)', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )
      const between = moment()
        .add(1, 'hour')
        .toDate()

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isBefore('tTimestamp', between))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(1)
        })
    })

    itBoth('isAfter works (col < date)', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )
      const between = moment()
        .add(1, 'hour')
        .toDate()

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isAfter('tTimestamp', between))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(2)
        })
    })

    itBoth('isBetween works', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const later = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )

      knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: later }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isBetween('tTimestamp', now, later))
            .select('*')
        )
        .then(rows => {
          expect(rows.length).to.equal(1)
          expect(rows[0].tId).to.equal(2)
        })
    })

    itBoth('isSameDay works', (knex, sampleTable) => {
      const now = helpers(knex).date.now()
      const laterToday = helpers(knex).date.format(
        moment()
          .add(1, 'minutes')
          .toDate()
      )
      const tomorrow = helpers(knex).date.format(
        moment()
          .add(1, 'days')
          .toDate()
      )

      return knex(sampleTable)
        .insert({ tTimestamp: now })
        .then(() => knex(sampleTable).insert({ tTimestamp: laterToday }))
        .then(() => knex(sampleTable).insert({ tTimestamp: tomorrow }))
        .then(() =>
          knex(sampleTable)
            .whereRaw(helpers(knex).date.isSameDay('tTimestamp', now))
            .select('*')
        )
        .then(rows => {
          return expect(rows.length).to.equal(2)
        })
    })
  })
})
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Icon from '../../Icon';

export default class TableHeaderCell extends Component {

  static propTypes = {
    children: PropTypes.node,
    scope: PropTypes.string,
    inputId: PropTypes.string,
    containerId: PropTypes.string,
    inputLabel: PropTypes.string,
    columnSort: PropTypes.func
  }

  static defaultProps = {
    scope: 'col'
  }

  constructor(props) {
    super(props)

    this.state = {
      iconName: 'sortable-18'
    }

    this.selectAll = _selectAll.bind(this);
    this.handleKey = _handleKey.bind(this);
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKey);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKey);
  }

  componentDidUpdate() {
    if (this.props.columnSort) this.props.columnSort();
  }

  iconToggle = () => {
    const { iconName } = this.state;
    if (iconName === 'sortable-18') {
      this.setState({ iconName: 'sort-up-18' })
    } else if (iconName === 'sort-up-18') {
      this.setState({ iconName: 'sort-down-18' })
    } else if (iconName === 'sort-down-18') {
      this.setState({ iconName: 'sort-up-18' })
    }
  }

  render() {
    const { children, scope, inputId, containerId, inputLabel, columnSort } = this.props;
    const { selectable, sortable } = this.context;
    const { iconName } = this.state;
    const sortClass = sortable ? 'pe-table__sortable' : null;

    return (

        {
          selectable && !children
            ?

                <input type="checkbox" id={inputId} />
                {inputLabel}

                  <Icon name="check-sm-18" />

            : children
        }
        {
          columnSort &&
            <button type="button" className="pe-icon--btn" onClick={this.iconToggle}>
              <Icon name={iconName} />
            </button>
        }

    )
  }
}

TableHeaderCell.contextTypes = {
  selectable: PropTypes.bool,
  sortable: PropTypes.bool
}

function _selectAll() {
  const checkboxes = document.querySelectorAll('div.pe-checkbox input');
  for (let i = 1; i < checkboxes.length; i++) {
    checkboxes[i].checked = checkboxes[0].checked;
  }
}

function _handleKey(e) {
  if (e.which === 32) {
    this.selectAll;
  }
}
<commit_msg>chore: ternary tweak<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Icon from '../../Icon';

export default class TableHeaderCell extends Component {

  static propTypes = {
    children: PropTypes.node,
    scope: PropTypes.string,
    inputId: PropTypes.string,
    containerId: PropTypes.string,
    inputLabel: PropTypes.string,
    columnSort: PropTypes.func
  }

  static defaultProps = {
    scope: 'col'
  }

  constructor(props) {
    super(props)

    this.state = {
      iconName: 'sortable-18'
    }

    this.selectAll = _selectAll.bind(this);
    this.handleKey = _handleKey.bind(this);
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKey);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKey);
  }

  componentDidUpdate() {
    if (this.props.columnSort) this.props.columnSort();
  }

  iconToggle = () => {
    const { iconName } = this.state;
    if (iconName === 'sortable-18') {
      this.setState({ iconName: 'sort-up-18' })
    } else if (iconName === 'sort-up-18') {
      this.setState({ iconName: 'sort-down-18' })
    } else if (iconName === 'sort-down-18') {
      this.setState({ iconName: 'sort-up-18' })
    }
  }

  render() {
    const { children, scope, inputId, containerId, inputLabel, columnSort } = this.props;
    const { selectable, sortable } = this.context;
    const { iconName } = this.state;
    const sortClass = sortable ? 'pe-table__sortable' :'';

    return (

        {
          selectable && !children
            ?

                <input type="checkbox" id={inputId} />
                {inputLabel}

                  <Icon name="check-sm-18" />

            : children
        }
        {
          columnSort &&
            <button type="button" className="pe-icon--btn" onClick={this.iconToggle}>
              <Icon name={iconName} />
            </button>
        }

    )
  }
}

TableHeaderCell.contextTypes = {
  selectable: PropTypes.bool,
  sortable: PropTypes.bool
}

function _selectAll() {
  const checkboxes = document.querySelectorAll('div.pe-checkbox input');
  for (let i = 1; i < checkboxes.length; i++) {
    checkboxes[i].checked = checkboxes[0].checked;
  }
}

function _handleKey(e) {
  if (e.which === 32) {
    this.selectAll;
  }
}
<|endoftext|>


<commit_before>
(function() {

// map mobile control
cdb.vis.Overlay.register('mobile', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '\

\

\

\

\
    \
    ',
    data.templateType || 'mustache'
  );

  var mobile = new cdb.geo.ui.Mobile({
    template: template,
    torqueLayer: data.torqueLayer,
    legends: data.legends,
    map: data.map
  });

  return mobile.render();
});

// map zoom control
cdb.vis.Overlay.register('zoom', function(data, vis) {

  if(!data.template) {
    vis.trigger('error', 'zoom template is empty')
    return;
  }

  var zoom = new cdb.geo.ui.Zoom({
    model: data.map,
    template: cdb.core.Template.compile(data.template)
  });

  return zoom.render();
});

// Tiles loader
cdb.vis.Overlay.register('loader', function(data) {

  var tilesLoader = new cdb.geo.ui.TilesLoader({
    template: cdb.core.Template.compile(data.template)
  });

  return tilesLoader.render();
});

cdb.vis.Overlay.register('time_slider', function(data, viz) {
  var slider = new cdb.geo.ui.TimeSlider(data);
  return slider.render();
});

// Header to show informtion (title and description)
cdb.vis.Overlay.register('header', function(data, vis) {
  var MAX_SHORT_DESCRIPTION_LENGTH = 100;

  // Add the complete url for facebook and twitter
  if (location.href) {
    data.share_url = encodeURIComponent(location.href);
  } else {
    data.share_url = data.url;
  }

  var template = cdb.core.Template.compile(
    data.template || "\
      {{#title}}\

\
          {{#url}}\
            {{title}}\
          {{/url}}\
          {{^url}}\
            {{title}}\
          {{/url}}\

\
      {{/title}}\
      {{#description}}
{{description}}
{{/description}}\
      {{#mobile_shareable}}\

\
          F\
          T\

\
      {{/mobile_shareable}}\
    ",
    data.templateType || 'mustache'
  );

  function truncate(s, length) {
    return s.substr(0, length-1) + (s.length > length ? '…' : '');
  }

  var title       = data.map.get('title');
  var description = data.map.get('description');

  var facebook_title = title + ": " + description;
  var twitter_title;

  if (title && description) {
    twitter_title = truncate(title + ": " + description, 112) + " %23map "
  } else if (title) {
    twitter_title = truncate(title, 112) + " %23map"
  } else if (description){
    twitter_title = truncate(description, 112) + " %23map"
  } else {
    twitter_title = "%23map"
  }

  var shareable = (data.shareable == "false" || !data.shareable) ? null : data.shareable;
  var mobile_shareable = shareable;

  mobile_shareable = mobile_shareable && (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));

  var header = new cdb.geo.ui.Header({
    title: title,
    description: description,
    facebook_title: facebook_title,
    twitter_title: twitter_title,
    url: data.url,
    share_url: data.share_url,
    mobile_shareable: mobile_shareable,
    shareable: shareable && !mobile_shareable,
    template: template
  });

  return header.render();
});

// infowindow
cdb.vis.Overlay.register('infowindow', function(data, vis) {

  if (_.size(data.fields) == 0) {
    return null;
  }

  var infowindowModel = new cdb.geo.ui.InfowindowModel({
    template: data.template,
    alternative_names: data.alternative_names,
    fields: data.fields,
    template_name: data.template_name
  });

  var templateType = data.templateType || 'mustache';

  var infowindow = new cdb.geo.ui.Infowindow({
     model: infowindowModel,
     mapView: vis.mapView,
     template: new cdb.core.Template({ template: data.template, type: templateType}).asFunction()
  });

  return infowindow;
});

// layer_selector
cdb.vis.Overlay.register('layer_selector', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '\
      Visible layers

\
      ',
    data.templateType || 'underscore'
  );

  var dropdown_template = cdb.core.Template.compile(
    data.template || '\

\
      ',
    data.templateType || 'underscore'
  );

  var layerSelector = new cdb.geo.ui.LayerSelector({
    mapView: vis.mapView,
    template: template,
    dropdown_template: dropdown_template,
    layer_names: data.layer_names
  });

  if(vis.legends) {
    layerSelector.bind('change:visible', function(visible, order, layer) {
      if (layer.get('type') === 'layergroup') {
        var legend = vis.legends && vis.legends.getLegendByIndex(order);
        if(legend) {
          legend[visible ? 'show': 'hide']();
        }
      } else if (layer.get('type') === 'torque') {
        var timeSlider = vis.getOverlay('time_slider');
        if (timeSlider) {
          timeSlider[visible ? 'show': 'hide']();
        }
      }

    });
  }

  return layerSelector.render();
});

// fullscreen
cdb.vis.Overlay.register('fullscreen', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '',
    data.templateType || 'mustache'
  );

  var fullscreen = new cdb.ui.common.FullScreen({
    doc: "#map > div",
    mapView: vis.mapView,
    template: template
  });

  return fullscreen.render();

});

// share content
cdb.vis.Overlay.register('share', function(data, vis) {

  // Add the complete url for facebook and twitter
  if (location.href) {
    data.share_url = encodeURIComponent(location.href);
  } else {
    data.share_url = data.url;
  }

  var template = cdb.core.Template.compile(
    data.template || '\

\

\
          x\

\

Share this map
\

\

\

\

Social
\

\

Share on Facebook
\

Share on Twitter
\

\

\

Embed this map
\
             <textarea id="" name="" cols="30" rows="10">{{ code }}</textarea>\

\

\

\

\
    ',
    data.templateType || 'mustache'
  );

  var code = "";

  var dialog = new cdb.ui.common.ShareDialog({
    title: data.map.get("title"),
    description: data.map.get("description"),
    model: vis.map,
    code: code,
    url: data.url,
    share_url: data.share_url,
    template: template,
    target: $(".cartodb-share a"),
    size: $(document).width() > 400 ? "" : "small",
    width: $(document).width() > 400 ? 430 : 216
  });

  return dialog.render();

});

// search content
cdb.vis.Overlay.register('search', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '\
      <form>\
        \
        <input type="text" class="text" value="" />\
        <input type="submit" class="submit" value="" />\
      </form>\
    ',
    data.templateType || 'mustache'
  );

  var search = new cdb.geo.ui.Search({
    template: template,
    model: vis.map
  });

  return search.render();
});

// tooltip
cdb.vis.Overlay.register('tooltip', function(data, vis) {
  var layer;
  if (!data.layer) {
    var layers = vis.getLayers();
    if(layers.length > 1) {
      layer = layers[1];
    }
    data.layer = layer;
  }

  if(!data.layer) {
    throw new Error("layer is null");
  }
  data.layer.setInteraction(true);
  var tooltip = new cdb.geo.ui.Tooltip(data);
  return tooltip;

});

cdb.vis.Overlay.register('infobox', function(data, vis) {
  var layer;
  var layers = vis.getLayers();
  if (!data.layer) {
    if(layers.length > 1) {
      layer = layers[1];
    }
    data.layer = layer;
  }
  if(!data.layer) {
    throw new Error("layer is null");
  }
  data.layer.setInteraction(true);
  var infobox = new cdb.geo.ui.InfoBox(data);
  return infobox;

});

})();
<commit_msg>Sets the right URL for sharing<commit_after>
(function() {

// map mobile control
cdb.vis.Overlay.register('mobile', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '\

\

\

\

\
    \
    ',
    data.templateType || 'mustache'
  );

  var mobile = new cdb.geo.ui.Mobile({
    template: template,
    torqueLayer: data.torqueLayer,
    legends: data.legends,
    map: data.map
  });

  return mobile.render();
});

// map zoom control
cdb.vis.Overlay.register('zoom', function(data, vis) {

  if(!data.template) {
    vis.trigger('error', 'zoom template is empty')
    return;
  }

  var zoom = new cdb.geo.ui.Zoom({
    model: data.map,
    template: cdb.core.Template.compile(data.template)
  });

  return zoom.render();
});

// Tiles loader
cdb.vis.Overlay.register('loader', function(data) {

  var tilesLoader = new cdb.geo.ui.TilesLoader({
    template: cdb.core.Template.compile(data.template)
  });

  return tilesLoader.render();
});

cdb.vis.Overlay.register('time_slider', function(data, viz) {
  var slider = new cdb.geo.ui.TimeSlider(data);
  return slider.render();
});

// Header to show informtion (title and description)
cdb.vis.Overlay.register('header', function(data, vis) {
  var MAX_SHORT_DESCRIPTION_LENGTH = 100;

  // Add the complete url for facebook and twitter
  if (location.href) {
    data.share_url = encodeURIComponent(location.href);
  } else {
    data.share_url = data.url;
  }

  var template = cdb.core.Template.compile(
    data.template || "\
      {{#title}}\

\
          {{#url}}\
            {{title}}\
          {{/url}}\
          {{^url}}\
            {{title}}\
          {{/url}}\

\
      {{/title}}\
      {{#description}}
{{description}}
{{/description}}\
      {{#mobile_shareable}}\

\
          F\
          T\

\
      {{/mobile_shareable}}\
    ",
    data.templateType || 'mustache'
  );

  function truncate(s, length) {
    return s.substr(0, length-1) + (s.length > length ? '…' : '');
  }

  var title       = data.map.get('title');
  var description = data.map.get('description');

  var facebook_title = title + ": " + description;
  var twitter_title;

  if (title && description) {
    twitter_title = truncate(title + ": " + description, 112) + " %23map "
  } else if (title) {
    twitter_title = truncate(title, 112) + " %23map"
  } else if (description){
    twitter_title = truncate(description, 112) + " %23map"
  } else {
    twitter_title = "%23map"
  }

  var shareable = (data.shareable == "false" || !data.shareable) ? null : data.shareable;
  var mobile_shareable = shareable;

  mobile_shareable = mobile_shareable && (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));

  var header = new cdb.geo.ui.Header({
    title: title,
    description: description,
    facebook_title: facebook_title,
    twitter_title: twitter_title,
    url: data.url,
    share_url: data.share_url,
    mobile_shareable: mobile_shareable,
    shareable: shareable && !mobile_shareable,
    template: template
  });

  return header.render();
});

// infowindow
cdb.vis.Overlay.register('infowindow', function(data, vis) {

  if (_.size(data.fields) == 0) {
    return null;
  }

  var infowindowModel = new cdb.geo.ui.InfowindowModel({
    template: data.template,
    alternative_names: data.alternative_names,
    fields: data.fields,
    template_name: data.template_name
  });

  var templateType = data.templateType || 'mustache';

  var infowindow = new cdb.geo.ui.Infowindow({
     model: infowindowModel,
     mapView: vis.mapView,
     template: new cdb.core.Template({ template: data.template, type: templateType}).asFunction()
  });

  return infowindow;
});

// layer_selector
cdb.vis.Overlay.register('layer_selector', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '\
      Visible layers

\
      ',
    data.templateType || 'underscore'
  );

  var dropdown_template = cdb.core.Template.compile(
    data.template || '\

\
      ',
    data.templateType || 'underscore'
  );

  var layerSelector = new cdb.geo.ui.LayerSelector({
    mapView: vis.mapView,
    template: template,
    dropdown_template: dropdown_template,
    layer_names: data.layer_names
  });

  if(vis.legends) {
    layerSelector.bind('change:visible', function(visible, order, layer) {
      if (layer.get('type') === 'layergroup') {
        var legend = vis.legends && vis.legends.getLegendByIndex(order);
        if(legend) {
          legend[visible ? 'show': 'hide']();
        }
      } else if (layer.get('type') === 'torque') {
        var timeSlider = vis.getOverlay('time_slider');
        if (timeSlider) {
          timeSlider[visible ? 'show': 'hide']();
        }
      }

    });
  }

  return layerSelector.render();
});

// fullscreen
cdb.vis.Overlay.register('fullscreen', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '',
    data.templateType || 'mustache'
  );

  var fullscreen = new cdb.ui.common.FullScreen({
    doc: "#map > div",
    mapView: vis.mapView,
    template: template
  });

  return fullscreen.render();

});

// share content
cdb.vis.Overlay.register('share', function(data, vis) {

  // Add the complete url for facebook and twitter
  if (location.href) {
    data.share_url = encodeURIComponent(location.href);
  } else {
    data.share_url = data.url;
  }

  var template = cdb.core.Template.compile(
    data.template || '\

\

\
          x\

\

Share this map
\

\

\

\

Social
\

\

Share on Facebook
\

Share on Twitter
\

\

\

Embed this map
\
             <textarea id="" name="" cols="30" rows="10">{{ code }}</textarea>\

\

\

\

\
    ',
    data.templateType || 'mustache'
  );

  var url = location.href;

  url = url.replace("public_map", "embed_map");

  var code = "";

  var dialog = new cdb.ui.common.ShareDialog({
    title: data.map.get("title"),
    description: data.map.get("description"),
    model: vis.map,
    code: code,
    url: data.url,
    share_url: data.share_url,
    template: template,
    target: $(".cartodb-share a"),
    size: $(document).width() > 400 ? "" : "small",
    width: $(document).width() > 400 ? 430 : 216
  });

  return dialog.render();

});

// search content
cdb.vis.Overlay.register('search', function(data, vis) {

  var template = cdb.core.Template.compile(
    data.template || '\
      <form>\
        \
        <input type="text" class="text" value="" />\
        <input type="submit" class="submit" value="" />\
      </form>\
    ',
    data.templateType || 'mustache'
  );

  var search = new cdb.geo.ui.Search({
    template: template,
    model: vis.map
  });

  return search.render();
});

// tooltip
cdb.vis.Overlay.register('tooltip', function(data, vis) {
  var layer;
  if (!data.layer) {
    var layers = vis.getLayers();
    if(layers.length > 1) {
      layer = layers[1];
    }
    data.layer = layer;
  }

  if(!data.layer) {
    throw new Error("layer is null");
  }
  data.layer.setInteraction(true);
  var tooltip = new cdb.geo.ui.Tooltip(data);
  return tooltip;

});

cdb.vis.Overlay.register('infobox', function(data, vis) {
  var layer;
  var layers = vis.getLayers();
  if (!data.layer) {
    if(layers.length > 1) {
      layer = layers[1];
    }
    data.layer = layer;
  }
  if(!data.layer) {
    throw new Error("layer is null");
  }
  data.layer.setInteraction(true);
  var infobox = new cdb.geo.ui.InfoBox(data);
  return infobox;

});

})();
<|endoftext|>


<commit_before>///////      Funciones de edicion de apps        //////

function doLogin(){
        localStorage["user"] = $("#inputUser").val ();
        localStorage["pass"] = $("#inputPass").val ();
        $.ajax
        ({
              type: "GET",
              url: "https://api.github.com/user",
              async: true,
              dataType: 'json',
              beforeSend: function (xhr) {
                 xhr.setRequestHeader('Authorization', make_base_auth(localStorage["user"], localStorage["pass"]));
             },
              success: function (data){
                  var loginUser = data.login;
                  localStorage["loginUser"] = loginUser;
              },
              error: function (msg){
                localStorage.removeItem("user");
                localStorage.removeItem("pass");
                if (msg.message == "Bad Credentials"){
                  alert("User/Password Incorrect");
                } else {
                  alert('Sorry no se pudo loguear: ' + msg.responseText);
                }
              }
        });
}

function build(){
        $.ajax
        ({
              type: "GET",
              url: "http://telus.crontopia.com/gisicom/updatecode.php",
              async: true,
              success: function (data){
                if (data == "OK"){
                  alert('Rebuild In Progress !!...');
                } else {
                  alert('Error in Rebuild Process...' + data);
                }
              },
              error: function (msg){
                alert('Sorry no se pudo contactar al proxy de telus: ' + msg.responseText);
              }
        });
}

function getContent(path){

        $.ajax
        ({
              type: "GET",
              url: "https://api.github.com/repos/Juanve/Gisicom/contents/" + path,
              async: true,
              dataType: 'json',
              beforeSend: function (xhr) {
                 xhr.setRequestHeader('Authorization', make_base_auth(localStorage["user"], localStorage["pass"]));
             },
              success: function (data){
                  var coden = data.content;
                  var codeRaw = Base64.decode(coden.replace('','\n'));
                  $("#codeArea").val(codeRaw);
                  $("#fileSha").text(data.sha);
                  $("#filePath").text(data.path);

              },
              error: function (msg){
                alert('Sorry no se pudo obtener el contenido del index: ' + msg.responseText);
              }
        });
}

function updateContent(){
        var content = btoa($("#codeArea").val());
        var fileSha = $("#fileSha").text();
        var filePath = $("#filePath").text();
        var msg = "Updating " + filePath;
        var dataObject = {
            'message': msg,
            'content': content,
            'sha': fileSha
        };
        $.ajax
        ({
              type: "PUT",
              url: "https://api.github.com/repos/Juanve/Gisicom/contents/" + filePath,
              contentType: 'application/json',
              data: JSON.stringify(dataObject),
              async: true,
              beforeSend: function (xhr) {
                 xhr.setRequestHeader('Authorization', make_base_auth(localStorage["user"], localStorage["pass"]));
             },
              success: function (data){
                 $("#fileSha").text(data.content.sha);
                 alert("Successfull Updated " + data.content.name );
              },
              error: function (msg){
                alert('Sorry no se pudo actualizar el contenido del index: ' + msg.responseText);
              }
        });
}

function make_base_auth(user, password) {
       var tok = user + ':' + password;
       var hash = btoa(tok);
       return 'Basic ' + hash;
}

function onPreview(){
        var ref = window.open('http://telus.crontopia.com/gisicomweb/www/', '_blank', 'location=no');
        //ref.addEventListener('loadstart', function() { alert(event.url); });
}

function goEdit(){
   if ($("#editBtn").html() == "Edit"){
    $("#editPanel").css ("display","block");
    $("#runPanel").css ("display","none");
    $("#editBtn").html("Run");
   } else {
    $("#editPanel").css ("display","none");
    $("#runPanel").css ("display","block");
    $("#editBtn").html("Edit");
   }
}<commit_msg>Updating www/js/telus.js<commit_after>///////      Funciones de edicion de apps        //////

function doLogin(){
        localStorage["user"] = $("#inputUser").val ();
        localStorage["pass"] = $("#inputPass").val ();
        $.ajax
        ({
              type: "GET",
              url: "https://api.github.com/user",
              async: true,
              dataType: 'json',
              beforeSend: function (xhr) {
                 xhr.setRequestHeader('Authorization', make_base_auth(localStorage["user"], localStorage["pass"]));
             },
              success: function (data){
                  var loginUser = data.login;
                  localStorage["loginUser"] = loginUser;
              },
              error: function (msg){
                localStorage.removeItem("user");
                localStorage.removeItem("pass");
                if (msg.message == "Bad credentials"){
                  alert("User/Password Incorrect");
                } else {
                  alert('Sorry no se pudo loguear: ' + msg.responseText);
                }
              }
        });
}

function build(){
        $.ajax
        ({
              type: "GET",
              url: "http://telus.crontopia.com/gisicom/updatecode.php",
              async: true,
              success: function (data){
                if (data == "OK"){
                  alert('Rebuild In Progress !!...');
                } else {
                  alert('Error in Rebuild Process...' + data);
                }
              },
              error: function (msg){
                alert('Sorry no se pudo contactar al proxy de telus: ' + msg.responseText);
              }
        });
}

function getContent(path){

        $.ajax
        ({
              type: "GET",
              url: "https://api.github.com/repos/Juanve/Gisicom/contents/" + path,
              async: true,
              dataType: 'json',
              beforeSend: function (xhr) {
                 xhr.setRequestHeader('Authorization', make_base_auth(localStorage["user"], localStorage["pass"]));
             },
              success: function (data){
                  var coden = data.content;
                  var codeRaw = Base64.decode(coden.replace('','\n'));
                  $("#codeArea").val(codeRaw);
                  $("#fileSha").text(data.sha);
                  $("#filePath").text(data.path);

              },
              error: function (msg){
                alert('Sorry no se pudo obtener el contenido del index: ' + msg.responseText);
              }
        });
}

function updateContent(){
        var content = btoa($("#codeArea").val());
        var fileSha = $("#fileSha").text();
        var filePath = $("#filePath").text();
        var msg = "Updating " + filePath;
        var dataObject = {
            'message': msg,
            'content': content,
            'sha': fileSha
        };
        $.ajax
        ({
              type: "PUT",
              url: "https://api.github.com/repos/Juanve/Gisicom/contents/" + filePath,
              contentType: 'application/json',
              data: JSON.stringify(dataObject),
              async: true,
              beforeSend: function (xhr) {
                 xhr.setRequestHeader('Authorization', make_base_auth(localStorage["user"], localStorage["pass"]));
             },
              success: function (data){
                 $("#fileSha").text(data.content.sha);
                 alert("Successfull Updated " + data.content.name );
              },
              error: function (msg){
                alert('Sorry no se pudo actualizar el contenido del index: ' + msg.responseText);
              }
        });
}

function make_base_auth(user, password) {
       var tok = user + ':' + password;
       var hash = btoa(tok);
       return 'Basic ' + hash;
}

function onPreview(){
        var ref = window.open('http://telus.crontopia.com/gisicomweb/www/', '_blank', 'location=no');
        //ref.addEventListener('loadstart', function() { alert(event.url); });
}

function goEdit(){
   if ($("#editBtn").html() == "Edit"){
    $("#editPanel").css ("display","block");
    $("#runPanel").css ("display","none");
    $("#editBtn").html("Run");
   } else {
    $("#editPanel").css ("display","none");
    $("#runPanel").css ("display","block");
    $("#editBtn").html("Edit");
   }
}<|endoftext|>


<commit_before>#!/bin/sh

console.error("The CLI has been moved into the package `babel-cli`.");
console.log();
console.log("$ npm install -g babel-cli");
console.log();
process.exit(1);
<commit_msg>fix bin cli shebang<commit_after>#!/usr/bin/env node

console.error("The CLI has been moved into the package `babel-cli`.");
console.log();
console.log("$ npm install -g babel-cli");
console.log();
process.exit(1);
<|endoftext|>