<commit_before>// using simple sub-module augmentation
define(['MainCore', 'ol'], function(OSMFire_Core, ol) {
    "use strict";
    let map = null;
    let view = null;
    let mouseProjection = "EPSG:4326";
    let mousePrecision = 0;
    let selectedLayer = null;

    let self = {};
    self.getMap = function() {
        return map;
    };
    self.setMap = function(value) {
        map = value;
    };
    self.getView = function() {
        return view;
    };
    // self.setView = function(value) {
    //     view = value;
    // };
    self.addControl = function(control) {
        map.addControl(control)
    };
    self.getMouseProjection = function() {
        return mouseProjection;
    };
    self.setMouseProjection = function(proj) {
        mouseProjection = proj;
    };
    self.getMousePrecision = function() {
        return mousePrecision;
    };
    self.setMousePrecision = function () {
        let res = view.getResolution();
        let oldProj = view.getProjection();
        let newProj = ol.proj.get(mouseProjection);
        if (oldProj !== newProj) {
            let coord0 = view.getCenter();
            let coord1 = [coord0[0] + res, coord0[1] + res];
            coord0 = ol.proj.transform(coord0, oldProj, newProj);
            coord1 = ol.proj.transform(coord1, oldProj, newProj);
            res = Math.max(Math.abs(coord1[0] - coord0[0]), Math.abs(coord1[1] - coord0[1]));
        } else {
            res = view.getResolution();
        }
        mousePrecision = Number(Math.abs(Math.min(0, Math.floor(Math.log10(res)))).toFixed());
    };
    self.getFormat = function (formatString) {
        var Formats = {
            'zip': function () {
                return new ol.format.GeoJSON();
            },
            'geojson': function () {
                return new ol.format.GeoJSON();
            },
            'topojson': function () {
                return new ol.format.TopoJSON();
            },
            'kml': function () {
                return new ol.format.KML();
            },
            'osm': function () {
                return new ol.format.OSMXML();
            },
            'wmscapabilities': function () {
                return new ol.format.WMSCapabilities();
            },
            'wfs': function () {
                return new ol.format.WFS();
            },
            'gml': function () {
                // TODO: Add a callback.
                return new ol.format.GML();
            }
        };
        return Formats[formatString]();
    };
    self.getLoadingStrategy = function(strategy) {
        var Strategies = {
            'tile': function () {
                return ol.loadingstrategy.tile(new ol.tilegrid.createXYZ({}))
            },
            'bbox': function () {
                return ol.loadingstrategy.bbox
            }
        };
        return Strategies[strategy]();
    };
    self.getSource = function(source, opt) {
        var Sources = {
            'TileWMS': function () {
                return new ol.source.TileWMS(opt)
            },
            'ImageWMS': function () {
                return new ol.source.ImageWMS(opt)
            },
            'ImageVector': function () {
                return new ol.source.ImageVector(opt)
            },
            'ImageStatic': function () {
                return new ol.source.ImageStatic(opt)
            },
            'BingMaps': function () {
                return new ol.source.BingMaps(opt)
            },
            'OSM': function () {
                return new ol.source.OSM(opt)
            },
            'Vector': function () {
                return new ol.source.Vector(opt)
            }
        };
        return Sources[source]();
    };
    self.getLayer = function(layer, opt) {
        var Layers = {
            'Group': function () {
                return new ol.layer.Group(opt)
            },
            'Vector': function () {
                return new ol.layer.Vector(opt)
            },
            'Image': function () {
                return new ol.layer.Image(opt)
            },
            'Tile': function () {
                return new ol.layer.Tile(opt)
            }
        };
        return Layers[layer]();
    };
    self.addLayer = function (layer) {
        map.addLayer(layer)
    };
    self.selectLayer = function (layer) {
        selectedLayer = layer;
        return selectedLayer
    };
    self.getSelectedLayer = function () {
        return selectedLayer
    };
    self.deselectLayer = function () {
        selectedLayer = null;
        return selectedLayer
    };

    self.recenterView = function(x, y) {
        var center = ol.proj.transform([x, y], 'EPSG:4326', 'EPSG:3857');
        view.setCenter(center);
    };
    self.initialize = function() {
        ol.Map
        ol.Attribution
        ol.View
        ol.inherits
        ol.Sphere
        ol.Feature
        ol.Overlay
        ol.Collection
        ol.Observable

        ol.style.Style
        ol.style.Text
        ol.style.Stroke
        ol.style.Fill
        ol.style.Circle
        ol.style.RegularShape
        ol.style.Icon

        // ol.layer.Group
        // ol.layer.Vector
        // ol.layer.Image
        // ol.layer.Tile

        // ol.source.TileWMS
        // ol.source.ImageWMS
        // ol.source.ImageVector
        // ol.source.ImageStatic
        // ol.source.BingMaps
        // ol.source.OSM
        // ol.source.OSM.ATTRIBUTION
        // ol.source.Vector

        // ol.format.GeoJSON
        // ol.format.TopoJSON
        // ol.format.OSMXML
        // ol.format.WMSCapabilities
        // ol.format.WFS
        // ol.format.KML
        // ol.format.GML

        ol.control.call
        ol.control.Control
        ol.control.LayerSwitcher
        ol.control.MousePosition
        ol.control.ScaleLine
        ol.control.Attribution
        ol.control.Zoom
        ol.control.Interaction

        ol.interaction.Select
        ol.interaction.Modify
        ol.interaction.Translate
        ol.interaction.Draw
        ol.interaction.ChooseHole
        ol.interaction.Pointer
        ol.interaction.defaults

        // ol.loadingstrategy
        // ol.tilegrid.createXYZ
        ol.coordinate.createStringXY
        ol.extent.getCenter

        ol.events.condition.never
        ol.events.condition.doubleClick
        ol.events.condition.singleClick

        ol.geom.Point
        ol.geom.Polygon
        ol.geom.LinearRing
        ol.geom.LineString

        ol.proj.transformExtent
        ol.proj.transform
        ol.proj.get

        map = new ol.Map({
            interactions: ol.interaction.defaults({doubleClickZoom: false}),
            loadTilesWhileInteracting: true,
            loadTilesWhileAnimating: true
        });
        view = new ol.View({});
        OSMFire_Core.log(1, 'OL Module has been initialized...', "blue");
    };
    // register with MainCore
    self.register = (function() {
        OSMFire_Core.registerModule(self);
    })();
    return OSMFire_Core.OL = {
        initialize: self.initialize,
        setMap: self.setMap,
        getMap: self.getMap,
        getView: self.getView,
        getMouseProjection: self.getMouseProjection,
        setMouseProjection: self.setMouseProjection,
        getMousePrecision: self.getMousePrecision,
        setMousePrecision: self.setMousePrecision,
        getLoadingStrategy: self.getLoadingStrategy,
        getFormat: self.getFormat,
        getSource: self.getSource,
        getLayer: self.getLayer,
        addLayer: self.addLayer,
        addControl: self.addControl,
        handlerObj: self
    };
});<commit_msg>refactor<commit_after>// using simple sub-module augmentation
define(['MainCore', 'ol'], function(OSMFire_Core, ol) {
    "use strict";
    let map = null;
    let view = null;
    let mouseProjection = "EPSG:4326";
    let mousePrecision = 0;
    let selectedLayer = null;

    let self = {};
    self.getMap = function() {
        return map;
    };
    self.setMap = function(value) {
        map = value;
    };
    self.getView = function() {
        return view;
    };
    // self.setView = function(value) {
    //     view = value;
    // };
    self.addControl = function(control) {
        map.addControl(control)
    };
    self.getMouseProjection = function() {
        return mouseProjection;
    };
    self.setMouseProjection = function(proj) {
        mouseProjection = proj;
    };
    self.getMousePrecision = function() {
        return mousePrecision;
    };
    self.setMousePrecision = function () {
        let res = view.getResolution();
        let oldProj = view.getProjection();
        let newProj = ol.proj.get(mouseProjection);
        if (oldProj !== newProj) {
            let coord0 = view.getCenter();
            let coord1 = [coord0[0] + res, coord0[1] + res];
            coord0 = ol.proj.transform(coord0, oldProj, newProj);
            coord1 = ol.proj.transform(coord1, oldProj, newProj);
            res = Math.max(Math.abs(coord1[0] - coord0[0]), Math.abs(coord1[1] - coord0[1]));
        } else {
            res = view.getResolution();
        }
        mousePrecision = Number(Math.abs(Math.min(0, Math.floor(Math.log10(res)))).toFixed());
    };
    self.getFormat = function (formatString) {
        var Formats = {
            'zip': function () {
                return new ol.format.GeoJSON();
            },
            'geojson': function () {
                return new ol.format.GeoJSON();
            },
            'topojson': function () {
                return new ol.format.TopoJSON();
            },
            'kml': function () {
                return new ol.format.KML();
            },
            'osm': function () {
                return new ol.format.OSMXML();
            },
            'wmscapabilities': function () {
                return new ol.format.WMSCapabilities();
            },
            'wfs': function () {
                return new ol.format.WFS();
            },
            'gml': function () {
                // TODO: Add a callback.
                return new ol.format.GML();
            }
        };
        return Formats[formatString]();
    };
    self.getLoadingStrategy = function(strategy) {
        var Strategies = {
            'tile': function () {
                return ol.loadingstrategy.tile(new ol.tilegrid.createXYZ({}))
            },
            'bbox': function () {
                return ol.loadingstrategy.bbox
            }
        };
        return Strategies[strategy]();
    };
    self.getSource = function(source, opt) {
        var Sources = {
            'TileWMS': function () {
                return new ol.source.TileWMS(opt)
            },
            'ImageWMS': function () {
                return new ol.source.ImageWMS(opt)
            },
            'ImageVector': function () {
                return new ol.source.ImageVector(opt)
            },
            'ImageStatic': function () {
                return new ol.source.ImageStatic(opt)
            },
            'BingMaps': function () {
                return new ol.source.BingMaps(opt)
            },
            'OSM': function () {
                return new ol.source.OSM(opt)
            },
            'Vector': function () {
                return new ol.source.Vector(opt)
            }
        };
        return Sources[source]();
    };
    self.getLayer = function(layer, opt) {
        var Layers = {
            'Group': function () {
                return new ol.layer.Group(opt)
            },
            'Vector': function () {
                return new ol.layer.Vector(opt)
            },
            'Image': function () {
                return new ol.layer.Image(opt)
            },
            'Tile': function () {
                return new ol.layer.Tile(opt)
            }
        };
        return Layers[layer]();
    };
    self.addLayer = function (layer) {
        map.addLayer(layer)
    };
    self.selectLayer = function (layer) {
        selectedLayer = layer;
        return selectedLayer
    };
    self.getSelectedLayer = function () {
        return selectedLayer
    };
    self.deselectLayer = function () {
        selectedLayer = null;
        return selectedLayer
    };

    self.recenterView = function(x, y) {
        var center = ol.proj.transform([x, y], 'EPSG:4326', 'EPSG:3857');
        view.setCenter(center);
    };
    self.initialize = function() {

        ol.Map
        ol.Attribution
        ol.View
        ol.inherits
        ol.Sphere
        ol.Feature
        ol.Overlay
        ol.Collection
        ol.Observable

        ol.style.Style
        ol.style.Text
        ol.style.Stroke
        ol.style.Fill
        ol.style.Circle
        ol.style.RegularShape
        ol.style.Icon

        ol.control.call
        ol.control.Control
        ol.control.LayerSwitcher
        ol.control.MousePosition
        ol.control.ScaleLine
        ol.control.Attribution
        ol.control.Zoom
        ol.control.Interaction

        ol.interaction.Select
        ol.interaction.Modify
        ol.interaction.Translate
        ol.interaction.Draw
        ol.interaction.ChooseHole
        ol.interaction.Pointer
        ol.interaction.defaults

        // ol.loadingstrategy
        // ol.tilegrid.createXYZ
        ol.coordinate.createStringXY
        ol.extent.getCenter

        ol.events.condition.never
        ol.events.condition.doubleClick
        ol.events.condition.singleClick

        ol.geom.Point
        ol.geom.Polygon
        ol.geom.LinearRing
        ol.geom.LineString

        ol.proj.transformExtent
        ol.proj.transform
        ol.proj.get

        // Done
        // ol.layer
        // ol.layer.Group
        // ol.layer.Vector
        // ol.layer.Image
        // ol.layer.Tile
        // ol.source
        // ol.source.TileWMS
        // ol.source.ImageWMS
        // ol.source.ImageVector
        // ol.source.ImageStatic
        // ol.source.BingMaps
        // ol.source.OSM
        // ol.source.OSM.ATTRIBUTION
        // ol.source.Vector
        // ol.format
        // ol.format.GeoJSON
        // ol.format.TopoJSON
        // ol.format.OSMXML
        // ol.format.WMSCapabilities
        // ol.format.WFS
        // ol.format.KML
        // ol.format.GML

        map = new ol.Map({
            interactions: ol.interaction.defaults({doubleClickZoom: false}),
            loadTilesWhileInteracting: true,
            loadTilesWhileAnimating: true
        });
        view = new ol.View({});
        OSMFire_Core.log(1, 'OL Module has been initialized...', "blue");
    };
    // register with MainCore
    self.register = (function() {
        OSMFire_Core.registerModule(self);
    })();
    return OSMFire_Core.OL = {
        initialize: self.initialize,
        setMap: self.setMap,
        getMap: self.getMap,
        getView: self.getView,
        getMouseProjection: self.getMouseProjection,
        setMouseProjection: self.setMouseProjection,
        getMousePrecision: self.getMousePrecision,
        setMousePrecision: self.setMousePrecision,
        getLoadingStrategy: self.getLoadingStrategy,
        getFormat: self.getFormat,
        getSource: self.getSource,
        getLayer: self.getLayer,
        addLayer: self.addLayer,
        addControl: self.addControl,
        handlerObj: self
    };
});<|endoftext|>


<commit_before>'use strict';
/* global angular, L */
/* jshint unused:false */

var controllersModule = require('./_index');
var Leaflet = require('../components/leaflet');
var GeoJSON = require('../components/geojson');

var result;
var marker=[];
/**
 * @ngInject
 */

 controllersModule.controller('MapCtrl', ['$rootScope','$http','$scope','HelloService','FollowersMapTemplateService', function($rootScope,$http,$scope,HelloService,FollowersMapTemplateService) {

        var hello=HelloService;
        var followerslayer = new L.LayerGroup();
        var followinglayer = new L.LayerGroup();
        var overlays = {
            "Followers" : followerslayer ,
            "Following" : followinglayer
        };
        $scope.followers={};
        $scope.following={};
        $scope.followers_status="Loading ...";
        $scope.following_status="Loading ..." ;

        var grayscale=L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data © OpenStreetMap contributors, ' +
                'CC-BY-SA, ' +
                'Imagery © Mapbox',
            id: 'examples.map-20v6611k'
        });
        var basemapObj = {
            "First Basemap": grayscale
        };

        var map = L.map('map',{layers:[grayscale,followerslayer,followinglayer]}).setView([20,0], 2);
        $rootScope.$watch(function() {
            return $rootScope.root.twitterSession;
            }, function(session) {
                if (session) {
                    plotFollowersonMap();
                    plotFollowingOnMap();
                }
            });

         stats();

         L.control.layers(basemapObj,overlays).addTo(map);

        function plotFollowersonMap()
        {
            //defining an object to store followers info
            var followers = [];
            var followers_location = [];

            //Marker array
            var followersMarker = {
                "type": "FeatureCollection",
                "features": []
            };

                //console.log( followers.propic[i]);
            //Calling the method to get Twitter followers
            hello('twitter').api('/me/followers', 'GET', {limit : 1000}).then(function(twitterFollowers) {
            $rootScope.$apply(function()
            {
                twitterFollowers.data.forEach(function(ele){
                    if(ele.location)
                    {
                        followers_location.push(ele.location);
                        followers.push({
                            "location" : ele.location,
                            "name" : ele.name,
                            "id_str" : ele.id_str,
                            "propic" : ele.profile_image_url_https,
                            "screenname" : ele.screen_name,
                            "followers" : ele.followers_count,
                            "following" : ele.friends_count,
                            "tweetcount" : ele.statuses_count,
                            "profile_banner" : ele.profile_background_image_url_https
                        });

                    }
                });
                $scope.followers=followers;
                Geocode();
            });
            }, function() {
            console.log("Unable to get your followers");
            $scope.followers_status="Load Failed.Twitter did not respond."
            });

            //getting the LatLong
            function Geocode()
            {

                var locarray = {

                    "places" : followers_location
                }

            $http.jsonp('http://loklak.org/api/geocode.json?callback=JSON_CALLBACK&minified=true', {params : { data : locarray } })
            .success(function(data, status, headers, config) {
                //console.log( followers.propic[i]);
                $scope.followers_status=followers_location.length;
                for(var i=0;i<followers_location.length;i++)
                {

                    var locationkey=followers_location[i];
                    if(data.locations[locationkey].mark)
                    {
                    var textpopup=FollowersMapTemplateService.genStaticTwitterFollower(followers , i);

                    //followers.preview[i]=textpopup;
                    var pointObject = {
                        "geometry": {
                            "type": "Point",
                            "coordinates": [
                                data.locations[locationkey].mark[0],
                                data.locations[locationkey].mark[1]
                            ]
                        },
                        "type": "Feature",
                        "properties": {
                            "popupContent" : "

Follower

" + textpopup + "
" ,
                            "propic" : followers[i].propic

                        },
                        "id": followers[i].id_str

                    };
                    followersMarker.features.push(pointObject);

                    }
                }
                   add_marker(followersMarker , 1);

                }).error(function(data, status, headers, config) {

                    $scope.followers_status="Load Failed.Twitter did not respond."

                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
            });
        }
    }

        function plotFollowingOnMap()
        {

            //defining an object to store following info
            var following = [];
            var following_location=[];

            //Marker array
            var followingMarker = {
                "type": "FeatureCollection",
                "features": []
            };

            //Calling the method to get Twitter followings
            hello('twitter').api('/me/following', 'GET').then(function(twitterfollowing) {
            $rootScope.$apply(function()
            {
                twitterfollowing.data.forEach(function(ele){
                    if(ele.location)
                    {
                        following_location.push(ele.location);
                        following.push({
                            "location" : ele.location,
                            "name" : ele.name,
                            "id_str" : ele.id_str,
                            "propic" : ele.profile_image_url_https,
                            "screenname" : ele.screen_name,
                            "followers" : ele.followers_count,
                            "following" : ele.friends_count,
                            "tweetcount" : ele.statuses_count,
                            "profile_banner" : ele.profile_background_image_url_https,
                            "latesttweet" : ele.status.text
                        });

                    }
                });
                $scope.following=following;
                Geocode_Plot();
            });
            }, function() {
            console.log("Unable to get your following");
            $scope.following_status="Load Failed.Twitter did not respond."
            });

            //getting the LatLong
            function Geocode_Plot()
            {

                var locarray = {

                    "places" : following_location
                }

            $http.jsonp('http://loklak.org/api/geocode.json?callback=JSON_CALLBACK&minified=true', {params : { data : locarray } })
            .success(function(data, status, headers, config) {
                $scope.following_status=following_location.length;
                for(var i=0;i<following_location.length;i++)
                {
                    var locationkey=following_location[i];
                    if(data.locations[locationkey].mark)
                    {
                    var textpopup=FollowersMapTemplateService.genStaticTwitterFollowing(following , i);
                    //var locationkey=following.location[i];

                    var pointObject = {
                        "geometry": {
                            "type": "Point",
                            "coordinates": [
                                data.locations[locationkey].mark[0],
                                data.locations[locationkey].mark[1]
                            ]
                        },
                        "type": "Feature",
                        "properties": {
                            "popupContent": "

Following

" + textpopup + "
",
                            "propic" : following[i].propic
                        },
                        "id": following[i].id_str
                    };
                    followingMarker.features.push(pointObject);
                }

                }
                   add_marker(followingMarker , 0);

                }).error(function(data, status, headers, config) {

                    console.log("There is error.Loklak Server did not respond with geodata.We will try again.");
                    $scope.following_status="Load Failed.Twitter did not respond."
                    Geocode_Plot();

                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
            });
        }
        }

      function add_marker(result , followerbool) {

                    var i;
                    for (i = 0; i < result.features.length; i++) {
                        //console.log(result.features[i].propic-url);
                        var tweetIcon = L.icon({
                        iconUrl: result.features[i].properties.propic ,
                        iconSize:     [30, 30]
                    });
                        var lat = result.features[i].geometry.coordinates[1];
                        var lng = result.features[i].geometry.coordinates[0];
                        marker[i] = new L.Marker([lat, lng], {
                            id: i,
                            icon: tweetIcon
                        });

                        if(followerbool)
                        {
                          marker[i].addTo(followerslayer);
                        }
                        else
                        {
                            marker[i].addTo(followinglayer);
                        }

                        var popup = L.popup({
                            autoPan: true
                        }).setContent(result.features[i].properties.popupContent);
                        marker[i].bindPopup(popup);

                    }

                }
      function stats()
      {
        console.log("stats being called");
        $http.jsonp("http://localhost:9000/api/account.json?callback=JSON_CALLBACK", {params : { screen_name : "mariobehling", followers : 2000  } })
            .success(function(data, status, headers, config) {
                var topology = data.topology;
                var country_stat_result = {};
                var country_Array=[];
                var followers_follower=[];
                var city_stat_result = {};
                var city_Array=[];
                var top5=[];

                //Getting citywise Stats
                data.topology.followers.forEach(function(ele){
                    if(ele.location)
                    {
                        city_Array.push(ele.location);
                        followers_follower.push ({
                            "followers" : ele.followers_count ,
                            "id_str" : ele.id_str

                        });

                    }

                });

                //Counting per city
                for(var i = 0; i < city_Array.length; ++i)
                {
                    if(!city_stat_result[city_Array[i]])
                    city_stat_result[city_Array[i]] = 0;
                    ++city_stat_result[city_Array[i]];
                }
                var citynames = Object.keys( city_stat_result );

                //Populating Data Set
                var cityData=[];
                citynames.forEach(function(ele){
                    cityData.push(
                    {
                         value: city_stat_result[ele],
                         color:"#F7464A",
                         highlight: "#FF5A5E",
                         label: ele
                    })
                });
                //console.log("city datauniques are");
                //console.log(citynames);

                //Getting country wise stats
                 data.topology.followers.forEach(function(ele){
                    if(ele.location_country)
                    {
                        country_Array.push(ele.location_country);
                    }

                });

                 //Counting country wise stats
                for(var i = 0; i < country_Array.length; ++i) {

                    if(!country_stat_result[country_Array[i]])
                    country_stat_result[country_Array[i]] = 0;
                    ++country_stat_result[country_Array[i]];
                }

                var countrynames = Object.keys( country_stat_result );

                //Populating Data Set
                var countryData=[];
                countrynames.forEach(function(ele){
                    countryData.push(
                    {
                         value: country_stat_result[ele],
                         color:"#F7464A",
                         highlight: "#FF5A5E",
                         label: ele
                    })
                });

               // console.log( city_stat_result);
                $scope.city_stat_result=city_stat_result;
                $scope.country_stat_result=country_stat_result;
                getTopfive(followers_follower);

                }).error(function(data, status, headers, config) {

                    $scope.followers_status="Load Failed.Twitter did not respond.";
                    /*followers_location.push(ele.location);
                        followers.push({
                            "location" : ele.location,
                            "name" : ele.name,
                            "id_str" : ele.id_str,
                            "propic" : ele.profile_image_url_https,
                            "screenname" : ele.screen_name,
                            "followers" : ele.followers_count,
                            "following" : ele.friends_count,
                            "tweetcount" : ele.statuses_count,
                            "profile_banner" : ele.profile_background_image_url_https
                        });
*/
console.log("error"+status);

                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
            });
        function getTopfive(followers_follower){
            function compare(a,b) {
                if (a.followers > b.followers)
                    return -1;
                if (a.followers < b.followers)
                    return 1;
                return 0;
            }
            followers_follower.sort(compare);
            console.log(followers_follower);
        }

      }

}]);

<commit_msg>Added Top5 followers info<commit_after>'use strict';
/* global angular, L */
/* jshint unused:false */

var controllersModule = require('./_index');
var Leaflet = require('../components/leaflet');
var GeoJSON = require('../components/geojson');

var result;
var marker=[];
/**
 * @ngInject
 */

 controllersModule.controller('MapCtrl', ['$rootScope','$http','$scope','HelloService','FollowersMapTemplateService', function($rootScope,$http,$scope,HelloService,FollowersMapTemplateService) {

        var hello=HelloService;
        var followerslayer = new L.LayerGroup();
        var followinglayer = new L.LayerGroup();
        var overlays = {
            "Followers" : followerslayer ,
            "Following" : followinglayer
        };
        $scope.followers={};
        $scope.following={};
        $scope.followers_status="Loading ...";
        $scope.following_status="Loading ..." ;

        var grayscale=L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data © OpenStreetMap contributors, ' +
                'CC-BY-SA, ' +
                'Imagery © Mapbox',
            id: 'examples.map-20v6611k'
        });
        var basemapObj = {
            "First Basemap": grayscale
        };

        var map = L.map('map',{layers:[grayscale,followerslayer,followinglayer]}).setView([20,0], 2);
        $rootScope.$watch(function() {
            return $rootScope.root.twitterSession;
            }, function(session) {
                if (session) {
                    plotFollowersonMap();
                    plotFollowingOnMap();
                }
            });

         stats();

         L.control.layers(basemapObj,overlays).addTo(map);

        function plotFollowersonMap()
        {
            //defining an object to store followers info
            var followers = [];
            var followers_location = [];

            //Marker array
            var followersMarker = {
                "type": "FeatureCollection",
                "features": []
            };

                //console.log( followers.propic[i]);
            //Calling the method to get Twitter followers
            hello('twitter').api('/me/followers', 'GET', {limit : 1000}).then(function(twitterFollowers) {
            $rootScope.$apply(function()
            {
                twitterFollowers.data.forEach(function(ele){
                    if(ele.location)
                    {
                        followers_location.push(ele.location);
                        followers.push({
                            "location" : ele.location,
                            "name" : ele.name,
                            "id_str" : ele.id_str,
                            "propic" : ele.profile_image_url_https,
                            "screenname" : ele.screen_name,
                            "followers" : ele.followers_count,
                            "following" : ele.friends_count,
                            "tweetcount" : ele.statuses_count,
                            "profile_banner" : ele.profile_background_image_url_https
                        });

                    }
                });
                $scope.followers=followers;
                Geocode();
            });
            }, function() {
            console.log("Unable to get your followers");
            $scope.followers_status="Load Failed.Twitter did not respond."
            });

            //getting the LatLong
            function Geocode()
            {

                var locarray = {

                    "places" : followers_location
                }

            $http.jsonp('http://loklak.org/api/geocode.json?callback=JSON_CALLBACK&minified=true', {params : { data : locarray } })
            .success(function(data, status, headers, config) {
                //console.log( followers.propic[i]);
                $scope.followers_status=followers_location.length;
                for(var i=0;i<followers_location.length;i++)
                {

                    var locationkey=followers_location[i];
                    if(data.locations[locationkey].mark)
                    {
                    var textpopup=FollowersMapTemplateService.genStaticTwitterFollower(followers , i);

                    //followers.preview[i]=textpopup;
                    var pointObject = {
                        "geometry": {
                            "type": "Point",
                            "coordinates": [
                                data.locations[locationkey].mark[0],
                                data.locations[locationkey].mark[1]
                            ]
                        },
                        "type": "Feature",
                        "properties": {
                            "popupContent" : "

Follower

" + textpopup + "
" ,
                            "propic" : followers[i].propic

                        },
                        "id": followers[i].id_str

                    };
                    followersMarker.features.push(pointObject);

                    }
                }
                   add_marker(followersMarker , 1);

                }).error(function(data, status, headers, config) {

                    $scope.followers_status="Load Failed.Twitter did not respond."

                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
            });
        }
    }

        function plotFollowingOnMap()
        {

            //defining an object to store following info
            var following = [];
            var following_location=[];

            //Marker array
            var followingMarker = {
                "type": "FeatureCollection",
                "features": []
            };

            //Calling the method to get Twitter followings
            hello('twitter').api('/me/following', 'GET').then(function(twitterfollowing) {
            $rootScope.$apply(function()
            {
                twitterfollowing.data.forEach(function(ele){
                    if(ele.location)
                    {
                        following_location.push(ele.location);
                        following.push({
                            "location" : ele.location,
                            "name" : ele.name,
                            "id_str" : ele.id_str,
                            "propic" : ele.profile_image_url_https,
                            "screenname" : ele.screen_name,
                            "followers" : ele.followers_count,
                            "following" : ele.friends_count,
                            "tweetcount" : ele.statuses_count,
                            "profile_banner" : ele.profile_background_image_url_https,
                            "latesttweet" : ele.status.text
                        });

                    }
                });
                $scope.following=following;
                Geocode_Plot();
            });
            }, function() {
            console.log("Unable to get your following");
            $scope.following_status="Load Failed.Twitter did not respond."
            });

            //getting the LatLong
            function Geocode_Plot()
            {

                var locarray = {

                    "places" : following_location
                }

            $http.jsonp('http://loklak.org/api/geocode.json?callback=JSON_CALLBACK&minified=true', {params : { data : locarray } })
            .success(function(data, status, headers, config) {
                $scope.following_status=following_location.length;
                for(var i=0;i<following_location.length;i++)
                {
                    var locationkey=following_location[i];
                    if(data.locations[locationkey].mark)
                    {
                    var textpopup=FollowersMapTemplateService.genStaticTwitterFollowing(following , i);
                    //var locationkey=following.location[i];

                    var pointObject = {
                        "geometry": {
                            "type": "Point",
                            "coordinates": [
                                data.locations[locationkey].mark[0],
                                data.locations[locationkey].mark[1]
                            ]
                        },
                        "type": "Feature",
                        "properties": {
                            "popupContent": "

Following

" + textpopup + "
",
                            "propic" : following[i].propic
                        },
                        "id": following[i].id_str
                    };
                    followingMarker.features.push(pointObject);
                }

                }
                   add_marker(followingMarker , 0);

                }).error(function(data, status, headers, config) {

                    console.log("There is error.Loklak Server did not respond with geodata.We will try again.");
                    $scope.following_status="Load Failed.Twitter did not respond."
                    Geocode_Plot();

                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
            });
        }
        }

      function add_marker(result , followerbool) {

                    var i;
                    for (i = 0; i < result.features.length; i++) {
                        //console.log(result.features[i].propic-url);
                        var tweetIcon = L.icon({
                        iconUrl: result.features[i].properties.propic ,
                        iconSize:     [30, 30]
                    });
                        var lat = result.features[i].geometry.coordinates[1];
                        var lng = result.features[i].geometry.coordinates[0];
                        marker[i] = new L.Marker([lat, lng], {
                            id: i,
                            icon: tweetIcon
                        });

                        if(followerbool)
                        {
                          marker[i].addTo(followerslayer);
                        }
                        else
                        {
                            marker[i].addTo(followinglayer);
                        }

                        var popup = L.popup({
                            autoPan: true
                        }).setContent(result.features[i].properties.popupContent);
                        marker[i].bindPopup(popup);

                    }

                }
      function stats()
      {
        console.log("stats being called");
        $http.jsonp("http://localhost:9000/api/account.json?callback=JSON_CALLBACK", {params : { screen_name : "mariobehling", followers : 2000  } })
            .success(function(data, status, headers, config) {
                var topology = data.topology;
                var country_stat_result = {};
                var country_Array=[];
                var followers_follower=[];
                var city_stat_result = {};
                var city_Array=[];
                var top5=[];

                //Getting citywise Stats
                data.topology.followers.forEach(function(ele){
                    if(ele.location)
                    {
                        city_Array.push(ele.location);
                        followers_follower.push ({
                            "followers" : ele.followers_count ,
                            "id_str" : ele.id_str,
                            "profileimg" : ele.profile_image_url_https,
                            "screenname" : ele.screen_name,
                            "statuses_count" : ele.statuses_count,
                            "following" : ele.friends_count,
                            "profile_banner" : ele.profile_background_image_url_https

                        });

                    }

                });

                //Counting per city
                for(var i = 0; i < city_Array.length; ++i)
                {
                    if(!city_stat_result[city_Array[i]])
                    city_stat_result[city_Array[i]] = 0;
                    ++city_stat_result[city_Array[i]];
                }
                var citynames = Object.keys( city_stat_result );

                //Populating Data Set
                var cityData=[];
                citynames.forEach(function(ele){
                    cityData.push(
                    {
                         value: city_stat_result[ele],
                         color:"#F7464A",
                         highlight: "#FF5A5E",
                         label: ele
                    })
                });
                //console.log("city datauniques are");
                //console.log(citynames);

                //Getting country wise stats
                 data.topology.followers.forEach(function(ele){
                    if(ele.location_country)
                    {
                        country_Array.push(ele.location_country);
                    }

                });

                 //Counting country wise stats
                for(var i = 0; i < country_Array.length; ++i) {

                    if(!country_stat_result[country_Array[i]])
                    country_stat_result[country_Array[i]] = 0;
                    ++country_stat_result[country_Array[i]];
                }

                var countrynames = Object.keys( country_stat_result );

                //Populating Data Set
                var countryData=[];
                countrynames.forEach(function(ele){
                    countryData.push(
                    {
                         value: country_stat_result[ele],
                         color:"#F7464A",
                         highlight: "#FF5A5E",
                         label: ele
                    })
                });

               // console.log( city_stat_result);
                $scope.city_stat_result=city_stat_result;
                $scope.country_stat_result=country_stat_result;
                getTopfive(followers_follower);

                }).error(function(data, status, headers, config) {

                    $scope.followers_status="Load Failed.Twitter did not respond.";
                    /*followers_location.push(ele.location);
                        followers.push({
                            "location" : ele.location,
                            "name" : ele.name,
                            "id_str" : ele.id_str,
                            "propic" : ele.profile_image_url_https,
                            "screenname" : ele.screen_name,
                            "followers" : ele.followers_count,
                            "following" : ele.friends_count,
                            "tweetcount" : ele.statuses_count,
                            "profile_banner" : ele.profile_background_image_url_https
                        });
*/
console.log("error"+status);

                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
            });
        function getTopfive(followers_follower){
            function compare(a,b) {
                if (a.followers > b.followers)
                    return -1;
                if (a.followers < b.followers)
                    return 1;
                return 0;
            }
            followers_follower.sort(compare);
            console.log(followers_follower);
        }

      }

}]);

<|endoftext|>


<commit_before>//
//   Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
//   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.
//

'use strict';

require('./commandParser');

Mas.Network = Ember.Object.extend({
    sessionId: 0,

    _pollSeq: 0,
    _sendSeq: 0,
    _sendQueue: [],
    _callbacks: {},
    _firstPoll: true,
    _unsolicitedParser: null,
    _state: 'normal',

    init: function() {
        this._super();
        this._pollMsgs();
        this._unsolicitedParser = Mas.CommandParser.create();
    },

    send: function(command, callback) {
        this._sendQueue.push(command);

        if (callback) {
            this._callbacks[command.id + '_RESP'] = callback;
        }

        Ember.Logger.info('Outgoing command buffered: ' + command.id + ' (Queue len: ' +
            this._sendQueue.length + ')');

        if (this._sendQueue.length === 1) {
            this._sendMsg(this._sendQueue[0]);
        }
    },

    _sendMsg: function(message) {
        var data = {
            sessionId: this.sessionId,
            seq: this._sendSeq,
            command: message
        };

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '/api/v1/send',
            data: JSON.stringify(data),
            success: this._sendMsgSuccess,
            error: this._sendMsgFailure,
            context: this,
            timeout: 10000
        });

        Ember.Logger.info('--> MSG: ' + message.id);
    },

    _sendMsgSuccess: function() {
        this._sendQueue.shift();
        this._sendSeq++;

        if (this._state === 'error') {
            this._state = 'normal';
            // this._.setStatusTextCb.call(this._cbCtx, '');
        }

        this._sendMsgFinished();
    },

    _sendMsgFailure: function(jqXHR) {
        var code = jqXHR.status;
        this._state = 'error';

        Ember.Logger.error('sendMsg: XHR request failed, code: ' + code);

        if (code === 401 || code === 406) {
            this._logout();
        } else {
            // TBD: Add notification: 'Connection to MAS server lost, trying to reconnect...'

            // Stay optimistic and keep trying
            setTimeout(function() {
                this._sendMsgFinished();
            }.bind(this), 2000);
        }
    },

    _sendMsgFinished: function() {
        if (this._sendQueue.length > 0) {
            var message = this._sendQueue[0];
            this._sendMsg(message);
        }
    },

    _pollMsgs: function() {
        var data = { seq: this._pollSeq };

        if (this._firstPoll) {
            data.clientName = 'webclient';
            data.clientOS = navigator.platform;
        } else {
            data.sessionId = this.sessionId;
        }

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: '/api/v1/listen',
            data: JSON.stringify(data),
            success: this._pollMsgsSuccess,
            error: this._pollMsgsFailure,
            context: this,
            timeout: 35000
        });

        Ember.Logger.info('--> Polling request sent (seq ' + this._pollSeq + ')');
    },

    _pollMsgsSuccess: function(data) {
        this._pollSeq++;

        if (this._firstPoll) {
            this._firstPoll = false;
        }

        this._processCommands(data);
        this._pollMsgs();
    },

    _processCommands: function(commands) {
        for (var i = 0; i < commands.length; i++) {
            var command = commands[i];
            Ember.Logger.info('<-- MSG: ' + JSON.stringify(command));

            if (this._callbacks[command.id]) {
                // Command is a response to command we sent earlier
                this._callbacks[command.id](command);
            } else if (command.id === 'SESSIONID') {
                // Special unsolicited command that can be handle directly here
                this.sessionId = command.sessionId;
            } else {
                // Other Unsolicited command
                this._unsolicitedParser.process(command);
            }
        }
    },

    _pollMsgsFailure: function(jqXHR, textStatus, error ) {
        var code = jqXHR.status;

        if (code === 401 || code === 406) {
            this._logout();
        }

        var err = textStatus + ', ' + error;
        console.log('Request Failed: ' + err );

        // Stay positive, keep trying
        setTimeout(function() {
            this._pollMsgs();
        }.bind(this), 2000);
    },

    _logout: function() {
        $.removeCookie('ProjectEvergreen', { path: '/' });
        window.location = '/';
    }
});
<commit_msg>Remove last console.log from the app<commit_after>//
//   Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
//   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.
//

'use strict';

require('./commandParser');

Mas.Network = Ember.Object.extend({
    sessionId: 0,

    _pollSeq: 0,
    _sendSeq: 0,
    _sendQueue: [],
    _callbacks: {},
    _firstPoll: true,
    _unsolicitedParser: null,
    _state: 'normal',

    init: function() {
        this._super();
        this._pollMsgs();
        this._unsolicitedParser = Mas.CommandParser.create();
    },

    send: function(command, callback) {
        this._sendQueue.push(command);

        if (callback) {
            this._callbacks[command.id + '_RESP'] = callback;
        }

        Ember.Logger.info('Outgoing command buffered: ' + command.id + ' (Queue len: ' +
            this._sendQueue.length + ')');

        if (this._sendQueue.length === 1) {
            this._sendMsg(this._sendQueue[0]);
        }
    },

    _sendMsg: function(message) {
        var data = {
            sessionId: this.sessionId,
            seq: this._sendSeq,
            command: message
        };

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '/api/v1/send',
            data: JSON.stringify(data),
            success: this._sendMsgSuccess,
            error: this._sendMsgFailure,
            context: this,
            timeout: 10000
        });

        Ember.Logger.info('--> MSG: ' + message.id);
    },

    _sendMsgSuccess: function() {
        this._sendQueue.shift();
        this._sendSeq++;

        if (this._state === 'error') {
            this._state = 'normal';
            // this._.setStatusTextCb.call(this._cbCtx, '');
        }

        this._sendMsgFinished();
    },

    _sendMsgFailure: function(jqXHR) {
        var code = jqXHR.status;
        this._state = 'error';

        Ember.Logger.error('sendMsg: XHR request failed, code: ' + code);

        if (code === 401 || code === 406) {
            this._logout();
        } else {
            // TBD: Add notification: 'Connection to MAS server lost, trying to reconnect...'

            // Stay optimistic and keep trying
            setTimeout(function() {
                this._sendMsgFinished();
            }.bind(this), 2000);
        }
    },

    _sendMsgFinished: function() {
        if (this._sendQueue.length > 0) {
            var message = this._sendQueue[0];
            this._sendMsg(message);
        }
    },

    _pollMsgs: function() {
        var data = { seq: this._pollSeq };

        if (this._firstPoll) {
            data.clientName = 'webclient';
            data.clientOS = navigator.platform;
        } else {
            data.sessionId = this.sessionId;
        }

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: '/api/v1/listen',
            data: JSON.stringify(data),
            success: this._pollMsgsSuccess,
            error: this._pollMsgsFailure,
            context: this,
            timeout: 35000
        });

        Ember.Logger.info('--> Polling request sent (seq ' + this._pollSeq + ')');
    },

    _pollMsgsSuccess: function(data) {
        this._pollSeq++;

        if (this._firstPoll) {
            this._firstPoll = false;
        }

        this._processCommands(data);
        this._pollMsgs();
    },

    _processCommands: function(commands) {
        for (var i = 0; i < commands.length; i++) {
            var command = commands[i];
            Ember.Logger.info('<-- MSG: ' + JSON.stringify(command));

            if (this._callbacks[command.id]) {
                // Command is a response to command we sent earlier
                this._callbacks[command.id](command);
            } else if (command.id === 'SESSIONID') {
                // Special unsolicited command that can be handle directly here
                this.sessionId = command.sessionId;
            } else {
                // Other Unsolicited command
                this._unsolicitedParser.process(command);
            }
        }
    },

    _pollMsgsFailure: function(jqXHR, textStatus, error ) {
        var code = jqXHR.status;

        if (code === 401 || code === 406) {
            this._logout();
        }

        var err = textStatus + ', ' + error;
        Ember.Logger.warn('Request Failed: ' + err );

        // Stay positive, keep trying
        setTimeout(function() {
            this._pollMsgs();
        }.bind(this), 2000);
    },

    _logout: function() {
        $.removeCookie('ProjectEvergreen', { path: '/' });
        window.location = '/';
    }
});
<|endoftext|>


<commit_before>(function() {
    var _ = {};
    _.type = function(obj) {
        var types = {
            "[object String]": "STRING",
            "[object Number]": "NUMBER",
            "[object Date]": "DATE",
            "[object Function]": "FUNCTION",
            "[object Array]": "ARRAY",
            "[object Object]": "OBJECT",
            "[object Null]": "NULL",
            "[object Boolean]": "BOOLEAN",
            "[object RegExp]": "REGEXP",
            "[object Undefined]": "UNDEFINED"
        };
        return types[Object.prototype.toString.call(obj)];
    }

    _.isString = function(obj) {
        return _.type(obj) === "STRING";
    }

    _.isStringF = function(obj) {
        return _.type(obj) === "STRING" && obj.trim() != '';
    }

    _.isNumber = function(obj) {
        return _.type(obj) === "NUMBER";
    }

    _.isDate = function(obj) {
        return _.type(obj) === "DATE";
    }

    _.isFunction = function(obj) {
        return _.type(obj) === "FUNCTION";
    }

    _.isArray = function(obj) {
        return _.type(obj) === "ARRAY";
    }

    _.isObject = function(obj) {
        return _.type(obj) === "OBJECT";
    }

    _.isNull = function(obj) {
        return _.type(obj) === "NULL";
    }

    _.isBoolean = function(obj) {
        return _.type(obj) === "BOOLEAN";
    }

    _.isRegExp = function(obj) {
        return _.type(obj) === "REGEXP";
    }

    _.isUndefined = function(obj) {
        return _.type(obj) === "UNDEFINED";
    }

    _.isChildOf = function(child, parent) {
        return child instanceof parent;
    }

    _.Getter = function(k) {
        return this['__'+k];
    }

    _.Setter = function(k, v) {
        if (_.isUndefined(k)) return this;
        if (!_.isUndefined(v) && _.isString(k)) {
            this['__'+k] = v;
            return this;
        }
        var ks = k;
        if (_.isObject(k)) {
            for (var i in ks) this['__'+i] = ks[i];
            return this;
        }
        return this;
    }

    _.Data = function(k, v) {
        if (arguments.length === 1 && _.isString(k)) return _.Getter.call(this, k);
        return _.Setter.call(this, k, v);
    }

    _.GUID = function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        }).toUpperCase();
    }

    _.namespace = function(namespaceStr) {
        var cur = window;
        var ns = namespaceStr.split('.');
        for (var i = 0, len = ns.length; i < len; i++) {
            if (!cur[ns[i]]) cur[ns[i]] = {};
            cur = cur[ns[i]];
        }
    };

    _.tmpl = function(str, data) {
        if (!_.isObject(data) || !_.isString(str)) return '';
        str = str.replace(/#{([^}]*)}/g, function(val, replacement) {
            return eval('data.' + replacement);
        });
        return str;
    }

    var root = typeof exports !== "undefined" && exports !== null ? exports : window;
    root._ = _;

}());
<commit_msg>remove abovescore.js<commit_after><|endoftext|>


<commit_before>/**
 * NOVIUS OS - Web OS for digital communication
 *
 * @copyright  2011 Novius
 * @license    GNU Affero General Public License v3 or (at your option) any later version
 *             http://www.gnu.org/licenses/agpl-3.0.html
 * @link http://www.novius-os.org
 */

define(
    [
        'jquery-nos'
    ],
    function ($) {
        "use strict";
        return function (data) {

            data = $.extend({
                form_id: '',
                tpvar_id: ''
            }, data);

            var int_nb_ligne;
            var int_nb_colonne;
            var tab_grid;
            var int_id_new_cell = 1;
            var tab_css;
            var compteur = 0;

            // initial : at drag/resize start
            // final : at drag/resize stop

            var x_init_px; // initial X coordonate in px
            var y_init_px; // initial y coordonate in px
            var x_init_grid; // initial X coordonate in grid frame
            var y_init_grid; // initial Y coordonate in grid frame
            var x_final_grid; // final X coordonate in grid frame
            var y_final_grid; // final X coordonate in grid frame
            var h_init_px; // initial height in px
            var w_init_px; // initial width in px
            var h_final_px; // final height in px
            var w_final_px; // final width in px
            var h_init_grid;  // initial height in grid frame
            var w_init_grid;  // initial width in grid frame
            var h_final_grid; // final height in grid frame
            var w_final_grid; // final width in grid frame

            int_nb_ligne = 12;
            int_nb_colonne = 12;
            tab_grid = new Array(int_nb_ligne);
            int_id_new_cell = 1;
            tab_css = new Array(1);

            function affiche_tab() {
                var chaine = "";

                for (var i = 0; i < int_nb_ligne; i++) {
                    for (var j = 0; j < int_nb_colonne; j++) {
                        chaine += tab_grid [i][j] + " ";
                    }
                    chaine = chaine.substr(0, chaine.length - 1);
                    chaine += "|";
                }
                chaine = chaine.substr(0, chaine.length - 1)
                $('[name="wysiwyg_layout"]').attr("value", chaine);
            }

            //--------------------------------------
            // Init JS table
            //--------------------------------------

            for (var i = 0; i < int_nb_ligne; i++) {
                tab_grid[i] = new Array(int_nb_colonne);
            }

            for (var i = 0; i < int_nb_ligne; i++) {
                for (var j = 0; j < int_nb_colonne; j++) {
                    tab_grid [i][j] = 0;
                }
            }

            //--------------------------------------
            // Init Html Grid
            //--------------------------------------

            //$("#div_grid").html("");

            for (var i = 0; i < int_nb_ligne; i++) {
                $("#div_grid").prepend("

");
                for (var j = 0; j < int_nb_colonne; j++) {
                    $("#div_l" + i).append("

");
                }
            }

            var chaine_tab = $('[name="wysiwyg_layout"]').val();
            load_grid(chaine_tab);

            $(".grid_pattern").click(function () {
                load_grid($(this).find('input[type="hidden"]').val());
            });

            //--------------------------------------
            // Keybord control
            //--------------------------------------

            //Delete Key
            $(document).keypress(function (e) {
                if (e.keyCode == 46) {
                    $("button[id='btn_suppr']").trigger("click");
                }
            });

            //--------------------------------------
            // Grid control Buttons
            //--------------------------------------

            // Clear the grid
            $("button[id='btn_vider']").click(function () {

                for (var t = 0; t < int_nb_ligne; t++) {
                    for (var s = 0; s < int_nb_colonne; s++) {
                        tab_grid[t][s] = 0;
                    }
                }
                $(".cell_new").remove();
            });

            // Delete an element
            $("button[id='btn_suppr']").click(function () {

                var cell = $(".selected");

                x_init_px = $(cell).css("top");
                y_init_px = $(cell).css("left");

                x_init_grid = (parseInt(x_init_px) - 4) / 48;
                y_init_grid = (parseInt(y_init_px) - 4) / 48;

                h_init_grid = ((parseInt($(cell).css("height")) - 40) / 48 ) + 1;
                w_init_grid = ((parseInt($(cell).css("width")) - 40) / 48) + 1;

                for (var t = x_init_grid; t < h_init_grid + x_init_grid; t++) {
                    for (var s = y_init_grid; s < w_init_grid + y_init_grid; s++) {
                        tab_grid[t][s] = 0;
                    }
                }
                $(".selected").remove();
            });

            $(".template-e-block-grid").on("dragstart", ".cell_new", function (e, ui) {
                x_init_px = $(this).css("top");
                y_init_px = $(this).css("left");
                $(this).trigger("click");
            });

            $(".template-e-block-grid").on("dragstop", ".cell_new", function (event, ui) {

                var collision = false;

                x_final_grid = (parseInt($(this).css("top")) - 4) / 48;
                y_final_grid = (parseInt($(this).css("left")) - 4) / 48;

                x_init_grid = (parseInt(x_init_px) - 4) / 48;
                y_init_grid = (parseInt(y_init_px) - 4) / 48;

                h_final_grid = ((parseInt($(this).css("height")) - 40) / 48 ) + 1;
                w_final_grid = ((parseInt($(this).css("width")) - 40) / 48) + 1;

                collision:
                    for (var t = x_final_grid; t < h_final_grid + x_final_grid; t++) {
                        for (var s = y_final_grid; s < w_final_grid + y_final_grid; s++) {
                            if (tab_grid[t][s] != 0 && tab_grid[t][s] != $(this).attr("data-new")) {
                                collision = true
                                break collision;
                            }
                        }
                    }

                if (collision) {
                    $(this).draggable('disable');
                    var $obj = $(this);
                    $(this).animate({
                        top: x_init_px,
                        left: y_init_px
                    }, 200, function () {
                        $(this).draggable('enable');
                    });
                }
                else {
                    if (j != y_init_grid || i != x_init_grid) {
                        for (var t = x_init_grid; t < h_final_grid + x_init_grid; t++) {
                            for (var s = y_init_grid; s < w_final_grid + y_init_grid; s++) {
                                tab_grid[t][s] = 0;
                            }
                        }
                    }

                    for (var t = x_final_grid; t < h_final_grid + x_final_grid; t++) {
                        for (var s = y_final_grid; s < w_final_grid + y_final_grid; s++) {
                            tab_grid[t][s] = $(this).attr("data-new");
                        }
                    }
                }
            });

            $(".template-e-block-grid").on("resizestart", ".cell_new", function (e, ui) {
                h_init_px = $(this).css("height");
                w_init_px = $(this).css("width");
                $(this).trigger("click");
            });

            $(".template-e-block-grid").on("resizestop", ".cell_new", function (e, ui) {
                var collision = false;

                x_final_grid = (parseInt($(this).css("top")) - 4) / 48;
                y_final_grid = (parseInt($(this).css("left")) - 4) / 48;

                h_final_px = $(this).css("height");
                w_final_px = $(this).css("width");

                h_init_grid = ((parseInt(h_init_px) - 40) / 48 ) + 1;
                w_init_grid = ((parseInt(w_init_px) - 40) / 48) + 1;

                h_final_grid = ((parseInt(h_final_px) - 40) / 48 ) + 1;
                w_final_grid = ((parseInt(w_final_px) - 40) / 48) + 1;

                collision:
                    for (var t = x_final_grid; t < x_final_grid + h_final_grid; t++) {

                        for (var s = y_final_grid; s < y_final_grid + w_final_grid; s++) {
                            if (tab_grid[t][s] != 0 && tab_grid[t][s] != $(this).attr("data-new")) {
                                collision = true
                                break collision;
                            }
                        }
                    }

                if (collision) {
                    $(this).animate({
                        width: w_init_px,
                        height: h_init_px
                    }, 200);
                } else {
                    for (var t = x_final_grid; t < x_final_grid + h_init_grid; t++) {
                        for (var s = y_final_grid; s < y_final_grid + w_init_grid; s++) {
                            tab_grid[t][s] = 0;
                        }
                    }

                    for (var t = x_final_grid; t < x_final_grid + h_final_grid; t++) {
                        for (var s = y_final_grid; s < y_final_grid + w_final_grid; s++) {
                            tab_grid[t][s] = $(this).attr("data-new");
                        }
                    }
                }
            });

            // Add an element
            $(".template-e-block-grid").on("click", "#btn_ajout", function (e) {

                boucle:
                    for (var i = 0; i < int_nb_ligne; i++) {
                        for (var j = 0; j < int_nb_colonne; j++) {
                            if (tab_grid[i][j] == 0) {
                                tab_grid[i][j] = "" + int_id_new_cell;
                                x_init_px = (4 + (i) * 48);
                                y_init_px = (4 + (j) * 48);
                                $(".selected").removeClass("selected");
                                $("#div_grid").append('

');
                                int_id_new_cell++;
                                break boucle;
                            }
                        }
                    }
                e.stopPropagation();

                activeNewCell();
            });

            $(".template-e-block-grid").on('dragstop resizestop click', '.cell_new', function (e, ui) {
                affiche_tab();
            });

            $(".template-e-block-grid").on('click', '#btn_ajout , #btn_suppr , #btn_vider', function () {
                affiche_tab();
            });

            function rgb2hex(rgb) {
                rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
                return "#" +
                    ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
                    ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
                    ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2);
            }

            function load_grid(chaine_tab) {
                var temp_tab;
                $(".cell_new").remove();

                if (chaine_tab == "") {
                    temp_tab = new Array(int_nb_ligne);

                    for (var i = 0; i < int_nb_ligne; i++) {
                        temp_tab[i] = new Array(int_nb_colonne);
                    }

                    for (var i = 0; i < int_nb_ligne; i++) {
                        for (var j = 0; j < int_nb_colonne; j++) {
                            temp_tab [i][j] = 0;
                        }
                    }
                }
                else {
                    temp_tab = chaine_tab.split("|");

                    for (var i = 0; i < temp_tab.length; i++) {
                        temp_tab[i] = temp_tab[i].split(" ");
                    }
                }

                tab_grid = temp_tab;
                var tab_done = new Array();

                for (var i = 0; i < 12; i++) {
                    for (var j = 0; j < 12; j++) {
                        if (tab_grid[i][j] != 0 && $.inArray(tab_grid[i][j], tab_done) == -1) {
                            var x = i;
                            var y = j;
                            var h = 0;
                            var w = 0;
                            var val = tab_grid[i][j];
                            tab_done.push(val);

                            while (x + h < 12 && tab_grid[x + h][y] == val) {
                                h++;
                            }

                            while (y + w < 12 && tab_grid[x][y + w] == val) {
                                w++;
                            }

                            $("#div_grid").append('

');
                            int_id_new_cell = parseInt(val) + 1;
                        }
                    }
                }

                activeNewCell();

                $(".cell_new:first").trigger("resizestop");
            }

            function activeNewCell() {
                $(".template-e-block-grid").on("click", ".cell_new", function (e) {
                    $(".selected").removeClass("selected");
                    $(this).addClass("selected");
                    $("#btn_suppr").prop("disabled", false);
                    e.stopPropagation();
                });

                $(document).click(function (e) {
                    $(".selected").removeClass("selected");
                    $("#btn_suppr").prop("disabled", true);
                });

                $(".cell_new").draggable({
                    containment: "#div_grid",
                    grid: [48, 48]
                });

                $(".cell_new").resizable({
                    containment: "#div_grid",
                    grid: [48, 48]
                });
            }
        }

    });<commit_msg>Correcting wrong variables names<commit_after>/**
 * NOVIUS OS - Web OS for digital communication
 *
 * @copyright  2011 Novius
 * @license    GNU Affero General Public License v3 or (at your option) any later version
 *             http://www.gnu.org/licenses/agpl-3.0.html
 * @link http://www.novius-os.org
 */

define(
    [
        'jquery-nos'
    ],
    function ($) {
        "use strict";
        return function (data) {

            data = $.extend({
                form_id: '',
                tpvar_id: ''
            }, data);

            var int_nb_lines;
            var int_nb_rows;
            var tab_grid;
            var int_id_new_cell = 1;
            var tab_css;

            // initial : at drag/resize start
            // final : at drag/resize stop

            var x_init_px; // initial X coordonate in px
            var y_init_px; // initial y coordonate in px
            var x_init_grid; // initial X coordonate in grid frame
            var y_init_grid; // initial Y coordonate in grid frame
            var x_final_grid; // final X coordonate in grid frame
            var y_final_grid; // final X coordonate in grid frame
            var h_init_px; // initial height in px
            var w_init_px; // initial width in px
            var h_final_px; // final height in px
            var w_final_px; // final width in px
            var h_init_grid;  // initial height in grid frame
            var w_init_grid;  // initial width in grid frame
            var h_final_grid; // final height in grid frame
            var w_final_grid; // final width in grid frame

            int_nb_lines = 12;
            int_nb_rows = 12;
            tab_grid = new Array(int_nb_lines);
            int_id_new_cell = 1;
            tab_css = new Array(1);

            function display_tab() {
                var tmp_string = "";

                for (var i = 0; i < int_nb_lines; i++) {
                    for (var j = 0; j < int_nb_rows; j++) {
                        tmp_string += tab_grid [i][j] + " ";
                    }
                    tmp_string = tmp_string.substr(0, tmp_string.length - 1);
                    tmp_string += "|";
                }
                tmp_string = tmp_string.substr(0, tmp_string.length - 1)
                $('[name="wysiwyg_layout"]').attr("value", tmp_string);
            }

            //--------------------------------------
            // Init JS table
            //--------------------------------------

            for (var i = 0; i < int_nb_lines; i++) {
                tab_grid[i] = new Array(int_nb_rows);
            }

            for (var i = 0; i < int_nb_lines; i++) {
                for (var j = 0; j < int_nb_rows; j++) {
                    tab_grid [i][j] = 0;
                }
            }

            //--------------------------------------
            // Init Html Grid
            //--------------------------------------

            //$("#div_grid").html("");

            for (var i = 0; i <int_nb_lines; i++) {
                $("#div_grid").prepend("

");
                for (var j = 0; j < int_nb_rows; j++) {
                    $("#div_l" + i).append("

");
                }
            }

            var string_tab = $('[name="wysiwyg_layout"]').val();
            load_grid(string_tab);

            $(".grid_pattern").click(function () {
                load_grid($(this).find('input[type="hidden"]').val());
            });

            //--------------------------------------
            // Keybord control
            //--------------------------------------

            //Delete Key
            $(document).keypress(function (e) {
                if (e.keyCode == 46) {
                    $("button[id='btn_suppr']").trigger("click");
                }
            });

            //--------------------------------------
            // Grid control Buttons
            //--------------------------------------

            // Clear the grid
            $("button[id='btn_vider']").click(function () {

                for (var t = 0; t < int_nb_lines; t++) {
                    for (var s = 0; s < int_nb_rows; s++) {
                        tab_grid[t][s] = 0;
                    }
                }
                $(".cell_new").remove();
            });

            // Delete an element
            $("button[id='btn_suppr']").click(function () {

                var cell = $(".selected");

                x_init_px = $(cell).css("top");
                y_init_px = $(cell).css("left");

                x_init_grid = (parseInt(x_init_px) - 4) / 48;
                y_init_grid = (parseInt(y_init_px) - 4) / 48;

                h_init_grid = ((parseInt($(cell).css("height")) - 40) / 48 ) + 1;
                w_init_grid = ((parseInt($(cell).css("width")) - 40) / 48) + 1;

                for (var t = x_init_grid; t < h_init_grid + x_init_grid; t++) {
                    for (var s = y_init_grid; s < w_init_grid + y_init_grid; s++) {
                        tab_grid[t][s] = 0;
                    }
                }
                $(".selected").remove();
            });

            $(".template-e-block-grid").on("dragstart", ".cell_new", function (e, ui) {
                x_init_px = $(this).css("top");
                y_init_px = $(this).css("left");
                $(this).trigger("click");
            });

            $(".template-e-block-grid").on("dragstop", ".cell_new", function (event, ui) {

                var collision = false;

                x_final_grid = (parseInt($(this).css("top")) - 4) / 48;
                y_final_grid = (parseInt($(this).css("left")) - 4) / 48;

                x_init_grid = (parseInt(x_init_px) - 4) / 48;
                y_init_grid = (parseInt(y_init_px) - 4) / 48;

                h_final_grid = ((parseInt($(this).css("height")) - 40) / 48 ) + 1;
                w_final_grid = ((parseInt($(this).css("width")) - 40) / 48) + 1;

                collision:
                    for (var t = x_final_grid; t < h_final_grid + x_final_grid; t++) {
                        for (var s = y_final_grid; s < w_final_grid + y_final_grid; s++) {
                            if (tab_grid[t][s] != 0 && tab_grid[t][s] != $(this).attr("data-new")) {
                                collision = true
                                break collision;
                            }
                        }
                    }

                if (collision) {
                    $(this).draggable('disable');
                    var $obj = $(this);
                    $(this).animate({
                        top: x_init_px,
                        left: y_init_px
                    }, 200, function () {
                        $(this).draggable('enable');
                    });
                }
                else {
                    if (j != y_init_grid || i != x_init_grid) {
                        for (var t = x_init_grid; t < h_final_grid + x_init_grid; t++) {
                            for (var s = y_init_grid; s < w_final_grid + y_init_grid; s++) {
                                tab_grid[t][s] = 0;
                            }
                        }
                    }

                    for (var t = x_final_grid; t < h_final_grid + x_final_grid; t++) {
                        for (var s = y_final_grid; s < w_final_grid + y_final_grid; s++) {
                            tab_grid[t][s] = $(this).attr("data-new");
                        }
                    }
                }
            });

            $(".template-e-block-grid").on("resizestart", ".cell_new", function (e, ui) {
                h_init_px = $(this).css("height");
                w_init_px = $(this).css("width");
                $(this).trigger("click");
            });

            $(".template-e-block-grid").on("resizestop", ".cell_new", function (e, ui) {
                var collision = false;

                x_final_grid = (parseInt($(this).css("top")) - 4) / 48;
                y_final_grid = (parseInt($(this).css("left")) - 4) / 48;

                h_final_px = $(this).css("height");
                w_final_px = $(this).css("width");

                h_init_grid = ((parseInt(h_init_px) - 40) / 48 ) + 1;
                w_init_grid = ((parseInt(w_init_px) - 40) / 48) + 1;

                h_final_grid = ((parseInt(h_final_px) - 40) / 48 ) + 1;
                w_final_grid = ((parseInt(w_final_px) - 40) / 48) + 1;

                collision:
                    for (var t = x_final_grid; t < x_final_grid + h_final_grid; t++) {

                        for (var s = y_final_grid; s < y_final_grid + w_final_grid; s++) {
                            if (tab_grid[t][s] != 0 && tab_grid[t][s] != $(this).attr("data-new")) {
                                collision = true
                                break collision;
                            }
                        }
                    }

                if (collision) {
                    $(this).animate({
                        width: w_init_px,
                        height: h_init_px
                    }, 200);
                } else {
                    for (var t = x_final_grid; t < x_final_grid + h_init_grid; t++) {
                        for (var s = y_final_grid; s < y_final_grid + w_init_grid; s++) {
                            tab_grid[t][s] = 0;
                        }
                    }

                    for (var t = x_final_grid; t < x_final_grid + h_final_grid; t++) {
                        for (var s = y_final_grid; s < y_final_grid + w_final_grid; s++) {
                            tab_grid[t][s] = $(this).attr("data-new");
                        }
                    }
                }
            });

            // Add an element
            $(".template-e-block-grid").on("click", "#btn_ajout", function (e) {

                buckle:
                    for (var i = 0; i < int_nb_lines; i++) {
                        for (var j = 0; j < int_nb_rows; j++) {
                            if (tab_grid[i][j] == 0) {
                                tab_grid[i][j] = "" + int_id_new_cell;
                                x_init_px = (4 + (i) * 48);
                                y_init_px = (4 + (j) * 48);
                                $(".selected").removeClass("selected");
                                $("#div_grid").append('

');
                                int_id_new_cell++;
                                break buckle;
                            }
                        }
                    }
                e.stopPropagation();

                activeNewCell();
            });

            $(".template-e-block-grid").on('dragstop resizestop click', '.cell_new', function (e, ui) {
                display_tab();
            });

            $(".template-e-block-grid").on('click', '#btn_ajout , #btn_suppr , #btn_vider', function () {
                display_tab();
            });

            function rgb2hex(rgb) {
                rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
                return "#" +
                    ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
                    ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
                    ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2);
            }

            function load_grid(chaine_tab) {
                var temp_tab;
                $(".cell_new").remove();

                if (chaine_tab == "") {
                    temp_tab = new Array(int_nb_lines);

                    for (var i = 0; i < int_nb_lines; i++) {
                        temp_tab[i] = new Array(int_nb_rows);
                    }

                    for (var i = 0; i < int_nb_lines; i++) {
                        for (var j = 0; j < int_nb_rows; j++) {
                            temp_tab [i][j] = 0;
                        }
                    }
                }
                else {
                    temp_tab = chaine_tab.split("|");

                    for (var i = 0; i < temp_tab.length; i++) {
                        temp_tab[i] = temp_tab[i].split(" ");
                    }
                }

                tab_grid = temp_tab;
                var tab_done = new Array();

                for (var i = 0; i < 12; i++) {
                    for (var j = 0; j < 12; j++) {
                        if (tab_grid[i][j] != 0 && $.inArray(tab_grid[i][j], tab_done) == -1) {
                            var x = i;
                            var y = j;
                            var h = 0;
                            var w = 0;
                            var val = tab_grid[i][j];
                            tab_done.push(val);

                            while (x + h < 12 && tab_grid[x + h][y] == val) {
                                h++;
                            }

                            while (y + w < 12 && tab_grid[x][y + w] == val) {
                                w++;
                            }

                            $("#div_grid").append('

');
                            int_id_new_cell = parseInt(val) + 1;
                        }
                    }
                }

                activeNewCell();

                $(".cell_new:first").trigger("resizestop");
            }

            function activeNewCell() {
                $(".template-e-block-grid").on("click", ".cell_new", function (e) {
                    $(".selected").removeClass("selected");
                    $(this).addClass("selected");
                    $("#btn_suppr").prop("disabled", false);
                    e.stopPropagation();
                });

                $(document).click(function (e) {
                    $(".selected").removeClass("selected");
                    $("#btn_suppr").prop("disabled", true);
                });

                $(".cell_new").draggable({
                    containment: "#div_grid",
                    grid: [48, 48]
                });

                $(".cell_new").resizable({
                    containment: "#div_grid",
                    grid: [48, 48]
                });
            }
        }

    });<|endoftext|>


<commit_before>/// @file JSRoot.openui5.js
/// Bootstraping of OpenUI5 functionality in JSROOT
/// Openui5 loaded directly in the script

(function( factory ) {
   if ( typeof define === "function" && define.amd ) {
      define( ['jquery', 'jquery-ui', 'JSRootCore' ], factory );
   } else {

      if (typeof jQuery == 'undefined')
         throw new Error('jQuery not defined', 'JSRoot.openui5.js');

      if (typeof jQuery.ui == 'undefined')
         throw new Error('jQuery-ui not defined','JSRoot.openui5.js');

      if (typeof JSROOT == 'undefined')
         throw new Error('JSROOT is not defined', 'JSRoot.openui5.js');

      factory(jQuery, jQuery.ui, JSROOT);
   }
} (function($, myui, JSROOT) {

   "use strict";

   JSROOT.sources.push("openui5");

   var load_callback = JSROOT.complete_script_load;
   delete JSROOT.complete_script_load; // normal callback is intercepted - we need to instantiate openui5

   JSROOT.completeUI5Loading = function() {
      // when running with THttpServer, automatically set "rootui5" folder
      var rootui5sys = undefined;
      if (JSROOT.source_dir.indexOf("jsrootsys") >= 0)
         rootui5sys = JSROOT.source_dir.replace(/jsrootsys/g, "rootui5sys");

      sap.ui.loader.config({
         paths: {
            jsroot: JSROOT.source_dir,
            rootui5: rootui5sys
         }
      });

      JSROOT.CallBack(load_callback);
      load_callback = null;
   }

   function TryOpenOpenUI(sources) {

      // where to take openui5 sources
      var src = sources.shift();

      if ((src.indexOf("roothandler")==0) && (src.indexOf("://")<0)) src = src.replace(/\:\//g,"://");

      var element = document.createElement("script");
      element.setAttribute('type', "text/javascript");
      element.setAttribute('id', "sap-ui-bootstrap");
      // use nojQuery while we are already load jquery and jquery-ui, later one can use directly sap-ui-core.js

      // this is location of openui5 scripts when working with THttpServer or when scripts are installed inside JSROOT
      element.setAttribute('src', src + "resources/sap-ui-core-nojQuery.js"); // latest openui5 version

      element.setAttribute('data-sap-ui-libs', JSROOT.openui5libs || "sap.m, sap.ui.layout, sap.ui.unified, sap.ui.commons");

      element.setAttribute('data-sap-ui-theme', 'sap_belize');
      element.setAttribute('data-sap-ui-compatVersion', 'edge');
      // element.setAttribute('data-sap-ui-bindingSyntax', 'complex');

      element.setAttribute('data-sap-ui-preload', 'async'); // '' to disable Component-preload.js

      element.setAttribute('data-sap-ui-evt-oninit', "JSROOT.completeUI5Loading()");

      element.onerror = function() {
         // remove failed element
         element.parentNode.removeChild(element);
         // and try next
         TryOpenOpenUI(sources);
      }

      element.onload = function() {
         console.log('Load openui5 from ' + src);
      }

      document.getElementsByTagName("head")[0].appendChild(element);
   }

   var openui5_sources = [],
       openui5_dflt = "https://openui5.hana.ondemand.com/1.64.1/",
       openui5_root = JSROOT.source_dir.replace(/jsrootsys/g, "rootui5sys/distribution");

   if (openui5_root == JSROOT.source_dir) openui5_root = "";

   if (typeof JSROOT.openui5src == 'string') {
      switch (JSROOT.openui5src) {
         case "nodefault": openui5_dflt = ""; break;
         case "default": openui5_sources.push(openui5_dflt); openui5_dflt = ""; break;
         case "nojsroot": openui5_root = ""; break;
         case "jsroot": openui5_sources.push(openui5_root); openui5_root = ""; break;
         default: openui5_sources.push(JSROOT.openui5src); break;
      }
   }

   if (openui5_root && (openui5_sources.indexOf(openui5_root)<0)) openui5_sources.push(openui5_root);
   if (openui5_dflt && (openui5_sources.indexOf(openui5_dflt)<0)) openui5_sources.push(openui5_dflt);

   TryOpenOpenUI(openui5_sources);

   return JSROOT;

}));

<commit_msg>Use openui5 1.70.0 - as it is in ROOT master now<commit_after>/// @file JSRoot.openui5.js
/// Bootstraping of OpenUI5 functionality in JSROOT
/// Openui5 loaded directly in the script

(function( factory ) {
   if ( typeof define === "function" && define.amd ) {
      define( ['jquery', 'jquery-ui', 'JSRootCore' ], factory );
   } else {

      if (typeof jQuery == 'undefined')
         throw new Error('jQuery not defined', 'JSRoot.openui5.js');

      if (typeof jQuery.ui == 'undefined')
         throw new Error('jQuery-ui not defined','JSRoot.openui5.js');

      if (typeof JSROOT == 'undefined')
         throw new Error('JSROOT is not defined', 'JSRoot.openui5.js');

      factory(jQuery, jQuery.ui, JSROOT);
   }
} (function($, myui, JSROOT) {

   "use strict";

   JSROOT.sources.push("openui5");

   var load_callback = JSROOT.complete_script_load;
   delete JSROOT.complete_script_load; // normal callback is intercepted - we need to instantiate openui5

   JSROOT.completeUI5Loading = function() {
      // when running with THttpServer, automatically set "rootui5" folder
      var rootui5sys = undefined;
      if (JSROOT.source_dir.indexOf("jsrootsys") >= 0)
         rootui5sys = JSROOT.source_dir.replace(/jsrootsys/g, "rootui5sys");

      sap.ui.loader.config({
         paths: {
            jsroot: JSROOT.source_dir,
            rootui5: rootui5sys
         }
      });

      JSROOT.CallBack(load_callback);
      load_callback = null;
   }

   function TryOpenOpenUI(sources) {

      // where to take openui5 sources
      var src = sources.shift();

      if ((src.indexOf("roothandler")==0) && (src.indexOf("://")<0)) src = src.replace(/\:\//g,"://");

      var element = document.createElement("script");
      element.setAttribute('type', "text/javascript");
      element.setAttribute('id', "sap-ui-bootstrap");
      // use nojQuery while we are already load jquery and jquery-ui, later one can use directly sap-ui-core.js

      // this is location of openui5 scripts when working with THttpServer or when scripts are installed inside JSROOT
      element.setAttribute('src', src + "resources/sap-ui-core-nojQuery.js"); // latest openui5 version

      element.setAttribute('data-sap-ui-libs', JSROOT.openui5libs || "sap.m, sap.ui.layout, sap.ui.unified, sap.ui.commons");

      element.setAttribute('data-sap-ui-theme', 'sap_belize');
      element.setAttribute('data-sap-ui-compatVersion', 'edge');
      // element.setAttribute('data-sap-ui-bindingSyntax', 'complex');

      element.setAttribute('data-sap-ui-preload', 'async'); // '' to disable Component-preload.js

      element.setAttribute('data-sap-ui-evt-oninit', "JSROOT.completeUI5Loading()");

      element.onerror = function() {
         // remove failed element
         element.parentNode.removeChild(element);
         // and try next
         TryOpenOpenUI(sources);
      }

      element.onload = function() {
         console.log('Load openui5 from ' + src);
      }

      document.getElementsByTagName("head")[0].appendChild(element);
   }

   var openui5_sources = [],
       openui5_dflt = "https://openui5.hana.ondemand.com/1.70.0/",
       openui5_root = JSROOT.source_dir.replace(/jsrootsys/g, "rootui5sys/distribution");

   if (openui5_root == JSROOT.source_dir) openui5_root = "";

   if (typeof JSROOT.openui5src == 'string') {
      switch (JSROOT.openui5src) {
         case "nodefault": openui5_dflt = ""; break;
         case "default": openui5_sources.push(openui5_dflt); openui5_dflt = ""; break;
         case "nojsroot": openui5_root = ""; break;
         case "jsroot": openui5_sources.push(openui5_root); openui5_root = ""; break;
         default: openui5_sources.push(JSROOT.openui5src); break;
      }
   }

   if (openui5_root && (openui5_sources.indexOf(openui5_root)<0)) openui5_sources.push(openui5_root);
   if (openui5_dflt && (openui5_sources.indexOf(openui5_dflt)<0)) openui5_sources.push(openui5_dflt);

   TryOpenOpenUI(openui5_sources);

   return JSROOT;

}));

<|endoftext|>