<commit_before>'use strict';

/**
 * @ngdoc function
 * @name openshiftConsole.controller:OverviewController
 * @description
 * # ProjectController
 * Controller of the openshiftConsole
 */
angular.module('openshiftConsole')
  .controller('OverviewController',
              function ($scope,
                        DataService,
                        annotationFilter,
                        hashSizeFilter,
                        imageObjectRefFilter,
                        deploymentCausesFilter,
                        LabelFilter,
                        Logger,
                        ImageStreamResolver) {
    $scope.pods = {};
    $scope.services = {};
    $scope.routesByService = {};
    // The "best" route to display on the overview page for each service
    // (one with a custom host if present)
    $scope.displayRouteByService = {};
    $scope.unfilteredServices = {};
    $scope.deployments = {};
    // Initialize to undefined so we know when deployment configs are actually loaded.
    $scope.deploymentConfigs = undefined;
    $scope.builds = {};
    $scope.imageStreams = {};
    $scope.imagesByDockerReference = {};
    $scope.imageStreamImageRefByDockerReference = {}; // lets us determine if a particular container's docker image reference belongs to an imageStream

    // All pods under a service (no "" service key)
    $scope.podsByService = {};
    // All pods under a deployment (no "" deployment key)
    $scope.podsByDeployment = {};
    // Pods not in a deployment
    // "" service key for pods not under any service
    $scope.monopodsByService = {};
    // All deployments
    // "" service key for deployments not under any service
    // "" deployment config for deployments not created from a deployment config
    $scope.deploymentsByServiceByDeploymentConfig = {};
    // All deployments
    // "" service key for deployments not under any service
    // Only being built to improve efficiency in the podRelationships method, not used by the view
    $scope.deploymentsByService = {};
    // All deployment configs
    // "" service key for deployment configs not under any service
    $scope.deploymentConfigsByService = {};

    $scope.labelSuggestions = {};
    $scope.alerts = $scope.alerts || {};
    $scope.emptyMessage = "Loading...";
    $scope.renderOptions = $scope.renderOptions || {};
    $scope.renderOptions.showSidebarRight = false;

    var watches = [];

    watches.push(DataService.watch("pods", $scope, function(pods) {
      $scope.pods = pods.by("metadata.name");
      podRelationships();
      // Must be called after podRelationships()
      updateShowGetStarted();
      ImageStreamResolver.fetchReferencedImageStreamImages($scope.pods, $scope.imagesByDockerReference, $scope.imageStreamImageRefByDockerReference, $scope);
      Logger.log("pods", $scope.pods);
    }));

    watches.push(DataService.watch("services", $scope, function(services) {
      $scope.unfilteredServices = services.by("metadata.name");

      LabelFilter.addLabelSuggestionsFromResources($scope.unfilteredServices, $scope.labelSuggestions);
      LabelFilter.setLabelSuggestions($scope.labelSuggestions);
      $scope.services = LabelFilter.getLabelSelector().select($scope.unfilteredServices);

      // Order is important here since podRelationships expects deploymentsByServiceByDeploymentConfig to be up to date
      deploymentsByService();
      deploymentConfigsByService();
      podRelationships();

      // Must be called after deploymentConfigsByService() and podRelationships()
      updateShowGetStarted();

      $scope.emptyMessage = "No services to show";
      updateFilterWarning();
      Logger.log("services (list)", $scope.services);
    }));

    watches.push(DataService.watch("routes", $scope, function(routes) {
      var routeMap = $scope.routesByService = {};
      var displayRouteMap = $scope.displayRouteByService = {};
      angular.forEach(routes.by("metadata.name"), function(route, routeName){
        if (route.spec.to.kind !== "Service") {
          return;
        }

        var serviceName = route.spec.to.name;
        routeMap[serviceName] = routeMap[serviceName] || {};
        routeMap[serviceName][routeName] = route;

        // Find the best route to display for a service. Prefer the first custom host we find.
        if (!displayRouteMap[serviceName] ||
            (!isGeneratedHost(route) && isGeneratedHost(displayRouteMap[serviceName]))) {
          displayRouteMap[serviceName] = route;
        }
      });

      Logger.log("routes (subscribe)", $scope.routesByService);
    }));

    // Expects deploymentsByServiceByDeploymentConfig to be up to date
    function podRelationships() {
      $scope.monopodsByService = {"": {}};
      $scope.podsByService = {};
      $scope.podsByDeployment = {};

      // Initialize all the label selectors upfront
      var depSelectors = {};
      angular.forEach($scope.deployments, function(deployment, depName){
        depSelectors[depName] = new LabelSelector(deployment.spec.selector);
        $scope.podsByDeployment[depName] = {};
      });
      var svcSelectors = {};
      angular.forEach($scope.unfilteredServices, function(service, svcName){
        svcSelectors[svcName] = new LabelSelector(service.spec.selector);
        $scope.podsByService[svcName] = {};
      });

      angular.forEach($scope.pods, function(pod, name){
        var deployments = [];
        var services = [];
        angular.forEach($scope.deployments, function(deployment, depName){
          var ls = depSelectors[depName];
          if (ls.matches(pod)) {
            deployments.push(depName);
            $scope.podsByDeployment[depName][name] = pod;
          }
        });
        angular.forEach($scope.unfilteredServices, function(service, svcName){
          var ls = svcSelectors[svcName];
          if (ls.matches(pod)) {
            services.push(svcName);
            $scope.podsByService[svcName][name] = pod;

            var isInDepInSvc = false;
            angular.forEach(deployments, function(depName) {
              isInDepInSvc = isInDepInSvc || ($scope.deploymentsByService[svcName] && $scope.deploymentsByService[svcName][depName]);
            });

            if (!isInDepInSvc) {
              $scope.monopodsByService[svcName] = $scope.monopodsByService[svcName] || {};
              $scope.monopodsByService[svcName][name] = pod;
            }
          }
        });
        if (deployments.length == 0 && services.length == 0 && showMonopod(pod)) {
          $scope.monopodsByService[""][name] = pod;
        }
      });

      Logger.log("podsByDeployment", $scope.podsByDeployment);
      Logger.log("podsByService", $scope.podsByService);
      Logger.log("monopodsByService", $scope.monopodsByService);
    };

    // Filter out monopods we know we don't want to see
    function showMonopod(pod) {
      // Hide pods in the Succeeded, Terminated, and Failed phases since these
      // are run once pods that are done.
      if (pod.status.phase === 'Succeeded' ||
          pod.status.phase === 'Terminated' ||
          pod.status.phase === 'Failed') {
        // TODO we may want to show pods for X amount of time after they have completed
        return false;
      }

      // Hide our deployer pods since it is obvious the deployment is
      // happening when the new deployment appears.
      if (annotationFilter(pod, "openshift.io/deployment.name")) {
        return false;
      }

      // Hide our build pods since we are already showing details for
      // currently running or recently run builds under the appropriate
      // areas.
      if (annotationFilter(pod, "openshift.io/build.name")) {
        return false;
      }

      return true;
    }

    function deploymentConfigsByService() {
      $scope.deploymentConfigsByService = {"": {}};
      angular.forEach($scope.deploymentConfigs, function(deploymentConfig, depName){
        var foundMatch = false;
        var depConfigSelector = new LabelSelector(deploymentConfig.spec.selector);
        angular.forEach($scope.unfilteredServices, function(service, name){
          $scope.deploymentConfigsByService[name] = $scope.deploymentConfigsByService[name] || {};

          var serviceSelector = new LabelSelector(service.spec.selector);
          if (serviceSelector.covers(depConfigSelector)) {
            $scope.deploymentConfigsByService[name][depName] = deploymentConfig;
            foundMatch = true;
          }
        });
        if (!foundMatch) {
          $scope.deploymentConfigsByService[""][depName] = deploymentConfig;
        }
      });
    };

    function deploymentsByService() {
      var bySvc = $scope.deploymentsByService = {"": {}};
      var bySvcByDepCfg = $scope.deploymentsByServiceByDeploymentConfig = {"": {}};

      angular.forEach($scope.deployments, function(deployment, depName){
        var foundMatch = false;
        var deploymentSelector = new LabelSelector(deployment.spec.selector);
        var depConfigName = annotationFilter(deployment, 'deploymentConfig') || "";

        angular.forEach($scope.unfilteredServices, function(service, name){
          bySvc[name] = bySvc[name] || {};
          bySvcByDepCfg[name] = bySvcByDepCfg[name] || {};

          var serviceSelector = new LabelSelector(service.spec.selector);
          if (serviceSelector.covers(deploymentSelector)) {
            bySvc[name][depName] = deployment;

            bySvcByDepCfg[name][depConfigName] = bySvcByDepCfg[name][depConfigName] || {};
            bySvcByDepCfg[name][depConfigName][depName] = deployment;
            foundMatch = true;
          }
        });
        if (!foundMatch) {
          bySvc[""][depName] = deployment;

          bySvcByDepCfg[""][depConfigName] = bySvcByDepCfg[""][depConfigName] || {};
          bySvcByDepCfg[""][depConfigName][depName] = deployment;
        }
      });
    };

    // Sets up subscription for deployments
    watches.push(DataService.watch("replicationcontrollers", $scope, function(deployments, action, deployment) {
      $scope.deployments = deployments.by("metadata.name");
      if (deployment) {
        if (action !== "DELETED") {
          deployment.causes = deploymentCausesFilter(deployment);
        }
      }
      else {
        angular.forEach($scope.deployments, function(deployment) {
          deployment.causes = deploymentCausesFilter(deployment);
        });
      }

      // Order is important here since podRelationships expects deploymentsByServiceByDeploymentConfig to be up to date
      deploymentsByService();
      podRelationships();

      // Must be called after podRelationships()
      updateShowGetStarted();

      Logger.log("deployments (subscribe)", $scope.deployments);
    }));

    // Sets up subscription for imageStreams
    watches.push(DataService.watch("imagestreams", $scope, function(imageStreams) {
      $scope.imageStreams = imageStreams.by("metadata.name");
      ImageStreamResolver.buildDockerRefMapForImageStreams($scope.imageStreams, $scope.imageStreamImageRefByDockerReference);
      ImageStreamResolver.fetchReferencedImageStreamImages($scope.pods, $scope.imagesByDockerReference, $scope.imageStreamImageRefByDockerReference, $scope);
      Logger.log("imagestreams (subscribe)", $scope.imageStreams);
    }));

    function associateDeploymentConfigTriggersToBuild(deploymentConfig, build) {
      // Make sure we have both a deploymentConfig and a build
      if (!deploymentConfig || !build) {
        return;
      }
      // Make sure the deployment config has triggers.
      if (!deploymentConfig.spec.triggers) {
        return;
      }
      // Make sure we have a build output
      if (!build.spec.output.to) {
        return;
      }
      for (var i = 0; i < deploymentConfig.spec.triggers.length; i++) {
        var trigger = deploymentConfig.spec.triggers[i];
        if (trigger.type === "ImageChange") {
          var buildOutputImage = imageObjectRefFilter(build.spec.output.to, build.metadata.namespace);
          var deploymentTriggerImage = imageObjectRefFilter(trigger.imageChangeParams.from, deploymentConfig.metadata.namespace);
          if (buildOutputImage !== deploymentTriggerImage) {
              continue;
          }

          trigger.builds = trigger.builds || {};
          trigger.builds[build.metadata.name] = build;
        }
      }
    };

    // Sets up subscription for deploymentConfigs, associates builds to triggers on deploymentConfigs
    watches.push(DataService.watch("deploymentconfigs", $scope, function(deploymentConfigs, action, deploymentConfig) {
      $scope.deploymentConfigs = deploymentConfigs.by("metadata.name");
      if (!action) {
        angular.forEach($scope.deploymentConfigs, function(depConfig) {
          angular.forEach($scope.builds, function(build) {
            associateDeploymentConfigTriggersToBuild(depConfig, build);
          });
        });
      }
      else if (action !== 'DELETED') {
        angular.forEach($scope.builds, function(build) {
          associateDeploymentConfigTriggersToBuild(deploymentConfig, build);
        });
      }

      deploymentConfigsByService();
      // Must be called after deploymentConfigsByService()
      updateShowGetStarted();

      Logger.log("deploymentconfigs (subscribe)", $scope.deploymentConfigs);
    }));

    // Sets up subscription for builds, associates builds to triggers on deploymentConfigs
    watches.push(DataService.watch("builds", $scope, function(builds, action, build) {
      $scope.builds = builds.by("metadata.name");
      if (!action) {
        angular.forEach($scope.builds, function(bld) {
          angular.forEach($scope.deploymentConfigs, function(depConfig) {
            associateDeploymentConfigTriggersToBuild(depConfig, bld);
          });
        });
      }
      else if (action === 'ADDED' || action === 'MODIFIED') {
        angular.forEach($scope.deploymentConfigs, function(depConfig) {
          associateDeploymentConfigTriggersToBuild(depConfig, build);
        });
      }
      else if (action === 'DELETED'){
        // TODO
      }
      Logger.log("builds (subscribe)", $scope.builds);
    }));

    // Show the "Get Started" message if the project is empty.
    function updateShowGetStarted() {
      var projectEmpty =
        hashSizeFilter($scope.unfilteredServices) === 0 &&
        hashSizeFilter($scope.pods) === 0 &&
        hashSizeFilter($scope.deployments) === 0 &&
        hashSizeFilter($scope.deploymentConfigs) === 0;

      $scope.renderOptions.showSidebarRight = !projectEmpty;
      $scope.renderOptions.showGetStarted = projectEmpty;
    }

    function updateFilterWarning() {
      if (!LabelFilter.getLabelSelector().isEmpty() && $.isEmptyObject($scope.services) && !$.isEmptyObject($scope.unfilteredServices)) {
        $scope.alerts["services"] = {
          type: "warning",
          details: "The active filters are hiding all services."
        };
      }
      else {
        delete $scope.alerts["services"];
      }
    };

    function isGeneratedHost(route) {
      return annotationFilter(route, "openshift.io/host.generated") === "true";
    }

    LabelFilter.onActiveFiltersChanged(function(labelSelector) {
      // trigger a digest loop
      $scope.$apply(function() {
        $scope.services = labelSelector.select($scope.unfilteredServices);
        updateFilterWarning();
      });
    });

    $scope.$on('$destroy', function(){
      DataService.unwatchAll(watches);
    });
  });
<commit_msg>Look for deployer label when filtering pods on overview page<commit_after>'use strict';

/**
 * @ngdoc function
 * @name openshiftConsole.controller:OverviewController
 * @description
 * # ProjectController
 * Controller of the openshiftConsole
 */
angular.module('openshiftConsole')
  .controller('OverviewController',
              function ($scope,
                        DataService,
                        annotationFilter,
                        hashSizeFilter,
                        imageObjectRefFilter,
                        deploymentCausesFilter,
                        labelFilter, // for getting k8s resource labels
                        LabelFilter, // for the label-selector widget in the navbar
                        Logger,
                        ImageStreamResolver) {
    $scope.pods = {};
    $scope.services = {};
    $scope.routesByService = {};
    // The "best" route to display on the overview page for each service
    // (one with a custom host if present)
    $scope.displayRouteByService = {};
    $scope.unfilteredServices = {};
    $scope.deployments = {};
    // Initialize to undefined so we know when deployment configs are actually loaded.
    $scope.deploymentConfigs = undefined;
    $scope.builds = {};
    $scope.imageStreams = {};
    $scope.imagesByDockerReference = {};
    $scope.imageStreamImageRefByDockerReference = {}; // lets us determine if a particular container's docker image reference belongs to an imageStream

    // All pods under a service (no "" service key)
    $scope.podsByService = {};
    // All pods under a deployment (no "" deployment key)
    $scope.podsByDeployment = {};
    // Pods not in a deployment
    // "" service key for pods not under any service
    $scope.monopodsByService = {};
    // All deployments
    // "" service key for deployments not under any service
    // "" deployment config for deployments not created from a deployment config
    $scope.deploymentsByServiceByDeploymentConfig = {};
    // All deployments
    // "" service key for deployments not under any service
    // Only being built to improve efficiency in the podRelationships method, not used by the view
    $scope.deploymentsByService = {};
    // All deployment configs
    // "" service key for deployment configs not under any service
    $scope.deploymentConfigsByService = {};

    $scope.labelSuggestions = {};
    $scope.alerts = $scope.alerts || {};
    $scope.emptyMessage = "Loading...";
    $scope.renderOptions = $scope.renderOptions || {};
    $scope.renderOptions.showSidebarRight = false;

    var watches = [];

    watches.push(DataService.watch("pods", $scope, function(pods) {
      $scope.pods = pods.by("metadata.name");
      podRelationships();
      // Must be called after podRelationships()
      updateShowGetStarted();
      ImageStreamResolver.fetchReferencedImageStreamImages($scope.pods, $scope.imagesByDockerReference, $scope.imageStreamImageRefByDockerReference, $scope);
      Logger.log("pods", $scope.pods);
    }));

    watches.push(DataService.watch("services", $scope, function(services) {
      $scope.unfilteredServices = services.by("metadata.name");

      LabelFilter.addLabelSuggestionsFromResources($scope.unfilteredServices, $scope.labelSuggestions);
      LabelFilter.setLabelSuggestions($scope.labelSuggestions);
      $scope.services = LabelFilter.getLabelSelector().select($scope.unfilteredServices);

      // Order is important here since podRelationships expects deploymentsByServiceByDeploymentConfig to be up to date
      deploymentsByService();
      deploymentConfigsByService();
      podRelationships();

      // Must be called after deploymentConfigsByService() and podRelationships()
      updateShowGetStarted();

      $scope.emptyMessage = "No services to show";
      updateFilterWarning();
      Logger.log("services (list)", $scope.services);
    }));

    watches.push(DataService.watch("routes", $scope, function(routes) {
      var routeMap = $scope.routesByService = {};
      var displayRouteMap = $scope.displayRouteByService = {};
      angular.forEach(routes.by("metadata.name"), function(route, routeName){
        if (route.spec.to.kind !== "Service") {
          return;
        }

        var serviceName = route.spec.to.name;
        routeMap[serviceName] = routeMap[serviceName] || {};
        routeMap[serviceName][routeName] = route;

        // Find the best route to display for a service. Prefer the first custom host we find.
        if (!displayRouteMap[serviceName] ||
            (!isGeneratedHost(route) && isGeneratedHost(displayRouteMap[serviceName]))) {
          displayRouteMap[serviceName] = route;
        }
      });

      Logger.log("routes (subscribe)", $scope.routesByService);
    }));

    // Expects deploymentsByServiceByDeploymentConfig to be up to date
    function podRelationships() {
      $scope.monopodsByService = {"": {}};
      $scope.podsByService = {};
      $scope.podsByDeployment = {};

      // Initialize all the label selectors upfront
      var depSelectors = {};
      angular.forEach($scope.deployments, function(deployment, depName){
        depSelectors[depName] = new LabelSelector(deployment.spec.selector);
        $scope.podsByDeployment[depName] = {};
      });
      var svcSelectors = {};
      angular.forEach($scope.unfilteredServices, function(service, svcName){
        svcSelectors[svcName] = new LabelSelector(service.spec.selector);
        $scope.podsByService[svcName] = {};
      });

      angular.forEach($scope.pods, function(pod, name){
        var deployments = [];
        var services = [];
        angular.forEach($scope.deployments, function(deployment, depName){
          var ls = depSelectors[depName];
          if (ls.matches(pod)) {
            deployments.push(depName);
            $scope.podsByDeployment[depName][name] = pod;
          }
        });
        angular.forEach($scope.unfilteredServices, function(service, svcName){
          var ls = svcSelectors[svcName];
          if (ls.matches(pod)) {
            services.push(svcName);
            $scope.podsByService[svcName][name] = pod;

            var isInDepInSvc = false;
            angular.forEach(deployments, function(depName) {
              isInDepInSvc = isInDepInSvc || ($scope.deploymentsByService[svcName] && $scope.deploymentsByService[svcName][depName]);
            });

            if (!isInDepInSvc) {
              $scope.monopodsByService[svcName] = $scope.monopodsByService[svcName] || {};
              $scope.monopodsByService[svcName][name] = pod;
            }
          }
        });
        if (deployments.length == 0 && services.length == 0 && showMonopod(pod)) {
          $scope.monopodsByService[""][name] = pod;
        }
      });

      Logger.log("podsByDeployment", $scope.podsByDeployment);
      Logger.log("podsByService", $scope.podsByService);
      Logger.log("monopodsByService", $scope.monopodsByService);
    };

    // Filter out monopods we know we don't want to see
    function showMonopod(pod) {
      // Hide pods in the Succeeded, Terminated, and Failed phases since these
      // are run once pods that are done.
      if (pod.status.phase === 'Succeeded' ||
          pod.status.phase === 'Terminated' ||
          pod.status.phase === 'Failed') {
        // TODO we may want to show pods for X amount of time after they have completed
        return false;
      }

      // Hide our deployer pods since it is obvious the deployment is
      // happening when the new deployment appears.
      if (labelFilter(pod, "openshift.io/deployer-pod-for.name")) {
        return false;
      }

      // Hide our build pods since we are already showing details for
      // currently running or recently run builds under the appropriate
      // areas.
      if (annotationFilter(pod, "openshift.io/build.name")) {
        return false;
      }

      return true;
    }

    function deploymentConfigsByService() {
      $scope.deploymentConfigsByService = {"": {}};
      angular.forEach($scope.deploymentConfigs, function(deploymentConfig, depName){
        var foundMatch = false;
        var depConfigSelector = new LabelSelector(deploymentConfig.spec.selector);
        angular.forEach($scope.unfilteredServices, function(service, name){
          $scope.deploymentConfigsByService[name] = $scope.deploymentConfigsByService[name] || {};

          var serviceSelector = new LabelSelector(service.spec.selector);
          if (serviceSelector.covers(depConfigSelector)) {
            $scope.deploymentConfigsByService[name][depName] = deploymentConfig;
            foundMatch = true;
          }
        });
        if (!foundMatch) {
          $scope.deploymentConfigsByService[""][depName] = deploymentConfig;
        }
      });
    };

    function deploymentsByService() {
      var bySvc = $scope.deploymentsByService = {"": {}};
      var bySvcByDepCfg = $scope.deploymentsByServiceByDeploymentConfig = {"": {}};

      angular.forEach($scope.deployments, function(deployment, depName){
        var foundMatch = false;
        var deploymentSelector = new LabelSelector(deployment.spec.selector);
        var depConfigName = annotationFilter(deployment, 'deploymentConfig') || "";

        angular.forEach($scope.unfilteredServices, function(service, name){
          bySvc[name] = bySvc[name] || {};
          bySvcByDepCfg[name] = bySvcByDepCfg[name] || {};

          var serviceSelector = new LabelSelector(service.spec.selector);
          if (serviceSelector.covers(deploymentSelector)) {
            bySvc[name][depName] = deployment;

            bySvcByDepCfg[name][depConfigName] = bySvcByDepCfg[name][depConfigName] || {};
            bySvcByDepCfg[name][depConfigName][depName] = deployment;
            foundMatch = true;
          }
        });
        if (!foundMatch) {
          bySvc[""][depName] = deployment;

          bySvcByDepCfg[""][depConfigName] = bySvcByDepCfg[""][depConfigName] || {};
          bySvcByDepCfg[""][depConfigName][depName] = deployment;
        }
      });
    };

    // Sets up subscription for deployments
    watches.push(DataService.watch("replicationcontrollers", $scope, function(deployments, action, deployment) {
      $scope.deployments = deployments.by("metadata.name");
      if (deployment) {
        if (action !== "DELETED") {
          deployment.causes = deploymentCausesFilter(deployment);
        }
      }
      else {
        angular.forEach($scope.deployments, function(deployment) {
          deployment.causes = deploymentCausesFilter(deployment);
        });
      }

      // Order is important here since podRelationships expects deploymentsByServiceByDeploymentConfig to be up to date
      deploymentsByService();
      podRelationships();

      // Must be called after podRelationships()
      updateShowGetStarted();

      Logger.log("deployments (subscribe)", $scope.deployments);
    }));

    // Sets up subscription for imageStreams
    watches.push(DataService.watch("imagestreams", $scope, function(imageStreams) {
      $scope.imageStreams = imageStreams.by("metadata.name");
      ImageStreamResolver.buildDockerRefMapForImageStreams($scope.imageStreams, $scope.imageStreamImageRefByDockerReference);
      ImageStreamResolver.fetchReferencedImageStreamImages($scope.pods, $scope.imagesByDockerReference, $scope.imageStreamImageRefByDockerReference, $scope);
      Logger.log("imagestreams (subscribe)", $scope.imageStreams);
    }));

    function associateDeploymentConfigTriggersToBuild(deploymentConfig, build) {
      // Make sure we have both a deploymentConfig and a build
      if (!deploymentConfig || !build) {
        return;
      }
      // Make sure the deployment config has triggers.
      if (!deploymentConfig.spec.triggers) {
        return;
      }
      // Make sure we have a build output
      if (!build.spec.output.to) {
        return;
      }
      for (var i = 0; i < deploymentConfig.spec.triggers.length; i++) {
        var trigger = deploymentConfig.spec.triggers[i];
        if (trigger.type === "ImageChange") {
          var buildOutputImage = imageObjectRefFilter(build.spec.output.to, build.metadata.namespace);
          var deploymentTriggerImage = imageObjectRefFilter(trigger.imageChangeParams.from, deploymentConfig.metadata.namespace);
          if (buildOutputImage !== deploymentTriggerImage) {
              continue;
          }

          trigger.builds = trigger.builds || {};
          trigger.builds[build.metadata.name] = build;
        }
      }
    };

    // Sets up subscription for deploymentConfigs, associates builds to triggers on deploymentConfigs
    watches.push(DataService.watch("deploymentconfigs", $scope, function(deploymentConfigs, action, deploymentConfig) {
      $scope.deploymentConfigs = deploymentConfigs.by("metadata.name");
      if (!action) {
        angular.forEach($scope.deploymentConfigs, function(depConfig) {
          angular.forEach($scope.builds, function(build) {
            associateDeploymentConfigTriggersToBuild(depConfig, build);
          });
        });
      }
      else if (action !== 'DELETED') {
        angular.forEach($scope.builds, function(build) {
          associateDeploymentConfigTriggersToBuild(deploymentConfig, build);
        });
      }

      deploymentConfigsByService();
      // Must be called after deploymentConfigsByService()
      updateShowGetStarted();

      Logger.log("deploymentconfigs (subscribe)", $scope.deploymentConfigs);
    }));

    // Sets up subscription for builds, associates builds to triggers on deploymentConfigs
    watches.push(DataService.watch("builds", $scope, function(builds, action, build) {
      $scope.builds = builds.by("metadata.name");
      if (!action) {
        angular.forEach($scope.builds, function(bld) {
          angular.forEach($scope.deploymentConfigs, function(depConfig) {
            associateDeploymentConfigTriggersToBuild(depConfig, bld);
          });
        });
      }
      else if (action === 'ADDED' || action === 'MODIFIED') {
        angular.forEach($scope.deploymentConfigs, function(depConfig) {
          associateDeploymentConfigTriggersToBuild(depConfig, build);
        });
      }
      else if (action === 'DELETED'){
        // TODO
      }
      Logger.log("builds (subscribe)", $scope.builds);
    }));

    // Show the "Get Started" message if the project is empty.
    function updateShowGetStarted() {
      var projectEmpty =
        hashSizeFilter($scope.unfilteredServices) === 0 &&
        hashSizeFilter($scope.pods) === 0 &&
        hashSizeFilter($scope.deployments) === 0 &&
        hashSizeFilter($scope.deploymentConfigs) === 0;

      $scope.renderOptions.showSidebarRight = !projectEmpty;
      $scope.renderOptions.showGetStarted = projectEmpty;
    }

    function updateFilterWarning() {
      if (!LabelFilter.getLabelSelector().isEmpty() && $.isEmptyObject($scope.services) && !$.isEmptyObject($scope.unfilteredServices)) {
        $scope.alerts["services"] = {
          type: "warning",
          details: "The active filters are hiding all services."
        };
      }
      else {
        delete $scope.alerts["services"];
      }
    };

    function isGeneratedHost(route) {
      return annotationFilter(route, "openshift.io/host.generated") === "true";
    }

    LabelFilter.onActiveFiltersChanged(function(labelSelector) {
      // trigger a digest loop
      $scope.$apply(function() {
        $scope.services = labelSelector.select($scope.unfilteredServices);
        updateFilterWarning();
      });
    });

    $scope.$on('$destroy', function(){
      DataService.unwatchAll(watches);
    });
  });
<|endoftext|>


<commit_before>import { ATTR_KEY } from '../constants';
import { hasOwnProperty, memoize } from '../util';
import { ensureNodeData, getNodeType } from '.';

/** DOM node pool, keyed on nodeName. */

let nodes = {};

let normalizeName = memoize(name => name.toUpperCase());

export function collectNode(node) {
	cleanNode(node);
	let name = normalizeName(node.nodeName),
		list = nodes[name];
	if (list) list.push(node);
	else nodes[name] = [node];
}

export function createNode(nodeName) {
	let name = normalizeName(nodeName),
		list = nodes[name],
		node = list && list.pop() || document.createElement(nodeName);
	ensureNodeData(node);
	return node;
}

function cleanNode(node) {
	let p = node.parentNode;
	if (p) p.removeChild(node);

	if (getNodeType(node)===3) return;

	let attrs = node[ATTR_KEY];
	for (let i in attrs) {
		if (hasOwnProperty.call(attrs, i)) {
			setAccessor(node, i, null, attrs[i]);
		}
	}

	node[ATTR_KEY] = node._component = node._componentConstructor = null;

	// if (node.childNodes.length>0) {
	// 	console.warn(`Warning: Recycler collecting <${node.nodeName}> with ${node.childNodes.length} children.`);
	// 	toArray(node.childNodes).forEach(recycler.collect);
	// }
}
<commit_msg>Optimization: when recycling DOM nodes, don't reset them. Subsequent re-use will do a diff against the cached properties anyway.<commit_after>import { memoize } from '../util';
import { ensureNodeData, getNodeType } from '.';

/** DOM node pool, keyed on nodeName. */

let nodes = {};

let normalizeName = memoize(name => name.toUpperCase());

export function collectNode(node) {
	cleanNode(node);
	let name = normalizeName(node.nodeName),
		list = nodes[name];
	if (list) list.push(node);
	else nodes[name] = [node];
}

export function createNode(nodeName) {
	let name = normalizeName(nodeName),
		list = nodes[name],
		node = list && list.pop() || document.createElement(nodeName);
	ensureNodeData(node);
	return node;
}

function cleanNode(node) {
	let p = node.parentNode;
	if (p) p.removeChild(node);

	if (getNodeType(node)===3) return;

	node._component = node._componentConstructor = null;

	// if (node.childNodes.length>0) {
	// 	console.trace(`Warning: Recycler collecting <${node.nodeName}> with ${node.childNodes.length} children.`);
	// 	for (let i=node.childNodes.length; i--; ) collectNode(node.childNodes[i]);
	// }
}
<|endoftext|>


<commit_before>'use strict';

// Common directive for Focus

angular.module('openhimWebui2App').directive('focus', function($timeout) {
    return {
      scope : {
        trigger : '@focus'
      },
      link : function(scope, element) {
        scope.$watch('trigger', function(value) {
          if (value === "true") {
            $timeout(function() {
              element[0].focus();
            });
          }
        });
      }
    };
  }); <commit_msg>fixed jshint error<commit_after>'use strict';

// Common directive for Focus

angular.module('openhimWebui2App').directive('focus', function($timeout) {
    return {
      scope : {
        trigger : '@focus'
      },
      link : function(scope, element) {
        scope.$watch('trigger', function(value) {
          if (value === 'true') {
            $timeout(function() {
              element[0].focus();
            });
          }
        });
      }
    };
  });<|endoftext|>


<commit_before>! function(window, angular, undefined) {
  var defaultMapSettings = {
      center: {
        lat: 12.94206,
        lng: 77.62229
      },
      zoom: 8
    },
    setMarkerFunc = undefined;

  function setMarkerCurryFunc(placesMap) {
    if (placesMap) {
      var map = placesMap;
    }
    return function(marker) {
      if (!map) {
        throw "Please pass a map reference before setting marker";
      }
      if (Object.prototype.toString.call(marker) == "[object Object]" && marker.position !== undefined) {
        marker.map = map;
        var newMarker = new google.maps.Marker(marker);
        newMarker.setMap(map);
        return newMarker;
      }
    }
  }

  angular.module('ds.map', []).
  factory('dsMapFactory', ['$http', function($http) {
    var obj = {
      getDefaultMapSettings: getDefaultMapSettingsFunc,
      setDefaultMapSettings: setDefaultMapSettingsFunc,
      setDirectionsToLocation: function() {}
    };

    function getDefaultMapSettingsFunc() {
      return defaultMapSettings;
    }

    function setDefaultMapSettingsFunc(settingsObj) {
      defaultMapSettings = settingsObj;
    }

    return obj;
  }]).
  directive('dsMap', ['$q', '$timeout', 'dsMapFactory', function($q, $timeout, dsMapFactory) {
    var deferred = $q.defer(),
      obj = {
        scope: {
          dsMapSettings: "="
        },
        restrict: "E",
        link: function(scope) {

        },
        controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) {
          var _deferred = $q.defer(),
            placesDeferred = $q.defer(),
            dsMapElements = 0,
            deferredArray = [],
            that = this,
            dsMapSettings = that.dsMapSettings = $scope.dsMapSettings || dsMapFactory.getDefaultMapSettings(),
            map = new google.maps.Map(document.createElement('div'), dsMapSettings);

          function getLocationFunc() {
            return that.dsPlacesLocation;
          }

          function setLocationFunc(center) {
            that.dsPlacesLocation = center || that.getMap().getCenter();
          }

          function getMapFunc() {
            return that.map;
          }

          function setMapFunc(map) {
            dsMapFactory.map = that.map = map;
            that.setLocation(that.map.getCenter());
            dsMapFactory.marker = {
              position: that.map.getCenter()
            };
          }

          function iterateAllMarkersFunc(callback) {
            for (var groups in that.placesGroupHash) {
              var eachGroupRef = that.placesGroupHash[groups];
              for (var _count = 0, len = eachGroupRef.length; _count < len; _count++) {
                var allIteratedMarkers = eachGroupRef[_count];
                callback.call(allIteratedMarkers);
              }
            }
          }

          function iterateMarkersMatchingBooleanFunc(bool, callback) {
            that.iterateAllMarkers(function() {
              var eachPreviousMarker = this;
              if (eachPreviousMarker.visible === bool) {
                callback.call(eachPreviousMarker);
                eachPreviousMarker.setMap(eachPreviousMarker.getMap());
              }
            });
          }

          function setGroupMarkerVisibilityFunc(group, bool, setVisibleMarkerBounds) {
            var currentGroupRef = that.placesGroupHash[group],
              previousGroup = undefined;
            if (previousGroup != group) {
              that.bounds = new google.maps.LatLngBounds();
              for (var currentGroupCount = 0, len = currentGroupRef.length; currentGroupCount < len; currentGroupCount++) {
                var eachCurrentMarker = currentGroupRef[currentGroupCount];
                if (eachCurrentMarker.visible !== bool) {
                  eachCurrentMarker.visible = bool;
                  eachCurrentMarker.setMap(eachCurrentMarker.getMap());
                  if (setVisibleMarkerBounds && eachCurrentMarker.visible) {
                    that.bounds.extend(eachCurrentMarker.position);
                  }
                }
              }

              if (setVisibleMarkerBounds) {
                that.changeMapBounds();
              }
            }

            previousGroup = group;
          }

          function hideAllVisibleMarkersFunc() {
            that.iterateMarkersMatchingBoolean(true, function() {
              var visibleMarker = this;
              visibleMarker.visible = false;
            });
          }

          function changeMapBoundsFunc() {
            that.getMap().fitBounds(that.bounds);
            that.getMap().setCenter(that.getLocation());
            that.getMap().setZoom(that.getMap().getZoom() - 1);
          }

          that.mapDeferred = deferred;
          that.mapRendered = deferred.promise;
          that.placesDeferred = placesDeferred;
          that.placesRendered = placesDeferred.promise;
          that.placesGroupHash = {};
          that.placesCount = 0;
          that.getLocation = getLocationFunc;
          that.setLocation = setLocationFunc;
          that.getMap = getMapFunc;
          that.setMap = setMapFunc;
          that.iterateAllMarkers = iterateAllMarkersFunc;
          that.iterateMarkersMatchingBoolean = iterateMarkersMatchingBooleanFunc;
          that.setGroupMarkerVisibility = setGroupMarkerVisibilityFunc;
          that.hideAllVisibleMarkers = hideAllVisibleMarkersFunc;
          that.changeMapBounds = changeMapBoundsFunc;

          that.setMap(map);

          that.placesRendered.then(function() {
            that.changeMapBounds();
          });

          (function(dfrd, _dfrd) {
            that.mapRendered.then(function() {
              dsMapFactory.setMarker = setMarkerFunc = setMarkerCurryFunc(that.getMap());
              setMarkerFunc(new google.maps.Marker(dsMapFactory.marker));
            });
          })(deferred, _deferred);

          that.nextDefer = deferred = _deferred;
        }]
      };
    return obj;
  }]).
  directive('dsMapView', function() {
      var obj = {
        scope: {
          dsMapSettings: "="
        },
        restrict: "E",
        replace: true,
        template: "

",
        require: "^?dsMap",
        link: function(scope, element, attrs, dsMapController) {
          var map = new google.maps.Map(element[0], scope.dsMapSettings || dsMapController.dsMapSettings);
          dsMapController.setMap(map);
          dsMapController.isViewSet = true;
        }
      };
      return obj;
    }).directive('dsMapPlaces', ['$q', 'dsMapFactory', function($q, dsMapFactory) {
      var initialdsMapView = true,
        deferred = $q.defer(),
        obj = {
          scope: {
            options: "="
          },
          restrict: "E",
          replace: true,
          require: "^?dsMap",
          link: function(scope, element, attrs, dsMapController) {
            var rankByDistance = google.maps.places.RankBy.DISTANCE;

            function setDirectionsToLocationFunc(location, mode) {
              var request = {
                origin: dsMapController.getLocation(),
                destination: location,
                travelMode: google.maps.TravelMode[mode]
              };

              dsMapController.hideAllVisibleMarkers();
              dsMapController.directionsDisplay.setMap(dsMapController.getMap());
              dsMapController.directionsService.route(request, function(response, status) {
                if (status == "OK") {
                  dsMapController.directionsDisplay.setDirections(response);
                  dsMapController.bounds = new google.maps.LatLngBounds();
                  dsMapController.bounds.extend(dsMapController.getLocation());
                  dsMapController.bounds.extend(location);
                  dsMapController.placesGroupHash['searchedLocation'] = [location];
                  setMarkerFunc({
                    position: location,
                    visible: true
                  });
                  dsMapController.changeMapBounds();
                }
              });
            }

            if (initialdsMapView) {
              dsMapController.mapDeferred.resolve();
              initialdsMapView = false;
            }

            dsMapController.mapRendered.then(function() {
              dsMapController.placesService = new google.maps.places.PlacesService(dsMapController.getMap());
              dsMapController.directionsService = new google.maps.DirectionsService();
              scope.options.map = dsMapController.getMap();
              dsMapController.directionsDisplay = new google.maps.DirectionsRenderer(scope.options);
              dsMapController.bounds = new google.maps.LatLngBounds();
              deferred.resolve(dsMapController.placesService);
            });

            dsMapFactory.dsMapPlacesLoaded(function() {
              if (dsMapController.isViewSet) {
                dsMapFactory.setDirectionsToLocation = setDirectionsToLocationFunc;
              }
            });
          },
          controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) {
            var that = this;

            function dsMapPlacesDeferredFunc() {
              var _deferred = $q.defer();
              return function() {
                return _deferred;
              };
            }

            function dsMapPlacesLoadedFunc(callback) {
              that.dsMapPlacesDeferred().promise.then(callback);
            }

            that.placesServiceSet = deferred.promise;
            that.dsMapPlacesDeferred = dsMapPlacesDeferredFunc();
            dsMapFactory.dsMapPlacesLoaded = that.dsMapPlacesLoaded = dsMapPlacesLoadedFunc;
          }]
        };
      return obj;
    }])
    .directive('dsHasGroup', [function() {
      var previousGroup = undefined,
        obj = {
          require: ["^?dsMap", "^?dsMapPlaces"],
          link: function(scope, element, attrs, dsMapControllers) {
            var dsMapController = dsMapControllers[0],
              dsMapPlacesController = dsMapControllers[1];

            function onToggleClickFunc(group) {
              dsMapController.directionsDisplay.setMap(null);
              if (previousGroup !== undefined) {
                if (previousGroup == group) {
                  return;
                }
                dsMapController.setGroupMarkerVisibility(previousGroup, false, true);
              } else {
                dsMapController.hideAllVisibleMarkers();
              }

              dsMapController.setGroupMarkerVisibility(group, true, true);

              previousGroup = group;
            }

            function toggleGroupVisibilityFunc(group) {
              dsMapPlacesController.dsMapPlacesLoaded(function() {
                onToggleClickFunc(group);
              });
            }

            dsMapController.toggleGroupVisibility = scope.toggleGroupVisibility = toggleGroupVisibilityFunc;
          },
          controller: ['$scope', function($scope) {
            var that = this;
            that.isGroupSet = true;
          }]
        };

      return obj;
    }])
    .directive('dsPlacesType', ['$q', '$timeout', function($q, $timeout) {
      var deferred = $q.defer(),
        placesServiceCount = 0,
        obj = {
          scope: {
            group: "@",
            types: "=",
            options: "=",
            sortOption: "@",
            radius: "="
          },
          templateUrl: "dsMapPlaces.html",
          restrict: "E",
          replace: true,
          require: ["^?dsMap", "^?dsMapPlaces", "^?dsHasGroup"],
          link: function(scope, element, attrs, dsMapControllers) {
            var dsMapController = dsMapControllers[0],
              dsMapPlacesController = dsMapControllers[1],
              dsHasGroupController = dsMapControllers[2],
              obj = {
                location: dsMapController.getMap().getCenter(),
                types: []
              },
              showDirectionTimeoutId = undefined;

            function callPlacesServiceFunc(dfrd, _dfrd, type) {
              dsMapController.placesCount++;
              dsMapController.mapRendered.then(function() {
                dfrd.promise.then(function() {
                  dsMapPlacesController.placesServiceSet.then(function(placesService) {
                    if (type) {
                      obj.types = [type];
                    }

                    placesService.nearbySearch(obj, function(results, status) {
                      if (status == "OK" && Object.prototype.toString.call(results) == "[object Array]") {
                        scope.Places = scope.Places.concat(type === undefined ? results : results.slice(0, scope.types[type]));
                      }
                      $timeout(function() {
                        if ((--dsMapController.placesCount) === 0) {
                          dsMapController.nextDefer.resolve();
                          dsMapController.nextDefer.promise.then(function() {
                            _dfrd.resolve();
                            dsMapPlacesController.dsMapPlacesDeferred().resolve();
                          });
                          dsMapController.placesDeferred.resolve();
                        } else {
                          _dfrd.resolve();
                        }
                      }, (dsMapController.placesCount % 10 !== 0 ? 0 : 1000));
                    });
                  });
                });
              });
            }

            function showDirectionFunc() {
              var that = this;
              $timeout.cancel(showDirectionTimeoutId);
              showDirectionTimeoutId = $timeout(function() {
                var request = {
                  origin: dsMapController.getLocation(),
                  destination: that.place.geometry.location,
                  travelMode: google.maps.TravelMode["DRIVING"]
                };

                if (dsHasGroupController && dsMapController.placesGroupHash[scope.group][0].visible === false) {
                  dsMapController.setGroupMarkerVisibility(scope.group, true, true);
                }

                dsMapController.directionsDisplay.setMap(dsMapController.getMap());

                try {
                  if (that.isDirectionResponseCallMade) {
                    if (that.directionResponse) {
                      dsMapController.directionsDisplay.setDirections(that.directionResponse);
                    }
                    return;
                  }
                  that.isDirectionResponseCallMade = true;
                  dsMapController.directionsService.route(request, function(response, status) {
                    if (status == "OK") {
                      dsMapController.directionsDisplay.setDirections(that.directionResponse = response);
                    }
                  });
                } catch (err) {}
              }, 300)
            }

            if (scope.group !== undefined) {
              dsMapController.placesGroupHash[scope.group] = [];
            }

            if (scope.sortOption && scope.sortOption == "radius") {
              obj.radius = scope.radius || 5000;
            } else {
              obj.rankBy = google.maps.places.RankBy.DISTANCE;
            }

            if (Object.prototype.toString.call(scope.types) == "[object Array]") {
              var _deferred = $q.defer();
              obj.types = scope.types;
              callPlacesServiceFunc(deferred, _deferred);
              deferred = _deferred;
            } else if (Object.prototype.toString.call(scope.types) == "[object Object]") {
              for (var _types in scope.types) {
                (function(_deferred) {
                  _deferred = $q.defer();
                  callPlacesServiceFunc(deferred, _deferred, _types);
                  deferred = _deferred;
                })(_deferred);
              }
            } else {
              throw "'types' attribute must be an array or object"
            }

            if (dsMapController.isViewSet) {
              dsMapPlacesController.dsMapPlacesLoaded(function() {
                scope.showDirection = showDirectionFunc;
              });
            }
          },
          controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) {
            $scope.Places = [];
          }]
        };

      deferred.resolve();

      return obj;
    }]).directive('dsEachPlace', [function() {
      var obj = {
        require: ["^?dsMap", "^?dsMapPlaces", "^?dsPlacesType"],
        link: function(scope, element, attrs, dsMapControllers) {
          var dsMapController = dsMapControllers[0],
            dsMapPlacesController = dsMapControllers[1],
            dsPlacesTypeController = dsMapControllers[2];

          if (scope.place) {
            var placeLocation = scope.place.geometry.location,
              setVisibility = scope.options === undefined ? true : !!scope.options.visible,
              distanceThis = parseFloat(google.maps.geometry.spherical.computeDistanceBetween(dsMapController.getLocation(), placeLocation) / 1000).toFixed(1),
              durationThis = parseInt(distanceThis * 42 / 3.5, 10);

            if (scope.options === undefined) {
              scope.options = {
                visible: true
              };
            } else if (Object.prototype.toString.call(scope.options) == "[object Object]") {
              scope.options.visible = !!scope.options.visible;
            }

            if (setVisibility) {
              dsMapController.bounds.extend(placeLocation);
            }

            scope.place.distance = distanceThis;
            scope.place.duration = durationThis;

            dsMapController.mapRendered.then(function() {
              var marker = setMarkerFunc({
                position: placeLocation,
                visible: setVisibility
              });
              try {
                dsMapController.placesGroupHash[scope.group].push(marker);
              } catch (err) {
                console.warn(err);
              }
            });
          }
        }
      };

      return obj;
    }]);
}(window, window.angular);
<commit_msg>Revert changes of previous commit<commit_after>! function(window, angular, undefined) {
  var defaultMapSettings = {
      center: {
        lat: 12.94206,
        lng: 77.62229
      },
      zoom: 8
    },
    setMarkerFunc = undefined;

  function setMarkerCurryFunc(placesMap) {
    if (placesMap) {
      var map = placesMap;
    }
    return function(marker) {
      if (!map) {
        throw "Please pass a map reference before setting marker";
      }
      if (Object.prototype.toString.call(marker) == "[object Object]" && marker.position !== undefined) {
        marker.map = map;
        var newMarker = new google.maps.Marker(marker);
        newMarker.setMap(map);
        return newMarker;
      }
    }
  }

  angular.module('ds.map', []).
  factory('dsMapFactory', ['$http', function($http) {
    var obj = {
      getDefaultMapSettings: getDefaultMapSettingsFunc,
      setDefaultMapSettings: setDefaultMapSettingsFunc,
      setDirectionsToLocation: function() {}
    };

    function getDefaultMapSettingsFunc() {
      return defaultMapSettings;
    }

    function setDefaultMapSettingsFunc(settingsObj) {
      defaultMapSettings = settingsObj;
    }

    return obj;
  }]).
  directive('dsMap', ['$q', '$timeout', 'dsMapFactory', function($q, $timeout, dsMapFactory) {
    var deferred = $q.defer(),
      obj = {
        scope: {
          dsMapSettings: "="
        },
        restrict: "E",
        link: function(scope) {

        },
        controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) {
          var _deferred = $q.defer(),
            placesDeferred = $q.defer(),
            dsMapElements = 0,
            deferredArray = [],
            that = this,
            dsMapSettings = that.dsMapSettings = $scope.dsMapSettings || dsMapFactory.getDefaultMapSettings(),
            map = new google.maps.Map(document.createElement('div'), dsMapSettings);

          function getLocationFunc() {
            return that.dsPlacesLocation;
          }

          function setLocationFunc(center) {
            that.dsPlacesLocation = center || that.getMap().getCenter();
          }

          function getMapFunc() {
            return that.map;
          }

          function setMapFunc(map) {
            dsMapFactory.map = that.map = map;
            that.setLocation(that.map.getCenter());
            dsMapFactory.marker = {
              position: that.map.getCenter()
            };
          }

          function iterateAllMarkersFunc(callback) {
            for (var groups in that.placesGroupHash) {
              var eachGroupRef = that.placesGroupHash[groups];
              for (var _count = 0, len = eachGroupRef.length; _count < len; _count++) {
                var allIteratedMarkers = eachGroupRef[_count];
                callback.call(allIteratedMarkers);
              }
            }
          }

          function iterateMarkersMatchingBooleanFunc(bool, callback) {
            that.iterateAllMarkers(function() {
              var eachPreviousMarker = this;
              if (eachPreviousMarker.visible === bool) {
                callback.call(eachPreviousMarker);
                eachPreviousMarker.setMap(eachPreviousMarker.getMap());
              }
            });
          }

          function setGroupMarkerVisibilityFunc(group, bool, setVisibleMarkerBounds) {
            var currentGroupRef = that.placesGroupHash[group],
              previousGroup = undefined;
            if (previousGroup != group) {
              that.bounds = new google.maps.LatLngBounds();
              for (var currentGroupCount = 0, len = currentGroupRef.length; currentGroupCount < len; currentGroupCount++) {
                var eachCurrentMarker = currentGroupRef[currentGroupCount];
                if (eachCurrentMarker.visible !== bool) {
                  eachCurrentMarker.visible = bool;
                  eachCurrentMarker.setMap(eachCurrentMarker.getMap());
                  if (setVisibleMarkerBounds && eachCurrentMarker.visible) {
                    that.bounds.extend(eachCurrentMarker.position);
                  }
                }
              }

              if (setVisibleMarkerBounds) {
                that.changeMapBounds();
              }
            }

            previousGroup = group;
          }

          function hideAllVisibleMarkersFunc() {
            that.iterateMarkersMatchingBoolean(true, function() {
              var visibleMarker = this;
              visibleMarker.visible = false;
            });
          }

          function changeMapBoundsFunc() {
            that.getMap().fitBounds(that.bounds);
            that.getMap().setCenter(that.getLocation());
            that.getMap().setZoom(that.getMap().getZoom() - 1);
          }

          that.mapDeferred = deferred;
          that.mapRendered = deferred.promise;
          that.placesDeferred = placesDeferred;
          that.placesRendered = placesDeferred.promise;
          that.placesGroupHash = {};
          that.placesCount = 0;
          that.getLocation = getLocationFunc;
          that.setLocation = setLocationFunc;
          that.getMap = getMapFunc;
          that.setMap = setMapFunc;
          that.iterateAllMarkers = iterateAllMarkersFunc;
          that.iterateMarkersMatchingBoolean = iterateMarkersMatchingBooleanFunc;
          that.setGroupMarkerVisibility = setGroupMarkerVisibilityFunc;
          that.hideAllVisibleMarkers = hideAllVisibleMarkersFunc;
          that.changeMapBounds = changeMapBoundsFunc;

          that.setMap(map);

          that.placesRendered.then(function() {
            that.changeMapBounds();
          });

          (function(dfrd, _dfrd) {
            that.mapRendered.then(function() {
              dsMapFactory.setMarker = setMarkerFunc = setMarkerCurryFunc(that.getMap());
              setMarkerFunc(new google.maps.Marker(dsMapFactory.marker));
            });
          })(deferred, _deferred);

          that.nextDefer = deferred = _deferred;
        }]
      };
    return obj;
  }]).
  directive('dsMapView', function() {
      var obj = {
        scope: {
          dsMapSettings: "="
        },
        restrict: "E",
        replace: true,
        template: "

",
        require: "^?dsMap",
        link: function(scope, element, attrs, dsMapController) {
          var map = new google.maps.Map(element[0], scope.dsMapSettings || dsMapController.dsMapSettings);
          dsMapController.setMap(map);
          dsMapController.isViewSet = true;
        }
      };
      return obj;
    }).directive('dsMapPlaces', ['$q', 'dsMapFactory', function($q, dsMapFactory) {
      var initialdsMapView = true,
        deferred = $q.defer(),
        obj = {
          scope: {
            options: "="
          },
          restrict: "E",
          replace: true,
          require: "^?dsMap",
          link: function(scope, element, attrs, dsMapController) {
            var rankByDistance = google.maps.places.RankBy.DISTANCE;

            function setDirectionsToLocationFunc(location, mode) {
              var request = {
                origin: dsMapController.getLocation(),
                destination: location,
                travelMode: google.maps.TravelMode[mode]
              };

              dsMapController.hideAllVisibleMarkers();
              dsMapController.directionsDisplay.setMap(dsMapController.getMap());
              dsMapController.directionsService.route(request, function(response, status) {
                if (status == "OK") {
                  dsMapController.directionsDisplay.setDirections(response);
                  dsMapController.bounds = new google.maps.LatLngBounds();
                  dsMapController.bounds.extend(dsMapController.getLocation());
                  dsMapController.bounds.extend(location);
                  dsMapController.placesGroupHash['searchedLocation'] = [location];
                  setMarkerFunc({
                    position: location,
                    visible: true
                  });
                  dsMapController.changeMapBounds();
                }
              });
            }

            if (initialdsMapView) {
              dsMapController.mapDeferred.resolve();
              initialdsMapView = false;
            }

            dsMapController.mapRendered.then(function() {
              dsMapController.placesService = new google.maps.places.PlacesService(dsMapController.getMap());
              dsMapController.directionsService = new google.maps.DirectionsService();
              scope.options.map = dsMapController.getMap();
              dsMapController.directionsDisplay = new google.maps.DirectionsRenderer(scope.options);
              dsMapController.bounds = new google.maps.LatLngBounds();
              deferred.resolve(dsMapController.placesService);
            });

            dsMapFactory.dsMapPlacesLoaded(function() {
              if (dsMapController.isViewSet) {
                dsMapFactory.setDirectionsToLocation = setDirectionsToLocationFunc;
              }
            });
          },
          controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) {
            var that = this;

            function dsMapPlacesDeferredFunc() {
              var _deferred = $q.defer();
              return function() {
                return _deferred;
              };
            }

            function dsMapPlacesLoadedFunc(callback) {
              that.dsMapPlacesDeferred().promise.then(callback);
            }

            that.placesServiceSet = deferred.promise;
            that.dsMapPlacesDeferred = dsMapPlacesDeferredFunc();
            dsMapFactory.dsMapPlacesLoaded = that.dsMapPlacesLoaded = dsMapPlacesLoadedFunc;
          }]
        };
      return obj;
    }])
    .directive('dsHasGroup', [function() {
      var previousGroup = undefined,
        obj = {
          require: ["^?dsMap", "^?dsMapPlaces"],
          link: function(scope, element, attrs, dsMapControllers) {
            var dsMapController = dsMapControllers[0],
              dsMapPlacesController = dsMapControllers[1];

            function onToggleClickFunc(group) {
              dsMapController.directionsDisplay.setMap(null);
              if (previousGroup !== undefined) {
                if (previousGroup == group) {
                  return;
                }
                dsMapController.setGroupMarkerVisibility(previousGroup, false, true);
              } else {
                dsMapController.hideAllVisibleMarkers();
              }

              dsMapController.setGroupMarkerVisibility(group, true, true);

              previousGroup = group;
            }

            function toggleGroupVisibilityFunc(group) {
              dsMapPlacesController.dsMapPlacesLoaded(function() {
                onToggleClickFunc(group);
              });
            }

            dsMapController.toggleGroupVisibility = scope.toggleGroupVisibility = toggleGroupVisibilityFunc;
          },
          controller: ['$scope', function($scope) {
            var that = this;
            that.isGroupSet = true;
          }]
        };

      return obj;
    }])
    .directive('dsPlacesType', ['$q', '$timeout', function($q, $timeout) {
      var deferred = $q.defer(),
        placesServiceCount = 0,
        obj = {
          scope: {
            group: "@",
            types: "=",
            options: "=",
            sortOption: "@",
            radius: "="
          },
          templateUrl: "dsMapPlaces.html",
          restrict: "E",
          replace: true,
          require: ["^?dsMap", "^?dsMapPlaces", "^?dsHasGroup"],
          link: function(scope, element, attrs, dsMapControllers) {
            var dsMapController = dsMapControllers[0],
              dsMapPlacesController = dsMapControllers[1],
              dsHasGroupController = dsMapControllers[2],
              obj = {
                location: dsMapController.getMap().getCenter(),
                types: []
              },
              showDirectionTimeoutId = undefined;

            function callPlacesServiceFunc(dfrd, _dfrd, type) {
              dsMapController.placesCount++;
              dsMapController.mapRendered.then(function() {
                dfrd.promise.then(function() {
                  dsMapPlacesController.placesServiceSet.then(function(placesService) {
                    if (type) {
                      obj.types = [type];
                    }

                    placesService.nearbySearch(obj, function(results, status) {
                      if (status == "OK" && Object.prototype.toString.call(results) == "[object Array]") {
                        scope.Places = scope.Places.concat(type === undefined ? results : results.slice(0, scope.types[type]));
                      }
                      $timeout(function() {
                        if ((--dsMapController.placesCount) === 0) {
                          dsMapController.nextDefer.resolve();
                          dsMapController.nextDefer.promise.then(function() {
                            _dfrd.resolve();
                            dsMapPlacesController.dsMapPlacesDeferred().resolve();
                          });
                          dsMapController.placesDeferred.resolve();
                        } else {
                          _dfrd.resolve();
                        }
                      }, 300);
                    });
                  });
                });
              });
            }

            function showDirectionFunc() {
              var that = this;
              $timeout.cancel(showDirectionTimeoutId);
              showDirectionTimeoutId = $timeout(function() {
                var request = {
                  origin: dsMapController.getLocation(),
                  destination: that.place.geometry.location,
                  travelMode: google.maps.TravelMode["DRIVING"]
                };

                if (dsHasGroupController && dsMapController.placesGroupHash[scope.group][0].visible === false) {
                  dsMapController.setGroupMarkerVisibility(scope.group, true, true);
                }

                dsMapController.directionsDisplay.setMap(dsMapController.getMap());

                try {
                  if (that.isDirectionResponseCallMade) {
                    if (that.directionResponse) {
                      dsMapController.directionsDisplay.setDirections(that.directionResponse);
                    }
                    return;
                  }
                  that.isDirectionResponseCallMade = true;
                  dsMapController.directionsService.route(request, function(response, status) {
                    if (status == "OK") {
                      dsMapController.directionsDisplay.setDirections(that.directionResponse = response);
                    }
                  });
                } catch (err) {}
              }, 300)
            }

            if (scope.group !== undefined) {
              dsMapController.placesGroupHash[scope.group] = [];
            }

            if (scope.sortOption && scope.sortOption == "radius") {
              obj.radius = scope.radius || 5000;
            } else {
              obj.rankBy = google.maps.places.RankBy.DISTANCE;
            }

            if (Object.prototype.toString.call(scope.types) == "[object Array]") {
              var _deferred = $q.defer();
              obj.types = scope.types;
              callPlacesServiceFunc(deferred, _deferred);
              deferred = _deferred;
            } else if (Object.prototype.toString.call(scope.types) == "[object Object]") {
              for (var _types in scope.types) {
                (function(_deferred) {
                  _deferred = $q.defer();
                  callPlacesServiceFunc(deferred, _deferred, _types);
                  deferred = _deferred;
                })(_deferred);
              }
            } else {
              throw "'types' attribute must be an array or object"
            }

            if (dsMapController.isViewSet) {
              dsMapPlacesController.dsMapPlacesLoaded(function() {
                scope.showDirection = showDirectionFunc;
              });
            }
          },
          controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) {
            $scope.Places = [];
          }]
        };

      deferred.resolve();

      return obj;
    }]).directive('dsEachPlace', [function() {
      var obj = {
        require: ["^?dsMap", "^?dsMapPlaces", "^?dsPlacesType"],
        link: function(scope, element, attrs, dsMapControllers) {
          var dsMapController = dsMapControllers[0],
            dsMapPlacesController = dsMapControllers[1],
            dsPlacesTypeController = dsMapControllers[2];

          if (scope.place) {
            var placeLocation = scope.place.geometry.location,
              setVisibility = scope.options === undefined ? true : !!scope.options.visible,
              distanceThis = parseFloat(google.maps.geometry.spherical.computeDistanceBetween(dsMapController.getLocation(), placeLocation) / 1000).toFixed(1),
              durationThis = parseInt(distanceThis * 42 / 3.5, 10);

            if (scope.options === undefined) {
              scope.options = {
                visible: true
              };
            } else if (Object.prototype.toString.call(scope.options) == "[object Object]") {
              scope.options.visible = !!scope.options.visible;
            }

            if (setVisibility) {
              dsMapController.bounds.extend(placeLocation);
            }

            scope.place.distance = distanceThis;
            scope.place.duration = durationThis;

            dsMapController.mapRendered.then(function() {
              var marker = setMarkerFunc({
                position: placeLocation,
                visible: setVisibility
              });
              try {
                dsMapController.placesGroupHash[scope.group].push(marker);
              } catch (err) {
                console.warn(err);
              }
            });
          }
        }
      };

      return obj;
    }]);
}(window, window.angular);
<|endoftext|>


<commit_before>(function highlightAnchorScroll() {
  const scrollPct = el => (el.scrollTop + el.offsetHeight) / el.scrollHeight;
  // eslint-disable-next-line no-confusing-arrow
  const easeInOutQuad = t => t < 0.5 ? 2 * t * t : -1 + ((4 - (2 * t)) * t);

  const anchors = Array.from(document.querySelectorAll('h2, h3, h4, h5'));
  const nav = document.querySelector('.docs-nav');
  let currentAnchor;
  let throttleScroll;

  const scrollToAnchor = (anchor) => {
    history.replaceState(undefined, undefined, `${anchor}`);

    const scroller = document.scrollingElement;
    const start = scroller.scrollTop;
    const end = anchor.length > 1 ? document.querySelector(anchor).offsetTop - 40 : 0;
    const dist = end - start;
    let t = 0;
    const step = () => {
      scroller.scrollTop = start + (easeInOutQuad(t) * dist);
      t += 0.06;
      if (t < 1) requestAnimationFrame(step);
      else scroller.scrollTop = end;
    };
    step();
  };

  const updateAnchor = () => {
    const scrollPos = document.scrollingElement.scrollTop;
    const i = anchors.findIndex(el => el.offsetTop > scrollPos);
    if (i !== -1) {
      let inview = anchors[i];
      if (inview.offsetTop > scrollPos + window.innerHeight) {
        inview = anchors[i - 1];
      }
      const newAnchor = document.querySelector(`[href='#${inview.id}']`);
      if (newAnchor && newAnchor !== currentAnchor) {
        if (currentAnchor) currentAnchor.classList.remove('selected');
        newAnchor.classList.add('selected');
        currentAnchor = newAnchor;
        history.replaceState(undefined, undefined, `#${inview.id}`);
      }
    }
    // if (nav) {
    //   const scroller = document.scrollingElement;
    //   const pct = scroller.scrollTop / scroller.scrollHeight;
    //   const navScrollMax = nav.scrollHeight - nav.offsetHeight;
    //   nav.scrollTop = navScrollMax * pct;
    //   console.log(pct);
    // }
    if (scrollPos > 10) {
      document.body.classList.add('docs-scrolled');
    } else {
      document.body.classList.remove('docs-scrolled');
    }
  };
  // updateAnchor();

  [...document.querySelectorAll('a')]
    .filter(a => a.getAttribute('href')[0] === '#')
    .forEach((a) => {
      // a.addEventListener('click', updateAnchor);
      a.addEventListener('click', (e) => {
        e.preventDefault();
        scrollToAnchor(a.getAttribute('href'));
      });
    });

  window.addEventListener('scroll', () => {
    if (!throttleScroll) {
      throttleScroll = setTimeout(() => {
        clearTimeout(throttleScroll);
        throttleScroll = null;
        updateAnchor();
      }, 50);
    }
  });
}());
<commit_msg>Update highlightAnchorScroll.js<commit_after>(function highlightAnchorScroll() {
  const scrollPct = el => (el.scrollTop + el.offsetHeight) / el.scrollHeight;

  // via https://gist.github.com/gre/1650294
  // eslint-disable-next-line no-confusing-arrow
  const easeInOutQuad = t => t < 0.5 ? 2 * t * t : -1 + ((4 - (2 * t)) * t);

  const anchors = Array.from(document.querySelectorAll('h2, h3, h4, h5'));
  const nav = document.querySelector('.docs-nav');

  let currentAnchor;
  let throttleScroll;

  const scrollToAnchor = (anchor) => {
    history.replaceState(undefined, undefined, `${anchor}`);

    const scroller = document.scrollingElement;
    const start = scroller.scrollTop;
    const end = anchor.length > 1 ? document.querySelector(anchor).offsetTop - 40 : 0;
    const dist = end - start;
    let t = 0;
    const step = () => {
      scroller.scrollTop = start + (easeInOutQuad(t) * dist);
      t += 0.06;
      if (t < 1) requestAnimationFrame(step);
      else scroller.scrollTop = end;
    };
    step();
  };

  const updateAnchor = () => {
    const scrollPos = document.scrollingElement.scrollTop;
    const i = anchors.findIndex(el => el.offsetTop > scrollPos);
    if (i !== -1) {
      let inview = anchors[i];
      if (inview.offsetTop > scrollPos + window.innerHeight) {
        inview = anchors[i - 1];
      }
      const newAnchor = document.querySelector(`[href='#${inview.id}']`);
      if (newAnchor && newAnchor !== currentAnchor) {
        if (currentAnchor) currentAnchor.classList.remove('selected');
        newAnchor.classList.add('selected');
        currentAnchor = newAnchor;
        history.replaceState(undefined, undefined, `#${inview.id}`);
      }
    }
    if (scrollPos > 10) {
      document.body.classList.add('docs-scrolled');
    } else {
      document.body.classList.remove('docs-scrolled');
    }
  };

  [...document.querySelectorAll('a')]
    .filter(a => a.getAttribute('href')[0] === '#')
    .forEach((a) => {
      a.addEventListener('click', (e) => {
        e.preventDefault();
        scrollToAnchor(a.getAttribute('href'));
      });
    });

  window.addEventListener('scroll', () => {
    if (!throttleScroll) {
      throttleScroll = setTimeout(() => {
        clearTimeout(throttleScroll);
        throttleScroll = null;
        updateAnchor();
      }, 50);
    }
  });
}());
<|endoftext|>


<commit_before>var FPS = 30;
var ctx = document.getElementById('finger-hero-canvas').getContext('2d');

setInterval(function() {
  update();
  draw();
}, 1000 / FPS);

function update() {

}

function draw() {
  ctx.clearRect(0, 0, 640, 480);
  drawFrets();
}

function drawFrets() {
  for(var i = 0; i < 5; i++) {
    ctx.moveTo(250 + 35 * i, 0);
    ctx.lineTo(180 + 70 * i, 480);
    ctx.stroke();
  }
}
<commit_msg>Create square class<commit_after>var FPS = 30;
var ctx = document.getElementById('finger-hero-canvas').getContext('2d');
var squares = [];

class Square {
  constructor(finger, length) {
    this.finger = finger;
    this.length = length;
    this.y = -length;
  }

  draw() {
    switch(finger) {
      case 0:
        ctx.fillStyle = '#4CAF50';
        break;
      case 1:
        ctx.fillStyle = '#FF4081';
        break;
      case 2:
        ctx.fillStyle = '#FFEB3B';
        break;
      case 3:
        ctx.fillStyle = '#2196F3';
        break;
    }
    ctx.beginPath();
    ctx.moveTo(this.xAt(this.y, this.finger), this.y);
    ctx.lineTo(this.xAt(this.y + this.length, this.finger), this.y + this.length);
    ctx.lineTo(this.xAt(this.y + this.length, this.finger + 1), this.y + this.length);
    ctx.lineTo(this.xAt(this.y, this.finger + 1), this.y);
    ctx.closePath();
    ctx.fill();

    console.log(this.y);
  }

  update() {
    this.y++;
  }

  xAt(y, f) {
    return 250 + 35 * f * (y/(480 / (-70 + 35 * f)));
  }
}

squares.push(new Square(0, 20));

setInterval(function() {
  update();
  draw();
}, 1000 / FPS);

function update() {
  squares.forEach(function(square) {square.update()});
}

function draw() {
  ctx.clearRect(0, 0, 640, 480);
  drawFrets();
  squares.forEach(function(square) {square.draw()});
}

function drawFrets() {
  for(var i = 0; i < 5; i++) {
    ctx.moveTo(250 + 35 * i, 0);
    ctx.lineTo(180 + 70 * i, 480);
    ctx.stroke();
  }
}
<|endoftext|>


<commit_before><commit_msg>Fix bug issue in Settings Ctrl<commit_after><|endoftext|>


<commit_before>/******************************************************************************
 *	Copyright (c) 2004 Actuate Corporation and others.
 *	All rights reserved. This program and the accompanying materials
 *	are made available under the terms of the Eclipse Public License v1.0
 *	which accompanies this distribution, and is available at
 *		http://www.eclipse.org/legal/epl-v10.html
 *
 *	Contributors:
 *		Actuate Corporation - Initial implementation.
 *****************************************************************************/

/**
 *	BirtParameterDialog
 *	...
 */
BirtParameterDialog = Class.create( );

BirtParameterDialog.prototype = Object.extend( new AbstractParameterDialog( ),
{
	/**
	 *	Parameter dialog working state. Whether embedded inside
	 *	designer dialog.
	 */
	__mode : 'frameset',

	/**
	 *	Identify the parameter is null.
	 */
	__isnull : '__isnull',

	/**
	 *	Initialization routine required by "ProtoType" lib.
	 *	@return, void
	 */
	initialize : function( id, mode )
	{
		this.initializeBase( id );
		this.__mode = mode;

		if ( this.__mode == 'parameter' )
		{
			// Hide dialog title bar if embedded in designer.
			var paramDialogTitleBar = $( id + 'dialogTitleBar' );
			paramDialogTitleBar.style.display = 'none';
		}
	},

	/**
	 *	Binding data to the dialog UI. Data includes zoom scaling factor.
	 *	@data, data DOM tree (schema TBD)
	 *	@return, void
	 */
	__bind : function( data )
	{
		if ( !data )
		{
			return;
		}

		var cascadeParamObj = data.getElementsByTagName( 'CascadeParameter' );
		var confirmObj = data.getElementsByTagName( 'Confirmation' );
		if ( cascadeParamObj.length > 0 )
		{
			this.__propogateCascadeParameter( data );
		}
		else if ( confirmObj.length > 0 )
		{
			this.__close( );
		}
	},

	/**
	 *	Collect parameters, include five cases appear in Birt1.0 Viewer.
	 *
	 *	@return, void
	 */
	collect_parameter : function( )
	{
		// Clear parameter array
		this.__parameter = new Array( );

		var k = 0;
		//oTRC[i] is

 section
		var oTRC = document.getElementById( "parameter_table" ).getElementsByTagName( "TR" );
		for( var i = 0; i < oTRC.length; i++ )
		{
			if( !this.__parameter[k] )
			{
				this.__parameter[k] = { };
			}

			//input element collection
			var oIEC = oTRC[i].getElementsByTagName( "input" );
			//select element collection
			var oSEC = oTRC[i].getElementsByTagName( "select" );
			//avoid group parameter
			var oTable = oTRC[i].getElementsByTagName( "table" );
			if( oTable.length > 0 || ( oSEC.length == 0 && oIEC.length == 0 ) || ( oIEC.length == 1 && oIEC[0].type == 'submit' ) )
			{
				continue;
			}

			if( oSEC.length == 1 && oIEC.length <= 1 )
			{
				// deal with "select" parameter
				if( oIEC.length == 1 )
				{
					this.__parameter[k].name = oIEC[0].name;
				}
				else
				{
					this.__parameter[k].name = oSEC[0].name;
				}
				this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
				k++;
			}

			if( oSEC.length == 0 && ( oIEC.length == 1 || oIEC.length == 2 ) )
			{
				var temp = {};
				var tempDef;
				if( oIEC.length == 1 )
				{
					temp = oIEC[0]
				}
				else if( oIEC[0].type == 'hidden' )
				{
					tempDef = oIEC[0]
					temp = oIEC[1];
				}
				else
				{
					continue;
				}

				if( temp.type == 'text' || temp.type == 'password' )
				{
					// deal with "text" parameter
					this.__parameter[k].name = temp.name;
					// if the parameter neither has a value nor a default value, error
					if( temp.value == "" )
					{
						if( tempDef )
						{
							temp.focus( );
							alert( temp.name + " should have a value" );
							return false;
						}
						else
						{
							this.__parameter[k].value = "";
						}
					}
					else
					{
						this.__parameter[k].value = temp.value;
					}
					k++;
				}
				else if( temp.type == 'checkbox' )
				{
					// deal with checkbox
					this.__parameter[k].name = temp.value;
					temp.checked?this.__parameter[k].value = 'true':this.__parameter[k].value = 'false';
					k++;
				}
				else
				{
					//handle more cases
				}
			}
			else if( oSEC.length <= 1 && oIEC.length > 2 )
			{
				for( var j = 0; j < oIEC.length; j++ )
				{
					// deal with radio
					if( oIEC[j].type == 'radio' && oIEC[j].checked )
					{
						if( oIEC[j+1] && ( oIEC[j+1].type == 'text' || oIEC[j+1].type == 'password' ) )
						{
							//Check if allow blank
							var temp = oIEC[j+2];
							if ( temp && temp.value == 'true' )
							{
								if ( oIEC[j+1].value == '' )
								{
									oIEC[j+1].focus( );
									alert( temp.name + " should have a value" );
									return false;
								}
							}

							// deal with radio box with textarea or password area
							if( oIEC[j+1].name && oIEC[j+1].value )
							{
								this.__parameter[k].name = oIEC[j+1].name
								this.__parameter[k].value = oIEC[j+1].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = oIEC[j].value
								this.__parameter[k].value = oIEC[j+1].value;
								oIEC[j+1].value = "";
								k++;
							}
						}
						else if( oSEC[0] )
						{
							// deal with "select" parameter
							if ( oSEC[0].selectedIndex == -1 )
							{
								oSEC[0].focus( );
								alert( oIEC[j].value + " should have a value" );
								return false;
							}

							// Check if select 'Null Value' option
							var temp = oSEC[0].options[oSEC[0].selectedIndex].text;
							if( temp && temp != 'Null Value' )
							{
								this.__parameter[k].name = oIEC[j].value;
								this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = this.__isnull;
								this.__parameter[k].value = oIEC[j].value;
								k++;
							}
						}
						else if( !oIEC[j+1] && !oIEC[j].name )
						{
							//deal with common radio with null value
							this.__parameter[k].name = this.__isnull;
							this.__parameter[k].value = oIEC[j-1].name;
							k++;
						}
						else
						{
							//deal with common radio
							this.__parameter[k].name = oIEC[j].name;
							this.__parameter[k].value = oIEC[j].value;
							k++;
						}
					}
				}
			}
		}
		return true;
	},

	/**
	 *	Handle clicking on okRun.
	 *
	 *	@event, incoming browser native event
	 *	@return, void
	 */
	__okPress : function( )
	{
		if( birtParameterDialog.collect_parameter( ) )
		{
			if ( this.__mode == 'parameter' )
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CACHE_PARAMETER );
			}
			else if ( this.__mode == 'run' )
			{
				this.__doSubmit( );
			}
			else
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CHANGE_PARAMETER );
				this.__l_hide( );
			}
		}
	},

	/**
	 *	Override cancel button click.
	 */
	__neh_cancel : function( )
	{
		if ( this.__mode == 'parameter' )
		{
			this.__cancel();
		}
		else
		{
			this.__l_hide( );
		}
	},

	/**
	 *	Handle submit form with current parameters.
	 *
	 *	@return, void
	 */
	__doSubmit : function( )
	{
		var divObj = document.createElement( "DIV" );
		document.body.appendChild( divObj );
		divObj.style.display = "none";

		var formObj = document.createElement( "FORM" );
		divObj.appendChild( formObj );
		formObj.action = window.location.href;
		formObj.method = "post";

		if ( this.__parameter != null )
		{
			for( var i = 0; i < this.__parameter.length; i++ )
			{
				var param = document.createElement( "INPUT" );
				formObj.appendChild( param );
				param.TYPE = "HIDDEN";
				param.name = this.__parameter[i].name;
				param.value = this.__parameter[i].value;
			}
		}

		this.__l_hide( );
		formObj.submit( );
	},

	/**
	 *	Caching parameters success, close window.
	 *
	 *	@return, void
	 */
	__close : function( )
	{
		window.status = "close";
		//window.opener = null;
		//window.close( );
	},

	/**
	 *	Click 'Cancel', close window.
	 *
	 *	@return, void
	 */
	__cancel : function( )
	{
		window.status = "cancel";
	}
}
);<commit_msg>Fix Bugzilla Bug 142705<commit_after>/******************************************************************************
 *	Copyright (c) 2004 Actuate Corporation and others.
 *	All rights reserved. This program and the accompanying materials
 *	are made available under the terms of the Eclipse Public License v1.0
 *	which accompanies this distribution, and is available at
 *		http://www.eclipse.org/legal/epl-v10.html
 *
 *	Contributors:
 *		Actuate Corporation - Initial implementation.
 *****************************************************************************/

/**
 *	BirtParameterDialog
 *	...
 */
BirtParameterDialog = Class.create( );

BirtParameterDialog.prototype = Object.extend( new AbstractParameterDialog( ),
{
	/**
	 *	Parameter dialog working state. Whether embedded inside
	 *	designer dialog.
	 */
	__mode : 'frameset',

	/**
	 *	Identify the parameter is null.
	 */
	__isnull : '__isnull',

	/**
	 *	Initialization routine required by "ProtoType" lib.
	 *	@return, void
	 */
	initialize : function( id, mode )
	{
		this.initializeBase( id );
		this.__mode = mode;

		if ( this.__mode == 'parameter' )
		{
			// Hide dialog title bar if embedded in designer.
			var paramDialogTitleBar = $( id + 'dialogTitleBar' );
			paramDialogTitleBar.style.display = 'none';
		}
	},

	/**
	 *	Binding data to the dialog UI. Data includes zoom scaling factor.
	 *	@data, data DOM tree (schema TBD)
	 *	@return, void
	 */
	__bind : function( data )
	{
		if ( !data )
		{
			return;
		}

		var cascadeParamObj = data.getElementsByTagName( 'CascadeParameter' );
		var confirmObj = data.getElementsByTagName( 'Confirmation' );
		if ( cascadeParamObj.length > 0 )
		{
			this.__propogateCascadeParameter( data );
		}
		else if ( confirmObj.length > 0 )
		{
			this.__close( );
		}
	},

	/**
	 *	Collect parameters, include five cases appear in Birt1.0 Viewer.
	 *
	 *	@return, void
	 */
	collect_parameter : function( )
	{
		// Clear parameter array
		this.__parameter = new Array( );

		var k = 0;
		//oTRC[i] is

 section
		var oTRC = document.getElementById( "parameter_table" ).getElementsByTagName( "TR" );
		for( var i = 0; i < oTRC.length; i++ )
		{
			if( !this.__parameter[k] )
			{
				this.__parameter[k] = { };
			}

			//input element collection
			var oIEC = oTRC[i].getElementsByTagName( "input" );
			//select element collection
			var oSEC = oTRC[i].getElementsByTagName( "select" );
			//avoid group parameter
			var oTable = oTRC[i].getElementsByTagName( "table" );
			if( oTable.length > 0 || ( oSEC.length == 0 && oIEC.length == 0 ) || ( oIEC.length == 1 && oIEC[0].type == 'submit' ) )
			{
				continue;
			}

			if( oSEC.length == 1 && oIEC.length <= 1 )
			{
				// deal with "select" parameter
				if( oIEC.length == 1 )
				{
					this.__parameter[k].name = oIEC[0].name;
				}
				else
				{
					this.__parameter[k].name = oSEC[0].name;
				}
				this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
				k++;
			}

			if( oSEC.length == 0 && ( oIEC.length == 1 || oIEC.length == 2 ) )
			{
				var temp = {};
				var tempDef = null;
				if( oIEC.length == 1 )
				{
					temp = oIEC[0]
				}
				else if( oIEC[0].type == 'hidden' )
				{
					tempDef = oIEC[0]
					temp = oIEC[1];
				}
				else
				{
					continue;
				}

				if( temp.type == 'text' || temp.type == 'password' )
				{
					// deal with "text" parameter
					this.__parameter[k].name = temp.name;
					// if the parameter neither has a value nor a default value, error
					if( temp.value == "" )
					{
						if( tempDef )
						{
							temp.focus( );
							alert( temp.name + " should have a value" );
							return false;
						}
						else
						{
							this.__parameter[k].value = "";
						}
					}
					else
					{
						this.__parameter[k].value = temp.value;
					}
					k++;
				}
				else if( temp.type == 'checkbox' )
				{
					// deal with checkbox
					this.__parameter[k].name = temp.value;
					temp.checked?this.__parameter[k].value = 'true':this.__parameter[k].value = 'false';
					k++;
				}
				else
				{
					//handle more cases
				}
			}
			else if( oSEC.length <= 1 && oIEC.length > 2 )
			{
				for( var j = 0; j < oIEC.length; j++ )
				{
					// deal with radio
					if( oIEC[j].type == 'radio' && oIEC[j].checked )
					{
						if( oIEC[j+1] && ( oIEC[j+1].type == 'text' || oIEC[j+1].type == 'password' ) )
						{
							//Check if allow blank
							var temp = oIEC[j+2];
							if ( temp && temp.value == 'true' )
							{
								if ( oIEC[j+1].value == '' )
								{
									oIEC[j+1].focus( );
									alert( temp.name + " should have a value" );
									return false;
								}
							}

							// deal with radio box with textarea or password area
							if( oIEC[j+1].name && oIEC[j+1].value )
							{
								this.__parameter[k].name = oIEC[j+1].name
								this.__parameter[k].value = oIEC[j+1].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = oIEC[j].value
								this.__parameter[k].value = oIEC[j+1].value;
								oIEC[j+1].value = "";
								k++;
							}
						}
						else if( oSEC[0] )
						{
							// deal with "select" parameter
							if ( oSEC[0].selectedIndex == -1 )
							{
								oSEC[0].focus( );
								alert( oIEC[j].value + " should have a value" );
								return false;
							}

							// Check if select 'Null Value' option
							var temp = oSEC[0].options[oSEC[0].selectedIndex].text;
							if( temp && temp != 'Null Value' )
							{
								this.__parameter[k].name = oIEC[j].value;
								this.__parameter[k].value = oSEC[0].options[oSEC[0].selectedIndex].value;
								k++;
							}
							else
							{
								this.__parameter[k].name = this.__isnull;
								this.__parameter[k].value = oIEC[j].value;
								k++;
							}
						}
						else if( !oIEC[j+1] && !oIEC[j].name )
						{
							//deal with common radio with null value
							this.__parameter[k].name = this.__isnull;
							this.__parameter[k].value = oIEC[j-1].name;
							k++;
						}
						else
						{
							//deal with common radio
							this.__parameter[k].name = oIEC[j].name;
							this.__parameter[k].value = oIEC[j].value;
							k++;
						}
					}
				}
			}
		}
		return true;
	},

	/**
	 *	Handle clicking on okRun.
	 *
	 *	@event, incoming browser native event
	 *	@return, void
	 */
	__okPress : function( )
	{
		if( birtParameterDialog.collect_parameter( ) )
		{
			if ( this.__mode == 'parameter' )
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CACHE_PARAMETER );
			}
			else if ( this.__mode == 'run' )
			{
				this.__doSubmit( );
			}
			else
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_CHANGE_PARAMETER );
				this.__l_hide( );
			}
		}
	},

	/**
	 *	Override cancel button click.
	 */
	__neh_cancel : function( )
	{
		if ( this.__mode == 'parameter' )
		{
			this.__cancel();
		}
		else
		{
			this.__l_hide( );
		}
	},

	/**
	 *	Handle submit form with current parameters.
	 *
	 *	@return, void
	 */
	__doSubmit : function( )
	{
		var action = window.location.href;

		var divObj = document.createElement( "DIV" );
		document.body.appendChild( divObj );
		divObj.style.display = "none";

		var formObj = document.createElement( "FORM" );
		divObj.appendChild( formObj );

		if ( this.__parameter != null )
		{
			for( var i = 0; i < this.__parameter.length; i++ )
			{
				var param = document.createElement( "INPUT" );
				formObj.appendChild( param );
				param.TYPE = "HIDDEN";
				param.name = this.__parameter[i].name;
				param.value = this.__parameter[i].value;

				//replace the URL parameter
				var reg = new RegExp( "&" + param.name + "[^&]*&*", "g" );
				action = action.replace( reg, "&" );
			}
		}

		formObj.action = action;
		formObj.method = "post";

		this.__l_hide( );
		formObj.submit( );
	},

	/**
	 *	Caching parameters success, close window.
	 *
	 *	@return, void
	 */
	__close : function( )
	{
		window.status = "close";
		//window.opener = null;
		//window.close( );
	},

	/**
	 *	Click 'Cancel', close window.
	 *
	 *	@return, void
	 */
	__cancel : function( )
	{
		window.status = "cancel";
	}
}
);<|endoftext|>