<commit_before>var uniquePositionMarker;

function getGoogleInfo(controlMap) {
    var controlInfo = document.getElementById(controlMap).aasControlInfo;
    if (controlInfo) {
        var googleInfo = controlInfo.aasGoogleInfo;
        if (googleInfo) {
            return googleInfo;
        }
    }
    return null;
}

Global.GoogleMapService = {

    aasService: 'GoogleMapService',
    aasPublished: true,

    GetDirectionUrl: function (addr) {
        var rootUrl = 'http://maps.apple.com/';

        if (addr) {
            rootUrl = rootUrl + '?daddr=' + addr.trim().replace(/\s/g, "+");
        }

        var urlEncode = encodeURI(rootUrl);

        return urlEncode;
    },

    CloseInfoBubble: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);

        var currentInfoBubble = googleInfo.InfoBubble;

        if (currentInfoBubble) currentInfoBubble.close();
    },

    ClikOnMarker: function (controlMap, id) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            google.maps.event.trigger(googleInfo.Markers[id], 'click');
        }
    },

    GotoMyPosition: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            if (typeof (navigator.geolocation) != 'undefined') {
                navigator.geolocation.getCurrentPosition(function (position) {
                    //googleInfo.GotoPosition(position);
                    initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                    googleInfo.GotoPosition(initialLocation);
                });
            }
        }
    },

    GotoAdress: function (controlMap, adress) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            googleInfo.GotoAdress(adress);
        }
    },

    Center: function (controlMap, lat, long) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var center = new google.maps.LatLng(lat, long);
            googleInfo.Map.setCenter(center);
        }
    },

    Refresh: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            google.maps.event.trigger(googleInfo.Map, "resize");
        }
    },

    ZoomPlus: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var zoom = googleInfo.Map.getZoom();
            zoom++;
            googleInfo.Map.setZoom(zoom);
        }
    },

    ZoomMinus: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var zoom = googleInfo.Map.getZoom();
            zoom--;
            googleInfo.Map.setZoom(zoom);
        }
    },

    AddUniquePositionMarker: function (controlMap, myPosition) {
        var googleInfo = getGoogleInfo(controlMap);

        if (uniquePositionMarker) {
            uniquePositionMarker.setMap(null);
        }

        uniquePositionMarker = new google.maps.Marker({
            position: myPosition,
            map: googleInfo.Map,
            optimized: false
        });

        var test = uniquePositionMarker;
    },

    RemoveUniquePositionMarker: function () {
        if (uniquePositionMarker) {
            uniquePositionMarker.setMap(null);
        }
    },

    GeoCode: function (controlMap, latitude, longitude, autoCompleteControl) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var googleMapService = Aspectize.Host.GetService('GoogleMapService');
            var geocoder = googleInfo.GeoCoder;
            if (geocoder) {
                if (latitude && longitude) {
                    var location = new google.maps.LatLng(latitude, longitude);
                    geocoder.geocode({ 'location': location }, function (results, status) {
                        var adressComponent = { Latitude: location.lat(), Longitude: location.lng(), FormatAdress: '', country: '', locality: '', postal_code: '', route: '', street_number: '' };
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {
                                if (autoCompleteControl) {

                                    var input = document.getElementById(autoCompleteControl);

                                    if (input) {
                                        input.value = results[0].formatted_address;
                                    }

                                    googleMapService.AddUniquePositionMarker(controlMap, location);
                                }
                            }
                        }
                        else googleMapService.RemoveUniquePositionMarker();
                    });
                }
                else googleMapService.RemoveUniquePositionMarker();
            }
        }
    }

};

Global.GoogleMapControlBuilder = {

    aasService: 'GoogleMapControlBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        controlInfo.aasGoogleInfo = {
            Map: null,
            Markers: {},
            GeoCoder: null,
            InfoWindow: null,
            InfoBubble: null,
            AutoComplete: null,
            GotoPosition: function (position) {
                gotoPosition(this.Map, position);
            },
            GotoAdress: function (adress) {
                gotoAdress(this.Map, this.GeoCoder, adress);
            }
        };

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var map = Aspectize.createElement('div', ownerWindow);

            map.aasSubControls = {};

            return map;
        };

        function addMarker(latitude, longitude, map, id) {

            var info = { IsNewMarker: false, Marker: null };

            var markers = controlInfo.aasGoogleInfo.Markers;

            if (id in markers) {

                info.Marker = markers[id];

                info.Marker.setMap(map);

            } else {

                info.IsNewMarker = true;

                var location = new google.maps.LatLng(latitude, longitude);

                info.Marker = new google.maps.Marker({ position: location, map: map });

                controlInfo.aasGoogleInfo.Markers[id] = info.Marker;
            }

            return info;
        }

        // Removes the overlays from the map, but keeps them in the array
        function hideOverlays() {

            var markers = controlInfo.aasGoogleInfo.Markers;

            for (id in markers) {

                markers[id].setMap(null);
            }
        }

        // delete invisible overlays
        function clearOverlays() {

            var markers = controlInfo.aasGoogleInfo.Markers;

            for (var id in markers) {
                if (markers[id].getMap() === null) {
                    delete markers[id];
                    break;
                }
            }
        }

        function gotoAdress(map, geocoder, adress) {
            geocoder.geocode({ 'address': adress }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    gotoPosition(map, results[0].geometry.location);
                }
            });
        }

        function gotoPosition(map, position) {
            map.setOptions({
                center: position,
                zoom: 14
            });
        }

        controlInfo.InitGrid = function (control) {

            var controlMap = control;

            controlMap.className = 'GoogleMap';

            google.maps.visualRefresh = true;

            var location = new google.maps.LatLng(48.857713, 2.344894);

            var initLat = Aspectize.UiExtensions.GetProperty(control, 'InitLat');
            var initLng = Aspectize.UiExtensions.GetProperty(control, 'InitLng');

            if (initLat && initLng) {
                location = new google.maps.LatLng(initLat, initLng);
            }

            var mapOptions = {
                center: location,
                zoom: Aspectize.UiExtensions.GetProperty(control, 'Zoom'),
                disableDefaultUI: Aspectize.UiExtensions.GetProperty(control, 'DisableDefaultUI'),
                zoomControl: false
            };

            var map = new google.maps.Map(controlMap, mapOptions);

            controlInfo.aasGoogleInfo.Map = map;

            // Styles de la map
            var styles = [
                {
                // stylers: [
                // { hue: "#7e4eA3" },
                // { saturation: 100 } //-100 N&B
                // ]
            }, {
                featureType: "road",
                elementType: "geometry",
                stylers: [
                { lightness: 100 },
                { visibility: "simplified" }
                ]
            }, {
                featureType: "road",
                elementType: "labels",
                stylers: [
                { visibility: "on" }
                ]
            }
            ];

            map.setOptions({ styles: styles });

            var geocoder = new google.maps.Geocoder();

            controlInfo.aasGoogleInfo.GeoCoder = geocoder;

            //var infoBubble = new InfoBubble({
            //    map: map,
            //    shadowStyle: 1,
            //    padding: 0,
            //    arrowSize: 10,
            //    borderWidth: 1,
            //    borderColor: '#bbb',
            //    disableAutoPan: false,
            //    arrowPosition: 50,
            //    disableAnimation: true,
            //    hideCloseButton: true,
            //    arrowStyle: 2,
            //    minHeight: 122
            //});

            //controlInfo.aasGoogleInfo.InfoBubble = infoBubble;

            var addMarkerOnClick = Aspectize.UiExtensions.GetProperty(control, 'AddMarkerOnClick');

            google.maps.event.addListener(map, 'click', function (event) {

                var currentInfoBubble = controlInfo.aasGoogleInfo.InfoBubble;

                if (currentInfoBubble) currentInfoBubble.close();

                if (addMarkerOnClick) {

                    var defaultMarkerUrlIcon = Aspectize.UiExtensions.GetProperty(control, 'DefaultMarkerUrlIcon');

                    geocoder.geocode({ 'location': event.latLng }, function (results, status) {
                        var adressComponent = { Latitude: event.latLng.lat(), Longitude: event.latLng.lng(), FormatAdress: '', country: '', locality: '', postal_code: '', route: '', street_number: '' };
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {
                                adressComponent['FormatAdress'] = results[0].formatted_address;
                                for (var i = 0; i < results[0].address_components.length; i++) {
                                    var address_component = results[0].address_components[i];
                                    var infoType = address_component.types[0];
                                    if (infoType in adressComponent) {
                                        adressComponent[infoType] = address_component.long_name;
                                    }
                                }
                            }
                        }
                        Aspectize.UiExtensions.Notify(control, 'OnMapClick', adressComponent);
                    });
                }
            });
        };

        controlInfo.BeforeRender = function (control) {
            hideOverlays();
        };

        controlInfo.RowCreated = function (control, rowId, cellControls) {

            var item = { id: rowId };

            var map = controlInfo.aasGoogleInfo.Map;
            var geocoder = controlInfo.aasGoogleInfo.GeoCoder;
            var infoWindow = controlInfo.aasGoogleInfo.InfoWindow;
            var infoBubble = controlInfo.aasGoogleInfo.InfoBubble;

            var controlMarker = cellControls[0];  // une seule colonne de type GoogleMarkerPart

            var title = Aspectize.UiExtensions.GetProperty(controlMarker, 'Title');
            var latitude = Aspectize.UiExtensions.GetProperty(controlMarker, 'Latitude');
            var longitude = Aspectize.UiExtensions.GetProperty(controlMarker, 'Longitude');

            var draggable = Aspectize.UiExtensions.GetProperty(controlMarker, 'Draggable');
            var visible = Aspectize.UiExtensions.GetProperty(controlMarker, 'Visible');
            var urlIcon = Aspectize.UiExtensions.GetProperty(controlMarker, 'UrlIcon');
            var infoWindowText = Aspectize.UiExtensions.GetProperty(controlMarker, 'InfoWindowText');

            var data = addMarker(latitude, longitude, map, rowId);

            if (data.IsNewMarker) {

                var marker = data.Marker;

                marker.setVisible(visible);
                marker.setDraggable(draggable);
                marker.setTitle(title);
                marker.infoWindowText = infoWindowText;

                controlMarker.aasMarkerInfo = marker;

                if (urlIcon) {

                    if (Aspectize.Host.MobileMode) {
                        var parts = Aspectize.Host.MobileUrl.split('/');
                        parts[parts.length - 1] = '';
                        urlIcon = parts.join('/') + urlIcon;
                    }

                    var image = new google.maps.MarkerImage(urlIcon, new google.maps.Size(32, 32), new google.maps.Point(0, 0),

                        new google.maps.Point(16, 32) // The anchor for this image is the base of the flagpole
                    );

                    marker.setIcon(image);
                }

                //marker.setMap(map);

                google.maps.event.addListener(marker, 'click', function () {
                    Aspectize.UiExtensions.SetCurrent(control, item.id);
                    Aspectize.UiExtensions.Notify(controlMarker, 'OnMarkerClick', { 'marker': marker, 'item': item, 'infoWindow': infoWindow, 'infoBubble': infoBubble });
                });

                if (draggable) {
                    google.maps.event.addListener(marker, 'dragstart', function () {
                        Aspectize.UiExtensions.SetCurrent(control, item.id);
                        Aspectize.UiExtensions.Notify(controlMarker, 'OnDragBegin', { 'marker': marker, 'item': item });
                    });

                    google.maps.event.addListener(marker, 'dragend', function () {
                        var newLatitude = marker.getPosition().lat();
                        var newLongitude = marker.getPosition().lng();
                        Aspectize.UiExtensions.ChangeProperty(controlMarker, 'Longitude', newLongitude);
                        Aspectize.UiExtensions.ChangeProperty(controlMarker, 'Latitude', newLatitude);
                        Aspectize.UiExtensions.Notify(controlMarker, 'OnDragEnd', { 'marker': marker, 'item': item });
                    });
                }
            }
        };

        controlInfo.GridRendered = function (control, rowControls) {
            clearOverlays();

            var autoCompleteControl = Aspectize.UiExtensions.GetProperty(control, 'AutoComplete');

            if (autoCompleteControl) {
                if (!control.aasControlInfo.aasGoogleInfo.AutoComplete) {

                    var input = document.getElementById(autoCompleteControl);

                    if (input) {
                        var autoComplete = new google.maps.places.Autocomplete(input);

                        google.maps.event.addListener(autoComplete, 'place_changed', function () {

                            var map = control.aasControlInfo.aasGoogleInfo.Map;

                            var place = autoComplete.getPlace();
                            if (!place.geometry) {
                                // Inform the user that the place was not found and return.
                                return;
                            }

                            // If the place has a geometry, then present it on a map.
                            if (place.geometry.viewport) {
                                map.fitBounds(place.geometry.viewport);
                            } else {
                                map.setCenter(place.geometry.location);
                                map.setZoom(14);
                            }

                            Aspectize.UiExtensions.Notify(control, 'OnAutoComplete', { 'place': place });

                        });

                        control.aasControlInfo.aasGoogleInfo.AutoComplete = autoComplete;
                    }
                }
            }
        };
    }
};

Global.GoogleMapControlMarkerBuilder = {

    aasService: 'GoogleMapControlMarkerBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        controlInfo.IsExtendedCell = true;

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var control = Aspectize.createElement('div', ownerWindow);

            return control;
        };

        controlInfo.InitCell = function (cell) {

            Aspectize.UiExtensions.AddPropertyChangeObserver(cell, function (sender, arg) {

                var marker = cell.aasMarkerInfo;

                if (marker) {

                    switch (arg.Name) {

                        case 'UrlIcon':
                            {
                                var urlIcon = arg.Value;

                                if (Aspectize.Host.MobileMode) {
                                    var parts = Aspectize.Host.MobileUrl.split('/');
                                    parts.splice(0, parts.length);
                                    urlIcon = parts.join('/') + urlIcon;
                                }
                                var image = new google.maps.MarkerImage(arg.Value,
                                new google.maps.Size(32, 32),
                                new google.maps.Point(0, 0),

                                new google.maps.Point(16, 32)); // The anchor for this image is the base of the flagpole.

                                marker.setIcon(image);

                            } break;

                        case 'Title': marker.setTitle(arg.Value); break;

                        case 'Longitude':
                        case 'Latitude':

                            var currentPosition = marker.getPosition();
                            var longitude = (arg.Name === 'Longitude') ? arg.Value : currentPosition.lng();
                            var latitude = (arg.Name === 'Latitude') ? arg.Value : currentPosition.lat();

                            var newPosition = new google.maps.LatLng(latitude, longitude);
                            marker.setPosition(newPosition);
                            break;
                    }
                }
            });

        };

    }
};
<commit_msg>FF : RowCreated sets allways : controlMarker.aasMarkerInfo = data.Marker;<commit_after>var uniquePositionMarker;

function getGoogleInfo(controlMap) {
    var controlInfo = document.getElementById(controlMap).aasControlInfo;
    if (controlInfo) {
        var googleInfo = controlInfo.aasGoogleInfo;
        if (googleInfo) {
            return googleInfo;
        }
    }
    return null;
}

Global.GoogleMapService = {

    aasService: 'GoogleMapService',
    aasPublished: true,

    GetDirectionUrl: function (addr) {
        var rootUrl = 'http://maps.apple.com/';

        if (addr) {
            rootUrl = rootUrl + '?daddr=' + addr.trim().replace(/\s/g, "+");
        }

        var urlEncode = encodeURI(rootUrl);

        return urlEncode;
    },

    CloseInfoBubble: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);

        var currentInfoBubble = googleInfo.InfoBubble;

        if (currentInfoBubble) currentInfoBubble.close();
    },

    ClikOnMarker: function (controlMap, id) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            google.maps.event.trigger(googleInfo.Markers[id], 'click');
        }
    },

    GotoMyPosition: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            if (typeof (navigator.geolocation) != 'undefined') {
                navigator.geolocation.getCurrentPosition(function (position) {
                    //googleInfo.GotoPosition(position);
                    initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                    googleInfo.GotoPosition(initialLocation);
                });
            }
        }
    },

    GotoAdress: function (controlMap, adress) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            googleInfo.GotoAdress(adress);
        }
    },

    Center: function (controlMap, lat, long) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var center = new google.maps.LatLng(lat, long);
            googleInfo.Map.setCenter(center);
        }
    },

    Refresh: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            google.maps.event.trigger(googleInfo.Map, "resize");
        }
    },

    ZoomPlus: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var zoom = googleInfo.Map.getZoom();
            zoom++;
            googleInfo.Map.setZoom(zoom);
        }
    },

    ZoomMinus: function (controlMap) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var zoom = googleInfo.Map.getZoom();
            zoom--;
            googleInfo.Map.setZoom(zoom);
        }
    },

    AddUniquePositionMarker: function (controlMap, myPosition) {
        var googleInfo = getGoogleInfo(controlMap);

        if (uniquePositionMarker) {
            uniquePositionMarker.setMap(null);
        }

        uniquePositionMarker = new google.maps.Marker({
            position: myPosition,
            map: googleInfo.Map,
            optimized: false
        });

        var test = uniquePositionMarker;
    },

    RemoveUniquePositionMarker: function () {
        if (uniquePositionMarker) {
            uniquePositionMarker.setMap(null);
        }
    },

    GeoCode: function (controlMap, latitude, longitude, autoCompleteControl) {
        var googleInfo = getGoogleInfo(controlMap);
        if (googleInfo) {
            var googleMapService = Aspectize.Host.GetService('GoogleMapService');
            var geocoder = googleInfo.GeoCoder;
            if (geocoder) {
                if (latitude && longitude) {
                    var location = new google.maps.LatLng(latitude, longitude);
                    geocoder.geocode({ 'location': location }, function (results, status) {
                        var adressComponent = { Latitude: location.lat(), Longitude: location.lng(), FormatAdress: '', country: '', locality: '', postal_code: '', route: '', street_number: '' };
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {
                                if (autoCompleteControl) {

                                    var input = document.getElementById(autoCompleteControl);

                                    if (input) {
                                        input.value = results[0].formatted_address;
                                    }

                                    googleMapService.AddUniquePositionMarker(controlMap, location);
                                }
                            }
                        }
                        else googleMapService.RemoveUniquePositionMarker();
                    });
                }
                else googleMapService.RemoveUniquePositionMarker();
            }
        }
    }

};

Global.GoogleMapControlBuilder = {

    aasService: 'GoogleMapControlBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        controlInfo.aasGoogleInfo = {
            Map: null,
            Markers: {},
            GeoCoder: null,
            InfoWindow: null,
            InfoBubble: null,
            AutoComplete: null,
            GotoPosition: function (position) {
                gotoPosition(this.Map, position);
            },
            GotoAdress: function (adress) {
                gotoAdress(this.Map, this.GeoCoder, adress);
            }
        };

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var map = Aspectize.createElement('div', ownerWindow);

            map.aasSubControls = {};

            return map;
        };

        function addMarker(latitude, longitude, map, id) {

            var info = { IsNewMarker: false, Marker: null };

            var markers = controlInfo.aasGoogleInfo.Markers;

            if (id in markers) {

                info.Marker = markers[id];

                info.Marker.setMap(map);

            } else {

                info.IsNewMarker = true;

                var location = new google.maps.LatLng(latitude, longitude);

                info.Marker = new google.maps.Marker({ position: location, map: map });

                controlInfo.aasGoogleInfo.Markers[id] = info.Marker;
            }

            return info;
        }

        // Removes the overlays from the map, but keeps them in the array
        function hideOverlays() {

            var markers = controlInfo.aasGoogleInfo.Markers;

            for (id in markers) {

                markers[id].setMap(null);
            }
        }

        // delete invisible overlays
        function clearOverlays() {

            var markers = controlInfo.aasGoogleInfo.Markers;

            for (var id in markers) {
                if (markers[id].getMap() === null) {
                    delete markers[id];
                    break;
                }
            }
        }

        function gotoAdress(map, geocoder, adress) {
            geocoder.geocode({ 'address': adress }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    gotoPosition(map, results[0].geometry.location);
                }
            });
        }

        function gotoPosition(map, position) {
            map.setOptions({
                center: position,
                zoom: 14
            });
        }

        controlInfo.InitGrid = function (control) {

            var controlMap = control;

            controlMap.className = 'GoogleMap';

            google.maps.visualRefresh = true;

            var location = new google.maps.LatLng(48.857713, 2.344894);

            var initLat = Aspectize.UiExtensions.GetProperty(control, 'InitLat');
            var initLng = Aspectize.UiExtensions.GetProperty(control, 'InitLng');

            if (initLat && initLng) {
                location = new google.maps.LatLng(initLat, initLng);
            }

            var mapOptions = {
                center: location,
                zoom: Aspectize.UiExtensions.GetProperty(control, 'Zoom'),
                disableDefaultUI: Aspectize.UiExtensions.GetProperty(control, 'DisableDefaultUI'),
                zoomControl: false
            };

            var map = new google.maps.Map(controlMap, mapOptions);

            controlInfo.aasGoogleInfo.Map = map;

            // Styles de la map
            var styles = [
                {
                // stylers: [
                // { hue: "#7e4eA3" },
                // { saturation: 100 } //-100 N&B
                // ]
            }, {
                featureType: "road",
                elementType: "geometry",
                stylers: [
                { lightness: 100 },
                { visibility: "simplified" }
                ]
            }, {
                featureType: "road",
                elementType: "labels",
                stylers: [
                { visibility: "on" }
                ]
            }
            ];

            map.setOptions({ styles: styles });

            var geocoder = new google.maps.Geocoder();

            controlInfo.aasGoogleInfo.GeoCoder = geocoder;

            //var infoBubble = new InfoBubble({
            //    map: map,
            //    shadowStyle: 1,
            //    padding: 0,
            //    arrowSize: 10,
            //    borderWidth: 1,
            //    borderColor: '#bbb',
            //    disableAutoPan: false,
            //    arrowPosition: 50,
            //    disableAnimation: true,
            //    hideCloseButton: true,
            //    arrowStyle: 2,
            //    minHeight: 122
            //});

            //controlInfo.aasGoogleInfo.InfoBubble = infoBubble;

            var addMarkerOnClick = Aspectize.UiExtensions.GetProperty(control, 'AddMarkerOnClick');

            google.maps.event.addListener(map, 'click', function (event) {

                var currentInfoBubble = controlInfo.aasGoogleInfo.InfoBubble;

                if (currentInfoBubble) currentInfoBubble.close();

                if (addMarkerOnClick) {

                    var defaultMarkerUrlIcon = Aspectize.UiExtensions.GetProperty(control, 'DefaultMarkerUrlIcon');

                    geocoder.geocode({ 'location': event.latLng }, function (results, status) {
                        var adressComponent = { Latitude: event.latLng.lat(), Longitude: event.latLng.lng(), FormatAdress: '', country: '', locality: '', postal_code: '', route: '', street_number: '' };
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {
                                adressComponent['FormatAdress'] = results[0].formatted_address;
                                for (var i = 0; i < results[0].address_components.length; i++) {
                                    var address_component = results[0].address_components[i];
                                    var infoType = address_component.types[0];
                                    if (infoType in adressComponent) {
                                        adressComponent[infoType] = address_component.long_name;
                                    }
                                }
                            }
                        }
                        Aspectize.UiExtensions.Notify(control, 'OnMapClick', adressComponent);
                    });
                }
            });
        };

        controlInfo.BeforeRender = function (control) {
            hideOverlays();
        };

        controlInfo.RowCreated = function (control, rowId, cellControls) {

            var item = { id: rowId };

            var map = controlInfo.aasGoogleInfo.Map;
            var geocoder = controlInfo.aasGoogleInfo.GeoCoder;
            var infoWindow = controlInfo.aasGoogleInfo.InfoWindow;
            var infoBubble = controlInfo.aasGoogleInfo.InfoBubble;

            var controlMarker = cellControls[0];  // une seule colonne de type GoogleMarkerPart

            var title = Aspectize.UiExtensions.GetProperty(controlMarker, 'Title');
            var latitude = Aspectize.UiExtensions.GetProperty(controlMarker, 'Latitude');
            var longitude = Aspectize.UiExtensions.GetProperty(controlMarker, 'Longitude');

            var draggable = Aspectize.UiExtensions.GetProperty(controlMarker, 'Draggable');
            var visible = Aspectize.UiExtensions.GetProperty(controlMarker, 'Visible');
            var urlIcon = Aspectize.UiExtensions.GetProperty(controlMarker, 'UrlIcon');
            var infoWindowText = Aspectize.UiExtensions.GetProperty(controlMarker, 'InfoWindowText');

            var data = addMarker(latitude, longitude, map, rowId);

            if (data.IsNewMarker) {

                var marker = data.Marker;

                marker.setVisible(visible);
                marker.setDraggable(draggable);
                marker.setTitle(title);
                marker.infoWindowText = infoWindowText;

                controlMarker.aasMarkerInfo = marker;

                if (urlIcon) {

                    if (Aspectize.Host.MobileMode) {
                        var parts = Aspectize.Host.MobileUrl.split('/');
                        parts[parts.length - 1] = '';
                        urlIcon = parts.join('/') + urlIcon;
                    }

                    var image = new google.maps.MarkerImage(urlIcon, new google.maps.Size(32, 32), new google.maps.Point(0, 0),

                        new google.maps.Point(16, 32) // The anchor for this image is the base of the flagpole
                    );

                    marker.setIcon(image);
                }

                //marker.setMap(map);

                google.maps.event.addListener(marker, 'click', function () {
                    Aspectize.UiExtensions.SetCurrent(control, item.id);
                    Aspectize.UiExtensions.Notify(controlMarker, 'OnMarkerClick', { 'marker': marker, 'item': item, 'infoWindow': infoWindow, 'infoBubble': infoBubble });
                });

                if (draggable) {
                    google.maps.event.addListener(marker, 'dragstart', function () {
                        Aspectize.UiExtensions.SetCurrent(control, item.id);
                        Aspectize.UiExtensions.Notify(controlMarker, 'OnDragBegin', { 'marker': marker, 'item': item });
                    });

                    google.maps.event.addListener(marker, 'dragend', function () {
                        var newLatitude = marker.getPosition().lat();
                        var newLongitude = marker.getPosition().lng();
                        Aspectize.UiExtensions.ChangeProperty(controlMarker, 'Longitude', newLongitude);
                        Aspectize.UiExtensions.ChangeProperty(controlMarker, 'Latitude', newLatitude);
                        Aspectize.UiExtensions.Notify(controlMarker, 'OnDragEnd', { 'marker': marker, 'item': item });
                    });
                }
            } else {

                controlMarker.aasMarkerInfo = data.Marker;
            }
        };

        controlInfo.GridRendered = function (control, rowControls) {
            clearOverlays();

            var autoCompleteControl = Aspectize.UiExtensions.GetProperty(control, 'AutoComplete');

            if (autoCompleteControl) {
                if (!control.aasControlInfo.aasGoogleInfo.AutoComplete) {

                    var input = document.getElementById(autoCompleteControl);

                    if (input) {
                        var autoComplete = new google.maps.places.Autocomplete(input);

                        google.maps.event.addListener(autoComplete, 'place_changed', function () {

                            var map = control.aasControlInfo.aasGoogleInfo.Map;

                            var place = autoComplete.getPlace();
                            if (!place.geometry) {
                                // Inform the user that the place was not found and return.
                                return;
                            }

                            // If the place has a geometry, then present it on a map.
                            if (place.geometry.viewport) {
                                map.fitBounds(place.geometry.viewport);
                            } else {
                                map.setCenter(place.geometry.location);
                                map.setZoom(14);
                            }

                            Aspectize.UiExtensions.Notify(control, 'OnAutoComplete', { 'place': place });

                        });

                        control.aasControlInfo.aasGoogleInfo.AutoComplete = autoComplete;
                    }
                }
            }
        };
    }
};

Global.GoogleMapControlMarkerBuilder = {

    aasService: 'GoogleMapControlMarkerBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        controlInfo.IsExtendedCell = true;

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var control = Aspectize.createElement('div', ownerWindow);

            return control;
        };

        controlInfo.InitCell = function (cell) {

            Aspectize.UiExtensions.AddPropertyChangeObserver(cell, function (sender, arg) {

                var marker = cell.aasMarkerInfo;

                if (marker) {

                    switch (arg.Name) {

                        case 'UrlIcon':
                            {
                                var urlIcon = arg.Value;

                                if (Aspectize.Host.MobileMode) {
                                    var parts = Aspectize.Host.MobileUrl.split('/');
                                    parts.splice(0, parts.length);
                                    urlIcon = parts.join('/') + urlIcon;
                                }
                                var image = new google.maps.MarkerImage(arg.Value,
                                new google.maps.Size(32, 32),
                                new google.maps.Point(0, 0),

                                new google.maps.Point(16, 32)); // The anchor for this image is the base of the flagpole.

                                marker.setIcon(image);

                            } break;

                        case 'Title': marker.setTitle(arg.Value); break;

                        case 'Longitude':
                        case 'Latitude':

                            var currentPosition = marker.getPosition();
                            var longitude = (arg.Name === 'Longitude') ? arg.Value : currentPosition.lng();
                            var latitude = (arg.Name === 'Latitude') ? arg.Value : currentPosition.lat();

                            var newPosition = new google.maps.LatLng(latitude, longitude);
                            marker.setPosition(newPosition);
                            break;
                    }
                }
            });

        };

    }
};
<|endoftext|>


<commit_before>/**
 * Component for rendering the connection indicators as an svg images, with unread count and select handle on the latest (possibly unread) connnectionuri
 * Created by fsuda on 10.04.2017.
 */
import angular from "angular";
import won from "../won-es6.js";
import "ng-redux";
import { labels } from "../won-label-utils.js";
import { actionCreators } from "../actions/actions.js";
import { selectAllOwnNeeds, selectAllNeeds } from "../selectors.js";

import { attach, sortByDate } from "../utils.js";
import { connect2Redux } from "../won-utils.js";
import { classOnComponentRoot } from "../cstm-ng-utils.js";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

                <svg class="indicators__item__icon"
                    title="Show latest message/request"
                    style="--local-primary:var(--won-primary-color-light);"
                    ng-show="!self.unreadConnectedCount">
                        <use xlink:href="#ico36_message" href="#ico36_message"></use>
                </svg>

                <svg style="--local-primary:var(--won-primary-color);"
                     title="Show latest unread message/request"
                     ng-show="self.unreadConnectedCount"
                     class="indicators__item__icon">
                        <use xlink:href="#ico36_message" href="#ico36_message"></use>
                </svg>

                    {{ self.getCountLimited(self.unreadConnectedCount)}}

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-disabled-color);">
                    <use xlink:href="#ico36_message" href="#ico36_message"></use>
            </svg>

                <svg class="indicators__item__icon"
                    style="--local-primary:var(--won-primary-color-light);"
                    ng-show="!self.unreadMatchesCount">
                        <use xlink:href="#ico36_match" href="#ico36_match"></use>
                </svg>

                <svg style="--local-primary:var(--won-primary-color);"
                    ng-show="self.unreadMatchesCount"
                    class="indicators__item__icon">
                        <use xlink:href="#ico36_match" href="#ico36_match"></use>
                </svg>

                    {{ self.getCountLimited(self.unreadMatchesCount) }}

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-disabled-color);">
                    <use xlink:href="#ico36_match" href="#ico36_match"></use>
            </svg>

        {{ self.getCountLimited(self.unreadCountSum) }}

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-skeleton-color);">
                    <use xlink:href="#ico36_message" href="#ico36_message"></use>
            </svg>

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-skeleton-color);">
                    <use xlink:href="#ico36_message" href="#ico36_match"></use>
            </svg>

    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      this.labels = labels;

      const selectFromState = state => {
        const ownNeeds = selectAllOwnNeeds(state);
        const allNeeds = selectAllNeeds(state);
        const need = ownNeeds && ownNeeds.get(this.needUri);
        const allConnectionsByNeedUri = need && need.get("connections");

        const matches =
          allConnectionsByNeedUri &&
          allConnectionsByNeedUri.filter(conn => {
            const remoteNeedUri = conn.get("remoteNeedUri");
            const remoteNeedActiveOrLoading =
              remoteNeedUri &&
              allNeeds &&
              allNeeds.get(remoteNeedUri) &&
              (allNeeds.getIn([remoteNeedUri, "isLoading"]) ||
                allNeeds.getIn([remoteNeedUri, "state"]) ===
                  won.WON.ActiveCompacted);

            return (
              remoteNeedActiveOrLoading &&
              conn.get("state") === won.WON.Suggested
            );
          });
        const connected =
          allConnectionsByNeedUri &&
          allConnectionsByNeedUri.filter(conn => {
            const remoteNeedUri = conn.get("remoteNeedUri");
            const remoteNeedActiveOrLoading =
              remoteNeedUri &&
              allNeeds &&
              allNeeds.get(remoteNeedUri) &&
              (allNeeds.getIn([remoteNeedUri, "isLoading"]) ||
                allNeeds.getIn([remoteNeedUri, "state"]) ===
                  won.WON.ActiveCompacted);

            return (
              remoteNeedActiveOrLoading &&
              conn.get("state") !== won.WON.Suggested &&
              conn.get("state") !== won.WON.Closed
            );
          });

        const unreadMatches =
          matches && matches.filter(conn => conn.get("unread"));
        const unreadConversations =
          connected && connected.filter(conn => conn.get("unread"));

        const unreadMatchesCount = unreadMatches && unreadMatches.size;
        const unreadConnectedCount =
          unreadConversations && unreadConversations.size;

        const unreadCountSum = unreadConnectedCount + unreadMatchesCount;

        return {
          WON: won.WON,
          need,
          unreadCountSum: unreadCountSum > 0 ? unreadCountSum : undefined,
          unreadConnectedCount:
            unreadConnectedCount > 0 ? unreadConnectedCount : undefined,
          unreadMatchesCount:
            unreadMatchesCount > 0 ? unreadMatchesCount : undefined,
          latestConnectedUri: this.retrieveLatestUri(connected),
          latestMatchUri: this.retrieveLatestUri(matches),
        };
      };

      connect2Redux(selectFromState, actionCreators, ["self.needUri"], this);

      classOnComponentRoot("won-is-loading", () => this.isLoading(), this);
    }

    isLoading() {
      return true || !this.need || this.need.get("isLoading");
    }

    /**
     * This method returns either the latest unread uri of the given connection elements, or the latest uri of a read connection, if nothing is found undefined is returned
     * @param elements connection elements to retrieve the latest uri from
     * @returns {*}
     */
    retrieveLatestUri(elements) {
      const unreadElements =
        elements && elements.filter(conn => conn.get("unread"));

      const sortedUnreadElements = sortByDate(unreadElements);
      const unreadUri =
        sortedUnreadElements &&
        sortedUnreadElements[0] &&
        sortedUnreadElements[0].get("uri");

      if (unreadUri) {
        return unreadUri;
      } else {
        const sortedElements = sortByDate(elements);
        return (
          sortedElements && sortedElements[0] && sortedElements[0].get("uri")
        );
      }
    }

    setOpen(connectionUri) {
      this.onSelectedConnection({ connectionUri: connectionUri }); //trigger callback with scope-object
      //TODO either publish a dom-event as well; or directly call the route-change
    }

    getCountLimited(count, threshold = 100) {
      if (!!count && threshold < count) {
        return threshold - 1 + "+";
      }
      return count;
    }
  }
  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      needUri: "=",
      onSelectedConnection: "&",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.connectionIndicators", [])
  .directive("wonConnectionIndicators", genComponentConf).name;
<commit_msg>remove always in Loading() return value<commit_after>/**
 * Component for rendering the connection indicators as an svg images, with unread count and select handle on the latest (possibly unread) connnectionuri
 * Created by fsuda on 10.04.2017.
 */
import angular from "angular";
import won from "../won-es6.js";
import "ng-redux";
import { labels } from "../won-label-utils.js";
import { actionCreators } from "../actions/actions.js";
import { selectAllOwnNeeds, selectAllNeeds } from "../selectors.js";

import { attach, sortByDate } from "../utils.js";
import { connect2Redux } from "../won-utils.js";
import { classOnComponentRoot } from "../cstm-ng-utils.js";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

                <svg class="indicators__item__icon"
                    title="Show latest message/request"
                    style="--local-primary:var(--won-primary-color-light);"
                    ng-show="!self.unreadConnectedCount">
                        <use xlink:href="#ico36_message" href="#ico36_message"></use>
                </svg>

                <svg style="--local-primary:var(--won-primary-color);"
                     title="Show latest unread message/request"
                     ng-show="self.unreadConnectedCount"
                     class="indicators__item__icon">
                        <use xlink:href="#ico36_message" href="#ico36_message"></use>
                </svg>

                    {{ self.getCountLimited(self.unreadConnectedCount)}}

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-disabled-color);">
                    <use xlink:href="#ico36_message" href="#ico36_message"></use>
            </svg>

                <svg class="indicators__item__icon"
                    style="--local-primary:var(--won-primary-color-light);"
                    ng-show="!self.unreadMatchesCount">
                        <use xlink:href="#ico36_match" href="#ico36_match"></use>
                </svg>

                <svg style="--local-primary:var(--won-primary-color);"
                    ng-show="self.unreadMatchesCount"
                    class="indicators__item__icon">
                        <use xlink:href="#ico36_match" href="#ico36_match"></use>
                </svg>

                    {{ self.getCountLimited(self.unreadMatchesCount) }}

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-disabled-color);">
                    <use xlink:href="#ico36_match" href="#ico36_match"></use>
            </svg>

        {{ self.getCountLimited(self.unreadCountSum) }}

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-skeleton-color);">
                    <use xlink:href="#ico36_message" href="#ico36_message"></use>
            </svg>

            <svg class="indicators__item__icon"
                style="--local-primary:var(--won-skeleton-color);">
                    <use xlink:href="#ico36_message" href="#ico36_match"></use>
            </svg>

    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      this.labels = labels;

      const selectFromState = state => {
        const ownNeeds = selectAllOwnNeeds(state);
        const allNeeds = selectAllNeeds(state);
        const need = ownNeeds && ownNeeds.get(this.needUri);
        const allConnectionsByNeedUri = need && need.get("connections");

        const matches =
          allConnectionsByNeedUri &&
          allConnectionsByNeedUri.filter(conn => {
            const remoteNeedUri = conn.get("remoteNeedUri");
            const remoteNeedActiveOrLoading =
              remoteNeedUri &&
              allNeeds &&
              allNeeds.get(remoteNeedUri) &&
              (allNeeds.getIn([remoteNeedUri, "isLoading"]) ||
                allNeeds.getIn([remoteNeedUri, "state"]) ===
                  won.WON.ActiveCompacted);

            return (
              remoteNeedActiveOrLoading &&
              conn.get("state") === won.WON.Suggested
            );
          });
        const connected =
          allConnectionsByNeedUri &&
          allConnectionsByNeedUri.filter(conn => {
            const remoteNeedUri = conn.get("remoteNeedUri");
            const remoteNeedActiveOrLoading =
              remoteNeedUri &&
              allNeeds &&
              allNeeds.get(remoteNeedUri) &&
              (allNeeds.getIn([remoteNeedUri, "isLoading"]) ||
                allNeeds.getIn([remoteNeedUri, "state"]) ===
                  won.WON.ActiveCompacted);

            return (
              remoteNeedActiveOrLoading &&
              conn.get("state") !== won.WON.Suggested &&
              conn.get("state") !== won.WON.Closed
            );
          });

        const unreadMatches =
          matches && matches.filter(conn => conn.get("unread"));
        const unreadConversations =
          connected && connected.filter(conn => conn.get("unread"));

        const unreadMatchesCount = unreadMatches && unreadMatches.size;
        const unreadConnectedCount =
          unreadConversations && unreadConversations.size;

        const unreadCountSum = unreadConnectedCount + unreadMatchesCount;

        return {
          WON: won.WON,
          need,
          unreadCountSum: unreadCountSum > 0 ? unreadCountSum : undefined,
          unreadConnectedCount:
            unreadConnectedCount > 0 ? unreadConnectedCount : undefined,
          unreadMatchesCount:
            unreadMatchesCount > 0 ? unreadMatchesCount : undefined,
          latestConnectedUri: this.retrieveLatestUri(connected),
          latestMatchUri: this.retrieveLatestUri(matches),
        };
      };

      connect2Redux(selectFromState, actionCreators, ["self.needUri"], this);

      classOnComponentRoot("won-is-loading", () => this.isLoading(), this);
    }

    isLoading() {
      return !this.need || this.need.get("isLoading");
    }

    /**
     * This method returns either the latest unread uri of the given connection elements, or the latest uri of a read connection, if nothing is found undefined is returned
     * @param elements connection elements to retrieve the latest uri from
     * @returns {*}
     */
    retrieveLatestUri(elements) {
      const unreadElements =
        elements && elements.filter(conn => conn.get("unread"));

      const sortedUnreadElements = sortByDate(unreadElements);
      const unreadUri =
        sortedUnreadElements &&
        sortedUnreadElements[0] &&
        sortedUnreadElements[0].get("uri");

      if (unreadUri) {
        return unreadUri;
      } else {
        const sortedElements = sortByDate(elements);
        return (
          sortedElements && sortedElements[0] && sortedElements[0].get("uri")
        );
      }
    }

    setOpen(connectionUri) {
      this.onSelectedConnection({ connectionUri: connectionUri }); //trigger callback with scope-object
      //TODO either publish a dom-event as well; or directly call the route-change
    }

    getCountLimited(count, threshold = 100) {
      if (!!count && threshold < count) {
        return threshold - 1 + "+";
      }
      return count;
    }
  }
  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      needUri: "=",
      onSelectedConnection: "&",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.connectionIndicators", [])
  .directive("wonConnectionIndicators", genComponentConf).name;
<|endoftext|>


<commit_before>/**
 *
 *   IntersectionParams.js
 *
 *   copyright 2002, Kevin Lindsey
 *
 */

/**
 *  IntersectionParams
 *
 *  @param {String} name
 *  @param {Array<Point2D} params
 *  @returns {IntersectionParams}
 */
function IntersectionParams(name, params) {
    this.init(name, params);
}

!function () {
    IntersectionParams.TYPE = {};
    var t = IntersectionParams.TYPE;
    var d = Object.defineProperty;

    d(t, 'LINE', { value: 'Line' });
    d(t, 'RECT', { value: 'Rectangle' });
    d(t, 'ROUNDRECT', { value: 'RoundRectangle' });
    d(t, 'CIRCLE', { value: 'Circle' });
    d(t, 'ELLIPSE', { value: 'Ellipse' });
    d(t, 'POLYGON', { value: 'Polygon' });
    d(t, 'POLYLINE', { value: 'Polyline' });
    d(t, 'PATH', { value: 'Path' });
    d(t, 'ARC', { value: 'Arc' });
    d(t, 'BEZIER2', { value: 'Bezier2' });
    d(t, 'BEZIER3', { value: 'Bezier3' });
}();

/**
 *  init
 *
 *  @param {String} name
 *  @param {Array<Point2D>} params
 */
IntersectionParams.prototype.init = function(name, params) {
    this.name   = name;
    this.params = params;
};

if (typeof module !== "undefined") {
    module.exports = IntersectionParams;
}<commit_msg>Property for additional data about IntersectionParams instance (for future use).<commit_after>/**
 *
 *   IntersectionParams.js
 *
 *   copyright 2002, Kevin Lindsey
 *
 */

/**
 *  IntersectionParams
 *
 *  @param {String} name
 *  @param {Array<Point2D} params
 *  @returns {IntersectionParams}
 */
function IntersectionParams(name, params) {
    this.init(name, params);
}

!function () {
    IntersectionParams.TYPE = {};
    var t = IntersectionParams.TYPE;
    var d = Object.defineProperty;

    d(t, 'LINE', { value: 'Line' });
    d(t, 'RECT', { value: 'Rectangle' });
    d(t, 'ROUNDRECT', { value: 'RoundRectangle' });
    d(t, 'CIRCLE', { value: 'Circle' });
    d(t, 'ELLIPSE', { value: 'Ellipse' });
    d(t, 'POLYGON', { value: 'Polygon' });
    d(t, 'POLYLINE', { value: 'Polyline' });
    d(t, 'PATH', { value: 'Path' });
    d(t, 'ARC', { value: 'Arc' });
    d(t, 'BEZIER2', { value: 'Bezier2' });
    d(t, 'BEZIER3', { value: 'Bezier3' });
}();

/**
 *  init
 *
 *  @param {String} name
 *  @param {Array<Point2D>} params
 */
IntersectionParams.prototype.init = function(name, params) {
    this.name   = name;
    this.params = params;
    this.meta = {};
};

if (typeof module !== "undefined") {
    module.exports = IntersectionParams;
}<|endoftext|>


<commit_before>// Object: javascript literal object
(function ($) {
    "use strict";

    if (!Object["eachAttrs"]) {
        $.defineProperty($.prototype, "eachAttrs", {
            value: function () {
                var
                    self = this,
                    attrs = Object.getOwnPropertyNames(self),
                    attr,
                    callback = arguments[0],
                    obj;

                // o for...in é para se usar break;
                for (attr in attrs) {
                    if (!isNaN(parseInt(attrs[attr], 10))) {
                        callback(self[attr], attr);
                    } else {
                        break;
                    }
                }
            }
        });
    }

    if (!Object["isEquivalent"]) {
        $.defineProperty($.prototype, "isEquivalent", {
            value: function () {
                var
                    self = this,
                    i;

                if (self instanceof Object && !(self instanceof Function)) {
                    if ((typeof arguments[0]) === (typeof self)) {
                        for (i in self) {
                            if (typeof arguments[0][i] !== "function") {
                                if ((typeof self[i]) ===
                                    (typeof arguments[0][i])) {
                                    if (typeof self[i] === "object") {
                                        if (self[i]
                                            .isEquivalent(arguments[0][i])
                                            === false) {
                                            return false;
                                        }
                                    } else {
                                        if (self[i] !== arguments[0][i]) {
                                            return false;
                                        }
                                    }
                                } else {
                                    return false;
                                }
                            }
                        }
                    } else {
                        return false;
                    }
                }

                return true;
            }
        });
    }

    if (!Object["flatten"]) {
        $.defineProperty($.prototype, "flatten", {
            value: function () {
                var
                    flat = [],
                    self = this,
                    i,
                    type;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        type = Object.prototype.toString.call(self[i]).split(' ')
                            .pop().split(']').shift().toLowerCase();
                        if (type) {
                            flat = flat
                                .concat(/^(array|arguments|collection)$/
                                    .test(type) ? self.flatten
                                        .call(self[i]) : self[i]);
                        }
                    }
                }

                return flat;
            }
        });
    }

    if (!Object["eachNodes"]) {
        $.defineProperty($.prototype, "eachNodes", {
            value: function (callback, trail) {
                trail = trail || [];

                var
                    self = this,
                    value;

                //for (var key in self) {
                Object.getOwnPropertyNames(self).forEach(function (key) {
                // Object.keys(self).forEach(function (key) {
                    value = self[key];

                    if (Object.getPrototypeOf(value) === Object.prototype) {
                        // chamar uma função recursivamente não substitui os valores do atual loop, nem o interrompe (salvo quando a instrução return é chamada), apenas define um novo loop com um novo valor para ser executado
                        // eachNodes(callback, trail.concat(key));
                        value.eachNodes(callback, trail.concat(key));
                    } else {
                        callback({name: key, value: value, trail: trail});
                    }
                });
                // }
            }
        });
    }

    if (!Object["merge"]) {
        $.defineProperty($.prototype, "merge", {
            value: function () {
                var
                    self = this,
                    merged = {},
                    i,
                    arg;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        merged[i] = self[i];
                    }
                }

                for (arg in arguments) {
                    if (arguments.hasOwnProperty(arg)) {
                        if (arguments[arg] instanceof Object) {
                            for (i in arguments[arg]) {
                                if (arguments[arg].hasOwnProperty(i)) {
                                    merged[i] = arguments[arg][i];
                                }
                            }
                        }
                    }
                }

                return merged;
            }
        });
    }

    if (!Object["indexOfConstructor"]) {
        $.defineProperty($.prototype, "indexOfConstructor", {
            value: function () {
                var
                    self = this,
                    calleeArgs = self.callee.arguments,
                    arg = arguments[0],
                    i;

                for(i in calleeArgs) {
                    if (calleeArgs[i].constructor === arg) {
                        return parseFloat(i);
                    }
                }

                return false;
            }
        });
    }

}(Object));
<commit_msg>ajusta bug em singleton<commit_after>// Object: javascript literal object
(function ($) {
    "use strict";

    if (!Object["eachAttrs"]) {
        $.defineProperty($.prototype, "eachAttrs", {
            value: function () {
                var
                    self = this,
                    attrs = Object.getOwnPropertyNames(self),
                    attr,
                    callback = arguments[0],
                    obj;

                // o for...in é para se usar break;
                for (attr in attrs) {
                    if (!isNaN(parseInt(attrs[attr], 10))) {
                        callback(self[attr], attr);
                    } else {
                        break;
                    }
                }
            }
        });
    }

    if (!Object["isEquivalent"]) {
        $.defineProperty($.prototype, "isEquivalent", {
            value: function () {
                var
                    self = this,
                    i;

                if (self instanceof Object && !(self instanceof Function)) {
                    if ((arguments[0]).constructor === self.constructor) {
                        for (i in self) {
                            if (self.hasOwnProperty(i)) {
                                // se o tipo for function a comparação será desprezada
                                if (typeof self[i] !== "function") {
                                    if ((typeof self[i]) ===
                                        (typeof arguments[0][i])) {
                                        if (self[i].constructor === Object) {
                                            if (self[i]
                                                .isEquivalent(arguments[0][i])
                                                === false) {
                                                return false;
                                            }
                                        } else {
                                            if (self[i] !== arguments[0][i]) {
                                                return false;
                                            }
                                        }
                                    } else {
                                        return false;
                                    }
                                }
                            }
                        }
                    } else {
                        return false;
                    }
                }

                return true;
            }
        });
    }

    if (!Object["flatten"]) {
        $.defineProperty($.prototype, "flatten", {
            value: function () {
                var
                    flat = [],
                    self = this,
                    i,
                    type;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        type = Object.prototype.toString.call(self[i]).split(' ')
                            .pop().split(']').shift().toLowerCase();
                        if (type) {
                            flat = flat
                                .concat(/^(array|arguments|collection)$/
                                    .test(type) ? self.flatten
                                        .call(self[i]) : self[i]);
                        }
                    }
                }

                return flat;
            }
        });
    }

    if (!Object["eachNodes"]) {
        $.defineProperty($.prototype, "eachNodes", {
            value: function (callback, trail) {
                trail = trail || [];

                var
                    self = this,
                    value;

                //for (var key in self) {
                Object.getOwnPropertyNames(self).forEach(function (key) {
                // Object.keys(self).forEach(function (key) {
                    value = self[key];

                    if (Object.getPrototypeOf(value) === Object.prototype) {
                        // chamar uma função recursivamente não substitui os valores do atual loop, nem o interrompe (salvo quando a instrução return é chamada), apenas define um novo loop com um novo valor para ser executado
                        // eachNodes(callback, trail.concat(key));
                        value.eachNodes(callback, trail.concat(key));
                    } else {
                        callback({name: key, value: value, trail: trail});
                    }
                });
                // }
            }
        });
    }

    if (!Object["merge"]) {
        $.defineProperty($.prototype, "merge", {
            value: function () {
                var
                    self = this,
                    merged = {},
                    i,
                    arg;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        merged[i] = self[i];
                    }
                }

                for (arg in arguments) {
                    if (arguments.hasOwnProperty(arg)) {
                        if (arguments[arg] instanceof Object) {
                            for (i in arguments[arg]) {
                                if (arguments[arg].hasOwnProperty(i)) {
                                    merged[i] = arguments[arg][i];
                                }
                            }
                        }
                    }
                }

                return merged;
            }
        });
    }

    if (!Object["indexOfConstructor"]) {
        $.defineProperty($.prototype, "indexOfConstructor", {
            value: function () {
                var
                    self = this,
                    calleeArgs = self.callee.arguments,
                    arg = arguments[0],
                    i;

                for(i in calleeArgs) {
                    if (calleeArgs[i].constructor === arg) {
                        return parseFloat(i);
                    }
                }

                return false;
            }
        });
    }

}(Object));
<|endoftext|>


<commit_before>function addEvent(element, type, listener) {
    if (element.addEventListener) {
        element.addEventListener(type, listener, false);
        return true;
    }
    else if (element.attachEvent) {
        return element.attachEvent("on" + type, listener);
    }
    return false;
}

<commit_msg>Removed obsolete trac.js file.<commit_after><|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
function NamedModulesPlugin(options) {
	this.options = options || {};
}
module.exports = NamedModulesPlugin;
NamedModulesPlugin.prototype.apply = function(compiler) {
	compiler.plugin("compilation", function(compilation) {
		compilation.plugin("before-module-ids", function(modules) {
			modules.forEach(function(module) {
				if(module.id === null && module.libIdent) {
					module.id = module.libIdent({
						context: this.options.context || compiler.options.context
					});
				}
			}, this);
		}.bind(this));
	}.bind(this));
};
<commit_msg>refactor(es6): Upgrade NamedModulesPlugin to es6 (#3619)<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

class NamedModulesPlugin {
	constructor(options) {
		this.options = options || {};
	}

	apply(compiler) {
		compiler.plugin("compilation", (compilation) => {
			compilation.plugin("before-module-ids", (modules) => {
				modules.forEach((module) => {
					if(module.id === null && module.libIdent) {
						module.id = module.libIdent({
							context: this.options.context || compiler.options.context
						});
					}
				});
			});
		});
	}
}

module.exports = NamedModulesPlugin;
<|endoftext|>


<commit_before>"use strict";

var _tk = require('rocambole-token');
var _ws = require('../whiteSpace/whiteSpace');

module.exports = function addSpaceInsideExpressionParentheses(node) {
  var opening = node.startToken;
  var closing = node.endToken;

  if (!isValidExpression(node)) {
    return;
  }

  if (node.type === 'BinaryExpression' || opening.value !== '(') {
    var prev = _tk.findPrevNonEmpty(opening);
    opening = isValidParens(prev, node) ? prev : null;
  }

  if (opening && (node.type === 'BinaryExpression' || closing.value !== ')')) {
    var possible = closing.value === ';' || closing.type === 'LineBreak' ?
      _tk.findPrevNonEmpty(closing) : _tk.findNextNonEmpty(closing);
    closing = possible && possible.value === ')' ? possible : null;
  }

  if (!opening || !closing) {
    return;
  }

  _ws.afterIfNeeded(opening, 'ExpressionOpeningParentheses');
  _ws.beforeIfNeeded(closing, 'ExpressionClosingParentheses');
};

// Literal when inside BinaryExpression might be surrounded by parenthesis
// CallExpression and ArrayExpression don't need spaces
var needExpressionParenthesesSpaces = {
  Literal: true,
  CallExpression: false,
  FunctionExpression: false,
  ArrayExpression: false
};

function isValidExpression(node) {
  var needSpaces = needExpressionParenthesesSpaces[node.type];

  if (needSpaces) {
    return true;
  }

  if (needSpaces == null && node.type.indexOf('Expression') !== -1) {
    if (node.type === 'ExpressionStatement' &&
      (node.expression.callee && node.expression.callee.type === 'FunctionExpression')) {
      // bypass IIFE
      return false;
    }
    return true;
  }

  return false;
}

// this is a hack to check if "(" is part of the parent node to avoid inserting
// unnecessary spaces inside function calls and if statements
function isValidParens(token, node) {
  if (!token || token.value !== '(') {
    return false;
  }

  var pType = node.parent.type;

  if (pType === 'ReturnStatement') return true;

  var prev = _tk.findPrevNonEmpty(token);
  if (pType === 'IfStatement' || pType === 'CallExpression') {
    // we make sure it is not the same
    var opening = _tk.findNext(node.parent.startToken, '(');
    return opening !== token;
  } else {
    // we make sure it is not a regular parentheses
    return !prev || (prev.type !== 'Identifier' && prev.type !== 'Keyword');
  }
}

<commit_msg>avoid adding spaces around ObjectExpression. closes #121<commit_after>"use strict";

var _tk = require('rocambole-token');
var _ws = require('../whiteSpace/whiteSpace');

module.exports = function addSpaceInsideExpressionParentheses(node) {
  var opening = node.startToken;
  var closing = node.endToken;

  if (!isValidExpression(node)) {
    return;
  }

  if (node.type === 'BinaryExpression' || opening.value !== '(') {
    var prev = _tk.findPrevNonEmpty(opening);
    opening = isValidParens(prev, node) ? prev : null;
  }

  if (opening && (node.type === 'BinaryExpression' || closing.value !== ')')) {
    var possible = closing.value === ';' || closing.type === 'LineBreak' ?
      _tk.findPrevNonEmpty(closing) : _tk.findNextNonEmpty(closing);
    closing = possible && possible.value === ')' ? possible : null;
  }

  if (!opening || !closing) {
    return;
  }

  _ws.afterIfNeeded(opening, 'ExpressionOpeningParentheses');
  _ws.beforeIfNeeded(closing, 'ExpressionClosingParentheses');
};

// Literal when inside BinaryExpression might be surrounded by parenthesis
// CallExpression and ArrayExpression don't need spaces
var needExpressionParenthesesSpaces = {
  Literal: true,
  CallExpression: false,
  FunctionExpression: false,
  ArrayExpression: false,
  ObjectExpression: false
};

function isValidExpression(node) {
  var needSpaces = needExpressionParenthesesSpaces[node.type];

  if (needSpaces) {
    return true;
  }

  if (needSpaces == null && node.type.indexOf('Expression') !== -1) {
    if (node.type === 'ExpressionStatement' &&
      (node.expression.callee && node.expression.callee.type === 'FunctionExpression')) {
      // bypass IIFE
      return false;
    }
    return true;
  }

  return false;
}

// this is a hack to check if "(" is part of the parent node to avoid inserting
// unnecessary spaces inside function calls and if statements
function isValidParens(token, node) {
  if (!token || token.value !== '(') {
    return false;
  }

  var pType = node.parent.type;

  if (pType === 'ReturnStatement') return true;

  var prev = _tk.findPrevNonEmpty(token);
  if (pType === 'IfStatement' || pType === 'CallExpression') {
    // we make sure it is not the same
    var opening = _tk.findNext(node.parent.startToken, '(');
    return opening !== token;
  } else {
    // we make sure it is not a regular parentheses
    return !prev || (prev.type !== 'Identifier' && prev.type !== 'Keyword');
  }
}

<|endoftext|>


<commit_before>/**
 *
 */
'use strict';

angular.module('material.components.table', ['material.core'])
        .controller('mdTableController', ['$scope', '$filter', mdTableController])
        .directive('mdTable', mdTableDirective)
        .filter('pageFilter', mdTablePageFilter);

/**
 * Create md-table Directive
 */
function mdTableDirective() {
    return {
        restrict: 'E',
        scope: {
            headers: '=',
            headersClass: '=',
            contents: '=',
            contentsClass: '=',
            enableSelection: '=selection',
            select: '&onSelect',
            enableAction: '=action',
            action: '&onAction',
            enablePagination: '=pagination',
            pageCount: '=?',
            contentFilter: '=filter'
        },
        link: mdTableLink,
        controller: mdTableController,
        template: '
\

\
			\

\

\
					\
					\
						\
						\
					\
					\
						\
						\
							{{header.label}}\
							\
								\
							\
							\
								\
							\
							\
							\
						\
						\
						\
							{{header.label}}\
						\
						\
					\
					\

\

\
			\

\

\
					\
					\
						<md-checkbox aria-label="Select content" ng-model="checkedValue" ng-change="select({checked: checkedValue, selectedContent: content})"></md-checkbox>\
						\
					\
					\

\
							\

\

\

\
                            \

\
                                <input ng-model="content[header.contentField]" />\

\
                            \

\
                            {{content[header.contentField] | contentFilter : header.contentFilter}}\

\

\
						\
					\
					\
						<md-button class="md-action" ng-click="action({selectedContent: content})" aria-label="Action">\
							\
						</md-button>\
						\

\

\

\
		\

\
			\
			\
				\
				<md-button aria-label="Previous" class="md-table-footer-item" ng-click="previous()" ng-disabled="previousDisabled();">\
					\
				</md-button>\
				\
				\
					<md-button aria-label="Index" class="md-primary md-table-footer-item" ng-click="selectPage(page.index)">\
						{{page.index}}\
					</md-button>\
				\
				\
				<md-button aria-label="Next" class="md-table-footer-item" ng-click="next()" ng-disabled="nextDisabled();">\
					\
				</md-button>\
			\

\

'
    };
}

/**
 * Create mdTableController
 */
function mdTableController($scope, $filter) {

    initializeControllerDatas($scope);
    initializePagination($scope);

    $scope.$watchCollection(function () {
        return $scope.contents;
    },
    function () {
        initializePagination($scope);
    });

    /**
     * Sorting content
     */
    $scope.sort = function (predicate, reverse) {
        $scope.reverse = !reverse;
        $scope.contents = $filter('orderBy')($scope.contents, predicate, $scope.reverse);
        $scope.predicate = predicate;
    };

    /**
     * Display next page
     */
    $scope.next = function () {
        $scope.currentPage = $scope.currentPage + 1;
    };

    /**
     * Display previous page
     */
    $scope.previous = function () {
        $scope.currentPage = $scope.currentPage - 1;
    };

    /**
     * Determine if  "Previous" button is enable
     */
    $scope.previousDisabled = function () {
        return $scope.currentPage == 0;
    };

    /**
     * Determine if  "Next" button is enable
     */
    $scope.nextDisabled = function () {
        return $scope.pages.length == 0 || $scope.currentPage == ($scope.pages.length - 1);
    };

    /**
     * Select the page
     */
    $scope.selectPage = function (pageIndex) {
        $scope.currentPage = pageIndex;
    };

    /* TODO Not implemented yet
     $scope.selectAll = function(checked) {
     checked = !checked;
     console.log(checked);
     }
     */
}

/**
 * Create mdTableLink
 */
function mdTableLink($scope, $element, $attr) {
    $element.attr({
        'role': 'table'
    });
}

/**
 * @return The filter use to paginate
 */
function mdTablePageFilter() {
    return function (contents, selectedPage) {
        selectedPage = +selectedPage;
        if (contents) {
            return contents.slice(selectedPage);
        } else {
            return '';
        }
    };
}

/**
 * Initialization of controller's data
 */
function initializeControllerDatas($scope) {
    // Sorting
    $scope.reverse = true;
    $scope.predicate = '';
    // Pagination
    $scope.currentPage = 0;
}

/**
 * Determine the number of pages
 *
 * @return Pages representing by an array
 */
function initializePagination($scope) {
    var contents = $scope.contents;
    var pages = [];
    if (contents) {
        if (!$scope.pageCount) {
            $scope.pageCount = contents.length;
        }
        var numberOfPages = Math.ceil(contents.length / $scope.pageCount);
        for (var i = 0; i < numberOfPages; i++) {
            pages.push({name: 'page' + i, index: i});
        }
    }
    $scope.pages = pages;
}

/**
 * This method help to create an header object
 *
 * @param label
 *            Label of the header (Mandatory)
 * @param contentField
 *            Link with the content's field (Mantadory)
 * @param contentType
 *            Nature of content's field (Default => 'text' :
 *            - 'input'
 *			  - 'text'
 *			  - 'image'
 * @param sortableField
 *            Flag to indicate if the field is sortable
 */
function mdTableHeader(label, contentField, contentType, sortableField) {
    this.label = label;
    this.contentField = contentField;
    this.contentType = contentType || 'text';
    this.sortableField = sortableField || false;
}

/**
 * This method help to create a content object
 *
 * @param data
 *            Content data's (Mandatory)
 */
function mdTableContent(data) {
    this.data = data;
}<commit_msg>Mis e 14;59R jour du fichier js<commit_after>/**
 *
 */
'use strict';

angular.module('material.components.table', ['material.core'])
        .controller('mdTableController', ['$scope', '$filter', mdTableController])
        .directive('mdTable', mdTableDirective)
        .filter('pageFilter', mdTablePageFilter)
        .filter('contentFilter', ['$filter', mdTableContentFilter]);

/**
 * Create md-table Directive
 */
function mdTableDirective() {
    return {
        restrict: 'E',
        scope: {
            headers: '=',
            headersClass: '=',
            contents: '=',
            contentsClass: '=',
            enableSelection: '=selection',
            select: '&onSelect',
            enableAction: '=action',
            action: '&onAction',
            enablePagination: '=pagination',
            pageCount: '=?',
            contentFilter: '=filter'
        },
        link: mdTableLink,
        controller: mdTableController,
        template: '
\

\
        \

\

\
        \
    \
        \
    	\
        \
    \
        \
    \
    {{header.label}}\
\
\
\
\
\
\
\
\
\
    \
\
{{header.label}}\
\
	\
    \
\

\

\
    \

\

\
    \
\
<md-checkbox aria-label="Select content" ng-model="checkedValue" ng-change="select({checked: checkedValue, selectedContent: content})"></md-checkbox>\
	\
    \
\

\
    \

\

\

\
    \

\
<input ng-model="content[header.contentField]" />\

\
    \

\
{{content[header.contentField] | contentFilter : header.contentFilter}}\

\
\

\
    	\
        \
    \
    <md-button class="md-action" ng-click="action({selectedContent: content})" aria-label="Action">\
    \
    </md-button>\
    	\

\

\

\
\
        \

\
    \
    \
        \
    <md-button aria-label="Previous" class="md-table-footer-item" ng-click="previous()" ng-disabled="previousDisabled();">\
    \
    </md-button>\
        \
    \
    <md-button aria-label="Index" class="md-primary md-table-footer-item" ng-click="selectPage(page.index)">\
    {{page.index}}\
</md-button>\
\
    \
<md-button aria-label="Next" class="md-table-footer-item" ng-click="next()" ng-disabled="nextDisabled();">\
\
</md-button>\
\

\

'
    };
}

/**
 * Create mdTableController
 *
 * @param {type} $scope
 * @param {type} $filter
 * @returns {undefined}
 */
function mdTableController($scope, $filter) {

    initializeControllerDatas($scope);
    initializePagination($scope);

    $scope.$watchCollection(function () {
        return $scope.contents;
    },
    function () {
        initializePagination($scope);
    });

    /**
     * Sorting content
     */
    $scope.sort = function (predicate, reverse) {
        $scope.reverse = !reverse;
        $scope.contents = $filter('orderBy')($scope.contents, predicate, $scope.reverse);
        $scope.predicate = predicate;
    };

    /**
     * Display next page
     */
    $scope.next = function () {
        $scope.currentPage = $scope.currentPage + 1;
    };

    /**
     * Display previous page
     */
    $scope.previous = function () {
        $scope.currentPage = $scope.currentPage - 1;
    };

    /**
     * Determine if  "Previous" button is enable
     */
    $scope.previousDisabled = function () {
        return $scope.currentPage == 0;
    };

    /**
     * Determine if  "Next" button is enable
     */
    $scope.nextDisabled = function () {
        return $scope.pages.length == 0 || $scope.currentPage == ($scope.pages.length - 1);
    };

    /**
     * Select the page
     */
    $scope.selectPage = function (pageIndex) {
        $scope.currentPage = pageIndex;
    };

    /* TODO Not implemented yet
     $scope.selectAll = function(checked) {
     checked = !checked;
     console.log(checked);
     }
     */
}

/**
 * Create mdTableLink
 */
function mdTableLink($scope, $element, $attr) {
    $element.attr({
        'role': 'table'
    });
}

/**
 * @return The filter use to paginate
 */
function mdTablePageFilter() {
    return function (contents, selectedPage) {
        selectedPage = +selectedPage;
        if (contents) {
            return contents.slice(selectedPage);
        } else {
            return '';
        }
    };
}

/**
 * @return The filter use to paginate
 */
function mdTableContentFilter($filter) {
    return function (value, contentFilter) {
        if(contentFilter) {
            if(contentFilter.pattern) {
                var result = $filter(contentFilter.filter)(value, contentFilter.pattern);
                console.log(result);
                return result;
            } else {
                var result = $filter(contentFilter.filter)(value);
                console.log(result);
                return result;
            }
        } else {
            return value;
        }
    };
}

/**
 * Initialization of controller's data
 */
function initializeControllerDatas($scope) {
    // Sorting
    $scope.reverse = true;
    $scope.predicate = '';
    // Pagination
    $scope.currentPage = 0;
    initializePagination($scope);
}

/**
 * Determine the number of pages
 *
 * @return Pages representing by an array
 */
function initializePagination($scope) {
    var contents = $scope.contents;
    var pages = [];
    if (contents) {
        if (!$scope.pageCount) {
            $scope.pageCount = contents.length;
        }
        var numberOfPages = Math.ceil(contents.length / $scope.pageCount);
        for (var i = 0; i < numberOfPages; i++) {
            pages.push({name: 'page' + i, index: i});
        }
    }
    $scope.pages = pages;
}

/**
 * This method help to create an header object
 *
 * @param label
 *            Label of the header (Mandatory)
 * @param contentField
 *            Link with the content's field (Mantadory)
 * @param contentType
 *            Nature of content's field (Default => 'text' :
 *            - 'input'
 *            - 'text'
 *            - 'image'
 * @param sortableField
 *            Flag to indicate if the field is sortable
 */
function mdTableHeader(label, contentField, contentType, sortableField) {
    this.label = label;
    this.contentField = contentField;
    this.contentType = contentType || 'text';
    this.sortableField = sortableField || false;
}

/**
 * This method help to create a content object
 *
 * @param data
 *            Content data's (Mandatory)
 */
function mdTableContent(data) {
    this.data = data;
}<|endoftext|>