<commit_before>/**
 * Created by Mariandi on 11/03/2014.
 */
/*global angular*/
'use strict';

angular.module('anguvideo',[])
    .directive("anguvideo", ['$sce', '$interval', function ($sce, $interval) {
        return {
            restrict: 'EA',
            scope: {
                source: '=ngModel',
                width: '@',
                height: '@'
            },
            replace: true,
            template: '
' +
                            '' +
                      '
',
            link: function (scope, element, attrs) {

              var player;
              scope.timer, scope.timeSpent = [];

              function onPlayerStateChange(event) {
                if (!event.data) {
                  scope.$emit("anguvideo:finishVideo");
                  $interval.cancel(scope.timer);
                }
                if(event.data === 1) { // Started playing
                      if(!scope.timeSpent.length){
                          for(var i=0, l=parseInt(player.getDuration()); i<l; i++) scope.timeSpent.push(false);
                      }
                    scope.timer = $interval(record,100);
                  } else {
                   $interval.cancel(scope.timer);
                }
              }
              (function onYouTubeIframeAPIReady() {
                player = new YT.Player('playerYV', {
                  events: {
                    'onStateChange': onPlayerStateChange
                  }
                });
              }());

              function record(){
              	scope.timeSpent[ parseInt(player.getCurrentTime()) ] = true;
              	showPercentage();
              }

              function showPercentage(){
                  var percent = 0;
                  for(var i=0, l=scope.timeSpent.length; i<l; i++){
                      if(scope.timeSpent[i]) percent++;
                  }
                  percent = Math.round(percent / scope.timeSpent.length * 100);
                  console.log(percent + "%");
                  if(percent >= 70){
                    broadcastWatchedMinPercentage();
                    $interval.cancel(scope.timer);
                  }
              }

              function broadcastWatchedMinPercentage(){
                if(!scope.watchedMinPercentage){
                  scope.$emit("anguvideo:watchedMinPercentage");
                  scope.watchedMinPercentage = true;
                }
              }

                var origin = location.origin;
                var embedFriendlyUrl = "",
                    urlSections,
                    index;

                var youtubeParams = (attrs.hideControls ? '?autoplay=0&showinfo=0&controls=0&enablejsapi=1&origin='+origin : '?autoplay=0&enablejsapi=1&origin='+origin);

                scope.$watch('source', function (newVal) {
                    if (newVal) {
                        /*
                        * Need to convert the urls into a friendly url that can be embedded and be used in the available online players the services have provided
                        * for youtube: src="//www.youtube.com/embed/{{video_id}}"
                        * for vimeo: src="http://player.vimeo.com/video/{{video_id}}
                        */
                        scope.timer, scope.timeSpent = [];
                        scope.watchedMinPercentage = 0;
                        if (newVal.indexOf("vimeo") >= 0) { // Displaying a vimeo video
                            if (newVal.indexOf("player.vimeo") >= 0) {
                                embedFriendlyUrl = newVal;
                            } else {
                                embedFriendlyUrl = newVal.replace("https:", "http:");
                                urlSections = embedFriendlyUrl.split(".com/");
                                embedFriendlyUrl = embedFriendlyUrl.replace("vimeo", "player.vimeo");
                                embedFriendlyUrl = embedFriendlyUrl.replace("/" + urlSections[urlSections.length - 1], "/video/" + urlSections[urlSections.length - 1] + "");
                                embedFriendlyUrl += '?autoplay=0&api=1&player_id=playerYV';
                            }

                            $(function() {
                                  var iframe = $('#playerYV')[0];
                                  var player = $f(iframe);
                                  // When the player is ready, add listeners for pause, finish, and playProgress
                                  player.addEvent('ready', function() {
                                      player.addEvent('pause', function(){
                                        $interval.cancel(scope.timer);
                                      });
                                      player.addEvent('finish', function(){
                                        scope.$emit("anguvideo:finishVideo");
                                        $interval.cancel(scope.timer);
                                      });
                                      player.addEvent('play', function(){
                                        var PlayerVimeoDuration, PlayerVimeoCurrentTime;
                                        player.api('getDuration', function(PlayerVimeoDuration) {
                                          if(!scope.timeSpent.length){
                                            for(var i=0, l=parseInt(PlayerVimeoDuration); i<l; i++) scope.timeSpent.push(false);
                                          }
                                        });
                                      });
                                      player.addEvent('playProgress', function(data, id){
                                        scope.timeSpent[parseInt(data.seconds)] = true;
                                        showPercentage();
                                      });
                                  });
                                  scope.$on("anguvideo:watchedMinPercentage", function(){
                                    player.removeEvent('play');
                                    player.removeEvent('playProgress');
                                    player = undefined;
                                    iframe = undefined;
                                  });
                            });

                        } else if (newVal.indexOf("youtu.be") >= 0) {

                            index = newVal.indexOf(".be/");

                            embedFriendlyUrl = newVal.slice(index + 4, newVal.length);
                            embedFriendlyUrl = "http://www.youtube.com/embed/" + embedFriendlyUrl + youtubeParams;

                        } else if (newVal.indexOf("youtube.com") >= 0) { // displaying a youtube video
                            if (newVal.indexOf("embed") >= 0) {
                                embedFriendlyUrl = newVal + youtubeParams;
                            } else {
                                embedFriendlyUrl = newVal.replace("/watch?v=", "/embed/") + youtubeParams;
                            }
                        }

                        scope.url = $sce.trustAsResourceUrl(embedFriendlyUrl);
                        //console.log("done",  scope.url, embedFriendlyUrl);

                    }

                });

                scope.$on("$destroy",function(){
                  $interval.cancel(scope.timer);
                });
                element.on("$destroy",function() {
                  $interval.cancel(scope.timer);
                  scope.watchedMinPercentage = 0;
                })
            }
        };
    }]);
<commit_msg>removendo console.log<commit_after>/**
 * Created by Mariandi on 11/03/2014.
 */
/*global angular*/
'use strict';

angular.module('anguvideo',[])
    .directive("anguvideo", ['$sce', '$interval', function ($sce, $interval) {
        return {
            restrict: 'EA',
            scope: {
                source: '=ngModel',
                width: '@',
                height: '@'
            },
            replace: true,
            template: '
' +
                            '' +
                      '
',
            link: function (scope, element, attrs) {

              var player;
              scope.timer, scope.timeSpent = [];

              function onPlayerStateChange(event) {
                if (!event.data) {
                  scope.$emit("anguvideo:finishVideo");
                  $interval.cancel(scope.timer);
                }
                if(event.data === 1) { // Started playing
                      if(!scope.timeSpent.length){
                          for(var i=0, l=parseInt(player.getDuration()); i<l; i++) scope.timeSpent.push(false);
                      }
                    scope.timer = $interval(record,100);
                  } else {
                   $interval.cancel(scope.timer);
                }
              }
              (function onYouTubeIframeAPIReady() {
                player = new YT.Player('playerYV', {
                  events: {
                    'onStateChange': onPlayerStateChange
                  }
                });
              }());

              function record(){
              	scope.timeSpent[ parseInt(player.getCurrentTime()) ] = true;
              	showPercentage();
              }

              function showPercentage(){
                  var percent = 0;
                  for(var i=0, l=scope.timeSpent.length; i<l; i++){
                      if(scope.timeSpent[i]) percent++;
                  }
                  percent = Math.round(percent / scope.timeSpent.length * 100);
                  //console.log(percent + "%");
                  if(percent >= 70){
                    broadcastWatchedMinPercentage();
                    $interval.cancel(scope.timer);
                  }
              }

              function broadcastWatchedMinPercentage(){
                if(!scope.watchedMinPercentage){
                  scope.$emit("anguvideo:watchedMinPercentage");
                  scope.watchedMinPercentage = true;
                }
              }

                var origin = location.origin;
                var embedFriendlyUrl = "",
                    urlSections,
                    index;

                var youtubeParams = (attrs.hideControls ? '?autoplay=0&showinfo=0&controls=0&enablejsapi=1&origin='+origin : '?autoplay=0&enablejsapi=1&origin='+origin);

                scope.$watch('source', function (newVal) {
                    if (newVal) {
                        /*
                        * Need to convert the urls into a friendly url that can be embedded and be used in the available online players the services have provided
                        * for youtube: src="//www.youtube.com/embed/{{video_id}}"
                        * for vimeo: src="http://player.vimeo.com/video/{{video_id}}
                        */
                        scope.timer, scope.timeSpent = [];
                        scope.watchedMinPercentage = 0;
                        if (newVal.indexOf("vimeo") >= 0) { // Displaying a vimeo video
                            if (newVal.indexOf("player.vimeo") >= 0) {
                                embedFriendlyUrl = newVal;
                            } else {
                                embedFriendlyUrl = newVal.replace("https:", "http:");
                                urlSections = embedFriendlyUrl.split(".com/");
                                embedFriendlyUrl = embedFriendlyUrl.replace("vimeo", "player.vimeo");
                                embedFriendlyUrl = embedFriendlyUrl.replace("/" + urlSections[urlSections.length - 1], "/video/" + urlSections[urlSections.length - 1] + "");
                                embedFriendlyUrl += '?autoplay=0&api=1&player_id=playerYV';
                            }

                            $(function() {
                                  var iframe = $('#playerYV')[0];
                                  var player = $f(iframe);
                                  // When the player is ready, add listeners for pause, finish, and playProgress
                                  player.addEvent('ready', function() {
                                      player.addEvent('pause', function(){
                                        $interval.cancel(scope.timer);
                                      });
                                      player.addEvent('finish', function(){
                                        scope.$emit("anguvideo:finishVideo");
                                        $interval.cancel(scope.timer);
                                      });
                                      player.addEvent('play', function(){
                                        var PlayerVimeoDuration, PlayerVimeoCurrentTime;
                                        player.api('getDuration', function(PlayerVimeoDuration) {
                                          if(!scope.timeSpent.length){
                                            for(var i=0, l=parseInt(PlayerVimeoDuration); i<l; i++) scope.timeSpent.push(false);
                                          }
                                        });
                                      });
                                      player.addEvent('playProgress', function(data, id){
                                        scope.timeSpent[parseInt(data.seconds)] = true;
                                        showPercentage();
                                      });
                                  });
                                  scope.$on("anguvideo:watchedMinPercentage", function(){
                                    player.removeEvent('play');
                                    player.removeEvent('playProgress');
                                    player = undefined;
                                    iframe = undefined;
                                  });
                            });

                        } else if (newVal.indexOf("youtu.be") >= 0) {

                            index = newVal.indexOf(".be/");

                            embedFriendlyUrl = newVal.slice(index + 4, newVal.length);
                            embedFriendlyUrl = "http://www.youtube.com/embed/" + embedFriendlyUrl + youtubeParams;

                        } else if (newVal.indexOf("youtube.com") >= 0) { // displaying a youtube video
                            if (newVal.indexOf("embed") >= 0) {
                                embedFriendlyUrl = newVal + youtubeParams;
                            } else {
                                embedFriendlyUrl = newVal.replace("/watch?v=", "/embed/") + youtubeParams;
                            }
                        }

                        scope.url = $sce.trustAsResourceUrl(embedFriendlyUrl);
                        //console.log("done",  scope.url, embedFriendlyUrl);

                    }

                });

                scope.$on("$destroy",function(){
                  $interval.cancel(scope.timer);
                });
                element.on("$destroy",function() {
                  $interval.cancel(scope.timer);
                  scope.watchedMinPercentage = 0;
                })
            }
        };
    }]);
<|endoftext|>


<commit_before>// The rest of GNU date. Maybe out to be broken up into localize and days.
new function () {
  function weekOfYear (date, startOfWeek) {
    var diff, nyd, weekStart;
    date = new Date(Date.UTC.call(Date.UTC, date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
    nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
    diff = (date.getTime() - nyd.getTime()) / 864e5;
    if (nyd.getUTCDay() == startOfWeek) {
      weekStart = 0;
    } else {
      weekStart = 7 - nyd.getUTCDay() + startOfWeek;
      if (weekStart == 8) {
        weekStart = 1;
      }
    }
    return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
  }

  function isoWeek (date) {
    var ny, nyd, nyy, offset, week;
    nyy = date.getUTCFullYear();
    nyd = new Date(Date.UTC(nyy, 0, 1)).getUTCDay();
    offset = nyd > 1 && nyd <= 4 ? 1 : 0;
    week = weekOfYear(date, 1) + offset;
    if (week === 0) {
      ny = new Date(Date.UTC(date.getUTCFullYear() - 1, 0, 1));
      nyd = ny.getUTCDay();
      nyy = ny.getUTCFullYear();
      week = nyd === 4 || (nyd === 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
      return [week, date.getUTCFullYear() - 1];
    } else if (week === 53 && !(nyd === 4 || (nyd === 3 && new Date(nyy, 1, 29).getDate() == 29))) {
      return [1, date.getUTCFullYear() + 1];
    } else {
      return [week, date.getUTCFullYear()];
    }
  }

  function date () {
    this.a = function (date) { return this[this.locale].day.abbrev[date.getUTCDay()] }
    this.A = function (date) { return this[this.locale].day.full[date.getUTCDay()] }
    this.j = function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1 }
    this.e = function (date) { return date.getUTCDate() }
    this.u = function (date) { return date.getUTCDay() == 0 ? 7 : date.getUTCDay() }
    this.w = function (date) { return date.getUTCDay() }
    this.U = function (date) { return weekOfYear(date, 0) }
    this.W = function (date) { return weekOfYear(date, 1) }
    this.V = function (date) { return isoWeek(date)[0] }
    this.G = function (date) { return isoWeek(date)[1] }
    this.g = function (date) { return isoWeek(date)[1] % 100 }
    this.h = function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    this.b = function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    this.B = function (date) { return this[this.locale].month.full[date.getUTCMonth()] }
    this.y = function (date) { return date.getUTCFullYear() % 100 }
    this.C = function (date) { return Math.floor(date.getFullYear() / 100) }
    this.D = function (date, posix) { return this.convert([ posix, "%m/%d/%y" ]) }
    this.x = function (date, posix) { return this.convert([ posix, this[this.locale].dateFormat ]) }
    this.l = function (date) { return date.getUTCHours() % 12 == 0 ? 12 : date.getUTCHours() % 12 }
    this.I = function (date) { return date.getUTCHours() % 12 == 0 ? 12 : date.getUTCHours() % 12 }
    this.k = function (date) { return date.getUTCHours() }
    this.P = function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase() }
    this.p = function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)] }
    this.r = function (date, posix) { return this.convert([ posix, "%I:%M:%S %p", "en_US" ]) }
    this.X = function (date, posix) { return this.convert([ posix, this[this.locale].timeFormat ]) }
    this.c = function (date, posix) { return this.convert([ posix, this[this.locale].dateTimeFormat ]) }

    this.U.pad = 2;
    this.W.pad = 2;
    this.V.pad = 2;
    this.g.pad = 2;
    this.j.pad = 3;
    this.C.pad = 2;
    this.I.pad = 2;
    this.k.pad = 2;
    this.y.pad = 2;

    this.k.style = "_";

    this.locale || (this.locale = "en_US")
    this.en_US = {
      day: {
        abbrev: "Sun Mon Tue Wed Thu Fri Sat".split(/\s/),
        full: "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(/\s+/)
      },
      month: {
        abbrev: "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(/\s+/),
        full: "January February March April May June July August September October November December".split(/\s+/)
      },
      dateFormat: "%m/%d/%Y",
      timeFormat: "%I:%M:%S %p",
      dateTimeFormat: "%a %d %b %Y %I:%M:%S %p %Z",
      meridiem: [ "AM", "PM" ]
    };
  }

  if (typeof module == "object") module.exports = date;
  else tz = tz(date);
}
<commit_msg>Smaller week of year formatting functions.<commit_after>// The rest of GNU date. Maybe out to be broken up into localize and days.
new function () {
  function weekOfYear (date, startOfWeek) {
    var diff, nyd, weekStart;
    nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
    diff = Math.floor((date.getTime() - nyd.getTime()) / 864e5);
    if (nyd.getUTCDay() == startOfWeek) {
      weekStart = 0;
    } else {
      weekStart = 7 - nyd.getUTCDay() + startOfWeek;
      if (weekStart == 8) {
        weekStart = 1;
      }
    }
    return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
  }

  function isoWeek (date) {
    var nyd, nyy, week;
    nyy = date.getUTCFullYear();
    nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
    week = weekOfYear(date, 1) + (nyd > 1 && nyd <= 4 ? 1 : 0);
    if (week == 0) {
      nyy = date.getUTCFullYear() - 1;
      nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
      week = nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
      return [week, date.getUTCFullYear() - 1];
    } else if (week == 53 && !(nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29))) {
      return [1, date.getUTCFullYear() + 1];
    } else {
      return [week, date.getUTCFullYear()];
    }
  }

  function date () {
    this.a = function (date) { return this[this.locale].day.abbrev[date.getUTCDay()] }
    this.A = function (date) { return this[this.locale].day.full[date.getUTCDay()] }
    this.j = function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1 }
    this.e = function (date) { return date.getUTCDate() }
    this.u = function (date) { return date.getUTCDay() == 0 ? 7 : date.getUTCDay() }
    this.w = function (date) { return date.getUTCDay() }
    this.U = function (date) { return weekOfYear(date, 0) }
    this.W = function (date) { return weekOfYear(date, 1) }
    this.V = function (date) { return isoWeek(date)[0] }
    this.G = function (date) { return isoWeek(date)[1] }
    this.g = function (date) { return isoWeek(date)[1] % 100 }
    this.h = function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    this.b = function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    this.B = function (date) { return this[this.locale].month.full[date.getUTCMonth()] }
    this.y = function (date) { return date.getUTCFullYear() % 100 }
    this.C = function (date) { return Math.floor(date.getFullYear() / 100) }
    this.D = function (date, posix) { return this.convert([ posix, "%m/%d/%y" ]) }
    this.x = function (date, posix) { return this.convert([ posix, this[this.locale].dateFormat ]) }
    this.l = function (date) { return date.getUTCHours() % 12 == 0 ? 12 : date.getUTCHours() % 12 }
    this.I = function (date) { return date.getUTCHours() % 12 == 0 ? 12 : date.getUTCHours() % 12 }
    this.k = function (date) { return date.getUTCHours() }
    this.P = function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase() }
    this.p = function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)] }
    this.r = function (date, posix) { return this.convert([ posix, "%I:%M:%S %p", "en_US" ]) }
    this.X = function (date, posix) { return this.convert([ posix, this[this.locale].timeFormat ]) }
    this.c = function (date, posix) { return this.convert([ posix, this[this.locale].dateTimeFormat ]) }

    this.U.pad = 2;
    this.W.pad = 2;
    this.V.pad = 2;
    this.g.pad = 2;
    this.j.pad = 3;
    this.C.pad = 2;
    this.I.pad = 2;
    this.k.pad = 2;
    this.y.pad = 2;

    this.k.style = "_";

    this.locale || (this.locale = "en_US")
    this.en_US = {
      day: {
        abbrev: "Sun Mon Tue Wed Thu Fri Sat".split(/\s/),
        full: "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(/\s+/)
      },
      month: {
        abbrev: "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(/\s+/),
        full: "January February March April May June July August September October November December".split(/\s+/)
      },
      dateFormat: "%m/%d/%Y",
      timeFormat: "%I:%M:%S %p",
      dateTimeFormat: "%a %d %b %Y %I:%M:%S %p %Z",
      meridiem: [ "AM", "PM" ]
    };
  }

  if (typeof module == "object") module.exports = date;
  else tz = tz(date);
}
<|endoftext|>


<commit_before>function GeoSearchResultsController($scope, $location, $routeParams, $http, $sce, chronontologySettings, $filter) {

    var _this = this;
    var popupinfo = [];

    _this.loading = false;
    _this.empty = false;

    this.$onChanges = function() {
        this.initMap();
        this.loadData();
    };

    this.loadData = function() {
        _this.loading = true;
        _this.empty = true;
        $http.get(_this.datasource, {
                headers: { 'Authorization': undefined }
        }).then(function success(geojson){
            _this.loading = false;
            _this.geojson = geojson.data;
            if (geojson.data.geometry) {
                _this.empty = false;
                _this.initPlaces(geojson.data);
            } else if (geojson.data.features) {
                if (geojson.data.features.length > 0) {
                    _this.empty = false;
                    _this.initPlaces(geojson.data);
                }
            } else {
                _this.empty = true;
            }
        }, function error(err) {
            console.warn(err) // TODO show error message
        });
    };

    this.initMap = function() {
        // init map
        _this.mapY = 50.1287762;
        _this.mapX = -5.4532871;
        _this.markersArea = 0;
        _this.mapZoom = 8;
        _this.baseLayer = L.tileLayer('http://{s}.tiles.mapbox.com/v3/isawnyu.map-knmctlkh/{z}/{x}/{y}.png', {
            maxZoom: 15,
            attribution: "Attribution"
        });
        _this.map = L.map("map3", {
            fullscreenControl: {pseudoFullscreen: false},
            center: [_this.mapY, _this.mapX],
            zoom: _this.mapZoom,
            layers: [_this.baseLayer]
        });
        // add scale
        L.control.scale().addTo(_this.map);
    };

    this.initPlaces = function(geojson) {

        // cluster
        _this.markers = null;
		_this.markers = L.markerClusterGroup();

        // add markers and polygons
        _this.orangeBowlIcon = L.icon({iconUrl: 'img/Icone_Boule_Orange.png', iconSize: [30, 30], iconAnchor: [15, 15]}),
        _this.marker = L.geoJson(geojson, {
          onEachFeature: _this.onEachFeature,
          pointToLayer: function (feature, latlng) {
              return L.marker(latlng, {icon: _this.orangeBowlIcon, name: feature.properties.names.prefName.name});
            }
        });
        _this.markers.addLayer(_this.marker);
        // add marker as layer
        _this.map.addLayer(_this.markers);
        // init search
        _this.controlSearch = new L.Control.Search({
    		position:'topleft',
    		layer: _this.markers,
            initial: false,
            propertyName: 'name',
    		marker: false,
            zoom: 13
    	});
        _this.controlSearch.on('search:locationfound', function(e) {
    		e.layer.openPopup();
    	});
        _this.map.addControl(_this.controlSearch);
        // calc layer center
        _this.mapY = _this.marker.getBounds().getCenter().lat;
        _this.mapX = _this.marker.getBounds().getCenter().lng;
        // set map
        _this.map.setView([_this.mapY, _this.mapX], _this.mapZoom);
        // zoom to bounds
        _this.map.fitBounds(_this.marker.getBounds());

        if (_this.map.tap) _this.map.tap.enable();
        document.getElementById('map3').style.cursor='grab';
    }

    this.onEachFeature = function(feature, layer) {
        var popupContent = "name: " + feature.properties.names.prefName.name + "
" + "uri: " + feature.properties["@id"] + "";
		if (feature.properties && feature.properties.popupContent) {
			popupContent += feature.properties.popupContent;
		}
		layer.bindPopup(popupContent);
    };

}

angular.module('chronontology.components')
    .component('geosearchresults',{
        templateUrl: '../../partials/geo/searchResults.html',
        bindings: {
            datasource: '@datasource'
        },
        controller: GeoSearchResultsController
    });
<commit_msg>delet unused variable<commit_after>function GeoSearchResultsController($scope, $location, $routeParams, $http, $sce, chronontologySettings, $filter) {

    var _this = this;

    _this.loading = false;
    _this.empty = false;

    this.$onChanges = function() {
        this.initMap();
        this.loadData();
    };

    this.loadData = function() {
        _this.loading = true;
        _this.empty = true;
        $http.get(_this.datasource, {
                headers: { 'Authorization': undefined }
        }).then(function success(geojson){
            _this.loading = false;
            _this.geojson = geojson.data;
            if (geojson.data.geometry) {
                _this.empty = false;
                _this.initPlaces(geojson.data);
            } else if (geojson.data.features) {
                if (geojson.data.features.length > 0) {
                    _this.empty = false;
                    _this.initPlaces(geojson.data);
                }
            } else {
                _this.empty = true;
            }
        }, function error(err) {
            console.warn(err) // TODO show error message
        });
    };

    this.initMap = function() {
        // init map
        _this.mapY = 50.1287762;
        _this.mapX = -5.4532871;
        _this.markersArea = 0;
        _this.mapZoom = 8;
        _this.baseLayer = L.tileLayer('http://{s}.tiles.mapbox.com/v3/isawnyu.map-knmctlkh/{z}/{x}/{y}.png', {
            maxZoom: 15,
            attribution: "Attribution"
        });
        _this.map = L.map("map3", {
            fullscreenControl: {pseudoFullscreen: false},
            center: [_this.mapY, _this.mapX],
            zoom: _this.mapZoom,
            layers: [_this.baseLayer]
        });
        // add scale
        L.control.scale().addTo(_this.map);
    };

    this.initPlaces = function(geojson) {

        // cluster
        _this.markers = null;
		_this.markers = L.markerClusterGroup();

        // add markers and polygons
        _this.orangeBowlIcon = L.icon({iconUrl: 'img/Icone_Boule_Orange.png', iconSize: [30, 30], iconAnchor: [15, 15]}),
        _this.marker = L.geoJson(geojson, {
          onEachFeature: _this.onEachFeature,
          pointToLayer: function (feature, latlng) {
              return L.marker(latlng, {icon: _this.orangeBowlIcon, name: feature.properties.names.prefName.name});
            }
        });
        _this.markers.addLayer(_this.marker);
        // add marker as layer
        _this.map.addLayer(_this.markers);
        // init search
        _this.controlSearch = new L.Control.Search({
    		position:'topleft',
    		layer: _this.markers,
            initial: false,
            propertyName: 'name',
    		marker: false,
            zoom: 13
    	});
        _this.controlSearch.on('search:locationfound', function(e) {
    		e.layer.openPopup();
    	});
        _this.map.addControl(_this.controlSearch);
        // calc layer center
        _this.mapY = _this.marker.getBounds().getCenter().lat;
        _this.mapX = _this.marker.getBounds().getCenter().lng;
        // set map
        _this.map.setView([_this.mapY, _this.mapX], _this.mapZoom);
        // zoom to bounds
        _this.map.fitBounds(_this.marker.getBounds());

        if (_this.map.tap) _this.map.tap.enable();
        document.getElementById('map3').style.cursor='grab';
    }

    this.onEachFeature = function(feature, layer) {
        var popupContent = "name: " + feature.properties.names.prefName.name + "
" + "uri: " + feature.properties["@id"] + "";
		if (feature.properties && feature.properties.popupContent) {
			popupContent += feature.properties.popupContent;
		}
		layer.bindPopup(popupContent);
    };

}

angular.module('chronontology.components')
    .component('geosearchresults',{
        templateUrl: '../../partials/geo/searchResults.html',
        bindings: {
            datasource: '@datasource'
        },
        controller: GeoSearchResultsController
    });
<|endoftext|>


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

/**
 * Manage Genoverse embedded browser.
 */

;(function(){

  /**
   * Internal object for storing the browser state.
   */
  params = {
    'chromosome': '',
    'start': '',
    'end': '',
    'species': '',
    '_species': '', // previous species
  };

  genoverse_container = '#genoverse';

  /**
   * Main function for launching Genoverse.
   */
  display_genomic_location = function() {

    show_genoverse_section_header();
    initialize_genoverse();
    navigate_to_feature();

    /**
     * Load Genoverse for the first time or switch to a different species.
     */
    function initialize_genoverse() {
      if (typeof window.browser === 'undefined' || switch_species()) {
          // (re-)create Genoverse object
          delete window.browser;
          $(this.genoverse_container).html('');
          window.browser = new Genoverse(get_genoverse_config_object());
          add_karyotype_placeholder();
      }

      /**
       * Return true if the current and the previous browser states refer to
       * different species.
       */
      function switch_species() {
        return this.params._species !== this.params.species && this.params._species !== '';
      }

      /**
       * Karyotype is supported only for a limited number of species,
       * so a placeholder div is used to replace the karyotype div
       * to keep the display consistent.
       */
      function add_karyotype_placeholder() {
        if (!is_karyotype_available()) {
            $('.gv_wrapper').prepend('
' +
                                     '
Karyotype display is not available for this species
' +
                                     '
');
        }
      }
    }

    /**
     * Navigate to the region of interest.
     */
    function navigate_to_feature() {
      browser.moveTo(this.params.start, this.params.end, false);
      browser.zoomOut();
    }

    /**
     * Display Genoverse section header.
     */
    function show_genoverse_section_header() {
      $('.genoverse-wrap h2').show();
    }

  };

  /**
   * Configure Genoverse initialization object.
   */
  get_genoverse_config_object = function() {

    var genoverseConfig = {
      container     : this.genoverse_container,
      chr           : this.params.chromosome,
      species       : this.params.species,
      showUrlCoords : false, // do not show genomic coordinates in the url
      plugins       : [ 'controlPanel', 'resizer', 'fileDrop' ],
      tracks        : [
        Genoverse.Track.Scalebar,
        Genoverse.Track.extend({
          name      : 'Sequence',
          model     : configure_genoverse_model('ensembl_sequence'),
          view      : Genoverse.Track.View.Sequence,
          resizable : 'auto',
          100000    : false,
        }),
        Genoverse.Track.extend({
          name      : 'Genes',
          info      : 'Ensembl API genes',
          resizable : 'auto',
          labels : true,
          model  : configure_genoverse_model('ensembl_gene'),
          view   : Genoverse.Track.View.Gene.Ensembl,
        }),
        Genoverse.Track.extend({
          name      : 'Transcripts',
          info      : 'Ensembl API transcripts',
          resizable : 'auto',
          labels : true,
          model  : configure_genoverse_model('ensembl_transcript'),
          view   : Genoverse.Track.View.Transcript.Ensembl,
        }),
        Genoverse.Track.extend({
          name      : 'RNAcentral',
          id        : 'RNAcentral',
          info      : 'Unique RNAcentral Sequences',
          resizable : 'auto',
          labels : true,
          model  : configure_genoverse_model('rnacentral'),
          view   : Genoverse.Track.View.Transcript.Ensembl,
        })
      ]
    };

    genoverseConfig = configure_karyotype_display(genoverseConfig);

    return genoverseConfig;

    /**
     * Determine whether karyotype should be displayed.
     */
    function configure_karyotype_display(genoverseConfig) {
      if (is_karyotype_available()) {
        genoverseConfig.plugins.push('karyotype');
        genoverseConfig.genome = 'grch38'; // determine dynamically when more karyotypes are available
      } else {
        genoverseConfig.chromosomeSize = Math.pow(10, 20); // should be greater than any chromosome size
      }
      return genoverseConfig;
    }

    /**
     * Dynamically choose whether to use E! or EG REST API based on species.
     * If species not in E!, use EG.
     * Ensembl species list: http://www.ensembl.org/info/about/species.html
     */
    function get_ensembl_or_ensemblgenomes_endpoint() {
      var endpoint;
      var ensembl_species = ["ailuropoda_melanoleuca", "anas_platyrhynchos", "anolis_carolinensis", "astyanax_mexicanus",
                             "bos_taurus", "callithrix_jacchus", "canis_lupus_familiaris",
                             "cavia_porcellus", "ceratotherium_simum_simum", "chlorocebus_sabaeus", "choloepus_hoffmanni",
                             "chrysemys_picta_bellii", "ciona_intestinalis", "ciona_savignyi", "cricetulus_griseus", "danio_rerio",
                             "dasypus_novemcinctus", "dipodomys_ordii", "drosophila_melanogaster", "echinops_telfairi",
                             "equus_caballus", "erinaceus_europaeus", "felis_catus", "ficedula_albicollis", "gadus_morhua",
                             "gallus_gallus", "gasterosteus_aculeatus", "gorilla_gorilla_gorilla", "heterocephalus_glaber",
                             "homo_sapiens", "ictidomys_tridecemlineatus", "latimeria_chalumnae", "lepisosteus_oculatus",
                             "loxodonta_africana", "macaca_fascicularis", "macaca_mulatta", "macropus_eugenii", "meleagris_gallopavo",
                             "melopsittacus_undulatus", "microcebus_murinus", "microtus_ochrogaster", "monodelphis_domestica",
                             "mus_musculus", "mustela_putorius_furo", "myotis_lucifugus", "nomascus_leucogenys", "ochotona_princeps",
                             "oreochromis_niloticus", "ornithorhynchus_anatinus", "orycteropus_afer_afer", "oryctolagus_cuniculus",
                             "oryzias_latipes", "otolemur_garnettii", "ovis_aries", "pan_troglodytes", "papio_anubis",
                             "papio_hamadryas", "pelodiscus_sinensis", "petromyzon_marinus", "poecilia_formosa", "pongo_abelii",
                             "procavia_capensis", "pteropus_vampyrus", "rattus_norvegicus",
                             "saimiri_boliviensis", "sarcophilus_harrisii", "sorex_araneus", "sus_scrofa", "sus_scrofa_map",
                             "taeniopygia_guttata", "takifugu_rubripes", "tarsius_syrichta", "tetraodon_nigroviridis", "tupaia_belangeri",
                             "tursiops_truncatus", "vicugna_pacos", "xenopus_tropicalis", "xiphophorus_maculatus"];
                             // "saccharomyces_cerevisiae", "caenorhabditis_elegans"];
                              // "saccharomyces_cerevisiae", "caenorhabditis_elegans" could use either E! or EG
      if (ensembl_species.indexOf(this.params.species) > -1) {
        endpoint = 'rest.ensembl.org';
      } else {
        endpoint = 'rest.ensemblgenomes.org';
      }
      return endpoint;
    }

    /**
     * Each Genoverse model is configured with an organism-specific url.
     * In addition, a new RNAcentral models that's mimicking Ensembl API is defined.
     */
    function configure_genoverse_model(model_type) {

      var model;
      var endpoint = get_ensembl_or_ensemblgenomes_endpoint();

      if (model_type === 'ensembl_gene') {
        // Ensembl Gene track
        new_url = '//__ENDPOINT__/overlap/region/__SPECIES__/__CHR__:__START__-__END__?feature=gene;content-type=application/json'.replace('__ENDPOINT__', endpoint).replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Gene.Ensembl.extend({
          url: new_url,
        });

      } else if (model_type === 'ensembl_transcript') {
        // Ensembl Transcript track
        new_url = '//__ENDPOINT__/overlap/region/__SPECIES__/__CHR__:__START__-__END__?feature=transcript;feature=exon;feature=cds;content-type=application/json'.replace('__ENDPOINT__', endpoint).replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Transcript.Ensembl.extend({
          url: new_url,
        });

      } else if (model_type === 'ensembl_sequence') {
        // Ensembl sequence view
        new_url = '//__ENDPOINT__/sequence/region/__SPECIES__/__CHR__:__START__-__END__?content-type=text/plain'.replace('__ENDPOINT__', endpoint).replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Sequence.Ensembl.extend({
          url: new_url,
        });

      } else if (model_type === 'rnacentral') {
        // custom RNAcentral track
        if (!window.location.origin) {
          window.location.origin = window.location.protocol + "//" + window.location.host + '/';
        }
        new_url = window.location.origin + '/api/v1/feature/region/__SPECIES__/__CHR__:__START__-__END__'.replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Gene.Ensembl.extend({
          url: new_url,

          parseData: function (data) {
            for (var i = 0; i < data.length; i++) {
              var feature = data[i];

              if (feature.feature_type === 'transcript' && !this.featuresById[feature.ID]) {
                feature.id    = feature.ID;
                feature.label = feature.external_name;
                feature.exons = [];
                feature.cds   = [];

                this.insertFeature(feature);
              } else if (feature.feature_type === 'exon' && this.featuresById[feature.Parent]) {
                feature.id = feature.ID;

                if (!this.featuresById[feature.Parent].exons[feature.id]) {
                  this.featuresById[feature.Parent].exons.push(feature);
                  this.featuresById[feature.Parent].exons[feature.id] = feature;
                }
              }
            }
          }
        });
      }

      return model;
    }

  };

  /**
   * Maximize Genoverse container width.
   */
  set_genoverse_width = function() {
    var w = $('.container').width();
    $('.wrap').width(w);
    $('#genoverse').width(w);
  };

  /**
   * Determine if karyotype information is available for this species.
   */
  is_karyotype_available = function() {
    var karyotype_available = ["homo_sapiens"]; // TODO: support more species
    if (karyotype_available.indexOf(this.params.species) === -1) {
      return false;
    } else {
      return true;
    }
  };

  /**
   * Attach all event handlers.
   */
  bind_events = function() {
    resize_genoverse_on_window_resize();
    genoverse_trigger();

    /**
     * Ensure Genoverse is resized when the browser window is resized.
     */
    function resize_genoverse_on_window_resize() {
      window.onresize = function() {
        set_genoverse_width();
      };
    }

    /**
     * Create an event for launching Genoverse.
     */
    function genoverse_trigger()  {
      $('body').on("click", '.genoverse-xref', function(e){
          e.preventDefault();
          set_params($(this));
          display_genomic_location();
      });

      /**
       * Store new parameters in the internal object.
       */
      function set_params($this) {

        var species = $this.data('species');
        if (species !== this.params.species) {
          _species = this.params.species;
        }

        this.params = {
          'chromosome': $this.data('chromosome'),
          'start': $this.data('genomic-start'),
          'end': $this.data('genomic-end'),
          'species': species,
          '_species': _species,
          'endpoint': $this.data('endpoint'),
        };
      }
    }

  };

  /**
   * Run module.
   */
  (function(){
    set_genoverse_width();
    bind_events();
  })();

})();
<commit_msg>Do not display karyotype for non-chromosomal regions like scaffolds etc<commit_after>/*
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Manage Genoverse embedded browser.
 */

;(function(){

  /**
   * Internal object for storing the browser state.
   */
  params = {
    'chromosome': '',
    'start': '',
    'end': '',
    'species': '',
    '_species': '', // previous species
  };

  genoverse_container = '#genoverse';

  /**
   * Main function for launching Genoverse.
   */
  display_genomic_location = function() {

    show_genoverse_section_header();
    initialize_genoverse();
    navigate_to_feature();

    /**
     * Load Genoverse for the first time or switch to a different species.
     */
    function initialize_genoverse() {
      if (typeof window.browser === 'undefined' || switch_species()) {
          // (re-)create Genoverse object
          delete window.browser;
          $(this.genoverse_container).html('');
          window.browser = new Genoverse(get_genoverse_config_object());
          add_karyotype_placeholder();
      }

      /**
       * Return true if the current and the previous browser states refer to
       * different species.
       */
      function switch_species() {
        return this.params._species !== this.params.species && this.params._species !== '';
      }

      /**
       * Karyotype is supported only for a limited number of species,
       * so a placeholder div is used to replace the karyotype div
       * to keep the display consistent.
       */
      function add_karyotype_placeholder() {
        if (!is_karyotype_available()) {
            $('.gv_wrapper').prepend('
' +
                                     '
Karyotype display is not available
' +
                                     '
');
        }
      }
    }

    /**
     * Navigate to the region of interest.
     */
    function navigate_to_feature() {
      browser.moveTo(this.params.start, this.params.end, false);
      browser.zoomOut();
    }

    /**
     * Display Genoverse section header.
     */
    function show_genoverse_section_header() {
      $('.genoverse-wrap h2').show();
    }

  };

  /**
   * Configure Genoverse initialization object.
   */
  get_genoverse_config_object = function() {

    var genoverseConfig = {
      container     : this.genoverse_container,
      chr           : this.params.chromosome,
      species       : this.params.species,
      showUrlCoords : false, // do not show genomic coordinates in the url
      plugins       : [ 'controlPanel', 'resizer', 'fileDrop' ],
      tracks        : [
        Genoverse.Track.Scalebar,
        Genoverse.Track.extend({
          name      : 'Sequence',
          model     : configure_genoverse_model('ensembl_sequence'),
          view      : Genoverse.Track.View.Sequence,
          resizable : 'auto',
          100000    : false,
        }),
        Genoverse.Track.extend({
          name      : 'Genes',
          info      : 'Ensembl API genes',
          resizable : 'auto',
          labels : true,
          model  : configure_genoverse_model('ensembl_gene'),
          view   : Genoverse.Track.View.Gene.Ensembl,
        }),
        Genoverse.Track.extend({
          name      : 'Transcripts',
          info      : 'Ensembl API transcripts',
          resizable : 'auto',
          labels : true,
          model  : configure_genoverse_model('ensembl_transcript'),
          view   : Genoverse.Track.View.Transcript.Ensembl,
        }),
        Genoverse.Track.extend({
          name      : 'RNAcentral',
          id        : 'RNAcentral',
          info      : 'Unique RNAcentral Sequences',
          resizable : 'auto',
          labels : true,
          model  : configure_genoverse_model('rnacentral'),
          view   : Genoverse.Track.View.Transcript.Ensembl,
        })
      ]
    };

    genoverseConfig = configure_karyotype_display(genoverseConfig);

    return genoverseConfig;

    /**
     * Determine whether karyotype should be displayed.
     */
    function configure_karyotype_display(genoverseConfig) {
      if (is_karyotype_available()) {
        genoverseConfig.plugins.push('karyotype');
        genoverseConfig.genome = 'grch38'; // determine dynamically when more karyotypes are available
      } else {
        genoverseConfig.chromosomeSize = Math.pow(10, 20); // should be greater than any chromosome size
      }
      return genoverseConfig;
    }

    /**
     * Dynamically choose whether to use E! or EG REST API based on species.
     * If species not in E!, use EG.
     * Ensembl species list: http://www.ensembl.org/info/about/species.html
     */
    function get_ensembl_or_ensemblgenomes_endpoint() {
      var endpoint;
      var ensembl_species = ["ailuropoda_melanoleuca", "anas_platyrhynchos", "anolis_carolinensis", "astyanax_mexicanus",
                             "bos_taurus", "callithrix_jacchus", "canis_lupus_familiaris",
                             "cavia_porcellus", "ceratotherium_simum_simum", "chlorocebus_sabaeus", "choloepus_hoffmanni",
                             "chrysemys_picta_bellii", "ciona_intestinalis", "ciona_savignyi", "cricetulus_griseus", "danio_rerio",
                             "dasypus_novemcinctus", "dipodomys_ordii", "drosophila_melanogaster", "echinops_telfairi",
                             "equus_caballus", "erinaceus_europaeus", "felis_catus", "ficedula_albicollis", "gadus_morhua",
                             "gallus_gallus", "gasterosteus_aculeatus", "gorilla_gorilla_gorilla", "heterocephalus_glaber",
                             "homo_sapiens", "ictidomys_tridecemlineatus", "latimeria_chalumnae", "lepisosteus_oculatus",
                             "loxodonta_africana", "macaca_fascicularis", "macaca_mulatta", "macropus_eugenii", "meleagris_gallopavo",
                             "melopsittacus_undulatus", "microcebus_murinus", "microtus_ochrogaster", "monodelphis_domestica",
                             "mus_musculus", "mustela_putorius_furo", "myotis_lucifugus", "nomascus_leucogenys", "ochotona_princeps",
                             "oreochromis_niloticus", "ornithorhynchus_anatinus", "orycteropus_afer_afer", "oryctolagus_cuniculus",
                             "oryzias_latipes", "otolemur_garnettii", "ovis_aries", "pan_troglodytes", "papio_anubis",
                             "papio_hamadryas", "pelodiscus_sinensis", "petromyzon_marinus", "poecilia_formosa", "pongo_abelii",
                             "procavia_capensis", "pteropus_vampyrus", "rattus_norvegicus",
                             "saimiri_boliviensis", "sarcophilus_harrisii", "sorex_araneus", "sus_scrofa", "sus_scrofa_map",
                             "taeniopygia_guttata", "takifugu_rubripes", "tarsius_syrichta", "tetraodon_nigroviridis", "tupaia_belangeri",
                             "tursiops_truncatus", "vicugna_pacos", "xenopus_tropicalis", "xiphophorus_maculatus"];
                             // "saccharomyces_cerevisiae", "caenorhabditis_elegans"];
                              // "saccharomyces_cerevisiae", "caenorhabditis_elegans" could use either E! or EG
      if (ensembl_species.indexOf(this.params.species) > -1) {
        endpoint = 'rest.ensembl.org';
      } else {
        endpoint = 'rest.ensemblgenomes.org';
      }
      return endpoint;
    }

    /**
     * Each Genoverse model is configured with an organism-specific url.
     * In addition, a new RNAcentral models that's mimicking Ensembl API is defined.
     */
    function configure_genoverse_model(model_type) {

      var model;
      var endpoint = get_ensembl_or_ensemblgenomes_endpoint();

      if (model_type === 'ensembl_gene') {
        // Ensembl Gene track
        new_url = '//__ENDPOINT__/overlap/region/__SPECIES__/__CHR__:__START__-__END__?feature=gene;content-type=application/json'.replace('__ENDPOINT__', endpoint).replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Gene.Ensembl.extend({
          url: new_url,
        });

      } else if (model_type === 'ensembl_transcript') {
        // Ensembl Transcript track
        new_url = '//__ENDPOINT__/overlap/region/__SPECIES__/__CHR__:__START__-__END__?feature=transcript;feature=exon;feature=cds;content-type=application/json'.replace('__ENDPOINT__', endpoint).replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Transcript.Ensembl.extend({
          url: new_url,
        });

      } else if (model_type === 'ensembl_sequence') {
        // Ensembl sequence view
        new_url = '//__ENDPOINT__/sequence/region/__SPECIES__/__CHR__:__START__-__END__?content-type=text/plain'.replace('__ENDPOINT__', endpoint).replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Sequence.Ensembl.extend({
          url: new_url,
        });

      } else if (model_type === 'rnacentral') {
        // custom RNAcentral track
        if (!window.location.origin) {
          window.location.origin = window.location.protocol + "//" + window.location.host + '/';
        }
        new_url = window.location.origin + '/api/v1/feature/region/__SPECIES__/__CHR__:__START__-__END__'.replace('__SPECIES__', this.params.species);
        model = Genoverse.Track.Model.Gene.Ensembl.extend({
          url: new_url,

          parseData: function (data) {
            for (var i = 0; i < data.length; i++) {
              var feature = data[i];

              if (feature.feature_type === 'transcript' && !this.featuresById[feature.ID]) {
                feature.id    = feature.ID;
                feature.label = feature.external_name;
                feature.exons = [];
                feature.cds   = [];

                this.insertFeature(feature);
              } else if (feature.feature_type === 'exon' && this.featuresById[feature.Parent]) {
                feature.id = feature.ID;

                if (!this.featuresById[feature.Parent].exons[feature.id]) {
                  this.featuresById[feature.Parent].exons.push(feature);
                  this.featuresById[feature.Parent].exons[feature.id] = feature;
                }
              }
            }
          }
        });
      }

      return model;
    }

  };

  /**
   * Maximize Genoverse container width.
   */
  set_genoverse_width = function() {
    var w = $('.container').width();
    $('.wrap').width(w);
    $('#genoverse').width(w);
  };

  /**
   * Determine if karyotype information is available for this species.
   */
  is_karyotype_available = function() {

    return species_supported() && chromosome_size_available();

    function species_supported() {
      var species = ["homo_sapiens"]; // TODO: support more species
      if (species.indexOf(this.params.species) !== -1) {
        return true;
      } else {
        return false;
      }
    }

    /**
     * Get a list of chromosomes from the karyotype object and determine
     * whether the size of the displayed region is known.
     * Some RNAs are defined on scaffolds or other non-chromosomal objects
     * for which the size is not stored in the karyotype object.
     */
    function chromosome_size_available() {
      var chromosomes = [];
      for(var key in grch38) {
        chromosomes.push(key);
      }
      if ( chromosomes.indexOf(this.params.chromosome.toString()) !== -1) {
        return true;
      } else {
        return false;
      }
    }

  }

  /**
   * Attach all event handlers.
   */
  bind_events = function() {
    resize_genoverse_on_window_resize();
    genoverse_trigger();

    /**
     * Ensure Genoverse is resized when the browser window is resized.
     */
    function resize_genoverse_on_window_resize() {
      window.onresize = function() {
        set_genoverse_width();
      };
    }

    /**
     * Create an event for launching Genoverse.
     */
    function genoverse_trigger()  {
      $('body').on("click", '.genoverse-xref', function(e){
          e.preventDefault();
          set_params($(this));
          display_genomic_location();
      });

      /**
       * Store new parameters in the internal object.
       */
      function set_params($this) {

        var species = $this.data('species');
        if (species !== this.params.species) {
          _species = this.params.species;
        }

        this.params = {
          'chromosome': $this.data('chromosome'),
          'start': $this.data('genomic-start'),
          'end': $this.data('genomic-end'),
          'species': species,
          '_species': _species,
          'endpoint': $this.data('endpoint'),
        };
      }
    }

  };

  /**
   * Run module.
   */
  (function(){
    set_genoverse_width();
    bind_events();
  })();

})();
<|endoftext|>


<commit_before>import Component from 'flarum/component';
import ItemList from 'flarum/utils/item-list';
import DiscussionList from 'flarum/components/discussion-list';
import DiscussionHero from 'flarum/components/discussion-hero';
import PostStream from 'flarum/components/post-stream';
import PostScrubber from 'flarum/components/post-scrubber';
import ReplyComposer from 'flarum/components/reply-composer';
import ActionButton from 'flarum/components/action-button';
import LoadingIndicator from 'flarum/components/loading-indicator';
import DropdownSplit from 'flarum/components/dropdown-split';
import Separator from 'flarum/components/separator';
import listItems from 'flarum/helpers/list-items';
import mixin from 'flarum/utils/mixin';
import evented from 'flarum/utils/evented';

export default class DiscussionPage extends mixin(Component, evented) {
  /**

   */
  constructor(props) {
    super(props);

    this.discussion = m.prop();
    this.refresh();

    if (app.cache.discussionList) {
      if (app.current instanceof DiscussionPage) {
        m.redraw.strategy('diff'); // otherwise pane redraws (killing retained subtrees) and mouseenter event is triggered so it doesn't hide
      }
      app.pane.enable();
      app.pane.hide();
    }

    app.history.push('discussion');
    app.current = this;
    app.session.on('loggedIn', this.loggedInHandler = this.refresh.bind(this));
  }

  refresh() {
    this.currentNear = m.route.param('near') || 0;
    this.discussion(null);

    var params = this.params();
    params.include = params.include.join(',');

    var discussion;
    if (app.preload.response) {
      // We must wrap this in a setTimeout because if we are mounting this
      // component for the first time on page load, then any calls to m.redraw
      // will be ineffective and thus any configs (scroll code) will be run
      // before stuff is drawn to the page.
      setTimeout(() => {
        var discussion = app.store.pushPayload(app.preload.response);
        app.preload.response = null;
        this.setupDiscussion(discussion);
      });
    } else {
      app.store.find('discussions', m.route.param('id'), params).then(this.setupDiscussion.bind(this));
    }

    // Trigger a redraw only if we're not already in a computation (e.g. route change)
    m.startComputation();
    m.endComputation();
  }

  params() {
    return {
      near: this.currentNear,
      include: ['posts', 'posts.user', 'posts.user.groups']
    };
  }

  /*

   */
  setupDiscussion(discussion) {
    // Hold up there skippy! If the slug in the URL doesn't match up, we'll
    // redirect so we have the correct one.
    // Waiting on https://github.com/lhorie/mithril.js/issues/539
    // if (m.route.param('id') === discussion.id() && m.route.param('slug') !== discussion.slug()) {
    //   var params = m.route.param();
    //   params.slug = discussion.slug();
    //   params.near = params.near || '';
    //   m.route(app.route('discussion.near', params), null, true);
    //   return;
    // }

    this.discussion(discussion);
    app.setTitle(discussion.title());

    var includedPosts = [];
    if (discussion.payload && discussion.payload.included) {
      discussion.payload.included.forEach(record => {
        if (record.type === 'posts' && record.links && record.links.discussion) {
          includedPosts.push(app.store.getById('posts', record.id));
        }
      });
      includedPosts.sort((a, b) => a.id() - b.id()).splice(20);
    }

    this.stream = new PostStream({ discussion, includedPosts });
    this.stream.on('positionChanged', this.positionChanged.bind(this));
    this.stream.goToNumber(m.route.param('near') || 1, true);

    this.trigger('loaded', discussion);
  }

  onload(element, isInitialized, context) {
    if (isInitialized) { return; }

    context.retain = true;

    $('body').addClass('discussion-page');
    context.onunload = function() {
      $('body').removeClass('discussion-page');
    }
  }

  /**

   */
  onunload(e) {
    // If we have routed to the same discussion as we were viewing previously,
    // cancel the unloading of this controller and instead prompt the post
    // stream to jump to the new 'near' param.
    var discussion = this.discussion();
    if (discussion) {
      if (m.route.param('id') == discussion.id()) {
        e.preventDefault();
        if (m.route.param('near') != this.currentNear) {
          this.stream.goToNumber(m.route.param('near') || 1);
        }
        this.currentNear = null;
        return;
      }
    }

    app.pane.disable();
    app.composer.minimize();
    app.session.off('loggedIn', this.loggedInHandler);
  }

  /**

   */
  view() {
    var discussion = this.discussion();

    return m('div', {config: this.onload.bind(this)}, [
      app.cache.discussionList ? m('div.index-area.paned', {config: this.configIndex.bind(this)}, app.cache.discussionList.view()) : '',
      m('div.discussion-area', discussion ? [
        DiscussionHero.component({discussion}),
        m('div.container', [
          m('nav.discussion-nav', [
            m('ul', listItems(this.sidebarItems().toArray()))
          ]),
          this.stream.view()
        ])
      ] : LoadingIndicator.component({className: 'loading-indicator-block'}))
    ]);
  }

  /**

   */
  configIndex(element, isInitialized, context) {
    if (isInitialized) { return; }

    context.retain = true;

    var $index = $(element);

    // When viewing a discussion (for which the discussions route is the
    // parent,) the discussion list is still rendered but it becomes a
    // pane hidden on the side of the screen. When the mouse enters and
    // leaves the discussions pane, we want to show and hide the pane
    // respectively. We also create a 10px 'hot edge' on the left of the
    // screen to activate the pane.
    var pane = app.pane;
    $index.hover(pane.show.bind(pane), pane.onmouseleave.bind(pane));

    var hotEdge = function(e) {
      if (e.pageX < 10) { pane.show(); }
    };
    $(document).on('mousemove', hotEdge);
    context.onunload = function() {
      $(document).off('mousemove', hotEdge);
    };

    var $discussion = $index.find('.discussion-summary.active');
    if ($discussion.length) {
      var indexTop = $index.offset().top;
      var discussionTop = $discussion.offset().top;
      if (discussionTop < indexTop || discussionTop + $discussion.outerHeight() > indexTop + $index.outerHeight()) {
        $index.scrollTop($index.scrollTop() - indexTop + discussionTop);
      }
    }
  }

  /**

   */
  sidebarItems() {
    var items = new ItemList();

    items.add('controls',
      DropdownSplit.component({
        items: this.discussion().controls(this).toArray(),
        icon: 'ellipsis-v',
        className: 'primary-control',
        buttonClass: 'btn btn-primary'
      })
    );

    items.add('scrubber',
      PostScrubber.component({
        stream: this.stream,
        className: 'title-control'
      })
    );

    return items;
  }

  /**

   */
  positionChanged(startNumber, endNumber) {
    var discussion = this.discussion();

    var url = app.route('discussion.near', {
      id: discussion.id(),
      slug: discussion.slug(),
      near: this.currentNear = startNumber
    });

    // https://github.com/lhorie/mithril.js/issues/559
    m.route(url, true);
    window.history.replaceState(null, document.title, (m.route.mode === 'hash' ? '#' : '')+url);

    app.history.push('discussion');

    if (app.session.user() && endNumber > discussion.readNumber()) {
      discussion.save({readNumber: endNumber});
      m.redraw();
    }
  }
}
<commit_msg>Close the composer completely if the reply is empty<commit_after>import Component from 'flarum/component';
import ItemList from 'flarum/utils/item-list';
import DiscussionList from 'flarum/components/discussion-list';
import DiscussionHero from 'flarum/components/discussion-hero';
import PostStream from 'flarum/components/post-stream';
import PostScrubber from 'flarum/components/post-scrubber';
import ReplyComposer from 'flarum/components/reply-composer';
import ActionButton from 'flarum/components/action-button';
import LoadingIndicator from 'flarum/components/loading-indicator';
import DropdownSplit from 'flarum/components/dropdown-split';
import Separator from 'flarum/components/separator';
import listItems from 'flarum/helpers/list-items';
import mixin from 'flarum/utils/mixin';
import evented from 'flarum/utils/evented';

export default class DiscussionPage extends mixin(Component, evented) {
  /**

   */
  constructor(props) {
    super(props);

    this.discussion = m.prop();
    this.refresh();

    if (app.cache.discussionList) {
      if (app.current instanceof DiscussionPage) {
        m.redraw.strategy('diff'); // otherwise pane redraws (killing retained subtrees) and mouseenter event is triggered so it doesn't hide
      }
      app.pane.enable();
      app.pane.hide();
    }

    app.history.push('discussion');
    app.current = this;
    app.session.on('loggedIn', this.loggedInHandler = this.refresh.bind(this));
  }

  refresh() {
    this.currentNear = m.route.param('near') || 0;
    this.discussion(null);

    var params = this.params();
    params.include = params.include.join(',');

    var discussion;
    if (app.preload.response) {
      // We must wrap this in a setTimeout because if we are mounting this
      // component for the first time on page load, then any calls to m.redraw
      // will be ineffective and thus any configs (scroll code) will be run
      // before stuff is drawn to the page.
      setTimeout(() => {
        var discussion = app.store.pushPayload(app.preload.response);
        app.preload.response = null;
        this.setupDiscussion(discussion);
      });
    } else {
      app.store.find('discussions', m.route.param('id'), params).then(this.setupDiscussion.bind(this));
    }

    // Trigger a redraw only if we're not already in a computation (e.g. route change)
    m.startComputation();
    m.endComputation();
  }

  params() {
    return {
      near: this.currentNear,
      include: ['posts', 'posts.user', 'posts.user.groups']
    };
  }

  /*

   */
  setupDiscussion(discussion) {
    // Hold up there skippy! If the slug in the URL doesn't match up, we'll
    // redirect so we have the correct one.
    // Waiting on https://github.com/lhorie/mithril.js/issues/539
    // if (m.route.param('id') === discussion.id() && m.route.param('slug') !== discussion.slug()) {
    //   var params = m.route.param();
    //   params.slug = discussion.slug();
    //   params.near = params.near || '';
    //   m.route(app.route('discussion.near', params), null, true);
    //   return;
    // }

    this.discussion(discussion);
    app.setTitle(discussion.title());

    var includedPosts = [];
    if (discussion.payload && discussion.payload.included) {
      discussion.payload.included.forEach(record => {
        if (record.type === 'posts' && record.links && record.links.discussion) {
          includedPosts.push(app.store.getById('posts', record.id));
        }
      });
      includedPosts.sort((a, b) => a.id() - b.id()).splice(20);
    }

    this.stream = new PostStream({ discussion, includedPosts });
    this.stream.on('positionChanged', this.positionChanged.bind(this));
    this.stream.goToNumber(m.route.param('near') || 1, true);

    this.trigger('loaded', discussion);
  }

  onload(element, isInitialized, context) {
    if (isInitialized) { return; }

    context.retain = true;

    $('body').addClass('discussion-page');
    context.onunload = function() {
      $('body').removeClass('discussion-page');
    }
  }

  /**

   */
  onunload(e) {
    // If we have routed to the same discussion as we were viewing previously,
    // cancel the unloading of this controller and instead prompt the post
    // stream to jump to the new 'near' param.
    var discussion = this.discussion();
    if (discussion) {
      if (m.route.param('id') == discussion.id()) {
        e.preventDefault();
        if (m.route.param('near') != this.currentNear) {
          this.stream.goToNumber(m.route.param('near') || 1);
        }
        this.currentNear = null;
        return;
      }
    }

    app.pane.disable();
    app.session.off('loggedIn', this.loggedInHandler);

    if (app.composingReplyTo(discussion) && !app.composer.component.content()) {
      app.composer.hide();
    } else {
      app.composer.minimize();
    }
  }

  /**

   */
  view() {
    var discussion = this.discussion();

    return m('div', {config: this.onload.bind(this)}, [
      app.cache.discussionList ? m('div.index-area.paned', {config: this.configIndex.bind(this)}, app.cache.discussionList.view()) : '',
      m('div.discussion-area', discussion ? [
        DiscussionHero.component({discussion}),
        m('div.container', [
          m('nav.discussion-nav', [
            m('ul', listItems(this.sidebarItems().toArray()))
          ]),
          this.stream.view()
        ])
      ] : LoadingIndicator.component({className: 'loading-indicator-block'}))
    ]);
  }

  /**

   */
  configIndex(element, isInitialized, context) {
    if (isInitialized) { return; }

    context.retain = true;

    var $index = $(element);

    // When viewing a discussion (for which the discussions route is the
    // parent,) the discussion list is still rendered but it becomes a
    // pane hidden on the side of the screen. When the mouse enters and
    // leaves the discussions pane, we want to show and hide the pane
    // respectively. We also create a 10px 'hot edge' on the left of the
    // screen to activate the pane.
    var pane = app.pane;
    $index.hover(pane.show.bind(pane), pane.onmouseleave.bind(pane));

    var hotEdge = function(e) {
      if (e.pageX < 10) { pane.show(); }
    };
    $(document).on('mousemove', hotEdge);
    context.onunload = function() {
      $(document).off('mousemove', hotEdge);
    };

    var $discussion = $index.find('.discussion-summary.active');
    if ($discussion.length) {
      var indexTop = $index.offset().top;
      var discussionTop = $discussion.offset().top;
      if (discussionTop < indexTop || discussionTop + $discussion.outerHeight() > indexTop + $index.outerHeight()) {
        $index.scrollTop($index.scrollTop() - indexTop + discussionTop);
      }
    }
  }

  /**

   */
  sidebarItems() {
    var items = new ItemList();

    items.add('controls',
      DropdownSplit.component({
        items: this.discussion().controls(this).toArray(),
        icon: 'ellipsis-v',
        className: 'primary-control',
        buttonClass: 'btn btn-primary'
      })
    );

    items.add('scrubber',
      PostScrubber.component({
        stream: this.stream,
        className: 'title-control'
      })
    );

    return items;
  }

  /**

   */
  positionChanged(startNumber, endNumber) {
    var discussion = this.discussion();

    var url = app.route('discussion.near', {
      id: discussion.id(),
      slug: discussion.slug(),
      near: this.currentNear = startNumber
    });

    // https://github.com/lhorie/mithril.js/issues/559
    m.route(url, true);
    window.history.replaceState(null, document.title, (m.route.mode === 'hash' ? '#' : '')+url);

    app.history.push('discussion');

    if (app.session.user() && endNumber > discussion.readNumber()) {
      discussion.save({readNumber: endNumber});
      m.redraw();
    }
  }
}
<|endoftext|>


<commit_before>/*
 * HOMER 5 UI (Xenophon)
 *
 * Copyright (C) 2011-2015 Alexandr Dubovikov <alexandr.dubovikov@gmail.com>
 * Copyright (C) 2011-2015 Lorenzo Mangani <lorenzo.mangani@gmail.com> QXIP B.V.
 * License AGPL-3.0 http://opensource.org/licenses/AGPL-3.0
 *
*/

(function (angular, homer) {
    'use strict';

    angular.module(homer.modules.pages.name)
	.controller(homer.modules.pages.controllers.result, [
	    '$scope',
	    '$rootScope',
	    'eventbus',
	    '$http',
	    '$location',
	    homer.modules.core.services.search,
	    '$timeout',
	    '$window',
	    '$homerModal',
	    homer.modules.core.services.profile,
	    function ($scope,$rootScope, eventbus, $http, $location, search, $timeout, $window, $homerModal, userProfile) {

		//$rootScope.loggedIn = false;
		$scope.expandme = true;
		$scope.showtable = true;
		$scope.dataLoading = false;

		if ($rootScope.loggedIn == false) {
		    console.log("AUTH FALSE");
		    $location.path(homer.modules.auth.routes.login);
		    return;
		} else {
		    console.log("AUTH TRUE");
		}

		/* hide left menu */
		eventbus.broadcast(homer.modules.pages.events.hideLeftMenu, "1");

		// process the form
		$scope.processSearchResult = function() {

		/* save data for next search */
		var data = {param:{}, timestamp:{}};

		var transaction = userProfile.getProfile("transaction");
		var limit = userProfile.getProfile("limit");
		var timedate = userProfile.getProfile("timerange");
		var value = userProfile.getProfile("search");
		var node = userProfile.getProfile("node").dbnode;

		/* make construct of query */
		data.param.transaction = {};
		data.param.limit = limit;
		data.param.search = value;
		data.param.node = node;
		data.timestamp.from = timedate.from.getTime();
		data.timestamp.to = timedate.to.getTime();

		angular.forEach(transaction.transaction, function(v, k) {
		    data.param.transaction[v.name] = true;
		});

		$scope.dataLoading = true;

		search.searchByMethod(data).then(
		function (sdata) {
		    if (sdata) {
			$scope.count = sdata.length;
			$scope.gridOpts.data = sdata;
			$timeout(function () {
			    angular.element($window).resize();
			}, 0)
		    }
		},
		function(sdata) {
		    return;
		}).finally(
		function(){
		    $scope.dataLoading = false;
		    //$scope.$apply();
		});
	    };

            //$timeout(function(){
                //any code in here will automatically have an apply run afterwards
           //     $scope.$apply();
            //});

            $scope.processSearchResult();

             /* DATA */
            $scope.swapData = function() {
		//$scope.gridOpts.data = data1;
		//$scope.$apply();
	    };

	    $scope.hashCode = function(str) { // java String#hashCode
		var hash = 0;
		for (var i = 0; i < str.length; i++) {
			hash = str.charCodeAt(i) + ((hash << 5) - hash);
		}
		return hash;
	    };

	    $scope.intToARGB = function (i){
		//return ((i>>24)&0xFF).toString(16) + ((i>>16)&0xFF).toString(16) + ((i>>8)&0xFF).toString(16) + (i&0xFF).toString(16);
		return ((i>>24)&0xFF);
	    }

	    $scope.getBkgColorTable = function (callid) {
			var his = $scope.hashCode(callid);
			//var color = "#"+$scope.intToARGB(his);
			var color = "hsl("+$scope.intToARGB(his)+", 75%, 75%)";
			return {
				"background-color": color
			}
            };

	    $scope.showMessage = function(localrow,event) {
		var search_data =  {
		    timestamp: {
			from: parseInt(localrow.entity.micro_ts/1000),
			to: parseInt(localrow.entity.micro_ts/1000)
		    },
		    param: {
			search: {
			    id: parseInt(localrow.entity.id),
			    callid: localrow.entity.callid
			},
			location: {
			    node: localrow.entity.dbnode
			},
			transaction: {
			    call: false,\
			    registration: false,\
			    rest: false
			}
		    }
		};

		search_data['param']['transaction'][localrow.entity.trans] = true;
		var messagewindowId = ""+localrow.entity.id+"_"+localrow.entity.trans;

		$homerModal.open({
		    url: 'templates/dialogs/message.html',
		    cls: 'homer-modal-content',
		    id: "message"+messagewindowId.hashCode(),
		    divLeft: event.clientX.toString()+'px',
		    divTop: event.clientY.toString()+'px',
		    params: search_data,
		    onOpen: function() {
			console.log('modal1 message opened from url '+this.id);
		    },
		    controller: 'messageCtrl'
		});
            };

	    $scope.getColumnValue = function(row,col) {
		return row.entity[col.field+'_alias']==undefined?row.entity[col.field+'_ip']:row.entity[col.field+'_alias'];
	    }
	    $scope.getColumnTooltip = function(row,col) {
		return row.entity[col.field+'_ip'];
	    }

	    $scope.showTransaction = function(localrow,event) {

		var rows = $scope.gridApi.selection.getSelectedRows();
		var callids = [];
		var nodes = [];

		callids.push(localrow.entity.callid);

		angular.forEach(rows, function(row, key){
		    if(callids.indexOf(row.callid) == -1) callids.push(row.callid);
		    if(callids.indexOf(row.callid_aleg) == -1 && row.callid_aleg.length > 1) callids.push(row.callid_aleg);
		    if(nodes.indexOf(row.dbnode) == -1) nodes.push(row.dbnode);
		});

		var search_data =  {
		    timestamp: {
			from: parseInt(localrow.entity.micro_ts/1000)-300,
			to: parseInt(localrow.entity.micro_ts/1000)+300
		    },
		    param: {
			search: {
			    id: parseInt(localrow.entity.id),
			    callid: callids
			},
			location: {
			    node: nodes
			},
			transaction: {
			    call: false,
			    registration: false,
			    rest: false
			}
		    }
		};

		/* set to to our last search time */
		//var timedate = search.getTimeRange();
		var timedate = userProfile.getProfile("timerange");
		search_data['timestamp']['to'] = timedate.to.getTime();

		search_data['param']['transaction'][localrow.entity.trans] = true;
		var trwindowId = ""+localrow.entity.callid + "_" +localrow.entity.dbnode;

		$homerModal.open({
		    url: 'templates/dialogs/transaction.html',
		    cls: 'homer-modal-content',
		    id: "trans"+trwindowId.hashCode(),
		    params: search_data,
		    divLeft: event.clientX.toString()+'px',
		    divTop: event.clientY.toString()+'px',
		    onOpen: function() {
			console.log('modal1 opened from url',this.id);
		    },
		    controller: 'transactionCtrl'
		});
	    };

	    $scope.fileOneUploaded = true;
	    $scope.fileTwoUploaded = false;

	    var rowtpl =  '
'
			+ '

'
			+'
';

	    $scope.gridOpts = {
		enableColumnResizing: true,
		enableSorting: true,
		enableRowSelection: true,
		enableGridMenu: true,
		showGridFooter:true,
		noUnselect: false,
		multiSelect:true,
		modifierKeysToMultiSelect: false,
		enablePaging  : true,
		paginationPageSizes: [25, 50, 75],
		paginationPageSize: 25,
		enableFiltering: true,
		rowTemplate: rowtpl,

		filterOptions: {
		    filterText: "",
		    useExternalFilter: false
		},
		columnDefs: [
		    {field: 'id',
			displayName: 'Id',
			width: 50},
		    {field: 'milli_ts',
			displayName: 'Date',
			cellFilter: 'date:\'yyyy-dd-MM HH:mm:ss.sss\'',
			width: 170
		    },
		    //{field: 'micro_ts', displayName: 'Micro TS', width: 80},
		    {field: 'method',
			displayName: 'Method',
			cellClass: function(grid, row, col, rowRenderIndex, colRenderIndex) {
			    if (grid.getCellValue(row,col) === 'INVITE') {
				return 'blue';
			    }
			},
			cellTemplate: '
{{COL_FIELD}}
'
		    },
		    {field: 'reply_reason', displayName: 'Reason', width: 70},
		    {field: 'ruri_user', displayName: 'RURI user'},
		    {field: 'from_user', displayName: 'From User'},
		    {field: 'callid',
			displayName: 'CallID',
			width: 160,
			cellTemplate: '
{{COL_FIELD}}
'
		    },
		    {field: 'user_agent', displayName: 'User Agent'},
		    {field: 'source',
			displayName: 'Source Host',
			cellTemplate: '
{{ grid.appScope.getColumnValue(row, col) }}
'
		    },
		    {field: 'source_port', displayName: 'SPort', width: 50},
		    {field: 'destination',
			displayName: 'Destination Host',
			cellTemplate: '
{{ grid.appScope.getColumnValue(row, col) }}
'
		    },
		    {field: 'destination_port', displayName: 'DPort', width: 50},
		    {field: 'proto', displayName: 'Proto', width: 40},
		    {field: 'node', displayName: 'Node'}
		]
	    };

	    $scope.gridOpts.rowIdentity = function(row) {
		return row.id;
	    };

	    $scope.gridOpts.onRegisterApi = function(gridApi){
	    //set gridApi on scope
	    $scope.gridApi = gridApi;
	    };
	}
    ])
    .filter('unixts', function() {
	return function(input) {
	    if (!input){
		return '';
	    } else {
		return new Date(input * 1000);
	    }
	};
     });
}(angular, homer));
<commit_msg>FIX: some syntax errors<commit_after>/*
 * HOMER 5 UI (Xenophon)
 *
 * Copyright (C) 2011-2015 Alexandr Dubovikov <alexandr.dubovikov@gmail.com>
 * Copyright (C) 2011-2015 Lorenzo Mangani <lorenzo.mangani@gmail.com> QXIP B.V.
 * License AGPL-3.0 http://opensource.org/licenses/AGPL-3.0
 *
*/

(function (angular, homer) {
    'use strict';

    angular.module(homer.modules.pages.name)
	.controller(homer.modules.pages.controllers.result, [
	    '$scope',
	    '$rootScope',
	    'eventbus',
	    '$http',
	    '$location',
	    homer.modules.core.services.search,
	    '$timeout',
	    '$window',
	    '$homerModal',
	    homer.modules.core.services.profile,
	    function ($scope,$rootScope, eventbus, $http, $location, search, $timeout, $window, $homerModal, userProfile) {

		//$rootScope.loggedIn = false;
		$scope.expandme = true;
		$scope.showtable = true;
		$scope.dataLoading = false;

		if ($rootScope.loggedIn == false) {
		    console.log("AUTH FALSE");
		    $location.path(homer.modules.auth.routes.login);
		    return;
		} else {
		    console.log("AUTH TRUE");
		}

		/* hide left menu */
		eventbus.broadcast(homer.modules.pages.events.hideLeftMenu, "1");

		// process the form
		$scope.processSearchResult = function() {

		/* save data for next search */
		var data = {param:{}, timestamp:{}};

		var transaction = userProfile.getProfile("transaction");
		var limit = userProfile.getProfile("limit");
		var timedate = userProfile.getProfile("timerange");
		var value = userProfile.getProfile("search");
		var node = userProfile.getProfile("node").dbnode;

		/* make construct of query */
		data.param.transaction = {};
		data.param.limit = limit;
		data.param.search = value;
		data.param.node = node;
		data.timestamp.from = timedate.from.getTime();
		data.timestamp.to = timedate.to.getTime();

		angular.forEach(transaction.transaction, function(v, k) {
		    data.param.transaction[v.name] = true;
		});
		$scope.dataLoading = true;

		search.searchByMethod(data).then(
		function (sdata) {
		    if (sdata) {
			$scope.count = sdata.length;
			$scope.gridOpts.data = sdata;
			$timeout(function () {
			    angular.element($window).resize();
			}, 0)
		    }
		},
		function(sdata) {
		    return;
		}).finally(
		function() {
		    $scope.dataLoading = false;
		    //$scope.$apply();
		});
	    };

            //$timeout(function(){
                //any code in here will automatically have an apply run afterwards
           //     $scope.$apply();
            //});

            $scope.processSearchResult();

             /* DATA */
            $scope.swapData = function() {
		//$scope.gridOpts.data = data1;
		//$scope.$apply();
	    };

	    $scope.hashCode = function(str) { // java String#hashCode
		var hash = 0;
		for (var i = 0; i < str.length; i++) {
			hash = str.charCodeAt(i) + ((hash << 5) - hash);
		}
		return hash;
	    };

	    $scope.intToARGB = function (i){
		//return ((i>>24)&0xFF).toString(16) + ((i>>16)&0xFF).toString(16) + ((i>>8)&0xFF).toString(16) + (i&0xFF).toString(16);
		return ((i>>24)&0xFF);
	    }

	    $scope.getBkgColorTable = function (callid) {
			var his = $scope.hashCode(callid);
			//var color = "#"+$scope.intToARGB(his);
			var color = "hsl("+$scope.intToARGB(his)+", 75%, 75%)";
			return {
				"background-color": color
			}
            };

	    $scope.showMessage = function(localrow, event) {
		var search_data =  {
		    timestamp: {
			from: parseInt(localrow.entity.micro_ts/1000),
			to: parseInt(localrow.entity.micro_ts/1000)
		    },
		    param: {
			search: {
			    id: parseInt(localrow.entity.id),
			    callid: localrow.entity.callid
			},
			location: {
			    node: localrow.entity.dbnode
			},
			transaction: {
			    call: false,
			    registration: false,
			    rest: false
			}
		    }
		};

		search_data['param']['transaction'][localrow.entity.trans] = true;
		var messagewindowId = ""+localrow.entity.id+"_"+localrow.entity.trans;

		$homerModal.open({
		    url: 'templates/dialogs/message.html',
		    cls: 'homer-modal-content',
		    id: "message"+messagewindowId.hashCode(),
		    divLeft: event.clientX.toString()+'px',
		    divTop: event.clientY.toString()+'px',
		    params: search_data,
		    onOpen: function() {
			console.log('modal1 message opened from url '+this.id);
		    },
		    controller: 'messageCtrl'
		});
            };

	    $scope.getColumnValue = function(row,col) {
		return row.entity[col.field+'_alias']==undefined?row.entity[col.field+'_ip']:row.entity[col.field+'_alias'];
	    }
	    $scope.getColumnTooltip = function(row,col) {
		return row.entity[col.field+'_ip'];
	    }

	    $scope.showTransaction = function(localrow,event) {

		var rows = $scope.gridApi.selection.getSelectedRows();
		var callids = [];
		var nodes = [];

		callids.push(localrow.entity.callid);

		angular.forEach(rows, function(row, key) {
		    if(callids.indexOf(row.callid) == -1) callids.push(row.callid);
		    if(callids.indexOf(row.callid_aleg) == -1 && row.callid_aleg.length > 1) callids.push(row.callid_aleg);
		    if(nodes.indexOf(row.dbnode) == -1) nodes.push(row.dbnode);
		});

		var search_data =  {
		    timestamp: {
			from: parseInt(localrow.entity.micro_ts/1000)-300,
			to: parseInt(localrow.entity.micro_ts/1000)+300
		    },
		    param: {
			search: {
			    id: parseInt(localrow.entity.id),
			    callid: callids
			},
			location: {
			    node: nodes
			},
			transaction: {
			    call: false,
			    registration: false,
			    rest: false
			}
		    }
		};

		/* set to to our last search time */
		//var timedate = search.getTimeRange();
		var timedate = userProfile.getProfile("timerange");
		search_data['timestamp']['to'] = timedate.to.getTime();

		search_data['param']['transaction'][localrow.entity.trans] = true;
		var trwindowId = ""+localrow.entity.callid + "_" +localrow.entity.dbnode;

		$homerModal.open({
		    url: 'templates/dialogs/transaction.html',
		    cls: 'homer-modal-content',
		    id: "trans"+trwindowId.hashCode(),
		    params: search_data,
		    divLeft: event.clientX.toString()+'px',
		    divTop: event.clientY.toString()+'px',
		    onOpen: function() {
			console.log('modal1 opened from url',this.id);
		    },
		    controller: 'transactionCtrl'
		});
	    };

	    $scope.fileOneUploaded = true;
	    $scope.fileTwoUploaded = false;

	    var rowtpl =  '
'
			+ '

'
			+'
';

	    $scope.gridOpts = {
		enableColumnResizing: true,
		enableSorting: true,
		enableRowSelection: true,
		enableGridMenu: true,
		showGridFooter:true,
		noUnselect: false,
		multiSelect:true,
		modifierKeysToMultiSelect: false,
		enablePaging  : true,
		paginationPageSizes: [25, 50, 75],
		paginationPageSize: 25,
		enableFiltering: true,
		rowTemplate: rowtpl,

		filterOptions: {
		    filterText: "",
		    useExternalFilter: false
		},
		columnDefs: [
		    {field: 'id',
			displayName: 'Id',
			width: 50},
		    {field: 'milli_ts',
			displayName: 'Date',
			cellFilter: 'date:\'yyyy-dd-MM HH:mm:ss.sss\'',
			width: 170
		    },
		    //{field: 'micro_ts', displayName: 'Micro TS', width: 80},
		    {field: 'method',
			displayName: 'Method',
			cellClass: function(grid, row, col, rowRenderIndex, colRenderIndex) {
			    if (grid.getCellValue(row,col) === 'INVITE') {
				return 'blue';
			    }
			},
			cellTemplate: '
{{COL_FIELD}}
'
		    },
		    {field: 'reply_reason', displayName: 'Reason', width: 70},
		    {field: 'ruri_user', displayName: 'RURI user'},
		    {field: 'from_user', displayName: 'From User'},
		    {field: 'callid',
			displayName: 'CallID',
			width: 160,
			cellTemplate: '
{{COL_FIELD}}
'
		    },
		    {field: 'user_agent', displayName: 'User Agent'},
		    {field: 'source',
			displayName: 'Source Host',
			cellTemplate: '
{{ grid.appScope.getColumnValue(row, col) }}
'
		    },
		    {field: 'source_port', displayName: 'SPort', width: 50},
		    {field: 'destination',
			displayName: 'Destination Host',
			cellTemplate: '
{{ grid.appScope.getColumnValue(row, col) }}
'
		    },
		    {field: 'destination_port', displayName: 'DPort', width: 50},
		    {field: 'proto', displayName: 'Proto', width: 40},
		    {field: 'node', displayName: 'Node'}
		]
	    };

	    $scope.gridOpts.rowIdentity = function(row) {
		return row.id;
	    };

	    $scope.gridOpts.onRegisterApi = function(gridApi) {
		//set gridApi on scope
		$scope.gridApi = gridApi;
	    };
	}
    ])
    .filter('unixts', function() {
	return function(input) {
	    if (!input){
		return '';
	    } else {
		return new Date(input * 1000);
	    }
	};
     });
}(angular, homer));
<|endoftext|>