<commit_before>var map;

var depart_arrivee = {
    depart :  { lat : -1, lon : -1},
    arrivee : { lat : -1, lon : -1}
};

var planner;

var destination_idx = -1;
var departure_idx = -1;
var debut_requete = -1;
var fin_requete = -1;
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

function format(datetime){

    datetime.trim();

    var year = datetime.slice(0, 4);
    var mounth = datetime.slice(4,6);
    var day = datetime.slice(6,8);
    var hour = datetime.slice(9, 13);
    var str = "";
    var hours = datetime.slice(9,11);
    var mins = datetime.slice(11,13);
    str += hours + "h";
    str += mins;

    str += " le " + day + "-" + mounth + "-" + year;
    return str;
}

function aff_planning(idPlanning) {

    if(!planner.journey_list[idPlanning].section_list){
        $("#details").html("Pas d'itinéraire trouvé :'(");
    } else {
        map.removeAllPolylines();
        map.removeAllMarkers();
        var arraypolys = new Array();

        $("#details").html("
");

        for(i=0;i<planner.journey_list[idPlanning].section_list.length;i++) {
            var item = planner.journey_list[idPlanning].section_list[i];
            var point = new mxn.LatLonPoint(item.origin.stop_area.coord.y, item.origin.stop_area.coord.x);
            var marker = new mxn.Marker(point);
            if(i==0) {
                marker.setInfoBubble("Depart");
                //  marker.openBubble();
            } else {
                marker.setInfoBubble("Depart arrivee");
            }
            map.addMarker(marker);
            if(item.type == "PUBLIC_TRANSPORT"){
                var sa_name = item.origin.stop_area.name;
                var line_name = item.line.name;
                $("#details").append("
Depart à " + format(item.departure_date_time)+" de "+ sa_name +" avec la ligne : "+ line_name + "
");
                $("#details").append("
Arrivée à : "+ format(item.arrival_date_time)+"
");
            } else {
                $("details").append("
Marche à pied
");
            }

            for(j=0;j<item.stop_point_list.length;j++) {
                arraypolys.push(new mxn.LatLonPoint(item.stop_point_list[j].coord.y, item.stop_point_list[j].coord.x));
            }
        }
        $("#details").append("
");

        var myPoly = new mxn.Polyline(arraypolys);
        myPoly.setWidth(5);
        map.addPolyline(myPoly);
    }
}

function aff_data(data) {
    fin_requete = new Date().getTime();
    planner = data.planner;

    $("#infos").text("");
    $("div#listecontainer ul").empty();
    if(planner.journey_list){
        for(i=0;i<planner.journey_list.length;++i) {
            $("div#listecontainer ul").append($("
Itineraire "+(i+1)+"
"));
        }
    } else {
        $("#details").append("On a trouvé aucun trajet
");
    }

    aff_planning(0);

    $("#details").append("timer : "+(fin_requete - debut_requete));

}

function planner() {

    if((departure_idx !== -1) && (destination_idx !== -1)) {
        debut_requete = new Date().getTime();
        $.getJSON("../journeys?format=json&origin="+departure_idx+"&destination="+destination_idx+"&datetime="+$("#date").val()+"T"+$("#timeheure").val()+""+$("#timemin").val()+"&date="+
                  +"&clockwise="+$("#typeitineraire option:selected'").val(),
                  aff_data
                  );

    } else {
        alert("Selectionnez une ville");
    }
}

function clickmap(event_name, event_source, event_args) {
    var p = event_args.location;

    if(depart_arrivee.depart.lat === -1) {
        depart_arrivee.depart.lat = p.lat;
        depart_arrivee.depart.lon = p.lon;
        $("#infos").text("Choisissez maintenant une destination");
    } else {
        depart_arrivee.arrivee.lat = p.lat;
        depart_arrivee.arrivee.lon = p.lon;
        $("#infos").text("Calcul en cours ... ");
        debut_requete = new Date().getTime();

        $.getJSON("../journeys?format=json&origin=coord:"+depart_arrivee.depart.lon+":"+depart_arrivee.depart.lat+
                  "&destination=coord:"+depart_arrivee.arrivee.lon+":"+depart_arrivee.arrivee.lat+"&datetime="+$("#date").val()
+"T"+$("#timeheure").val()+""+$("#timemin").val()+"&clockwise="+$("#typeitineraire option:selected'").val(),
                  aff_data
                  );

        depart_arrivee.depart.lat = -1;
    }

}

window.onload= function() {

            map = new mxn.Mapstraction('mapdiv', 'openlayers');
            map.click.addHandler(clickmap);
            $("#go").click(planner);
            $("#centrer").change(function() {
                var sels = $("#centrer option:selected");
                var sel = sels[0].value;
                centrer(sel);
            } );
            centrer("paris");
        }

function centrer(ville) {
    var villes = {
                    "paris" : {"x" :48.85341 ,"y": 2.3488, "zoom" : 13},
                    "lille" : {"x" :50.6367, "y" : 3.0373, "zoom" : 13},
                    "lyon"  : {"x" :45.74846, "y" : 4.84671, "zoom" : 13}
                  };

    var latlon = new mxn.LatLonPoint(villes[ville].x, villes[ville].y);
    map.setCenterAndZoom(latlon, villes[ville].zoom);

}

$(function() {
      $( "#departure" ).autocomplete({
                                         source: function( request, response ) {
                                                     $.ajax({
                                                                url: "http://127.0.0.1/firstletter",
                                                                dataType: "json",
                                                                data: {
                                                                    format : "json",
                                                                    name: request.term,
                                                                },
                                                                success: function( data ) {
                                                                             response( $.map( data.firstletter.items, function( item ) {
                                                                                return {
                                                                                label: item.name,
                                                                                value: item.uri
                                                                                }
                                                                                }));
                                                                         }
                                                            });
                                                 },
                                         minLength: 2,
                                         select: function( event, ui ) {
                                                     departure_idx = ui.item.value;
                                                 },
                                         open: function() {
                                                   $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
                                               },
                                         close: function() {
                                                    $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
                                                }
                                     });

      $( "#destination" ).autocomplete({
                                           source: function( request, response ) {
                                                       $.ajax({
                                                                  url: "http://127.0.0.1/firstletter",
                                                                  dataType: "json",
                                                                  data: {
                                                                      format : "json",
                                                                      name: request.term,
                                                                  },
                                                                  success: function( data ) {
                                                                               response( $.map( data.firstletter.items, function( item ) {
                                                                                return {
                                                                                label: item.name,
                                                                                value: item.uri
                                                                                }

                                                                                }));
                                                                           }
                                                              });
                                                   },
                                           minLength: 2,
                                           select: function( event, ui ) {
                                                       destination_idx = ui.item.value;
                                                   },
                                           open: function() {
                                                     $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
                                                 },
                                           close: function() {
                                                      $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
                                                  }
                                       });

  });
<commit_msg>Démoplanner : intégration du cheminement piéton<commit_after>var map;

var depart_arrivee = {
    depart :  { lat : -1, lon : -1},
    arrivee : { lat : -1, lon : -1}
};

var planner;

var destination_idx = -1;
var departure_idx = -1;
var debut_requete = -1;
var fin_requete = -1;
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

function format(datetime){

    datetime.trim();

    var year = datetime.slice(0, 4);
    var mounth = datetime.slice(4,6);
    var day = datetime.slice(6,8);
    var hour = datetime.slice(9, 13);
    var str = "";
    var hours = datetime.slice(9,11);
    var mins = datetime.slice(11,13);
    str += hours + "h";
    str += mins;

    str += " le " + day + "-" + mounth + "-" + year;
    return str;
}

function aff_planning(idPlanning) {

    if(!planner.journey_list[idPlanning].section_list){
        $("#details").html("Pas d'itinéraire trouvé :'(");
    } else {
        map.removeAllPolylines();
        map.removeAllMarkers();

        $("#details").html("
");

        for(i=0;i<planner.journey_list[idPlanning].section_list.length;i++) {
            var item = planner.journey_list[idPlanning].section_list[i];
            if(item.type === "PUBLIC_TRANSPORT"){
                var point = new mxn.LatLonPoint(item.origin.stop_area.coord.y, item.origin.stop_area.coord.x);
                var marker = new mxn.Marker(point);
                map.addMarker(marker);
                if(i==0) {
                    marker.setInfoBubble("Depart");
                    //  marker.openBubble();
                } else {
                    marker.setInfoBubble("Depart arrivee");
                }
                var sa_name = item.origin.stop_area.name;
                var line_name = item.line.name;
                $("#details").append("
Depart à " + format(item.departure_date_time)+" de "+ sa_name +" avec la ligne : "+ line_name + "
");
                $("#details").append("
Arrivée à : "+ format(item.arrival_date_time)+"
");
                var arraypolys = new Array();
                for(j=0;j<item.stop_point_list.length;j++) {
                    arraypolys.push(new mxn.LatLonPoint(item.stop_point_list[j].coord.y, item.stop_point_list[j].coord.x));
                }
                var myPoly = new mxn.Polyline(arraypolys);
                myPoly.setWidth(5);
                map.addPolyline(myPoly);

            } else if(item.type === "ROAD_NETWORK") {
                $("details").append("
Marche à pied sur " + item.street_network.length +" mètres
");
                var arraypolys = new Array();
                for(j=0 ; j < item.street_network.coordinate_list.length; j++){
                    arraypolys.push(new mxn.LatLonPoint(item.street_network.coordinate_list[j].y, item.street_network.coordinate_list[j].x));
                }
                var myPoly = new mxn.Polyline(arraypolys);
                myPoly.setWidth(2);
                map.addPolyline(myPoly);
            }

        }
        $("#details").append("
");

    }
}

function aff_data(data) {
    fin_requete = new Date().getTime();
    planner = data.planner;

    $("#infos").text("");
    $("div#listecontainer ul").empty();
    if(planner.journey_list){
        for(i=0;i<planner.journey_list.length;++i) {
            $("div#listecontainer ul").append($("
Itineraire "+(i+1)+"
"));
        }
    } else {
        $("#details").append("On a trouvé aucun trajet
");
    }

    aff_planning(0);

    $("#details").append("timer : "+(fin_requete - debut_requete));

}

function planner() {

    if((departure_idx !== -1) && (destination_idx !== -1)) {
        debut_requete = new Date().getTime();
        $.getJSON("../journeys?format=json&origin="+departure_idx+"&destination="+destination_idx+"&datetime="+$("#date").val()+"T"+$("#timeheure").val()+""+$("#timemin").val()+"&date="+
                +"&clockwise="+$("#typeitineraire option:selected'").val(),
                aff_data
                );

    } else {
        alert("Selectionnez une ville");
    }
}

function clickmap(event_name, event_source, event_args) {
    var p = event_args.location;

    if(depart_arrivee.depart.lat === -1) {
        depart_arrivee.depart.lat = p.lat;
        depart_arrivee.depart.lon = p.lon;
        $("#infos").text("Choisissez maintenant une destination");
    } else {
        depart_arrivee.arrivee.lat = p.lat;
        depart_arrivee.arrivee.lon = p.lon;
        $("#infos").text("Calcul en cours ... ");
        debut_requete = new Date().getTime();

        $.getJSON("../journeys?format=json&origin=coord:"+depart_arrivee.depart.lon+":"+depart_arrivee.depart.lat+
                "&destination=coord:"+depart_arrivee.arrivee.lon+":"+depart_arrivee.arrivee.lat+"&datetime="+$("#date").val()
                +"T"+$("#timeheure").val()+""+$("#timemin").val()+"&clockwise="+$("#typeitineraire option:selected'").val(),
                aff_data
                );

        depart_arrivee.depart.lat = -1;
    }

}

window.onload= function() {

    map = new mxn.Mapstraction('mapdiv', 'openlayers');
    map.click.addHandler(clickmap);
    $("#go").click(planner);
    $("#centrer").change(function() {
        var sels = $("#centrer option:selected");
        var sel = sels[0].value;
        centrer(sel);
    } );
    centrer("paris");
}

function centrer(ville) {
    var villes = {
        "paris" : {"x" :48.85341 ,"y": 2.3488, "zoom" : 13},
        "lille" : {"x" :50.6367, "y" : 3.0373, "zoom" : 13},
        "lyon"  : {"x" :45.74846, "y" : 4.84671, "zoom" : 13}
    };

    var latlon = new mxn.LatLonPoint(villes[ville].x, villes[ville].y);
    map.setCenterAndZoom(latlon, villes[ville].zoom);

}

$(function() {
    $( "#departure" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "http://127.0.0.1/firstletter",
            dataType: "json",
            data: {
                format : "json",
            name: request.term,
            },
            success: function( data ) {
                response( $.map( data.firstletter.items, function( item ) {
                    return {
                        label: item.name,
                value: item.uri
                    }
                }));
            }
            });
        },
    minLength: 2,
    select: function( event, ui ) {
        departure_idx = ui.item.value;
    },
    open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
    },
    close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
    }
    });

    $( "#destination" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "http://127.0.0.1/firstletter",
                dataType: "json",
                data: {
                    format : "json",
                name: request.term,
                },
                success: function( data ) {
                    response( $.map( data.firstletter.items, function( item ) {
                        return {
                            label: item.name,
                    value: item.uri
                        }

                    }));
                }
            });
        },
            minLength: 2,
            select: function( event, ui ) {
                destination_idx = ui.item.value;
            },
            open: function() {
                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
            },
            close: function() {
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
            }
    });

});
<|endoftext|>


<commit_before>fdefineSuite([
        'DataSources/StaticGroundPolylinePerMaterialBatch',
        'Core/ApproximateTerrainHeights',
        'Core/BoundingSphere',
        'Core/Cartesian3',
        'Core/Color',
        'Core/defined',
        'Core/DistanceDisplayCondition',
        'Core/JulianDate',
        'Core/Math',
        'Core/TimeInterval',
        'Core/TimeIntervalCollection',
        'DataSources/BoundingSphereState',
        'DataSources/ColorMaterialProperty',
        'DataSources/ConstantProperty',
        'DataSources/Entity',
        'DataSources/PolylineOutlineMaterialProperty',
        'DataSources/PolylineGeometryUpdater',
        'DataSources/PolylineGraphics',
        'DataSources/TimeIntervalCollectionProperty',
        'Scene/GroundPolylinePrimitive',
        'Specs/createScene',
        'Specs/pollToPromise'
    ], function(
        StaticGroundPolylinePerMaterialBatch,
        ApproximateTerrainHeights,
        BoundingSphere,
        Cartesian3,
        Color,
        defined,
        DistanceDisplayCondition,
        JulianDate,
        CesiumMath,
        TimeInterval,
        TimeIntervalCollection,
        BoundingSphereState,
        ColorMaterialProperty,
        ConstantProperty,
        Entity,
        PolylineOutlineMaterialProperty,
        PolylineGeometryUpdater,
        PolylineGraphics,
        TimeIntervalCollectionProperty,
        GroundPolylinePrimitive,
        createScene,
        pollToPromise) {
    'use strict';

    var time = JulianDate.now();
    var batch;
    var scene;
    beforeAll(function() {
        scene = createScene();

        return GroundPolylinePrimitive.initializeTerrainHeights();
    });

    afterAll(function() {
        scene.destroyForSpecs();

        GroundPolylinePrimitive._initPromise = undefined;
        GroundPolylinePrimitive._initialized = false;

        ApproximateTerrainHeights._initPromise = undefined;
        ApproximateTerrainHeights._terrainHeights = undefined;
    });

    afterEach(function() {
        if (defined(batch)) {
            batch.removeAllPrimitives();
            batch = undefined;
        }
    });

    function createGroundPolyline() {
        var polyline = new PolylineGraphics();
        polyline.clampToGround = new ConstantProperty(true);
        polyline.positions = new ConstantProperty(Cartesian3.fromDegreesArray([
            0, 0,
            0.1, 0,
            0.1, 0.1,
            0, 0.1
        ]));
        return polyline;
    }

    it('handles shared material being invalidated with geometry', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();

        var entity = new Entity({
            polyline : polyline1
        });

        var polyline2 = createGroundPolyline();
        polyline2.material = new PolylineOutlineMaterialProperty();

        var entity2 = new Entity({
            polyline : polyline2
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);
        batch.add(time, updater);
        batch.add(time, updater2);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);
            polyline1.material.outlineWidth = new ConstantProperty(0.5);

            return pollToPromise(function() {
                scene.initializeFrame();
                var isUpdated = batch.update(time);
                scene.render(time);
                return isUpdated;
            }).then(function() {
                expect(scene.groundPrimitives.length).toEqual(2);
                batch.removeAllPrimitives();
            });
        });
    });

    it('updates with sampled color out of range', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        var validTime = JulianDate.fromIso8601('2018-02-14T04:10:00+1100');
        var color = new TimeIntervalCollectionProperty();
        color.intervals.addInterval(TimeInterval.fromIso8601({
            iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100',
            data: Color.RED
        }));
        var polyline = createGroundPolyline();
        polyline.material = new ColorMaterialProperty(color);
        var entity = new Entity({
            availability: new TimeIntervalCollection([TimeInterval.fromIso8601({iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100'})]),
            polyline: polyline
        });

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var updater = new PolylineGeometryUpdater(entity, scene);
        batch.add(validTime, updater);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(validTime);
            scene.render(validTime);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);
            var primitive = scene.groundPrimitives.get(0);
            var attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.color).toEqual([255, 0, 0, 255]);

            batch.update(time);
            scene.render(time);

            primitive = scene.groundPrimitives.get(0);
            attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.color).toEqual([255, 255, 255, 255]);

            batch.removeAllPrimitives();
        });
    });

    it('updates with sampled distance display condition out of range', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }
        var validTime = JulianDate.fromIso8601('2018-02-14T04:10:00+1100');
        var ddc = new TimeIntervalCollectionProperty();
        ddc.intervals.addInterval(TimeInterval.fromIso8601({
            iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100',
            data: new DistanceDisplayCondition(1.0, 2.0)
        }));

        var polyline = createGroundPolyline();
        polyline.distanceDisplayCondition = ddc;
        var entity = new Entity({
            availability: new TimeIntervalCollection([TimeInterval.fromIso8601({iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100'})]),
            polyline: polyline
        });

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var updater = new PolylineGeometryUpdater(entity, scene);
        batch.add(validTime, updater);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(validTime);
            scene.render(validTime);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);
            var primitive = scene.groundPrimitives.get(0);
            var attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.distanceDisplayCondition).toEqualEpsilon([1.0, 2.0], CesiumMath.EPSILON6);

            batch.update(time);
            scene.render(time);

            primitive = scene.groundPrimitives.get(0);
            attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.distanceDisplayCondition).toEqual([0.0, Infinity]);

            batch.removeAllPrimitives();
        });
    });

    it('shows only one primitive while rebuilding primitive', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        function buildEntity() {
            var polyline = createGroundPolyline();
            polyline.material = new PolylineOutlineMaterialProperty({
                color : Color.ORANGE,
                outlineWidth : 2,
                outlineColor : Color.BLACK
            });

            return new Entity({
                polyline : polyline
            });
        }

        function renderScene() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }

        var entity1 = buildEntity();
        var entity2 = buildEntity();

        var updater1 = new PolylineGeometryUpdater(entity1, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);

        batch.add(time, updater1);
        return pollToPromise(renderScene)
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                expect(primitive.show).toBeTruthy();
            })
            .then(function() {
                batch.add(time, updater2);
            })
            .then(function() {
                return pollToPromise(function() {
                    renderScene();
                    return scene.groundPrimitives.length === 2;
                });
            })
            .then(function() {
                var showCount = 0;
                expect(scene.groundPrimitives.length).toEqual(2);
                showCount += !!scene.groundPrimitives.get(0).show;
                showCount += !!scene.groundPrimitives.get(1).show;
                expect(showCount).toEqual(1);
            })
            .then(function() {
                return pollToPromise(renderScene);
            })
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                expect(primitive.show).toBeTruthy();

                batch.removeAllPrimitives();
            });
    });

    it('batches entities that both use color materials', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);
        var polyline1 = createGroundPolyline();
        polyline1.material = Color.RED;
        var entity = new Entity({
            polyline : polyline1
        });

        var polyline2 = createGroundPolyline();
        polyline2.material = Color.RED;
        var entity2 = new Entity({
            polyline : polyline2
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);
        batch.add(time, updater);
        batch.add(time, updater2);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);

            batch.removeAllPrimitives();
        });
    });

    it('batches entities with the same material but different Z indices separately', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();
        polyline1.zIndex = 0;

        var entity = new Entity({
            polyline : polyline1
        });

        var polyline2 = createGroundPolyline();
        polyline2.material = new PolylineOutlineMaterialProperty();
        polyline2.zIndex = 1;

        var entity2 = new Entity({
            polyline : polyline2
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);
        batch.add(time, updater);
        batch.add(time, updater2);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(2);

            batch.removeAllPrimitives();
        });
    });

    it('removes entities', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();

        var entity = new Entity({
            polyline : polyline1
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        batch.add(time, updater);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);

            batch.remove(updater);

            return pollToPromise(function() {
                scene.initializeFrame();
                var isUpdated = batch.update(time);
                scene.render(time);
                return isUpdated;
            });
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(0);
            batch.removeAllPrimitives();
        });
    });

    it('gets bounding spheres', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        var resultSphere = new BoundingSphere();
        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();

        var entity = new Entity({
            polyline : polyline1
        });

        var updater = new PolylineGeometryUpdater(entity, scene);

        var state = batch.getBoundingSphere(updater, resultSphere);
        expect(state).toEqual(BoundingSphereState.FAILED);

        batch.add(time, updater);

        batch.update(time);
        state = batch.getBoundingSphere(updater, resultSphere);
        expect(state).toEqual(BoundingSphereState.PENDING);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);

            state = batch.getBoundingSphere(updater, resultSphere);
            expect(state).toEqual(BoundingSphereState.DONE);

            batch.removeAllPrimitives();
        });
    });

    it('has correct show attribute after rebuilding primitive', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }
        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        function buildEntity() {
            var polyline = createGroundPolyline();
            polyline.material = new PolylineOutlineMaterialProperty({
                color : Color.ORANGE,
                outlineWidth : 2,
                outlineColor : Color.BLACK
            });

            return new Entity({
                polyline : polyline
            });
        }

        function renderScene() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }

        var entity1 = buildEntity();
        var updater1 = new PolylineGeometryUpdater(entity1, scene);
        batch.add(time, updater1);

        var entity2 = buildEntity();
        var updater2 = new PolylineGeometryUpdater(entity2, scene);

        return pollToPromise(renderScene)
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                var attributes = primitive.getGeometryInstanceAttributes(entity1);
                expect(attributes.show).toEqual([1]);

                entity1.show = false;
                updater1._onEntityPropertyChanged(entity1, 'isShowing');
                return pollToPromise(renderScene);
            })
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                var attributes = primitive.getGeometryInstanceAttributes(entity1);
                expect(attributes.show).toEqual([0]);

                batch.add(time, updater2);
                return pollToPromise(renderScene);
            })
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                var attributes = primitive.getGeometryInstanceAttributes(entity1);
                expect(attributes.show).toEqual([0]);

                attributes = primitive.getGeometryInstanceAttributes(entity2);
                expect(attributes.show).toEqual([1]);

                batch.removeAllPrimitives();
            });
    });
});
<commit_msg>Remove fdefineSuite<commit_after>defineSuite([
        'DataSources/StaticGroundPolylinePerMaterialBatch',
        'Core/ApproximateTerrainHeights',
        'Core/BoundingSphere',
        'Core/Cartesian3',
        'Core/Color',
        'Core/defined',
        'Core/DistanceDisplayCondition',
        'Core/JulianDate',
        'Core/Math',
        'Core/TimeInterval',
        'Core/TimeIntervalCollection',
        'DataSources/BoundingSphereState',
        'DataSources/ColorMaterialProperty',
        'DataSources/ConstantProperty',
        'DataSources/Entity',
        'DataSources/PolylineOutlineMaterialProperty',
        'DataSources/PolylineGeometryUpdater',
        'DataSources/PolylineGraphics',
        'DataSources/TimeIntervalCollectionProperty',
        'Scene/GroundPolylinePrimitive',
        'Specs/createScene',
        'Specs/pollToPromise'
    ], function(
        StaticGroundPolylinePerMaterialBatch,
        ApproximateTerrainHeights,
        BoundingSphere,
        Cartesian3,
        Color,
        defined,
        DistanceDisplayCondition,
        JulianDate,
        CesiumMath,
        TimeInterval,
        TimeIntervalCollection,
        BoundingSphereState,
        ColorMaterialProperty,
        ConstantProperty,
        Entity,
        PolylineOutlineMaterialProperty,
        PolylineGeometryUpdater,
        PolylineGraphics,
        TimeIntervalCollectionProperty,
        GroundPolylinePrimitive,
        createScene,
        pollToPromise) {
    'use strict';

    var time = JulianDate.now();
    var batch;
    var scene;
    beforeAll(function() {
        scene = createScene();

        return GroundPolylinePrimitive.initializeTerrainHeights();
    });

    afterAll(function() {
        scene.destroyForSpecs();

        GroundPolylinePrimitive._initPromise = undefined;
        GroundPolylinePrimitive._initialized = false;

        ApproximateTerrainHeights._initPromise = undefined;
        ApproximateTerrainHeights._terrainHeights = undefined;
    });

    afterEach(function() {
        if (defined(batch)) {
            batch.removeAllPrimitives();
            batch = undefined;
        }
    });

    function createGroundPolyline() {
        var polyline = new PolylineGraphics();
        polyline.clampToGround = new ConstantProperty(true);
        polyline.positions = new ConstantProperty(Cartesian3.fromDegreesArray([
            0, 0,
            0.1, 0,
            0.1, 0.1,
            0, 0.1
        ]));
        return polyline;
    }

    it('handles shared material being invalidated with geometry', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();

        var entity = new Entity({
            polyline : polyline1
        });

        var polyline2 = createGroundPolyline();
        polyline2.material = new PolylineOutlineMaterialProperty();

        var entity2 = new Entity({
            polyline : polyline2
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);
        batch.add(time, updater);
        batch.add(time, updater2);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);
            polyline1.material.outlineWidth = new ConstantProperty(0.5);

            return pollToPromise(function() {
                scene.initializeFrame();
                var isUpdated = batch.update(time);
                scene.render(time);
                return isUpdated;
            }).then(function() {
                expect(scene.groundPrimitives.length).toEqual(2);
                batch.removeAllPrimitives();
            });
        });
    });

    it('updates with sampled color out of range', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        var validTime = JulianDate.fromIso8601('2018-02-14T04:10:00+1100');
        var color = new TimeIntervalCollectionProperty();
        color.intervals.addInterval(TimeInterval.fromIso8601({
            iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100',
            data: Color.RED
        }));
        var polyline = createGroundPolyline();
        polyline.material = new ColorMaterialProperty(color);
        var entity = new Entity({
            availability: new TimeIntervalCollection([TimeInterval.fromIso8601({iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100'})]),
            polyline: polyline
        });

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var updater = new PolylineGeometryUpdater(entity, scene);
        batch.add(validTime, updater);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(validTime);
            scene.render(validTime);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);
            var primitive = scene.groundPrimitives.get(0);
            var attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.color).toEqual([255, 0, 0, 255]);

            batch.update(time);
            scene.render(time);

            primitive = scene.groundPrimitives.get(0);
            attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.color).toEqual([255, 255, 255, 255]);

            batch.removeAllPrimitives();
        });
    });

    it('updates with sampled distance display condition out of range', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }
        var validTime = JulianDate.fromIso8601('2018-02-14T04:10:00+1100');
        var ddc = new TimeIntervalCollectionProperty();
        ddc.intervals.addInterval(TimeInterval.fromIso8601({
            iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100',
            data: new DistanceDisplayCondition(1.0, 2.0)
        }));

        var polyline = createGroundPolyline();
        polyline.distanceDisplayCondition = ddc;
        var entity = new Entity({
            availability: new TimeIntervalCollection([TimeInterval.fromIso8601({iso8601: '2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100'})]),
            polyline: polyline
        });

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var updater = new PolylineGeometryUpdater(entity, scene);
        batch.add(validTime, updater);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(validTime);
            scene.render(validTime);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);
            var primitive = scene.groundPrimitives.get(0);
            var attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.distanceDisplayCondition).toEqualEpsilon([1.0, 2.0], CesiumMath.EPSILON6);

            batch.update(time);
            scene.render(time);

            primitive = scene.groundPrimitives.get(0);
            attributes = primitive.getGeometryInstanceAttributes(entity);
            expect(attributes.distanceDisplayCondition).toEqual([0.0, Infinity]);

            batch.removeAllPrimitives();
        });
    });

    it('shows only one primitive while rebuilding primitive', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        function buildEntity() {
            var polyline = createGroundPolyline();
            polyline.material = new PolylineOutlineMaterialProperty({
                color : Color.ORANGE,
                outlineWidth : 2,
                outlineColor : Color.BLACK
            });

            return new Entity({
                polyline : polyline
            });
        }

        function renderScene() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }

        var entity1 = buildEntity();
        var entity2 = buildEntity();

        var updater1 = new PolylineGeometryUpdater(entity1, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);

        batch.add(time, updater1);
        return pollToPromise(renderScene)
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                expect(primitive.show).toBeTruthy();
            })
            .then(function() {
                batch.add(time, updater2);
            })
            .then(function() {
                return pollToPromise(function() {
                    renderScene();
                    return scene.groundPrimitives.length === 2;
                });
            })
            .then(function() {
                var showCount = 0;
                expect(scene.groundPrimitives.length).toEqual(2);
                showCount += !!scene.groundPrimitives.get(0).show;
                showCount += !!scene.groundPrimitives.get(1).show;
                expect(showCount).toEqual(1);
            })
            .then(function() {
                return pollToPromise(renderScene);
            })
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                expect(primitive.show).toBeTruthy();

                batch.removeAllPrimitives();
            });
    });

    it('batches entities that both use color materials', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);
        var polyline1 = createGroundPolyline();
        polyline1.material = Color.RED;
        var entity = new Entity({
            polyline : polyline1
        });

        var polyline2 = createGroundPolyline();
        polyline2.material = Color.RED;
        var entity2 = new Entity({
            polyline : polyline2
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);
        batch.add(time, updater);
        batch.add(time, updater2);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);

            batch.removeAllPrimitives();
        });
    });

    it('batches entities with the same material but different Z indices separately', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();
        polyline1.zIndex = 0;

        var entity = new Entity({
            polyline : polyline1
        });

        var polyline2 = createGroundPolyline();
        polyline2.material = new PolylineOutlineMaterialProperty();
        polyline2.zIndex = 1;

        var entity2 = new Entity({
            polyline : polyline2
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        var updater2 = new PolylineGeometryUpdater(entity2, scene);
        batch.add(time, updater);
        batch.add(time, updater2);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(2);

            batch.removeAllPrimitives();
        });
    });

    it('removes entities', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();

        var entity = new Entity({
            polyline : polyline1
        });

        var updater = new PolylineGeometryUpdater(entity, scene);
        batch.add(time, updater);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);

            batch.remove(updater);

            return pollToPromise(function() {
                scene.initializeFrame();
                var isUpdated = batch.update(time);
                scene.render(time);
                return isUpdated;
            });
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(0);
            batch.removeAllPrimitives();
        });
    });

    it('gets bounding spheres', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }

        var resultSphere = new BoundingSphere();
        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        var polyline1 = createGroundPolyline();
        polyline1.material = new PolylineOutlineMaterialProperty();

        var entity = new Entity({
            polyline : polyline1
        });

        var updater = new PolylineGeometryUpdater(entity, scene);

        var state = batch.getBoundingSphere(updater, resultSphere);
        expect(state).toEqual(BoundingSphereState.FAILED);

        batch.add(time, updater);

        batch.update(time);
        state = batch.getBoundingSphere(updater, resultSphere);
        expect(state).toEqual(BoundingSphereState.PENDING);

        return pollToPromise(function() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }).then(function() {
            expect(scene.groundPrimitives.length).toEqual(1);

            state = batch.getBoundingSphere(updater, resultSphere);
            expect(state).toEqual(BoundingSphereState.DONE);

            batch.removeAllPrimitives();
        });
    });

    it('has correct show attribute after rebuilding primitive', function() {
        if (!GroundPolylinePrimitive.isSupported(scene)) {
            // Don't fail if GroundPolylinePrimitive is not supported
            return;
        }
        batch = new StaticGroundPolylinePerMaterialBatch(scene.groundPrimitives, false);

        function buildEntity() {
            var polyline = createGroundPolyline();
            polyline.material = new PolylineOutlineMaterialProperty({
                color : Color.ORANGE,
                outlineWidth : 2,
                outlineColor : Color.BLACK
            });

            return new Entity({
                polyline : polyline
            });
        }

        function renderScene() {
            scene.initializeFrame();
            var isUpdated = batch.update(time);
            scene.render(time);
            return isUpdated;
        }

        var entity1 = buildEntity();
        var updater1 = new PolylineGeometryUpdater(entity1, scene);
        batch.add(time, updater1);

        var entity2 = buildEntity();
        var updater2 = new PolylineGeometryUpdater(entity2, scene);

        return pollToPromise(renderScene)
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                var attributes = primitive.getGeometryInstanceAttributes(entity1);
                expect(attributes.show).toEqual([1]);

                entity1.show = false;
                updater1._onEntityPropertyChanged(entity1, 'isShowing');
                return pollToPromise(renderScene);
            })
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                var attributes = primitive.getGeometryInstanceAttributes(entity1);
                expect(attributes.show).toEqual([0]);

                batch.add(time, updater2);
                return pollToPromise(renderScene);
            })
            .then(function() {
                expect(scene.groundPrimitives.length).toEqual(1);
                var primitive = scene.groundPrimitives.get(0);
                var attributes = primitive.getGeometryInstanceAttributes(entity1);
                expect(attributes.show).toEqual([0]);

                attributes = primitive.getGeometryInstanceAttributes(entity2);
                expect(attributes.show).toEqual([1]);

                batch.removeAllPrimitives();
            });
    });
});
<|endoftext|>


<commit_before>/**
 *
 * SugarCRM Community Edition is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
 *
 * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
 * Copyright (C) 2011 - 2016 SalesAgility Ltd.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
 */
$(document).ready(function () {
    loadSidebar();
    $("ul.clickMenu").each(function (index, node) {
        $(node).sugarActionMenu();
    });
    // Back to top animation
    $('#backtotop').click(function(event) {
        event.preventDefault();
        $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
    });
});
YAHOO.util.Event.onAvailable('sitemapLinkSpan', function () {
    document.getElementById('sitemapLinkSpan').onclick = function () {
        ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING_PAGE'));
        var smMarkup = '';
        var callback = {
            success: function (r) {
                ajaxStatus.hideStatus();
                document.getElementById('sm_holder').innerHTML = r.responseText;
                with (document.getElementById('sitemap').style) {
                    display = "block";
                    position = "absolute";
                    right = 0;
                    top = 80;
                }
                document.getElementById('sitemapClose').onclick = function () {
                    document.getElementById('sitemap').style.display = "none";
                }
            }
        }
        postData = 'module=Home&action=sitemap&GetSiteMap=now&sugar_body_only=true';
        YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, postData);
    }
});
function IKEADEBUG() {
    var moduleLinks = document.getElementById('moduleList').getElementsByTagName("a");
    moduleLinkMouseOver = function () {
        var matches = /grouptab_([0-9]+)/i.exec(this.id);
        var tabNum = matches[1];
        var moduleGroups = document.getElementById('subModuleList').getElementsByTagName("span");
        for (var i = 0; i < moduleGroups.length; i++) {
            if (i == tabNum) {
                moduleGroups[i].className = 'selected';
            }
            else {
                moduleGroups[i].className = '';
            }
        }
        var groupList = document.getElementById('moduleList').getElementsByTagName("li");
        var currentGroupItem = tabNum;
        for (var i = 0; i < groupList.length; i++) {
            var aElem = groupList[i].getElementsByTagName("a")[0];
            if (aElem == null) {
                continue;
            }
            var classStarter = 'notC';
            if (aElem.id == "grouptab_" + tabNum) {
                classStarter = 'c';
                currentGroupItem = i;
            }
            var spanTags = groupList[i].getElementsByTagName("span");
            for (var ii = 0; ii < spanTags.length; ii++) {
                if (spanTags[ii].className == null) {
                    continue;
                }
                var oldClass = spanTags[ii].className.match(/urrentTab.*/);
                spanTags[ii].className = classStarter + oldClass;
            }
        }
        var menuHandle = moduleGroups[tabNum];
        var parentMenu = groupList[currentGroupItem];
        if (menuHandle && parentMenu) {
            updateSubmenuPosition(menuHandle, parentMenu);
        }
    };
    for (var i = 0; i < moduleLinks.length; i++) {
        moduleLinks[i].onmouseover = moduleLinkMouseOver;
    }
};
function updateSubmenuPosition(menuHandle, parentMenu) {
    var left = '';
    if (left == "") {
        p = parentMenu;
        var left = 0;
        while (p && p.tagName.toUpperCase() != 'BODY') {
            left += p.offsetLeft;
            p = p.offsetParent;
        }
    }
    var bw = checkBrowserWidth();
    if (!parentMenu) {
        return;
    }
    var groupTabLeft = left + (parentMenu.offsetWidth / 2);
    var subTabHalfLength = 0;
    var children = menuHandle.getElementsByTagName('li');
    for (var i = 0; i < children.length; i++) {
        if (children[i].className == 'subTabMore' || children[i].parentNode.className == 'cssmenu') {
            continue;
        }
        subTabHalfLength += parseInt(children[i].offsetWidth);
    }
    if (subTabHalfLength != 0) {
        subTabHalfLength = subTabHalfLength / 2;
    }
    var totalLengthInTheory = subTabHalfLength + groupTabLeft;
    if (subTabHalfLength > 0 && groupTabLeft > 0) {
        if (subTabHalfLength >= groupTabLeft) {
            left = 1;
        } else {
            left = groupTabLeft - subTabHalfLength;
        }
    }
    if (totalLengthInTheory > bw) {
        var differ = totalLengthInTheory - bw;
        left = groupTabLeft - subTabHalfLength - differ - 2;
    }
    if (left >= 0) {
        menuHandle.style.marginLeft = left + 'px';
    }
}
YAHOO.util.Event.onDOMReady(function () {
    if (document.getElementById('subModuleList')) {
        var parentMenu = false;
        var moduleListDom = document.getElementById('moduleList');
        if (moduleListDom != null) {
            var parentTabLis = moduleListDom.getElementsByTagName("li");
            var tabNum = 0;
            for (var ii = 0; ii < parentTabLis.length; ii++) {
                var spans = parentTabLis[ii].getElementsByTagName("span");
                for (var jj = 0; jj < spans.length; jj++) {
                    if (spans[jj].className.match(/currentTab.*/)) {
                        tabNum = ii;
                    }
                }
            }
            var parentMenu = parentTabLis[tabNum];
        }
        var moduleGroups = document.getElementById('subModuleList').getElementsByTagName("span");
        for (var i = 0; i < moduleGroups.length; i++) {
            if (moduleGroups[i].className.match(/selected/)) {
                tabNum = i;
            }
        }
        var menuHandle = moduleGroups[tabNum];
        if (menuHandle && parentMenu) {
            updateSubmenuPosition(menuHandle, parentMenu);
        }
    }
});
SUGAR.themes = SUGAR.namespace("themes");
SUGAR.append(SUGAR.themes, {
    allMenuBars: {}, setModuleTabs: function (html) {
        var el = document.getElementById('ajaxHeader');
        if (el) {
            $('#ajaxHeader').html(html);
            loadSidebar();
            if ($(window).width() < 979) {
                $('#bootstrap-container').removeClass('main');
            }
        }
    }, actionMenu: function () {
        $("ul.clickMenu").each(function (index, node) {
            $(node).sugarActionMenu();
        });
    }, loadModuleList: function () {
        var nodes = YAHOO.util.Selector.query('#moduleList>div'), currMenuBar;
        this.allMenuBars = {};
        for (var i = 0; i < nodes.length; i++) {
            currMenuBar = SUGAR.themes.currMenuBar = new YAHOO.widget.MenuBar(nodes[i].id, {
                autosubmenudisplay: true,
                visible: false,
                hidedelay: 750,
                lazyload: true
            });
            currMenuBar.render();
            this.allMenuBars[nodes[i].id.substr(nodes[i].id.indexOf('_') + 1)] = currMenuBar;
            if (typeof YAHOO.util.Dom.getChildren(nodes[i]) == 'object' && YAHOO.util.Dom.getChildren(nodes[i]).shift().style.display != 'none') {
                oMenuBar = currMenuBar;
            }
        }
        YAHOO.util.Event.onAvailable('subModuleList', IKEADEBUG);
    }, setCurrentTab: function () {
    }
});
YAHOO.util.Event.onDOMReady(SUGAR.themes.loadModuleList, SUGAR.themes, true);

// Custom jQuery for theme

// Script to toggle copyright popup
$( "button" ).click(function() {
    $( "#sugarcopy" ).toggle();

});

// Custom JavaScript for copyright pop-ups
$(function() {
    $( "#dialog, #dialog2" ).dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 100
        },
        hide: {
            effect: "fade",
            duration: 1000
        }
    });
    $( "#powered_by" ).click(function() {
        $( "#dialog" ).dialog( "open" );
        $("#overlay").show().css({"opacity": "0.5"});
    });
    $( "#admin_options" ).click(function() {
        $( "#dialog2" ).dialog( "open" );
    });
});

// Back to top animation
$('#backtotop').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
});

// Tabs jQuery for Admin panel
$(function() {
    var tabs = $( "#tabs" ).tabs();
    tabs.find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        stop: function() {
            tabs.tabs( "refresh" );
        }
    });
});

jQuery(function($){
    $('table.footable').footable({
        "breakpoints": {
            "x-small": 480,
            "small": 768,
            "medium": 992,
            "large": 1200,
            "x-large": 1400
        }
    });
})

// JavaScript fix to remove unrequired classes on smaller screens where sidebar is obsolete
$(window).resize(function () {
    if ($(window).width() < 979) {
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 sidebar main');
    }
    if ($(window).width() > 980 && $('.sidebar').is(':visible')) {
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
});

// jQuery to toggle sidebar
function loadSidebar() {
    if($('#sidebar_container').length) {
        $('#buttontoggle').click(function () {
            $('.sidebar').toggle();
            if ($('.sidebar').is(':visible')) {
                $.cookie('sidebartoggle', 'expanded');
                $('#buttontoggle').removeClass('button-toggle-collapsed');
                $('#buttontoggle').addClass('button-toggle-expanded');
                $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
            }
            if ($('.sidebar').is(':hidden')) {
                $.cookie('sidebartoggle', 'collapsed');
                $('#buttontoggle').removeClass('button-toggle-expanded');
                $('#buttontoggle').addClass('button-toggle-collapsed');
                $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
            }
        });

        var sidebartoggle = $.cookie('sidebartoggle');
        if (sidebartoggle == 'collapsed') {
            $('.sidebar').hide();
            $('#buttontoggle').removeClass('button-toggle-expanded');
            $('#buttontoggle').addClass('button-toggle-collapsed');
            $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
        }
        else {
            $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
            $('#buttontoggle').removeClass('button-toggle-collapsed');
            $('#buttontoggle').addClass('button-toggle-expanded');
        }
    }
}

update_screen_resolution();

    $(window).resize(function () {
        update_screen_resolution();
    });

function update_screen_resolution(){
    $.ajax({
        url: 'index.php?module=Calendar&action=processScreenSize',
        type: 'post',
        data: { 'width' : $( window ).width(), 'height' : $( window ).height(), 'to_pdf': true}
    });
}

// Alerts Notification
$(document).ready(function() {
    $('#alert-nav').click(function() {
        $('#alert-nav #alerts').css('display', 'inherit');
    });
});

function changeFirstTab(src) {
    var selected = $(src);
    var selectedHtml = $(selected.context).html();
    $('#xstab0').html(selectedHtml);
    return true;
}
// End of custom jQuery
<commit_msg>fix for task 196 - SuiteP Theme – User Profile, All options on one screen (Regardless of Current Tab)<commit_after>/**
 *
 * SugarCRM Community Edition is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
 *
 * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
 * Copyright (C) 2011 - 2016 SalesAgility Ltd.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
 */
$(document).ready(function () {
    loadSidebar();
    $("ul.clickMenu").each(function (index, node) {
        $(node).sugarActionMenu();
    });
    // Back to top animation
    $('#backtotop').click(function(event) {
        event.preventDefault();
        $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
    });
});
YAHOO.util.Event.onAvailable('sitemapLinkSpan', function () {
    document.getElementById('sitemapLinkSpan').onclick = function () {
        ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING_PAGE'));
        var smMarkup = '';
        var callback = {
            success: function (r) {
                ajaxStatus.hideStatus();
                document.getElementById('sm_holder').innerHTML = r.responseText;
                with (document.getElementById('sitemap').style) {
                    display = "block";
                    position = "absolute";
                    right = 0;
                    top = 80;
                }
                document.getElementById('sitemapClose').onclick = function () {
                    document.getElementById('sitemap').style.display = "none";
                }
            }
        }
        postData = 'module=Home&action=sitemap&GetSiteMap=now&sugar_body_only=true';
        YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, postData);
    }
});
function IKEADEBUG() {
    var moduleLinks = document.getElementById('moduleList').getElementsByTagName("a");
    moduleLinkMouseOver = function () {
        var matches = /grouptab_([0-9]+)/i.exec(this.id);
        var tabNum = matches[1];
        var moduleGroups = document.getElementById('subModuleList').getElementsByTagName("span");
        for (var i = 0; i < moduleGroups.length; i++) {
            if (i == tabNum) {
                moduleGroups[i].className = 'selected';
            }
            else {
                moduleGroups[i].className = '';
            }
        }
        var groupList = document.getElementById('moduleList').getElementsByTagName("li");
        var currentGroupItem = tabNum;
        for (var i = 0; i < groupList.length; i++) {
            var aElem = groupList[i].getElementsByTagName("a")[0];
            if (aElem == null) {
                continue;
            }
            var classStarter = 'notC';
            if (aElem.id == "grouptab_" + tabNum) {
                classStarter = 'c';
                currentGroupItem = i;
            }
            var spanTags = groupList[i].getElementsByTagName("span");
            for (var ii = 0; ii < spanTags.length; ii++) {
                if (spanTags[ii].className == null) {
                    continue;
                }
                var oldClass = spanTags[ii].className.match(/urrentTab.*/);
                spanTags[ii].className = classStarter + oldClass;
            }
        }
        var menuHandle = moduleGroups[tabNum];
        var parentMenu = groupList[currentGroupItem];
        if (menuHandle && parentMenu) {
            updateSubmenuPosition(menuHandle, parentMenu);
        }
    };
    for (var i = 0; i < moduleLinks.length; i++) {
        moduleLinks[i].onmouseover = moduleLinkMouseOver;
    }
};
function updateSubmenuPosition(menuHandle, parentMenu) {
    var left = '';
    if (left == "") {
        p = parentMenu;
        var left = 0;
        while (p && p.tagName.toUpperCase() != 'BODY') {
            left += p.offsetLeft;
            p = p.offsetParent;
        }
    }
    var bw = checkBrowserWidth();
    if (!parentMenu) {
        return;
    }
    var groupTabLeft = left + (parentMenu.offsetWidth / 2);
    var subTabHalfLength = 0;
    var children = menuHandle.getElementsByTagName('li');
    for (var i = 0; i < children.length; i++) {
        if (children[i].className == 'subTabMore' || children[i].parentNode.className == 'cssmenu') {
            continue;
        }
        subTabHalfLength += parseInt(children[i].offsetWidth);
    }
    if (subTabHalfLength != 0) {
        subTabHalfLength = subTabHalfLength / 2;
    }
    var totalLengthInTheory = subTabHalfLength + groupTabLeft;
    if (subTabHalfLength > 0 && groupTabLeft > 0) {
        if (subTabHalfLength >= groupTabLeft) {
            left = 1;
        } else {
            left = groupTabLeft - subTabHalfLength;
        }
    }
    if (totalLengthInTheory > bw) {
        var differ = totalLengthInTheory - bw;
        left = groupTabLeft - subTabHalfLength - differ - 2;
    }
    if (left >= 0) {
        menuHandle.style.marginLeft = left + 'px';
    }
}
YAHOO.util.Event.onDOMReady(function () {
    if (document.getElementById('subModuleList')) {
        var parentMenu = false;
        var moduleListDom = document.getElementById('moduleList');
        if (moduleListDom != null) {
            var parentTabLis = moduleListDom.getElementsByTagName("li");
            var tabNum = 0;
            for (var ii = 0; ii < parentTabLis.length; ii++) {
                var spans = parentTabLis[ii].getElementsByTagName("span");
                for (var jj = 0; jj < spans.length; jj++) {
                    if (spans[jj].className.match(/currentTab.*/)) {
                        tabNum = ii;
                    }
                }
            }
            var parentMenu = parentTabLis[tabNum];
        }
        var moduleGroups = document.getElementById('subModuleList').getElementsByTagName("span");
        for (var i = 0; i < moduleGroups.length; i++) {
            if (moduleGroups[i].className.match(/selected/)) {
                tabNum = i;
            }
        }
        var menuHandle = moduleGroups[tabNum];
        if (menuHandle && parentMenu) {
            updateSubmenuPosition(menuHandle, parentMenu);
        }
    }
});
SUGAR.themes = SUGAR.namespace("themes");
SUGAR.append(SUGAR.themes, {
    allMenuBars: {}, setModuleTabs: function (html) {
        var el = document.getElementById('ajaxHeader');
        if (el) {
            $('#ajaxHeader').html(html);
            loadSidebar();
            if ($(window).width() < 979) {
                $('#bootstrap-container').removeClass('main');
            }
        }
    }, actionMenu: function () {
        $("ul.clickMenu").each(function (index, node) {
            $(node).sugarActionMenu();
        });
    }, loadModuleList: function () {
        var nodes = YAHOO.util.Selector.query('#moduleList>div'), currMenuBar;
        this.allMenuBars = {};
        for (var i = 0; i < nodes.length; i++) {
            currMenuBar = SUGAR.themes.currMenuBar = new YAHOO.widget.MenuBar(nodes[i].id, {
                autosubmenudisplay: true,
                visible: false,
                hidedelay: 750,
                lazyload: true
            });
            currMenuBar.render();
            this.allMenuBars[nodes[i].id.substr(nodes[i].id.indexOf('_') + 1)] = currMenuBar;
            if (typeof YAHOO.util.Dom.getChildren(nodes[i]) == 'object' && YAHOO.util.Dom.getChildren(nodes[i]).shift().style.display != 'none') {
                oMenuBar = currMenuBar;
            }
        }
        YAHOO.util.Event.onAvailable('subModuleList', IKEADEBUG);
    }, setCurrentTab: function () {
    }
});
YAHOO.util.Event.onDOMReady(SUGAR.themes.loadModuleList, SUGAR.themes, true);

// Custom jQuery for theme

// Script to toggle copyright popup
$( "button" ).click(function() {
    $( "#sugarcopy" ).toggle();

});

// Custom JavaScript for copyright pop-ups
$(function() {
    $( "#dialog, #dialog2" ).dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 100
        },
        hide: {
            effect: "fade",
            duration: 1000
        }
    });
    $( "#powered_by" ).click(function() {
        $( "#dialog" ).dialog( "open" );
        $("#overlay").show().css({"opacity": "0.5"});
    });
    $( "#admin_options" ).click(function() {
        $( "#dialog2" ).dialog( "open" );
    });
});

// Back to top animation
$('#backtotop').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
});

// Tabs jQuery for Admin panel
$(function() {
    var tabs = $( "#tabs" ).tabs();
    tabs.find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        stop: function() {
            tabs.tabs( "refresh" );
        }
    });
});

jQuery(function($){
    $('table.footable').footable({
        "breakpoints": {
            "x-small": 480,
            "small": 768,
            "medium": 992,
            "large": 1200,
            "x-large": 1400
        }
    });
})

// JavaScript fix to remove unrequired classes on smaller screens where sidebar is obsolete
$(window).resize(function () {
    if ($(window).width() < 979) {
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 sidebar main');
    }
    if ($(window).width() > 980 && $('.sidebar').is(':visible')) {
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
});

// jQuery to toggle sidebar
function loadSidebar() {
    if($('#sidebar_container').length) {
        $('#buttontoggle').click(function () {
            $('.sidebar').toggle();
            if ($('.sidebar').is(':visible')) {
                $.cookie('sidebartoggle', 'expanded');
                $('#buttontoggle').removeClass('button-toggle-collapsed');
                $('#buttontoggle').addClass('button-toggle-expanded');
                $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
            }
            if ($('.sidebar').is(':hidden')) {
                $.cookie('sidebartoggle', 'collapsed');
                $('#buttontoggle').removeClass('button-toggle-expanded');
                $('#buttontoggle').addClass('button-toggle-collapsed');
                $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
            }
        });

        var sidebartoggle = $.cookie('sidebartoggle');
        if (sidebartoggle == 'collapsed') {
            $('.sidebar').hide();
            $('#buttontoggle').removeClass('button-toggle-expanded');
            $('#buttontoggle').addClass('button-toggle-collapsed');
            $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
        }
        else {
            $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
            $('#buttontoggle').removeClass('button-toggle-collapsed');
            $('#buttontoggle').addClass('button-toggle-expanded');
        }
    }
}

update_screen_resolution();

    $(window).resize(function () {
        update_screen_resolution();
    });

function update_screen_resolution(){
    $.ajax({
        url: 'index.php?module=Calendar&action=processScreenSize',
        type: 'post',
        data: { 'width' : $( window ).width(), 'height' : $( window ).height(), 'to_pdf': true}
    });
}

// Alerts Notification
$(document).ready(function() {
    $('#alert-nav').click(function() {
        $('#alert-nav #alerts').css('display', 'inherit');
    });
});

function changeFirstTab(src) {
    var selected = $(src);
    var selectedHtml = $(selected.context).html();
    $('#xstab0').html(selectedHtml);
    return true;
}
// End of custom jQuery

// fix for tab navigation on user profile for SuiteP theme
var isUserProfileEditViewPage = function() {
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
          results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    var module = getParameterByName('module');
    var action = getParameterByName('action');
    return module == 'Users' && action == 'EditView';
};

if(isUserProfileEditViewPage()) {
    var tabsRefresh = function() {
        var tabFrames = {
            // User Profile
            'tab1': [
                // User Profile & Employee Information
                'form#EditView div#EditView_tabs.yui-navset.yui-navset-top div.yui-content div div#EditView_tabs',
                // Email Settings
                '#email_options'
            ],
            // Password
            'tab2': [
                // Password
                '#generate_password'
            ],
            // Themes
            'tab3': [
                // Themes
                '#themepicker'
            ],
            // Advanced
            'tab4': [
                // User Settings
                '#settings',
                // Layout Options
                '#layout',
                // Locale Settings
                '#locale',
                // Calendar Options
                '#calendar_options'
            ],
            // External Account
            'tab5': [
                '#eapm_area'
            ]
        };
        // hide all tabs..
        for(var i=1; i<=5; i++) {
            for(var j=0; j<tabFrames['tab'+i].length; j++) {
                $(tabFrames['tab'+i][j]).hide();
            }
        }

        // show the active only
        var activeTab = $('#EditView_tabs.yui-navset.yui-navset-top ul.yui-nav li.selected a').first().attr('id');
        for(i=0; i<tabFrames[activeTab].length; i++) {
            $(tabFrames[activeTab][i]).show();
        }
    }
    $(function () {
        for(var i=1; i<=5; i++) {
            $('#tab'+i).click(function () {
                setTimeout(function(){tabsRefresh();}, 300);
            });
        }
        setTimeout(function(){tabsRefresh();}, 300);
    });
}
<|endoftext|>


<commit_before>/**
 * Copyright 2016, Google, Inc.
 * 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';

// [START functions_pubsub_setup]
const {PubSub} = require('@google-cloud/pubsub');

// Instantiates a client
const pubsub = new PubSub();
// [END functions_pubsub_setup]

const {Buffer} = require('safe-buffer');

// [START functions_pubsub_publish]
/**
 * Publishes a message to a Cloud Pub/Sub Topic.
 *
 * @example
 * gcloud alpha functions call publish --data '{"topic":"[YOUR_TOPIC_NAME]","message":"Hello, world!"}'
 *
 *   - Replace `[YOUR_TOPIC_NAME]` with your Cloud Pub/Sub topic name.
 *
 * @param {object} req Cloud Function request context.
 * @param {object} req.body The request body.
 * @param {string} req.body.topic Topic name on which to publish.
 * @param {string} req.body.message Message to publish.
 * @param {object} res Cloud Function response context.
 */
exports.publish = async (req, res) => {
  if (!req.body.topic || !req.body.message) {
    res
      .status(500)
      .send(
        'Missing parameter(s); include "topic" and "subscription" properties in your request.'
      );
    return;
  }

  console.log(`Publishing message to topic ${req.body.topic}`);

  // References an existing topic
  const topic = pubsub.topic(req.body.topic);

  const messageObject = {
    data: {
      message: req.body.message,
    },
  };
  const messageBuffer = Buffer.from(JSON.stringify(messageObject), 'base64');

  // Publishes a message
  try {
    await topic.publish(messageBuffer);
    res.status(200).send('Message published.');
  } catch (err) {
    console.error(err);
    res.status(500).send(err);
    return Promise.reject(err);
  }
};
// [END functions_pubsub_publish]

// [START functions_pubsub_subscribe]
/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {object} pubsubMessage The Cloud Pub/Sub Message object.
 * @param {string} pubsubMessage.data The "data" property of the Cloud Pub/Sub Message.
 */
exports.subscribe = pubsubMessage => {
  // Print out the data from Pub/Sub, to prove that it worked
  console.log(Buffer.from(pubsubMessage.data, 'base64').toString());
};
// [END functions_pubsub_subscribe]
<commit_msg>Remove stray alpha statement (#1389)<commit_after>/**
 * Copyright 2016, Google, Inc.
 * 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';

// [START functions_pubsub_setup]
const {PubSub} = require('@google-cloud/pubsub');

// Instantiates a client
const pubsub = new PubSub();
// [END functions_pubsub_setup]

const {Buffer} = require('safe-buffer');

// [START functions_pubsub_publish]
/**
 * Publishes a message to a Cloud Pub/Sub Topic.
 *
 * @example
 * gcloud functions call publish --data '{"topic":"[YOUR_TOPIC_NAME]","message":"Hello, world!"}'
 *
 *   - Replace `[YOUR_TOPIC_NAME]` with your Cloud Pub/Sub topic name.
 *
 * @param {object} req Cloud Function request context.
 * @param {object} req.body The request body.
 * @param {string} req.body.topic Topic name on which to publish.
 * @param {string} req.body.message Message to publish.
 * @param {object} res Cloud Function response context.
 */
exports.publish = async (req, res) => {
  if (!req.body.topic || !req.body.message) {
    res
      .status(500)
      .send(
        'Missing parameter(s); include "topic" and "subscription" properties in your request.'
      );
    return;
  }

  console.log(`Publishing message to topic ${req.body.topic}`);

  // References an existing topic
  const topic = pubsub.topic(req.body.topic);

  const messageObject = {
    data: {
      message: req.body.message,
    },
  };
  const messageBuffer = Buffer.from(JSON.stringify(messageObject), 'base64');

  // Publishes a message
  try {
    await topic.publish(messageBuffer);
    res.status(200).send('Message published.');
  } catch (err) {
    console.error(err);
    res.status(500).send(err);
    return Promise.reject(err);
  }
};
// [END functions_pubsub_publish]

// [START functions_pubsub_subscribe]
/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {object} pubsubMessage The Cloud Pub/Sub Message object.
 * @param {string} pubsubMessage.data The "data" property of the Cloud Pub/Sub Message.
 */
exports.subscribe = pubsubMessage => {
  // Print out the data from Pub/Sub, to prove that it worked
  console.log(Buffer.from(pubsubMessage.data, 'base64').toString());
};
// [END functions_pubsub_subscribe]
<|endoftext|>