<commit_before>this.mmooc = this.mmooc || {};

this.mmooc.enroll = (function() {
  return {
    changeEnrollConfirmationButton: function() {
      var enrollForm = $('#enroll_form');
      enrollForm
        .find('.btn')
        .text('Gå til mine ' + mmooc.i18n.CoursePlural.toLowerCase());
      enrollForm.find('.btn').attr('href', '/courses');
      enrollForm.find('.btn-primary').hide();
    },
    changeEnrollTitle: function(s) {
      var headline = $('.ic-Login-confirmation__headline');
      headline.text(s);
    },
    getEnrollInformationElement: function() {
      //There might be several p elements, depending on which self registration screen we are on.
      //Only return the first one.
      return $('#enroll_form > p:first');
    },
    getEnrollAction: function() {
      return $('#enroll_form').attr('action');
    },
    changeEnrollInformation: function(from, to) {
      var confirmEnrollmentElement = this.getEnrollInformationElement();
      confirmEnrollmentElement.text(
        confirmEnrollmentElement.text().replace(from, to)
      );
    },
    hideEnrollInformationPolicy: function() {
      var informationPolicy = $('.ic-Self-enrollment-footer__Secondary');
      informationPolicy.hide();
    },
    changeEnrollButton: function() {
      var enrollForm = $('#enroll_form');
      var confirmButton = enrollForm.find('.btn');
      confirmButton.text('Ja takk, jeg vil registrere meg!');
    },
    hideEnrollButton: function() {
      var enrollForm = $('#enroll_form');
      var confirmButton = enrollForm.find('.btn');
      confirmButton.hide();
    },
    isAlreadyEnrolled: function() {
      confirmEnrollmentElement = this.getEnrollInformationElement();
      var i = confirmEnrollmentElement
        .text()
        .indexOf('Du er allerede registrert i');
      if (i == -1) {
        return false;
      }
      return true;
    },
    selectRegisterUserCheckbox: function() {
      //The checkbox is hidden by canvas-enroll.less, but we need to check it to get the right fields to display.
      setTimeout(function() {
        var createNewUserRadioButton = $('#selfEnrollmentAuthRegCreate');
        createNewUserRadioButton.click();
      }, 1000); // set timeout in ms
    },
    updatePrivacyPolicyLinks: function() {
      html = mmooc.util.renderTemplateWithData('enrollprivacypolicy', {
        privacypolicylink: mmooc.settings.privacyPolicyLink
      });
      $("label[for='selfEnrollmentAuthRegLoginAgreeTerms']").html(html);
    },
    isSelfEnrollmentPage: function() {
      var i = this.getEnrollInformationElement()
        .text()
        .indexOf('Du registrerer deg i');
      if (i == -1) {
        return false;
      }
      return true;
    },
    changeEnrollPage: function() {
      this.changeEnrollTitle('Påmelding');
      if (this.isAlreadyEnrolled()) {
        this.changeEnrollConfirmationButton();
      } else {
        this.hideEnrollInformationPolicy();
        if (this.isSelfEnrollmentPage()) {
          //When self enrolling, give the user the impression of registering on the platform, and not on the course
          //we use to make self enrollment possible. See settings.js/selfRegisterCourseCode
          this.getEnrollInformationElement().text('');
          $('#enroll_form > p:nth-child(2)').text(
            'Vennligst fyll inn informasjonen nedenfor for å registrere deg på ' +
              mmooc.settings.platformName
          );
          this.selectRegisterUserCheckbox();
          this.updatePrivacyPolicyLinks();
          this.changeEnrollButton();
        } else {
          this.hideEnrollButton();
          this.changeEnrollInformation(
            'Du registrere deg på ',
            'Vi registrerer deg på ' +
              mmooc.i18n.CourseDefinite.toLowerCase() +
              ' '
          );
          var enrollInformationElement = this.getEnrollInformationElement();
          enrollInformationElement.html(" ");
          var enrollAction = this.getEnrollAction();
          mmooc.api.enrollUser(enrollAction, function(data) {
            $('.loading-gif').remove();
            window.location.href = '/search/all_courses';
          });
        }
      }
    },
    printAllCoursesContainer: function() {
      html = mmooc.util.renderTemplateWithData('allcoursescontainer', {
        courseLabel: mmooc.i18n.Course.toLowerCase()
      });
      document.title = 'Tilgjengelige ' + mmooc.i18n.CoursePlural.toLowerCase();
      document.getElementById('content').innerHTML = html;
    },
    printAllCourses: function() {
      html = "";
      $('.mmooc-all-courses-list').append(html);
      mmooc.api.getAllCourses(function(allCourses) {
        mmooc.api.getEnrolledCourses(function(enrolledCourses) {
          var allCoursesWithStatus = mmooc.enroll.setCourseEnrolledStatus(
            allCourses,
            enrolledCourses
          );

          var categorys = mmooc.util.getCourseCategories(allCoursesWithStatus);

          /* If the amount of courses is large, the filter select box and corresponding javascript code in allcoursescontainer.hbs should be enabled

          mmooc.enroll.populateFilter(categorys);

          $("#filter").change(function () {
            mmooc.enroll.applyFilter();
          });

          */

          var coursesCategorized = mmooc.util.getCoursesCategorized(
            allCoursesWithStatus,
            categorys
          );

          $('.loading-gif').remove();

          for (var i = 0; i < coursesCategorized.length; i++) {
            html = mmooc.util.renderTemplateWithData('allcourseslist', {
              title: coursesCategorized[i].title,
              courses: coursesCategorized[i].courses,
              courseLabel: mmooc.i18n.Course.toLowerCase(),
              index: i
            });
            $('.mmooc-all-courses-list').append(html);
          }
          mmooc.enroll.insertModalAndOverlay();
          mmooc.enroll.setClickHandlers();

          // TODO: move if there is a better place for this code - it handles course list UI
          // accordion UI
          $('.mmooc-accordion-header').click(event => {
            let accordionIndex = event.target.getAttribute('index');

            if (
              $(`#mmooc-accordion-header-${accordionIndex}`).hasClass(
                'mmooc-accordion-header-active'
              )
            ) {
              $(`#mmooc-accordion-header-${accordionIndex}`).toggleClass(
                'mmooc-accordion-header-active'
              );
            } else {
              $('.mmooc-accordion-header-active').removeClass(
                'mmooc-accordion-header-active'
              );

              $(`#mmooc-accordion-header-${accordionIndex}`).addClass(
                'mmooc-accordion-header-active'
              );
            }

            // remove active tabs when new accordion element is clicked
            $('.mmooc-tab-head').removeClass('mmooc-tab-head-active');
            $('.mmooc-tab-content').removeClass('mmooc-tab-content-active');
            $('.mmooc-tabs-mobile-header-active').removeClass(
              'mmooc-tabs-mobile-header-active'
            );
            $('.mmooc-tabs-mobile-content-active').removeClass(
              'mmooc-tabs-mobile-content-active'
            );

            // add active class to first tab when the accordion element is opened
            $('.mmooc-tab-head-0').addClass('mmooc-tab-head-active');
            $('.mmooc-tab-content-0').addClass('mmooc-tab-content-active');
          });

          // tabs
          $('.mmooc-tab-head').click(event => {
            let tabIndex = event.target.getAttribute('index');

            $('.mmooc-tab-head').removeClass('mmooc-tab-head-active');
            $(`#mmooc-tab-head-${tabIndex}`).addClass('mmooc-tab-head-active');

            $('.mmooc-tab-content').removeClass('mmooc-tab-content-active');
            $(`#mmooc-tab-content-${tabIndex}`).addClass(
              'mmooc-tab-content-active'
            );
          });

          // tabs-mobile

          $('.mmooc-tabs-mobile-header').click(event => {
            let mobileTabIndex = event.target.getAttribute('index');

            if (
              $(`#mmooc-tabs-mobile-header-${mobileTabIndex}`).hasClass(
                'mmooc-tabs-mobile-header-active'
              )
            ) {
              $(`#mmooc-tabs-mobile-header-${mobileTabIndex}`).toggleClass(
                'mmooc-tabs-mobile-header-active'
              );
              $(`#mmooc-tabs-mobile-content-${mobileTabIndex}`).toggleClass(
                'mmooc-tabs-mobile-content-active'
              );
            } else {
              $('.mmooc-tabs-mobile-header-active').removeClass(
                'mmooc-tabs-mobile-header-active'
              );
              $('.mmooc-tabs-mobile-content-active').removeClass(
                'mmooc-tabs-mobile-content-active'
              );

              $(`#mmooc-tabs-mobile-header-${mobileTabIndex}`).addClass(
                'mmooc-tabs-mobile-header-active'
              );
              $(`#mmooc-tabs-mobile-content-${mobileTabIndex}`).addClass(
                'mmooc-tabs-mobile-content-active'
              );
            }
          });
        });
      });
    },
    setCourseEnrolledStatus: function(allCourses, enrolledCourses) {
      var allCoursesWithStatus = [];
      for (var i = 0; i < allCourses.length; i++) {
        allCourses[i].course.enrolled = false;
        for (var j = 0; j < enrolledCourses.length; j++) {
          if (allCourses[i].course.id == enrolledCourses[j].id) {
            allCourses[i].course.enrolled = true;
          }
        }
        allCoursesWithStatus.push(allCourses[i].course);
      }
      return allCoursesWithStatus;
    },
    insertModalAndOverlay: function() {
      $('body').append("

");
      $('body').append("

");
    },
    handleEnrollClick: function(e, html) {
      $('.mmooc-modal').html(html);
      $('.mmooc-modal-overlay').show();
      $('.mmooc-modal').show();
      $('.mmooc-modal .modal-back').click(function(e) {
        e.preventDefault();
        $('.mmooc-modal-overlay').hide();
        $('.mmooc-modal').hide();
      });
    },
    setClickHandlers: function() {
      $('.notenrolled').click(function(e) {
        e.preventDefault();
        var html = $(this)
          .next()
          .html();
        mmooc.enroll.handleEnrollClick(e, html);
      });
      $('.all-courses-show-modal').click(function(e) {
        e.preventDefault();
        var html = $(this)
          .parent()
          .next()
          .html();
        mmooc.enroll.handleEnrollClick(e, html);
      });
      $('.mmooc-modal-overlay').click(function(e) {
        e.preventDefault();
        $('.mmooc-modal-overlay').hide();
        $('.mmooc-modal').hide();
      });
      $(document).on('keydown', function(e) {
        if (e.keyCode === 27) {
          $('.mmooc-modal-overlay').hide();
          $('.mmooc-modal').hide();
        }
      });
    },
    populateFilter: function(categorys) {
      var options =
        '<option value="Alle">Alle tilgjengelige ' +
        mmooc.i18n.CoursePlural.toLowerCase() +
        '</option>';
      for (var i = 0; i < categorys.length; i++) {
        options +=
          '<option value="' + categorys[i] + '">' + categorys[i] + '</option>';
      }
      $('#filter').append(options);
    },
    applyFilter: function() {
      var value = $('#filter').val();
      if (value == 'Alle') {
        $('.mmooc-all-courses-list').removeClass('filter-active');
        $('.mmooc-all-courses-list h2').each(function() {
          $(this).show();
          $(this)
            .next()
            .show();
        });
      } else {
        $('.mmooc-all-courses-list').addClass('filter-active');
        $('.mmooc-all-courses-list h2').each(function() {
          if ($(this).text() == value) {
            $(this).show();
            $(this)
              .next()
              .show();
          } else {
            $(this).hide();
            $(this)
              .next()
              .hide();
          }
        });
      }
    }
  };
})();
<commit_msg>update data that is passed to handlebars template<commit_after>this.mmooc = this.mmooc || {};

this.mmooc.enroll = (function() {
  return {
    changeEnrollConfirmationButton: function() {
      var enrollForm = $('#enroll_form');
      enrollForm
        .find('.btn')
        .text('Gå til mine ' + mmooc.i18n.CoursePlural.toLowerCase());
      enrollForm.find('.btn').attr('href', '/courses');
      enrollForm.find('.btn-primary').hide();
    },
    changeEnrollTitle: function(s) {
      var headline = $('.ic-Login-confirmation__headline');
      headline.text(s);
    },
    getEnrollInformationElement: function() {
      //There might be several p elements, depending on which self registration screen we are on.
      //Only return the first one.
      return $('#enroll_form > p:first');
    },
    getEnrollAction: function() {
      return $('#enroll_form').attr('action');
    },
    changeEnrollInformation: function(from, to) {
      var confirmEnrollmentElement = this.getEnrollInformationElement();
      confirmEnrollmentElement.text(
        confirmEnrollmentElement.text().replace(from, to)
      );
    },
    hideEnrollInformationPolicy: function() {
      var informationPolicy = $('.ic-Self-enrollment-footer__Secondary');
      informationPolicy.hide();
    },
    changeEnrollButton: function() {
      var enrollForm = $('#enroll_form');
      var confirmButton = enrollForm.find('.btn');
      confirmButton.text('Ja takk, jeg vil registrere meg!');
    },
    hideEnrollButton: function() {
      var enrollForm = $('#enroll_form');
      var confirmButton = enrollForm.find('.btn');
      confirmButton.hide();
    },
    isAlreadyEnrolled: function() {
      confirmEnrollmentElement = this.getEnrollInformationElement();
      var i = confirmEnrollmentElement
        .text()
        .indexOf('Du er allerede registrert i');
      if (i == -1) {
        return false;
      }
      return true;
    },
    selectRegisterUserCheckbox: function() {
      //The checkbox is hidden by canvas-enroll.less, but we need to check it to get the right fields to display.
      setTimeout(function() {
        var createNewUserRadioButton = $('#selfEnrollmentAuthRegCreate');
        createNewUserRadioButton.click();
      }, 1000); // set timeout in ms
    },
    updatePrivacyPolicyLinks: function() {
      html = mmooc.util.renderTemplateWithData('enrollprivacypolicy', {
        privacypolicylink: mmooc.settings.privacyPolicyLink
      });
      $("label[for='selfEnrollmentAuthRegLoginAgreeTerms']").html(html);
    },
    isSelfEnrollmentPage: function() {
      var i = this.getEnrollInformationElement()
        .text()
        .indexOf('Du registrerer deg i');
      if (i == -1) {
        return false;
      }
      return true;
    },
    changeEnrollPage: function() {
      this.changeEnrollTitle('Påmelding');
      if (this.isAlreadyEnrolled()) {
        this.changeEnrollConfirmationButton();
      } else {
        this.hideEnrollInformationPolicy();
        if (this.isSelfEnrollmentPage()) {
          //When self enrolling, give the user the impression of registering on the platform, and not on the course
          //we use to make self enrollment possible. See settings.js/selfRegisterCourseCode
          this.getEnrollInformationElement().text('');
          $('#enroll_form > p:nth-child(2)').text(
            'Vennligst fyll inn informasjonen nedenfor for å registrere deg på ' +
              mmooc.settings.platformName
          );
          this.selectRegisterUserCheckbox();
          this.updatePrivacyPolicyLinks();
          this.changeEnrollButton();
        } else {
          this.hideEnrollButton();
          this.changeEnrollInformation(
            'Du registrere deg på ',
            'Vi registrerer deg på ' +
              mmooc.i18n.CourseDefinite.toLowerCase() +
              ' '
          );
          var enrollInformationElement = this.getEnrollInformationElement();
          enrollInformationElement.html(" ");
          var enrollAction = this.getEnrollAction();
          mmooc.api.enrollUser(enrollAction, function(data) {
            $('.loading-gif').remove();
            window.location.href = '/search/all_courses';
          });
        }
      }
    },
    printAllCoursesContainer: function() {
      html = mmooc.util.renderTemplateWithData('allcoursescontainer', {
        courseLabel: mmooc.i18n.Course.toLowerCase()
      });
      document.title = 'Tilgjengelige ' + mmooc.i18n.CoursePlural.toLowerCase();
      document.getElementById('content').innerHTML = html;
    },
    printAllCourses: function() {
      html = "";
      $('.mmooc-all-courses-list').append(html);
      mmooc.api.getAllCourses(function(allCourses) {
        mmooc.api.getEnrolledCourses(function(enrolledCourses) {
          var allCoursesWithStatus = mmooc.enroll.setCourseEnrolledStatus(
            allCourses,
            enrolledCourses
          );

          var categorys = mmooc.util.getCourseCategories(allCoursesWithStatus);

          /* If the amount of courses is large, the filter select box and corresponding javascript code in allcoursescontainer.hbs should be enabled

          mmooc.enroll.populateFilter(categorys);

          $("#filter").change(function () {
            mmooc.enroll.applyFilter();
          });

          */

          var coursesCategorized = mmooc.util.getCoursesCategorized(
            allCoursesWithStatus,
            categorys
          );

          $('.loading-gif').remove();

          for (var i = 0; i < coursesCategorized.length; i++) {
            const coursesCategory = coursesCategorized[i];
            const coursesEnrolled = coursesCategory.courses.filter(c => c.enrolled === true ).length;

            html = mmooc.util.renderTemplateWithData('allcourseslist', {
              title: coursesCategory.title,
              isAuthenticated: mmooc.util.isAuthenticated(),
              courses: coursesCategory.courses,
              coursesEnrolled: coursesEnrolled,
              coursesAmount: coursesCategory.courses && coursesCategory.courses.length,
              courseLabel: mmooc.i18n.Course.toLowerCase(),
              index: i
            });
            $('.mmooc-all-courses-list').append(html);
          }
          mmooc.enroll.insertModalAndOverlay();
          mmooc.enroll.setClickHandlers();

          // TODO: move if there is a better place for this code - it handles course list UI
          // accordion UI
          $('.mmooc-accordion-header').click(event => {
            let accordionIndex = event.target.getAttribute('index');

            if (
              $(`#mmooc-accordion-header-${accordionIndex}`).hasClass(
                'mmooc-accordion-header-active'
              )
            ) {
              $(`#mmooc-accordion-header-${accordionIndex}`).toggleClass(
                'mmooc-accordion-header-active'
              );
            } else {
              $('.mmooc-accordion-header-active').removeClass(
                'mmooc-accordion-header-active'
              );

              $(`#mmooc-accordion-header-${accordionIndex}`).addClass(
                'mmooc-accordion-header-active'
              );
            }

            // remove active tabs when new accordion element is clicked
            $('.mmooc-tab-head').removeClass('mmooc-tab-head-active');
            $('.mmooc-tab-content').removeClass('mmooc-tab-content-active');
            $('.mmooc-tabs-mobile-header-active').removeClass(
              'mmooc-tabs-mobile-header-active'
            );
            $('.mmooc-tabs-mobile-content-active').removeClass(
              'mmooc-tabs-mobile-content-active'
            );

            // add active class to first tab when the accordion element is opened
            $('.mmooc-tab-head-0').addClass('mmooc-tab-head-active');
            $('.mmooc-tab-content-0').addClass('mmooc-tab-content-active');
          });

          // tabs
          $('.mmooc-tab-head').click(event => {
            let tabIndex = event.target.getAttribute('index');

            $('.mmooc-tab-head').removeClass('mmooc-tab-head-active');
            $(`#mmooc-tab-head-${tabIndex}`).addClass('mmooc-tab-head-active');

            $('.mmooc-tab-content').removeClass('mmooc-tab-content-active');
            $(`#mmooc-tab-content-${tabIndex}`).addClass(
              'mmooc-tab-content-active'
            );
          });

          // tabs-mobile

          $('.mmooc-tabs-mobile-header').click(event => {
            let mobileTabIndex = event.target.getAttribute('index');

            if (
              $(`#mmooc-tabs-mobile-header-${mobileTabIndex}`).hasClass(
                'mmooc-tabs-mobile-header-active'
              )
            ) {
              $(`#mmooc-tabs-mobile-header-${mobileTabIndex}`).toggleClass(
                'mmooc-tabs-mobile-header-active'
              );
              $(`#mmooc-tabs-mobile-content-${mobileTabIndex}`).toggleClass(
                'mmooc-tabs-mobile-content-active'
              );
            } else {
              $('.mmooc-tabs-mobile-header-active').removeClass(
                'mmooc-tabs-mobile-header-active'
              );
              $('.mmooc-tabs-mobile-content-active').removeClass(
                'mmooc-tabs-mobile-content-active'
              );

              $(`#mmooc-tabs-mobile-header-${mobileTabIndex}`).addClass(
                'mmooc-tabs-mobile-header-active'
              );
              $(`#mmooc-tabs-mobile-content-${mobileTabIndex}`).addClass(
                'mmooc-tabs-mobile-content-active'
              );
            }
          });
        });
      });
    },
    setCourseEnrolledStatus: function(allCourses, enrolledCourses) {
      var allCoursesWithStatus = [];
      for (var i = 0; i < allCourses.length; i++) {
        allCourses[i].course.enrolled = false;
        for (var j = 0; j < enrolledCourses.length; j++) {
          if (allCourses[i].course.id == enrolledCourses[j].id) {
            allCourses[i].course.enrolled = true;
          }
        }
        allCoursesWithStatus.push(allCourses[i].course);
      }
      return allCoursesWithStatus;
    },
    insertModalAndOverlay: function() {
      $('body').append("

");
      $('body').append("

");
    },
    handleEnrollClick: function(e, html) {
      $('.mmooc-modal').html(html);
      $('.mmooc-modal-overlay').show();
      $('.mmooc-modal').show();
      $('.mmooc-modal .modal-back').click(function(e) {
        e.preventDefault();
        $('.mmooc-modal-overlay').hide();
        $('.mmooc-modal').hide();
      });
    },
    setClickHandlers: function() {
      $('.notenrolled').click(function(e) {
        e.preventDefault();
        var html = $(this)
          .next()
          .html();
        mmooc.enroll.handleEnrollClick(e, html);
      });
      $('.all-courses-show-modal').click(function(e) {
        e.preventDefault();
        var html = $(this)
          .parent()
          .next()
          .html();
        mmooc.enroll.handleEnrollClick(e, html);
      });
      $('.mmooc-modal-overlay').click(function(e) {
        e.preventDefault();
        $('.mmooc-modal-overlay').hide();
        $('.mmooc-modal').hide();
      });
      $(document).on('keydown', function(e) {
        if (e.keyCode === 27) {
          $('.mmooc-modal-overlay').hide();
          $('.mmooc-modal').hide();
        }
      });
    },
    populateFilter: function(categorys) {
      var options =
        '<option value="Alle">Alle tilgjengelige ' +
        mmooc.i18n.CoursePlural.toLowerCase() +
        '</option>';
      for (var i = 0; i < categorys.length; i++) {
        options +=
          '<option value="' + categorys[i] + '">' + categorys[i] + '</option>';
      }
      $('#filter').append(options);
    },
    applyFilter: function() {
      var value = $('#filter').val();
      if (value == 'Alle') {
        $('.mmooc-all-courses-list').removeClass('filter-active');
        $('.mmooc-all-courses-list h2').each(function() {
          $(this).show();
          $(this)
            .next()
            .show();
        });
      } else {
        $('.mmooc-all-courses-list').addClass('filter-active');
        $('.mmooc-all-courses-list h2').each(function() {
          if ($(this).text() == value) {
            $(this).show();
            $(this)
              .next()
              .show();
          } else {
            $(this).hide();
            $(this)
              .next()
              .hide();
          }
        });
      }
    }
  };
})();
<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiDocumentTableCtrl', function (
        _,
        $scope,
        $rootScope,
        rgiDialogFactory,
        rgiAssessmentSrvc,
        rgiDocumentSrvc,
        rgiHttpResponseProcessorSrvc,
        rgiIdentitySrvc,
        rgiNotifier
    ) {
        var limit = 100,
            currentPage = 0,
            totalPages = 0;

        $scope.current_user = rgiIdentitySrvc.currentUser;
        $scope.busy = false;

        $scope.assessment_filter_options = [
            {value: 'all', text: 'Show all documents'}
            // {value: 'type', text: 'Sort by document type'},
            // {value: 'assessments', text: 'Sort by attached assessments'}
        ];

        $scope.assessment_filter = $scope.assessment_filter_options[0].value;

        rgiAssessmentSrvc.query({}, function (assessments) {
            if(assessments.reason) {
                rgiNotifier.error('No assessments');
            } else {
                assessments.forEach(function(assessment) {
                    console.log(assessment);
                    $scope.assessment_filter_options.push({
                        value: assessment.assessment_ID,
                        text: assessment.country + ' ' + assessment.year + ' ' + assessment.version
                    });
                });
            }
        });

        rgiDocumentSrvc.query({skip: currentPage, limit: limit}, function (response) {
            if(response.reason) {
                rgiNotifier.error('Load document data failure');
            } else {
                $scope.count = response.count;
                $scope.documents = response.data;
                totalPages = Math.ceil(response.count / limit);
                currentPage = currentPage + 1;
            }
        }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));

        $scope.loadMoreDocs = function() {
            if ($scope.busy) {
                return;
            }

            $scope.busy = true;

            if(currentPage < totalPages) {
                rgiDocumentSrvc.query({skip: currentPage, limit: limit}, function (response) {
                    if(response.reason) {
                        rgiNotifier.error('Documents loading failure');
                    } else {
                        $scope.documents = _.union($scope.documents, response.data);
                        currentPage = currentPage + 1;
                        $scope.busy = false;
                    }
                }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
            }
        };

        $scope.deleteDocument = function(doc) {
            rgiDialogFactory.deleteDocument($scope, doc);
        };
    });
<commit_msg>fix the 'Document Table' directive controller<commit_after>'use strict';

angular.module('app')
    .controller('rgiDocumentTableCtrl', function (
        _,
        $scope,
        $rootScope,
        rgiDialogFactory,
        rgiAssessmentSrvc,
        rgiDocumentSrvc,
        rgiHttpResponseProcessorSrvc,
        rgiNotifier
    ) {
        var currentPage, totalPages, limit = 100;

        $scope.busy = false;
        $scope.assessment_filter_options = [];
        $scope.assessment_filter = '';

        rgiAssessmentSrvc.query({}, function (assessments) {
            if(assessments.reason) {
                rgiNotifier.error('No assessments');
            } else {
                assessments.forEach(function(assessment) {
                    $scope.assessment_filter_options.push({
                        value: assessment.assessment_ID,
                        text: assessment.country + ' ' + assessment.year + ' ' + assessment.version
                    });
                });
            }
        });

        $scope.$watch('assessment_filter', function(assessment) {
            currentPage = 0;
            totalPages = 0;
            var searchOptions = {skip: currentPage, limit: limit};

            if(assessment) {
                searchOptions.assessments = assessment;
            }

            rgiDocumentSrvc.queryCached(searchOptions, function (response) {
                if(response.reason) {
                    rgiNotifier.error('Load document data failure');
                } else {
                    $scope.count = response.count;
                    $scope.documents = response.data;

                    if($scope.documents.length === 0) {
                        rgiNotifier.error('No documents uploaded');
                    }

                    totalPages = Math.ceil(response.count / limit);
                    currentPage = 1;
                }
            }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
        });

        $scope.loadMoreDocs = function() {
            if ($scope.busy) {
                return;
            }

            $scope.busy = true;

            if(currentPage < totalPages) {
                var searchOptions = {skip: currentPage, limit: limit};

                if($scope.assessment_filter) {
                    searchOptions.assessments = $scope.assessment_filter;
                }

                rgiDocumentSrvc.query(searchOptions, function (response) {
                    if(response.reason) {
                        rgiNotifier.error('Documents loading failure');
                    } else {
                        $scope.documents = _.union($scope.documents, response.data);
                        currentPage = currentPage + 1;
                        $scope.busy = false;
                    }
                }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
            }
        };

        $scope.deleteDocument = function(doc) {
            rgiDialogFactory.deleteDocument($scope, doc);
        };
    });
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.min.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
      ],
      js: [
        'public/lib/angular/angular.min.js',
        'public/lib/angular-resource/angular-resource.min.js',
        'public/lib/angular-animate/angular-animate.min.js',
        'public/lib/angular-messages/angular-messages.min.js',
        'public/lib/angular-ui-router/release/angular-ui-router.min.js',
        'public/lib/angular-ui-utils/ui-utils.min.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'public/lib/angular-file-upload/angular-file-upload.min.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};
<commit_msg>add filesaver dependency in production mode<commit_after>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.min.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
      ],
      js: [
        'public/lib/angular/angular.min.js',
        'public/lib/angular-resource/angular-resource.min.js',
        'public/lib/angular-animate/angular-animate.min.js',
        'public/lib/angular-messages/angular-messages.min.js',
        'public/lib/angular-ui-router/release/angular-ui-router.min.js',
        'public/lib/angular-ui-utils/ui-utils.min.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'public/lib/angular-file-upload/angular-file-upload.min.js',
        'public/lib/file-saver/FileSaver.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};
<|endoftext|>


<commit_before>/**
 *

 *  Constructs a ProAct.Stream. The stream is a simple {@link ProAct.Actor}, without state.
 *

 *

 *  The streams are ment to emit values, events, changes and can be plugged into another actor.
 *  For example you can connect many streams, to merge them and to divide them, to plug them into properties.
 *

 *

 *  The reactive environment consists of the properties and the objects containing them, but
 *  the outside world is not reactive. It is possible to use the ProAct.Streams as connections from the
 *  outside world to the reactive environment.
 *

 *

 *    The transformations can be used to change the events or values emitetted.
 *

 *

 *  ProAct.Stream is part of the streams module of ProAct.js.
 *

 *
 * @class ProAct.Stream
 * @extends ProAct.Actor
 * @param {String} queueName
 *      The name of the queue all the updates should be pushed to.
 *

 *        If this parameter is null/undefined the default queue of
 *        {@link ProAct.flow} is used.
 *

 *

 *        If this parameter is not a string it is used as the
 *        source.
 *

 * @param {ProAct.Actor} source
 *      A default source of the stream, can be null.
 * @param {Array} transforms
 *      A list of transformation to be used on all incoming chages.
 */
function Stream (queueName, source, transforms) {
  if (queueName && !P.U.isString(queueName)) {
    transforms = source;
    source = queueName;
    queueName = null;
  }
  P.Actor.call(this, queueName, transforms);

  this.sourceNumber = 0;

  if (source) {
    this.into(source);
  }
}
ProAct.Stream = ProAct.S = Stream;

ProAct.Stream.prototype = P.U.ex(Object.create(P.Actor.prototype), {

  /**
   * Reference to the constructor of this object.
   *
   * @memberof ProAct.Stream
   * @instance
   * @constant
   * @type {Object}
   * @default ProAct.Stream
   */
  constructor: ProAct.Stream,

  /**
   * Creates the event to be send to the listeners on update.
   *

   *  Streams don't create new events by default, the event is the source.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeEvent
   * @param {ProAct.Event} source
   *      The source event of the event. It can be null
   * @return {ProAct.Event}
   *      The event.
   */
  makeEvent: function (source) {
    return source;
  },

  /**
   * Creates the listener of this stream.
   *

   *  The listener of the stream just calls the method {@link ProAct.Stream#trigger} with the incoming event/value.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeListener
   * @return {Object}
   *      The listener of this stream.
   */
  makeListener: function () {
    if (!this.listener) {
      var stream = this;
      this.listener = function (event) {
        stream.trigger(event, true);
      };
    }

    return this.listener;
  },

  /**
   * Creates the error listener of this stream.
   *

   *  The listener just calls {@link ProAct.Stream#triggerErr} of this with the incoming error.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeErrListener
   * @return {Object}
   *      The error listener of this stream.
   */
  makeErrListener: function () {
    if (!this.errListener) {
      var stream = this;
      this.errListener = function (error) {
        stream.triggerErr(error);
      };
    }

    return this.errListener;
  },

  /**
   * Creates the closing listener of this stream.
   *

   *  The listener just calls {@link ProAct.Stream#triggerClose} of this with the incoming closing data.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeCloseListener
   * @return {Object}
   *      The closing listener of this stream.
   */
  makeCloseListener: function () {
    if (!this.closeListener) {
      var stream = this;
      this.closeListener = function (error) {
        stream.triggerClose(error);
      };
    }

    return this.closeListener;
  },

  /**
   * Defers a ProAct.Actor listener.
   *

   *  For streams this means pushing it to active flow using {@link ProAct.Flow#push}.
   *  If the listener is object with 'property' field, it is done using {@link ProAct.Actor#defer}.
   *  That way the reactive environment is updated only once, but the streams are not part of it.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method defer
   * @param {Object} event
   *      The event/value to pass to the listener.
   * @param {Object} listener
   *      The listener to defer. It should be a function or object defining the call method.
   * @return {ProAct.Actor}
   *      this
   * @see {@link ProAct.Actor#willUpdate}
   * @see {@link ProAct.Actor#makeListener}
   * @see {@link ProAct.flow}
   */
  defer: function (event, listener) {
    if (!listener) {
      return;
    }

    if (listener.property) {
      P.Actor.prototype.defer.call(this, event, listener);
      return;
    }
    var queueName = (listener.queueName) ? listener.queueName : this.queueName;

    if (P.U.isFunction(listener)) {
      P.flow.push(queueName, listener, [event]);
    } else {
      P.flow.push(queueName, listener, listener.call, [event]);
    }
  },

  /**
   *

   *  Triggers a new event/value to the stream. Anything that is listening for events from
   *  this stream will get updated.
   *

   *

   *  ProAct.Stream.t is alias of this method.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method trigger
   * @param {Object} event
   *      The event/value to pass to trigger.
   * @param {Boolean} useTransformations
   *      If the stream should transform the triggered value. By default it is true (if not passed)
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Actor#update}
   */
  trigger: function (event, useTransformations) {
    if (this.listeners.change.length === 0) {
      return this;
    }
    if (useTransformations === undefined) {
      useTransformations = true;
    }

    return this.go(event, useTransformations);
  },

  /**
   *

   *  Triggers all the passed params, using transformations.
   *

   *

   *  ProAct.Stream.tt is alias of this method.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method triggerMany
   * @param [...]
   *      A list of events/values to trigger
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Stream#trigger}
   */
  triggerMany: function () {
    var i, args = slice.call(arguments), ln = args.length;

    for (i = 0; i < ln; i++) {
      this.trigger(args[i], true);
    }

    return this;
  },

  /**
   *

   *  Triggers a new error to the stream. Anything that is listening for errors from
   *  this stream will get updated.
   *

   *

   *  ProAct.Stream.te is alias of this method.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method triggerErr
   * @param {Error} err
   *      The error to trigger.
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Actor#update}
   */
  triggerErr: function (err) {
    return this.update(err, 'error');
  },

  /**
   *

   *  Triggers a closing event to the stream. Anything that is listening for closing events from
   *  this stream will get updated.
   *

   *

   *  The stream will be closed and unusable.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method triggerClose
   * @param {Object} data
   *      Data connected to the closing event.
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Actor#update}
   */
  triggerClose: function (data) {
    return this.update(data, 'close');
  },

  // private
  go: function (event, useTransformations) {
    if (useTransformations) {
      try {
        event = P.Actor.transform(this, event);
      } catch (e) {
        this.triggerErr(e);
        return this;
      }
    }

    if (event === P.Actor.BadValue) {
      return this;
    }

    return this.update(event);
  },

  /**
   * Creates a new ProAct.Stream instance with source this and mapping
   * the passed mapping function.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method map
   * @param {Object} mappingFunction
   *      Function or object with a call method to use as map function.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the mapping applied.
   * @see {@link ProAct.Actor#mapping}
   */
  map: function (mappingFunction) {
    return new P.S(this).mapping(mappingFunction);
  },

  /**
   * Creates a new ProAct.Stream instance with source this and filtering
   * the passed filtering function.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method filter
   * @param {Object} filteringFunction
   *      The filtering function or object with a call method, should return boolean.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the filtering applied.
   * @see {@link ProAct.Actor#filtering}
   */
  filter: function (filteringFunction) {
    return new P.S(this).filtering(filteringFunction);
  },

  /**
   * Creates a new ProAct.Stream instance with source this and accumulation
   * the passed accumulation function.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method accumulate
   * @param {Object} initVal
   *      Initial value for the accumulation. For example '0' for sum.
   * @param {Object} accumulationFunction
   *      The function to accumulate.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the accumulation applied.
   * @see {@link ProAct.Actor#accumulation}
   */
  accumulate: function (initVal, accumulationFunction) {
    return new P.S(this).accumulation(initVal, accumulationFunction);
  },

  /**
   * Creates a new ProAct.Stream instance that merges this with other streams.
   * The new instance will have new value on value from any of the source streams.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method merge
   * @param [...]
   *      A list of streams to be set as sources.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the sources this and all the passed streams.
   */
  merge: function () {
    var sources = [this].concat(slice.call(arguments)),
        result = new P.S();

    return P.S.prototype.into.apply(result, sources);
  },

  into: function () {
    ProAct.Actor.prototype.into.apply(this, arguments);

    this.sourceNumber += arguments.length;

    return this;
  },

  canClose: function () {
    this.sourceNumber -= 1;

    return this.sourceNumber <= 0;
  }
});

P.U.ex(P.F.prototype, {

  /**
   * Retrieves the errStream for logging errors from this flow.
   * If there is no error stream, it is created.
   *
   * @memberof ProAct.Flow
   * @instance
   * @method errStream
   * @return {ProAct.Stream}
   *      The error stream of the flow.
   */
  errStream: function () {
    if (!this.errStreamVar) {
      this.errStreamVar = new P.S();
    }

    return this.errStreamVar;
  }
});

P.S.prototype.t = P.S.prototype.trigger;
P.S.prototype.tt = P.S.prototype.triggerMany;
P.S.prototype.te = P.S.prototype.triggerErr;
<commit_msg>toStream method for all the actors.<commit_after>/**
 *

 *  Constructs a ProAct.Stream. The stream is a simple {@link ProAct.Actor}, without state.
 *

 *

 *  The streams are ment to emit values, events, changes and can be plugged into another actor.
 *  For example you can connect many streams, to merge them and to divide them, to plug them into properties.
 *

 *

 *  The reactive environment consists of the properties and the objects containing them, but
 *  the outside world is not reactive. It is possible to use the ProAct.Streams as connections from the
 *  outside world to the reactive environment.
 *

 *

 *    The transformations can be used to change the events or values emitetted.
 *

 *

 *  ProAct.Stream is part of the streams module of ProAct.js.
 *

 *
 * @class ProAct.Stream
 * @extends ProAct.Actor
 * @param {String} queueName
 *      The name of the queue all the updates should be pushed to.
 *

 *        If this parameter is null/undefined the default queue of
 *        {@link ProAct.flow} is used.
 *

 *

 *        If this parameter is not a string it is used as the
 *        source.
 *

 * @param {ProAct.Actor} source
 *      A default source of the stream, can be null.
 * @param {Array} transforms
 *      A list of transformation to be used on all incoming chages.
 */
function Stream (queueName, source, transforms) {
  if (queueName && !P.U.isString(queueName)) {
    transforms = source;
    source = queueName;
    queueName = null;
  }
  P.Actor.call(this, queueName, transforms);

  this.sourceNumber = 0;

  if (source) {
    this.into(source);
  }
}
ProAct.Stream = ProAct.S = Stream;

ProAct.Stream.prototype = P.U.ex(Object.create(P.Actor.prototype), {

  /**
   * Reference to the constructor of this object.
   *
   * @memberof ProAct.Stream
   * @instance
   * @constant
   * @type {Object}
   * @default ProAct.Stream
   */
  constructor: ProAct.Stream,

  /**
   * Creates the event to be send to the listeners on update.
   *

   *  Streams don't create new events by default, the event is the source.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeEvent
   * @param {ProAct.Event} source
   *      The source event of the event. It can be null
   * @return {ProAct.Event}
   *      The event.
   */
  makeEvent: function (source) {
    return source;
  },

  /**
   * Creates the listener of this stream.
   *

   *  The listener of the stream just calls the method {@link ProAct.Stream#trigger} with the incoming event/value.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeListener
   * @return {Object}
   *      The listener of this stream.
   */
  makeListener: function () {
    if (!this.listener) {
      var stream = this;
      this.listener = function (event) {
        stream.trigger(event, true);
      };
    }

    return this.listener;
  },

  /**
   * Creates the error listener of this stream.
   *

   *  The listener just calls {@link ProAct.Stream#triggerErr} of this with the incoming error.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeErrListener
   * @return {Object}
   *      The error listener of this stream.
   */
  makeErrListener: function () {
    if (!this.errListener) {
      var stream = this;
      this.errListener = function (error) {
        stream.triggerErr(error);
      };
    }

    return this.errListener;
  },

  /**
   * Creates the closing listener of this stream.
   *

   *  The listener just calls {@link ProAct.Stream#triggerClose} of this with the incoming closing data.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method makeCloseListener
   * @return {Object}
   *      The closing listener of this stream.
   */
  makeCloseListener: function () {
    if (!this.closeListener) {
      var stream = this;
      this.closeListener = function (error) {
        stream.triggerClose(error);
      };
    }

    return this.closeListener;
  },

  /**
   * Defers a ProAct.Actor listener.
   *

   *  For streams this means pushing it to active flow using {@link ProAct.Flow#push}.
   *  If the listener is object with 'property' field, it is done using {@link ProAct.Actor#defer}.
   *  That way the reactive environment is updated only once, but the streams are not part of it.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method defer
   * @param {Object} event
   *      The event/value to pass to the listener.
   * @param {Object} listener
   *      The listener to defer. It should be a function or object defining the call method.
   * @return {ProAct.Actor}
   *      this
   * @see {@link ProAct.Actor#willUpdate}
   * @see {@link ProAct.Actor#makeListener}
   * @see {@link ProAct.flow}
   */
  defer: function (event, listener) {
    if (!listener) {
      return;
    }

    if (listener.property) {
      P.Actor.prototype.defer.call(this, event, listener);
      return;
    }
    var queueName = (listener.queueName) ? listener.queueName : this.queueName;

    if (P.U.isFunction(listener)) {
      P.flow.push(queueName, listener, [event]);
    } else {
      P.flow.push(queueName, listener, listener.call, [event]);
    }
  },

  /**
   *

   *  Triggers a new event/value to the stream. Anything that is listening for events from
   *  this stream will get updated.
   *

   *

   *  ProAct.Stream.t is alias of this method.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method trigger
   * @param {Object} event
   *      The event/value to pass to trigger.
   * @param {Boolean} useTransformations
   *      If the stream should transform the triggered value. By default it is true (if not passed)
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Actor#update}
   */
  trigger: function (event, useTransformations) {
    if (this.listeners.change.length === 0) {
      return this;
    }
    if (useTransformations === undefined) {
      useTransformations = true;
    }

    return this.go(event, useTransformations);
  },

  /**
   *

   *  Triggers all the passed params, using transformations.
   *

   *

   *  ProAct.Stream.tt is alias of this method.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method triggerMany
   * @param [...]
   *      A list of events/values to trigger
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Stream#trigger}
   */
  triggerMany: function () {
    var i, args = slice.call(arguments), ln = args.length;

    for (i = 0; i < ln; i++) {
      this.trigger(args[i], true);
    }

    return this;
  },

  /**
   *

   *  Triggers a new error to the stream. Anything that is listening for errors from
   *  this stream will get updated.
   *

   *

   *  ProAct.Stream.te is alias of this method.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method triggerErr
   * @param {Error} err
   *      The error to trigger.
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Actor#update}
   */
  triggerErr: function (err) {
    return this.update(err, 'error');
  },

  /**
   *

   *  Triggers a closing event to the stream. Anything that is listening for closing events from
   *  this stream will get updated.
   *

   *

   *  The stream will be closed and unusable.
   *

   *
   * @memberof ProAct.Stream
   * @instance
   * @method triggerClose
   * @param {Object} data
   *      Data connected to the closing event.
   * @return {ProAct.Stream}
   *      this
   * @see {@link ProAct.Actor#update}
   */
  triggerClose: function (data) {
    return this.update(data, 'close');
  },

  // private
  go: function (event, useTransformations) {
    if (useTransformations) {
      try {
        event = P.Actor.transform(this, event);
      } catch (e) {
        this.triggerErr(e);
        return this;
      }
    }

    if (event === P.Actor.BadValue) {
      return this;
    }

    return this.update(event);
  },

  /**
   * Creates a new ProAct.Stream instance with source this and mapping
   * the passed mapping function.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method map
   * @param {Object} mappingFunction
   *      Function or object with a call method to use as map function.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the mapping applied.
   * @see {@link ProAct.Actor#mapping}
   */
  map: function (mappingFunction) {
    return new P.S(this).mapping(mappingFunction);
  },

  /**
   * Creates a new ProAct.Stream instance with source this and filtering
   * the passed filtering function.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method filter
   * @param {Object} filteringFunction
   *      The filtering function or object with a call method, should return boolean.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the filtering applied.
   * @see {@link ProAct.Actor#filtering}
   */
  filter: function (filteringFunction) {
    return new P.S(this).filtering(filteringFunction);
  },

  /**
   * Creates a new ProAct.Stream instance with source this and accumulation
   * the passed accumulation function.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method accumulate
   * @param {Object} initVal
   *      Initial value for the accumulation. For example '0' for sum.
   * @param {Object} accumulationFunction
   *      The function to accumulate.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the accumulation applied.
   * @see {@link ProAct.Actor#accumulation}
   */
  accumulate: function (initVal, accumulationFunction) {
    return new P.S(this).accumulation(initVal, accumulationFunction);
  },

  /**
   * Creates a new ProAct.Stream instance that merges this with other streams.
   * The new instance will have new value on value from any of the source streams.
   *
   * @memberof ProAct.Stream
   * @instance
   * @method merge
   * @param [...]
   *      A list of streams to be set as sources.
   * @return {ProAct.Stream}
   *      A new ProAct.Stream instance with the sources this and all the passed streams.
   */
  merge: function () {
    var sources = [this].concat(slice.call(arguments)),
        result = new P.S();

    return P.S.prototype.into.apply(result, sources);
  },

  into: function () {
    ProAct.Actor.prototype.into.apply(this, arguments);

    this.sourceNumber += arguments.length;

    return this;
  },

  canClose: function () {
    this.sourceNumber -= 1;

    return this.sourceNumber <= 0;
  }
});

P.U.ex(P.F.prototype, {

  /**
   * Retrieves the errStream for logging errors from this flow.
   * If there is no error stream, it is created.
   *
   * @memberof ProAct.Flow
   * @instance
   * @method errStream
   * @return {ProAct.Stream}
   *      The error stream of the flow.
   */
  errStream: function () {
    if (!this.errStreamVar) {
      this.errStreamVar = new P.S();
    }

    return this.errStreamVar;
  }
});

P.U.ex(P.Actor.prototype, {
  toStream: function () {
    return new P.S(this.queueName, this);
  },

  take: function () {
  }
});

P.S.prototype.t = P.S.prototype.trigger;
P.S.prototype.tt = P.S.prototype.triggerMany;
P.S.prototype.te = P.S.prototype.triggerErr;
<|endoftext|>


<commit_before>'use strict';

var services = require('./_index.js');
var AppSettings = require('../config.js');

/**
 * @ngInject
 */
function Mission($q, $http) {

  var _default = {
    type: 'User',
    email: ""
  }

  return {
    reset: function() {
      return _default;
    },

    get: function(uname, mslug) {
      var deferred = $q.defer();
      $http({
        method: 'GET',
        url: AppSettings.apiPath + '/orgs/' + uname + '/missions/' + mslug,
        withCredentials: true,
        dataType: "json"
      }).success(function(data) {
        deferred.resolve(data);
      }).error(function(err, status) {
        deferred.reject(err, status);
      })
      return deferred.promise;
    },

    milestones: function() {
      return []
    },

    tasks: function() {
      return []
    }
  }
}

services.service('Mission', Mission);
<commit_msg>adding milestones method to mission service<commit_after>'use strict';

var services = require('./_index.js');
var AppSettings = require('../config.js');

/**
 * @ngInject
 */
function Mission($q, $http) {

  var _default = {
    type: 'User',
    email: ""
  }

  return {
    reset: function() {
      return _default;
    },

    get: function(uname, mslug) {
      var deferred = $q.defer();
      $http({
        method: 'GET',
        url: AppSettings.apiPath + '/orgs/' + uname + '/missions/' + mslug,
        withCredentials: true,
        dataType: "json"
      }).success(function(data) {
        deferred.resolve(data);
      }).error(function(err, status) {
        deferred.reject(err, status);
      })
      return deferred.promise;
    },

    milestones: function(mission_id) {
      var deferred = $q.defer();
      $http({
        method: 'GET',
        url: AppSettings.apiPath + '/missions/' + mission_id + '/milestones',
        withCredentials: true,
        dataType: "json"
      }).success(function(data) {
        deferred.resolve(data);
      }).error(function(err, status) {
        deferred.reject(err, status);
      })
      return deferred.promise;
    }
  }
}

services.service('Mission', Mission);
<|endoftext|>


<commit_before>(function () {

  // Grab body node
  const bodyNode = document.querySelector('body');

  // Callback function to execute when mutations are observed
  const watchForBootstrap = function(mutationsList, observer) {
      for(let mutation of mutationsList) {
          if (mutation.type === 'attributes') {
            // only init if we're using a Synthwave 84 subtheme
            const isUsingSynthwave = document.querySelector('[class*="RobbOwen-synthwave-vscode-themes"]');
            const tokensLoaded = document.querySelector('.vscode-tokens-styles');
            const tokenStyles = document.querySelector('.vscode-tokens-styles').innerText;

            // Everything we need is ready, so initialise
            if (isUsingSynthwave && tokensLoaded && tokenStyles) {
                initNeonDreams([DISABLE_GLOW]);
            }
          }
      }
  };

  // Use a mutation observer to check when we can bootstrap the theme
  const observer = new MutationObserver(watchForBootstrap);
  observer.observe(bodyNode, { attributes: true });

  // Replace the styles with the glow theme
  const initNeonDreams = (disableGlow) => {
    var themeStyleTag = document.querySelector('.vscode-tokens-styles');

    var initialThemeStyles = themeStyleTag.innerText;

    var updatedThemeStyles = initialThemeStyles;

    if (!disableGlow) {
      /* replace neon red */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #fe4450;/g, "color: #fff5f6; text-shadow: 0 0 2px #000, 0 0 10px #fc1f2c[NEON_BRIGHTNESS], 0 0 5px #fc1f2c[NEON_BRIGHTNESS], 0 0 25px #fc1f2c[NEON_BRIGHTNESS];");

      /* replace neon pink */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #ff7edb;/g, "color: #f92aad; text-shadow: 0 0 2px #100c0f, 0 0 5px #dc078e33, 0 0 10px #fff3;");

      /* replace yellow */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #fede5d;/g, "color: #f4eee4; text-shadow: 0 0 2px #393a33, 0 0 8px #f39f05[NEON_BRIGHTNESS], 0 0 2px #f39f05[NEON_BRIGHTNESS];");

      /* replace green */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #72f1b8;/g, "color: #72f1b8; text-shadow: 0 0 2px #100c0f, 0 0 10px #257c55[NEON_BRIGHTNESS], 0 0 35px #212724[NEON_BRIGHTNESS];");

      /* replace blue */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #36f9f6;/g, "color: #fdfdfd; text-shadow: 0 0 2px #001716, 0 0 3px #03edf9[NEON_BRIGHTNESS], 0 0 5px #03edf9[NEON_BRIGHTNESS], 0 0 8px #03edf9[NEON_BRIGHTNESS];");
    }

    /* append the remaining styles */
    updatedThemeStyles = `${updatedThemeStyles}[CHROME_STYLES]`;

    themeStyleTag.innerText = updatedThemeStyles.replace(/(\r\n|\n|\r)/gm, '');

    console.log('Synthwave \'84: NEON DREAMS initialised!');
    // disconnect the observer because we don't need it anymore
    observer.disconnect();
  };

})();<commit_msg>Rewrite mutation observer template to check for style injection before initialising the glow<commit_after>(function () {

  // Grab body node
  const bodyNode = document.querySelector('body');

  // Replace the styles with the glow theme
  const initNeonDreams = (disableGlow, obs) => {
    var themeStyleTag = document.querySelector('.vscode-tokens-styles');

    var initialThemeStyles = themeStyleTag.innerText;

    var updatedThemeStyles = initialThemeStyles;

    if (!disableGlow) {
      /* replace neon red */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #fe4450;/g, "color: #fff5f6; text-shadow: 0 0 2px #000, 0 0 10px #fc1f2c[NEON_BRIGHTNESS], 0 0 5px #fc1f2c[NEON_BRIGHTNESS], 0 0 25px #fc1f2c[NEON_BRIGHTNESS];");

      /* replace neon pink */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #ff7edb;/g, "color: #f92aad; text-shadow: 0 0 2px #100c0f, 0 0 5px #dc078e33, 0 0 10px #fff3;");

      /* replace yellow */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #fede5d;/g, "color: #f4eee4; text-shadow: 0 0 2px #393a33, 0 0 8px #f39f05[NEON_BRIGHTNESS], 0 0 2px #f39f05[NEON_BRIGHTNESS];");

      /* replace green */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #72f1b8;/g, "color: #72f1b8; text-shadow: 0 0 2px #100c0f, 0 0 10px #257c55[NEON_BRIGHTNESS], 0 0 35px #212724[NEON_BRIGHTNESS];");

      /* replace blue */
      updatedThemeStyles = updatedThemeStyles.replace(/color: #36f9f6;/g, "color: #fdfdfd; text-shadow: 0 0 2px #001716, 0 0 3px #03edf9[NEON_BRIGHTNESS], 0 0 5px #03edf9[NEON_BRIGHTNESS], 0 0 8px #03edf9[NEON_BRIGHTNESS];");
    }

    /* append the remaining styles */
    updatedThemeStyles = `${updatedThemeStyles}[CHROME_STYLES]`;

    themeStyleTag.innerText = updatedThemeStyles.replace(/(\r\n|\n|\r)/gm, '');

    console.log('Synthwave \'84: NEON DREAMS initialised!');
    // disconnect the observer because we don't need it anymore
    obs.disconnect();
  };

  // Callback function to execute when mutations are observed
  const watchForBootstrap = function(mutationsList, observer) {
      for(let mutation of mutationsList) {
          if (mutation.type === 'attributes') {
            // only init if we're using a Synthwave 84 subtheme
            const isUsingSynthwave = document.querySelector('[class*="RobbOwen-synthwave-vscode-themes"]');
            // does the style div exist yet?
            const tokensLoaded = document.querySelector('.vscode-tokens-styles');
            // does it have content ?
            const tokenStyles = document.querySelector('.vscode-tokens-styles').innerText;

            // sometimes VS code takes a while to init the styles content, so stop this observer and add an observer for that
            if (isUsingSynthwave && tokensLoaded) {
              observer.disconnect();
              observer.observe(tokensLoaded, { childList: true });
            }
          }
          if (mutation.type === 'childList') {
            const isUsingSynthwave = document.querySelector('[class*="RobbOwen-synthwave-vscode-themes"]');
            const tokensLoaded = document.querySelector('.vscode-tokens-styles');
            const tokenStyles = document.querySelector('.vscode-tokens-styles').innerText;

            // Everything we need is ready, so initialise
            if (isUsingSynthwave && tokensLoaded && tokenStyles) {
                initNeonDreams([DISABLE_GLOW], observer);
            }
          }
      }
  };

  // Use a mutation observer to check when we can bootstrap the theme
  const observer = new MutationObserver(watchForBootstrap);
  observer.observe(bodyNode, { attributes: true });

})();<|endoftext|>


<commit_before>
  // CONST
  var NAMESPACE = 'touch-carousel',

  // TouchCarousel Constructor
  // -------------------
  TouchCarousel = function (element, options) {
    this.$element       = $(element)
    this.$itemsWrapper  = this.$element.find('.carousel-inner')
    this.$items         = this.$element.find('.item')
    this.$indicators    = this.$element.find('.carousel-indicators')
    this.pane_width     =
    this.pane_count     =
    this.current_pane   = 0
    this.onGesture      = false
    this.options        = options

    this._setPaneDimensions()
    // disable carousel if there is only one
    // or no item. (fixes # 6)
    if (this.$items.length <= 1) return this.disable()

    this._regTouchGestures()

    $(window).on('orientationchange resize', $.proxy(this._setPaneDimensions, this) );
  }

  TouchCarousel.DEFAULTS = {
    interval: false,
    toughness: 0.25
  }

  // TouchCarousel Prototype methods
  // -------------------

  TouchCarousel.prototype.cycle = function (e) {
    if (!e) this.paused = false
    if (this.interval) clearInterval(this.interval);
    this.options.interval
      && !this.paused
      && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
    return this
  }

  TouchCarousel.prototype.to = function (pos) {
    if (pos > (this.$items.length - 1) || pos < 0) return
    return this._showPane( pos );
  }

  TouchCarousel.prototype.pause = function (e) {
    if (!e) this.paused = true

    clearInterval(this.interval)
    this.interval = null
    return this
  }

  TouchCarousel.prototype._regTouchGestures = function() {
    this.$itemsWrapper
      .add(this.$indicators) // fixes issue #9
      .hammer({ drag_lock_to_axis: true })
      .on("release dragleft dragright swipeleft swiperight", $.proxy(this._handleGestures, this));
  }

  TouchCarousel.prototype._setPaneDimensions= function() {
    this.pane_width = this.$element.width();
    this.pane_count = this.$items.length;

    // Set items & wrapper to fixed width
    this.$itemsWrapper.width( this.pane_width * this.pane_count );
    this.$items.width( this.pane_width );
  }

  TouchCarousel.prototype._showPane= function( index ) {

      // remove class from prev pane
      this.$items.eq( this.current_pane ).toggleClass('active');

      // Last Item reached
      if( index >= this.pane_count) {
        this.pause();
      }

      // between the bounds
      // add active state to the current pane
      index = Math.max(0, Math.min(index, this.pane_count-1));
      var $next = this.$items.eq( index ).toggleClass('active');
      this.current_pane = index;

      var offset = -((100/this.pane_count) * this.current_pane);
      this._setContainerOffset(offset, true, index);

      return this;
  }

  TouchCarousel.prototype._setContainerOffset= function(percent, animate, index) {
      var that = this;

      this.$itemsWrapper.removeClass('animate');

      if(animate) this.$itemsWrapper.addClass('animate');

      // CSS3 Transforms3D Animation
      if($.support.csstransforms3d) {
          this.onGesture = true;
          this.$itemsWrapper.css("transform", "translate3d("+ percent +"%,0,0) scale3d(1,1,1)");
      }

      // CSS3 Transform Animation
      else if($.support.csstransforms) {
          this.onGesture = true;
          this.$itemsWrapper.css("transform", "translate("+ percent +"%,0)");
      }

      // CSS3 Transition
      else {
        var px = (( this.pane_width * this.pane_count) / 100) * percent;
        this.$itemsWrapper.css("left", px +"px");
      }

      // Transition Complete
      if( $.support.transition ) {
        this.$itemsWrapper.one($.support.transition.end, function (e) {
          that.$itemsWrapper.removeClass('animate');
          that.onGesture = false;
          that._updateIndicators(index);
        });
      } else {
        this.$itemsWrapper.removeClass('animate');
        this.onGesture = false;
        this._updateIndicators(index);
      }
  }

  TouchCarousel.prototype.next = function() {
    return this._showPane( this.current_pane+1 );
  }

  TouchCarousel.prototype.prev = function() {
    return this._showPane( this.current_pane-1 );
  }

  TouchCarousel.prototype._handleGestures = function( e ) {
    // disable browser scrolling
    e.gesture.preventDefault();

    if(this.sliding) return;

    // Stop slideshow onGesture
    this.pause();

    switch(e.type) {
      case 'dragright':
      case 'dragleft':
        // stick to the finger
        var pane_offset = -(100/  this.pane_count) * this.current_pane;
        var drag_offset = ((100/ this.pane_width) * e.gesture.deltaX) / this.pane_count;

        // slow down at the first and last pane
        if( (this.current_pane === 0 && e.gesture.direction == Hammer.DIRECTION_RIGHT) ||
            ( this.current_pane == this.pane_count-1 && e.gesture.direction == Hammer.DIRECTION_LEFT)) {
            drag_offset *= this.options.toughness;
        }

        this._setContainerOffset(drag_offset + pane_offset);
        break;

      case 'swipeleft':
          this.next();
          e.gesture.stopDetect();
          break;

      case 'swiperight':
          this.prev();
          e.gesture.stopDetect();
          break;

      case 'release':
        // more then 50% moved, navigate
        if(Math.abs(e.gesture.deltaX) > this.pane_width/2) {
            if(e.gesture.direction == 'right') {
                this.prev();
            } else {
                this.next();
            }
        }
        else {
            this._showPane( this.current_pane, true );
        }
        break;
    }
  }

  TouchCarousel.prototype.disable = function() {
    this.$indicators.hide()
    this.$element.removeData( NAMESPACE );

    return false;
  }

  TouchCarousel.prototype._updateIndicators = function(index) {
    if (this.$indicators.length) {
      this.$indicators.find('.active').removeClass('active');
      this.$indicators.children().eq(index).addClass('active');
    }

    this.$element.trigger('slid.bs.carousel');

    return this;
  }

  // CAROUSEL PLUGIN DEFINITION
  // ==========================

  var old = $.fn.carousel

  // Overwrite default fn.carousel
  $.fn.carousel = function (option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data( NAMESPACE )
      var options = $.extend({}, TouchCarousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
      var action  = typeof option == 'string' ? option : options.slide

      if (!data) $this.data( NAMESPACE, (data = new TouchCarousel(this, options))).addClass(NAMESPACE)
      if (typeof option == 'number') data.to(option)
      else if (action) data[action]()
      else if (options.interval) data.pause().cycle()
    })
  }

  $.fn.carousel.Constructor = TouchCarousel

  // CAROUSEL NO CONFLICT
  // ====================

  $.fn.carousel.noConflict = function () {
    $.fn.carousel = old
    return this
  }

  // CAROUSEL DATA-API
  // =================

  // unbind default carousel data-API
  $(document).off('click.bs.carousel').on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
    var $this   = $(this), href
    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
    var options = $.extend({}, $target.data(), $this.data())
    var slideIndex = $this.attr('data-slide-to')
    if (slideIndex) options.interval = false

    $target.carousel(options)

    if (slideIndex = $this.attr('data-slide-to')) {
      $target.data( NAMESPACE ).to(slideIndex)
    }

    e.preventDefault()
  })
<commit_msg>preventDefault<commit_after>
  // CONST
  var NAMESPACE = 'touch-carousel',

  // TouchCarousel Constructor
  // -------------------
  TouchCarousel = function (element, options) {
    this.$element       = $(element)
    this.$itemsWrapper  = this.$element.find('.carousel-inner')
    this.$items         = this.$element.find('.item')
    this.$indicators    = this.$element.find('.carousel-indicators')
    this.pane_width     =
    this.pane_count     =
    this.current_pane   = 0
    this.onGesture      = false
    this.options        = options

    this._setPaneDimensions()
    // disable carousel if there is only one
    // or no item. (fixes # 6)
    if (this.$items.length <= 1) return this.disable()

    this._regTouchGestures()

    $(window).on('orientationchange resize', $.proxy(this._setPaneDimensions, this) );
  }

  TouchCarousel.DEFAULTS = {
    interval: false,
    toughness: 0.25
  }

  // TouchCarousel Prototype methods
  // -------------------

  TouchCarousel.prototype.cycle = function (e) {
    if (!e) this.paused = false
    if (this.interval) clearInterval(this.interval);
    this.options.interval
      && !this.paused
      && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
    return this
  }

  TouchCarousel.prototype.to = function (pos) {
    if (pos > (this.$items.length - 1) || pos < 0) return
    return this._showPane( pos );
  }

  TouchCarousel.prototype.pause = function (e) {
    if (!e) this.paused = true

    clearInterval(this.interval)
    this.interval = null
    return this
  }

  TouchCarousel.prototype._regTouchGestures = function() {
    this.$itemsWrapper
      .add(this.$indicators) // fixes issue #9
      .hammer({
        drag_lock_to_axis: true,
        preventDefault: true,
      })
      .on("release dragleft dragright swipeleft swiperight", $.proxy(this._handleGestures, this));
  }

  TouchCarousel.prototype._setPaneDimensions= function() {
    this.pane_width = this.$element.width();
    this.pane_count = this.$items.length;

    // Set items & wrapper to fixed width
    this.$itemsWrapper.width( this.pane_width * this.pane_count );
    this.$items.width( this.pane_width );
  }

  TouchCarousel.prototype._showPane= function( index ) {

      // remove class from prev pane
      this.$items.eq( this.current_pane ).toggleClass('active');

      // Last Item reached
      if( index >= this.pane_count) {
        this.pause();
      }

      // between the bounds
      // add active state to the current pane
      index = Math.max(0, Math.min(index, this.pane_count-1));
      var $next = this.$items.eq( index ).toggleClass('active');
      this.current_pane = index;

      var offset = -((100/this.pane_count) * this.current_pane);
      this._setContainerOffset(offset, true, index);

      return this;
  }

  TouchCarousel.prototype._setContainerOffset= function(percent, animate, index) {
      var that = this;

      this.$itemsWrapper.removeClass('animate');

      if(animate) this.$itemsWrapper.addClass('animate');

      // CSS3 Transforms3D Animation
      if($.support.csstransforms3d) {
          this.onGesture = true;
          this.$itemsWrapper.css("transform", "translate3d("+ percent +"%,0,0) scale3d(1,1,1)");
      }

      // CSS3 Transform Animation
      else if($.support.csstransforms) {
          this.onGesture = true;
          this.$itemsWrapper.css("transform", "translate("+ percent +"%,0)");
      }

      // CSS3 Transition
      else {
        var px = (( this.pane_width * this.pane_count) / 100) * percent;
        this.$itemsWrapper.css("left", px +"px");
      }

      // Transition Complete
      if( $.support.transition ) {
        this.$itemsWrapper.one($.support.transition.end, function (e) {
          that.$itemsWrapper.removeClass('animate');
          that.onGesture = false;
          that._updateIndicators(index);
        });
      } else {
        this.$itemsWrapper.removeClass('animate');
        this.onGesture = false;
        this._updateIndicators(index);
      }
  }

  TouchCarousel.prototype.next = function() {
    return this._showPane( this.current_pane+1 );
  }

  TouchCarousel.prototype.prev = function() {
    return this._showPane( this.current_pane-1 );
  }

  TouchCarousel.prototype._handleGestures = function( e ) {

    if(this.sliding) return;

    // Stop slideshow onGesture
    this.pause();

    switch(e.type) {
      case 'dragright':
      case 'dragleft':
        // stick to the finger
        var pane_offset = -(100/  this.pane_count) * this.current_pane;
        var drag_offset = ((100/ this.pane_width) * e.gesture.deltaX) / this.pane_count;

        // slow down at the first and last pane
        if( (this.current_pane === 0 && e.gesture.direction == Hammer.DIRECTION_RIGHT) ||
            ( this.current_pane == this.pane_count-1 && e.gesture.direction == Hammer.DIRECTION_LEFT)) {
            drag_offset *= this.options.toughness;
        }

        this._setContainerOffset(drag_offset + pane_offset);
        break;

      case 'swipeleft':
          this.next();
          e.gesture.stopDetect();
          break;

      case 'swiperight':
          this.prev();
          e.gesture.stopDetect();
          break;

      case 'release':
        // more then 50% moved, navigate
        if(Math.abs(e.gesture.deltaX) > this.pane_width/2) {
            if(e.gesture.direction == 'right') {
                this.prev();
            } else {
                this.next();
            }
        }
        else {
            this._showPane( this.current_pane, true );
        }
        break;
    }
  }

  TouchCarousel.prototype.disable = function() {
    this.$indicators.hide()
    this.$element.removeData( NAMESPACE );

    return false;
  }

  TouchCarousel.prototype._updateIndicators = function(index) {
    if (this.$indicators.length) {
      this.$indicators.find('.active').removeClass('active');
      this.$indicators.children().eq(index).addClass('active');
    }

    this.$element.trigger('slid.bs.carousel');

    return this;
  }

  // CAROUSEL PLUGIN DEFINITION
  // ==========================

  var old = $.fn.carousel

  // Overwrite default fn.carousel
  $.fn.carousel = function (option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data( NAMESPACE )
      var options = $.extend({}, TouchCarousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
      var action  = typeof option == 'string' ? option : options.slide

      if (!data) $this.data( NAMESPACE, (data = new TouchCarousel(this, options))).addClass(NAMESPACE)
      if (typeof option == 'number') data.to(option)
      else if (action) data[action]()
      else if (options.interval) data.pause().cycle()
    })
  }

  $.fn.carousel.Constructor = TouchCarousel

  // CAROUSEL NO CONFLICT
  // ====================

  $.fn.carousel.noConflict = function () {
    $.fn.carousel = old
    return this
  }

  // CAROUSEL DATA-API
  // =================

  // unbind default carousel data-API
  $(document).off('click.bs.carousel').on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
    var $this   = $(this), href
    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
    var options = $.extend({}, $target.data(), $this.data())
    var slideIndex = $this.attr('data-slide-to')
    if (slideIndex) options.interval = false

    $target.carousel(options)

    if (slideIndex = $this.attr('data-slide-to')) {
      $target.data( NAMESPACE ).to(slideIndex)
    }

    e.preventDefault()
  })
<|endoftext|>


<commit_before>//create  UI

var d=new Date();
d.toLocaleDateString();

// create table view data object
var data = [
	{title:'SiteID:', hasChild:false},
	{title:'River:', hasChild:true, url:'v_SiteDataRiver.js'},
	{title:'Date:' + d, hasChild:false},
	{title:'Map Ref:', hasChild:false},
	{title:'Entered by:', hasChild:true,url:'v_SiteDataUser.js'}
];

// create table view
var tableview = Titanium.UI.createTableView({
	data:data,
});

tableview.addEventListener('click', function(e)
{
	if (e.rowData.url)
	{
		var win = null;
		if (Ti.Platform.name == "android") {
			win = Titanium.UI.createWindow({
				url:e.rowData.url,
				title:e.rowData.title
			});
		} else {
			win = Titanium.UI.createWindow({
				url:e.rowData.url,
				title:e.rowData.title,
				backgroundColor:'#fff',
				barColor:'#1A75A2'
			});
		}
		Titanium.UI.currentTab.open(win,{animated:true});
	}
});

Ti.App.addEventListener('change_river',function(e)
{
	tableview.updateRow(0 ,{title:'SiteID: ' + e.siteid, hasChild:false});
	tableview.updateRow(1 ,{title:'River: ' + e.title, hasChild:true, url:'v_SiteDataRiver.js'});
	tableview.updateRow(3 ,{title:'Map Ref: ' + e.mapref, hasChild:false});
});

// add table view to the window
Titanium.UI.currentWindow.add(tableview);

//add history of button
var btn_history = Titanium.UI.createButton({
   title: 'History',
   width: 70,
   height: 30,
});

btn_history.addEventListener('click',function(e)
{
   Titanium.API.info("You clicked the history button");
	var alertDialog = Titanium.UI.createAlertDialog({
   	 				title: 'History',
				    message: 'history of guage would show (toggle) & read only',
				    buttonNames: ['OK']
					});
	alertDialog.show();
	if(btn_history.title === 'History')
	{
	btn_history.title = 'New';
	tableview.allowsSelection = false;
	}
	else{
		btn_history.title = 'History';
		tableview.allowsSelection = true;
	}
});
Titanium.UI.currentWindow.rightNavButton = btn_history;
<commit_msg>not needed<commit_after>//create  UI

var d=new Date();
d.toLocaleDateString();

// create table view data object
var data = [
	{title:'SiteID:', hasChild:false},
	{title:'River:', hasChild:true, url:'v_SiteDataRiver.js'},
	{title:'Date:' + d, hasChild:false},
	{title:'Map Ref:', hasChild:false}
];

// create table view
var tableview = Titanium.UI.createTableView({
	data:data,
});

tableview.addEventListener('click', function(e)
{
	if (e.rowData.url)
	{
		var win = null;
		if (Ti.Platform.name == "android") {
			win = Titanium.UI.createWindow({
				url:e.rowData.url,
				title:e.rowData.title
			});
		} else {
			win = Titanium.UI.createWindow({
				url:e.rowData.url,
				title:e.rowData.title,
				backgroundColor:'#fff',
				barColor:'#1A75A2'
			});
		}
		Titanium.UI.currentTab.open(win,{animated:true});
	}
});

Ti.App.addEventListener('change_river',function(e)
{
	tableview.updateRow(0 ,{title:'SiteID: ' + e.siteid, hasChild:false});
	tableview.updateRow(1 ,{title:'River: ' + e.title, hasChild:true, url:'v_SiteDataRiver.js'});
	tableview.updateRow(3 ,{title:'Map Ref: ' + e.mapref, hasChild:false});
});

// add table view to the window
Titanium.UI.currentWindow.add(tableview);

//add history of button
var btn_history = Titanium.UI.createButton({
   title: 'History',
   width: 70,
   height: 30,
});

btn_history.addEventListener('click',function(e)
{
   Titanium.API.info("You clicked the history button");
	var alertDialog = Titanium.UI.createAlertDialog({
   	 				title: 'History',
				    message: 'history of guage would show (toggle) & read only',
				    buttonNames: ['OK']
					});
	alertDialog.show();
	if(btn_history.title === 'History')
	{
	btn_history.title = 'New';
	tableview.allowsSelection = false;
	}
	else{
		btn_history.title = 'History';
		tableview.allowsSelection = true;
	}
});
Titanium.UI.currentWindow.rightNavButton = btn_history;
<|endoftext|>