<commit_before>/**
 * Created by Juan on 4/6/14.
 */

define('ui', ['visualization', 'jquery', 'underscore'], function() {
    var self = {};

    var visibleViewClass = 'active';
    var defaultTabElementId = '#mapTab';
    var defaultContentElementId = '#mapContent';

    self.loadView = function(view) {
        if ($('#' + view + 'Tab').hasClass('active')) {
            return;
        }
        var contentElement = view + 'Content';
        //contentElement = (contentElement.length == 0)? $(defaultContentElementId): contentElement;
        $(".nav-tabs").find("a[href='#" + contentElement + "']").click();
    };

    self.getActiveView = function() {
        return $(".nav-tabs .active").prop("id").replace("Tab", "");
    };

    self.getBrowserName= (function(){
        var ua= navigator.userAgent, tem,
        M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if(/trident/i.test(M[1])){
            tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE '+(tem[1] || '');
        }
        if(M[1]=== 'Chrome'){
            tem= ua.match(/\bOPR\/(\d+)/)
            if(tem!= null) return 'Opera '+tem[1];
        }
        M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
        if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
        return M.join(' ');
    })();

    self.facetsTemplate = _.template("
\

\

\
                <a data-toggle='collapse' class='accordion-toggle' data-parent='#accordion' href='#<%= facetid %>'>\
                    <%= facettitle %> \
                \

\

\
        <div id='<%= facetid %>' class='facet-list panel-collapse collapse in'>\

\

\

\

\
                    <ul id='more-<%= facetid %>' class='list-group inputs-group collapse more'>\

\

\

\

\

");

    self.filterTemplate = _.template("<li class='list-group-item' id='<%= id %>'>\
        <%= count %>\
        \
            <input type='checkbox' data-facet='<%= facet %>' value='<%= id %>' <%= checked %>>\
            <%= name %>\
        \

");

    self.siteInfoWindowTemplate = _.template("
\

<%= sitename %>

<%= sitecode %>
\

\

\
                Network: <%= network %>\
                State: <%= state %>\
                Site Type: <%= sitetype %>\

\

\
                County: <%= county %>\
                Latitude: <%= latitude %>\
                Longitude: <%= longitude %>\

\

\

\
        <button data-sitecode='<%= sitecode %>' class='btnViewSeries'>View Dataseries</button>\

");

    self.renderFacets = function(parent){
        var data = require('data');
        var facets = [];
        var facetsHtml;

        data.facets.forEach(function(facet){
            facets = facets.concat(self.facetsTemplate({facetid: facet.keyfield, facettitle: facet.name}));
        });

        facetsHtml = facets.join('');
        parent.append($(facetsHtml));
    };

    self.renderFilterItems = function() {
        var data = require('data');

        $(".facet-list").find("ul").empty();

        data.facets.forEach(function(facet) {
            var filters = [];           // Default filters
            var filters2 = [];          // Non-default filters. Must click "Show more" to display.
            var counter = 0;
            var maxDefault = 6;         // Number of default filters
            var orderedFilters = (_(facet.filters)
                .chain()
                .sortBy('dataseriesCount')
                .sortBy('applied')
                .reverse()
                .value()
            );

            orderedFilters.forEach(function(filter) {
                if (!filter.dataseriesCount) {
                    return;
                }

                var filterName = _.map(facet.namefields, function(namefield){ return filter[namefield]; }).join(', ');
                var elementData = {
                    facet: facet.keyfield,
                    id: filter[facet.keyfield],
                    name: filterName,
                    count: filter.dataseriesCount,
                    checked: (filter.applied? 'checked': '')
                };
                if (counter < maxDefault){
                    filters.push(self.filterTemplate(elementData));
                    counter++;
                }
                else{
                    filters2.push(self.filterTemplate(elementData));
                }
            });

            var filterElements = $(filters.join('')).appendTo($("#" + facet.keyfield + "  .default-values"));

            if($("#morebtn-" + facet.keyfield).length == 0){
                var text = "Show more";

                if ($("#more-" + facet.keyfield + ".in").length > 0){
                    text = "Show less";
                }

                var button = "
"+
                                text +"
";

                $("#" + facet.keyfield).append(button);
                // Toggle between "Show more" and "Show less"
                $("#morebtn-" + facet.keyfield + " a").click(function(){
                    $(this).html($(this).html() == "Show more" ? "Show less" : "Show more");
                });
            }

            // Bind checkbox check event for the default values
            filterElements.find("input:checkbox").on('change', function() {
                data.toggleFilter(this.dataset.facet, this.value);
            });

            if (!filters2.length){
                $("#morebtn-" + facet.keyfield).remove();       // If there is nothing to show, remove the button
            }
            else{
                filterElements = $(filters2.join('')).appendTo($("#" + facet.keyfield + " .more"));

                // Bind checkbox check event for the non-default values
                filterElements.find("input:checkbox").on('change', function() {
                    data.toggleFilter(this.dataset.facet, this.value);
                });
            }
        });

    };

    self.showDataseriesDialog = function(series) {
        var dialog = $('#InfoDialog');
        var plottedSeries = visualization.plottedSeries;
        var isAlreadyPlotted = _(_(plottedSeries).pluck('seriesid')).contains(series.seriesid);

         $(".modal-header").find(".alert").remove();    // Clear previous download links

        dialog.get(0).dataset['series'] = series.seriesid;
        dialog.find("#series-active-info").text((series.isactive? "Active": "Not Active"));
        dialog.find(".series-item-value").each(function(index, item) {
            if (series.hasOwnProperty(item.dataset.field)) {
                $(item).text(series[item.dataset.field]);
            }
        });

        dialog.find("#btnAddToPlot").prop('disabled',
            !visualization.canPlot() || isAlreadyPlotted);
        dialog.modal('show');
    }

    self.updateTabsFilteredCount = function() {
        var data = require('data');
        var sitesCount = data.filteredSites.length;
        var seriesCount = data.filteredDataseries.length;
        $("div#datasetsTab .badge").text(seriesCount);
        $("div#mapTab .badge").text(sitesCount);
    };

    self.getMapCanvas = function() {
        return document.getElementById("map_canvas");
    };

    self.generateClusterClass = function(networkId) {
        return ('network' + networkId);
    };

    self.addColorToClass = function(cssClass, color) {
        var rgbaString = 'rgba(' + color.rgb.red + ', ' + color.rgb.green + ', ' + color.rgb.blue + ', 0.86)';
        var backgroundColorString = 'background-color: ' + rgbaString;
        $('').appendTo('head');
    };

    self.customizeTableStyle = function() {
        $('.ColVis_MasterButton').removeClass('ColVis_Button').addClass('btn btn-default glyphicon');

        $('#tableButtons').detach().prependTo('#datasetsTable_wrapper');

        if ($.support.placeholder) {
            var filter = $('#datasetsTable_filter');
            var txtSearch = filter.find('input[type="search"]').detach();
            txtSearch.prop({placeholder: 'Search', results: 5});
            filter.empty().append(txtSearch);
        }
    };

    self.startPlotAnimation = function() {
        $("#summarystats").hide();
        $("div#graphArea .ring").show();
    };

    self.endPlotAnimation = function() {
        $("div#graphArea .ring").hide();
        $("#summarystats").show();
    };

    jQuery(function() {
        jQuery.support.placeholder = false;
        var test = document.createElement('input');
        if('placeholder' in test) jQuery.support.placeholder = true;
    });

	return self;
});<commit_msg>Set map as default tab and make it load when an incorrect tab is specified in the url parameters.<commit_after>/**
 * Created by Juan on 4/6/14.
 */

define('ui', ['visualization', 'jquery', 'underscore'], function() {
    var self = {};

    var visibleViewClass = 'active';
    var defaultView = 'map';

    self.loadView = function(view) {
        view = ($('.nav-tabs').find('li[id*="' + view + '"]').length === 0)? 'map': view;
        if ($('#' + view + 'Tab').hasClass(visibleViewClass)) {
            return;
        }

        var contentLink = $("a[href='#" + view + "Content']");
        contentLink.click();
    };

    self.getActiveView = function() {
        return $('.nav-tabs').find('.active').prop("id").replace("Tab", "");
    };

    self.getBrowserName= (function(){
        var ua= navigator.userAgent, tem,
        M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if(/trident/i.test(M[1])){
            tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE '+(tem[1] || '');
        }
        if(M[1]=== 'Chrome'){
            tem= ua.match(/\bOPR\/(\d+)/)
            if(tem!= null) return 'Opera '+tem[1];
        }
        M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
        if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
        return M.join(' ');
    })();

    self.facetsTemplate = _.template("
\

\

\
                <a data-toggle='collapse' class='accordion-toggle' data-parent='#accordion' href='#<%= facetid %>'>\
                    <%= facettitle %> \
                \

\

\
        <div id='<%= facetid %>' class='facet-list panel-collapse collapse in'>\

\

\

\

\
                    <ul id='more-<%= facetid %>' class='list-group inputs-group collapse more'>\

\

\

\

\

");

    self.filterTemplate = _.template("<li class='list-group-item' id='<%= id %>'>\
        <%= count %>\
        \
            <input type='checkbox' data-facet='<%= facet %>' value='<%= id %>' <%= checked %>>\
            <%= name %>\
        \

");

    self.siteInfoWindowTemplate = _.template("
\

<%= sitename %>

<%= sitecode %>
\

\

\
                Network: <%= network %>\
                State: <%= state %>\
                Site Type: <%= sitetype %>\

\

\
                County: <%= county %>\
                Latitude: <%= latitude %>\
                Longitude: <%= longitude %>\

\

\

\
        <button data-sitecode='<%= sitecode %>' class='btnViewSeries'>View Dataseries</button>\

");

    self.renderFacets = function(parent){
        var data = require('data');
        var facets = [];
        var facetsHtml;

        data.facets.forEach(function(facet){
            facets = facets.concat(self.facetsTemplate({facetid: facet.keyfield, facettitle: facet.name}));
        });

        facetsHtml = facets.join('');
        parent.append($(facetsHtml));
    };

    self.renderFilterItems = function() {
        var data = require('data');

        $(".facet-list").find("ul").empty();

        data.facets.forEach(function(facet) {
            var filters = [];           // Default filters
            var filters2 = [];          // Non-default filters. Must click "Show more" to display.
            var counter = 0;
            var maxDefault = 6;         // Number of default filters
            var orderedFilters = (_(facet.filters)
                .chain()
                .sortBy('dataseriesCount')
                .sortBy('applied')
                .reverse()
                .value()
            );

            orderedFilters.forEach(function(filter) {
                if (!filter.dataseriesCount) {
                    return;
                }

                var filterName = _.map(facet.namefields, function(namefield){ return filter[namefield]; }).join(', ');
                var elementData = {
                    facet: facet.keyfield,
                    id: filter[facet.keyfield],
                    name: filterName,
                    count: filter.dataseriesCount,
                    checked: (filter.applied? 'checked': '')
                };
                if (counter < maxDefault){
                    filters.push(self.filterTemplate(elementData));
                    counter++;
                }
                else{
                    filters2.push(self.filterTemplate(elementData));
                }
            });

            var filterElements = $(filters.join('')).appendTo($("#" + facet.keyfield + "  .default-values"));

            if($("#morebtn-" + facet.keyfield).length == 0){
                var text = "Show more";

                if ($("#more-" + facet.keyfield + ".in").length > 0){
                    text = "Show less";
                }

                var button = "
"+
                                text +"
";

                $("#" + facet.keyfield).append(button);
                // Toggle between "Show more" and "Show less"
                $("#morebtn-" + facet.keyfield + " a").click(function(){
                    $(this).html($(this).html() == "Show more" ? "Show less" : "Show more");
                });
            }

            // Bind checkbox check event for the default values
            filterElements.find("input:checkbox").on('change', function() {
                data.toggleFilter(this.dataset.facet, this.value);
            });

            if (!filters2.length){
                $("#morebtn-" + facet.keyfield).remove();       // If there is nothing to show, remove the button
            }
            else{
                filterElements = $(filters2.join('')).appendTo($("#" + facet.keyfield + " .more"));

                // Bind checkbox check event for the non-default values
                filterElements.find("input:checkbox").on('change', function() {
                    data.toggleFilter(this.dataset.facet, this.value);
                });
            }
        });

    };

    self.showDataseriesDialog = function(series) {
        var dialog = $('#InfoDialog');
        var plottedSeries = visualization.plottedSeries;
        var isAlreadyPlotted = _(_(plottedSeries).pluck('seriesid')).contains(series.seriesid);

         $(".modal-header").find(".alert").remove();    // Clear previous download links

        dialog.get(0).dataset['series'] = series.seriesid;
        dialog.find("#series-active-info").text((series.isactive? "Active": "Not Active"));
        dialog.find(".series-item-value").each(function(index, item) {
            if (series.hasOwnProperty(item.dataset.field)) {
                $(item).text(series[item.dataset.field]);
            }
        });

        dialog.find("#btnAddToPlot").prop('disabled',
            !visualization.canPlot() || isAlreadyPlotted);
        dialog.modal('show');
    }

    self.updateTabsFilteredCount = function() {
        var data = require('data');
        var sitesCount = data.filteredSites.length;
        var seriesCount = data.filteredDataseries.length;
        $("div#datasetsTab .badge").text(seriesCount);
        $("div#mapTab .badge").text(sitesCount);
    };

    self.getMapCanvas = function() {
        return document.getElementById("map_canvas");
    };

    self.generateClusterClass = function(networkId) {
        return ('network' + networkId);
    };

    self.addColorToClass = function(cssClass, color) {
        var rgbaString = 'rgba(' + color.rgb.red + ', ' + color.rgb.green + ', ' + color.rgb.blue + ', 0.86)';
        var backgroundColorString = 'background-color: ' + rgbaString;
        $('').appendTo('head');
    };

    self.customizeTableStyle = function() {
        $('.ColVis_MasterButton').removeClass('ColVis_Button').addClass('btn btn-default glyphicon');

        $('#tableButtons').detach().prependTo('#datasetsTable_wrapper');

        if ($.support.placeholder) {
            var filter = $('#datasetsTable_filter');
            var txtSearch = filter.find('input[type="search"]').detach();
            txtSearch.prop({placeholder: 'Search', results: 5});
            filter.empty().append(txtSearch);
        }
    };

    self.startPlotAnimation = function() {
        $("#summarystats").hide();
        $("div#graphArea .ring").show();
    };

    self.endPlotAnimation = function() {
        $("div#graphArea .ring").hide();
        $("#summarystats").show();
    };

    jQuery(function() {
        jQuery.support.placeholder = false;
        var test = document.createElement('input');
        if('placeholder' in test) jQuery.support.placeholder = true;
    });

	return self;
});<|endoftext|>


<commit_before>var timerModule = angular.module('timer', [])
  .directive('timer', ['$compile', function ($compile) {
    return  {
      restrict: 'EA',
      replace: false,
      scope: {
        interval: '=interval',
        startTimeAttr: '=startTime',
        endTimeAttr: '=endTime',
        countdownattr: '=countdown',
        finishCallback: '&finishCallback',
        autoStart: '&autoStart',
        language: '@?',
        fallback: '@?',
        maxTimeUnit: '=',
        seconds: '=?',
        minutes: '=?',
        hours: '=?',
        days: '=?',
        months: '=?',
        years: '=?',
        secondsS: '=?',
        minutesS: '=?',
        hoursS: '=?',
        daysS: '=?',
        monthsS: '=?',
        yearsS: '=?'
      },
      controller: ['$scope', '$element', '$attrs', '$timeout', 'I18nService', '$interpolate', 'progressBarService', function ($scope, $element, $attrs, $timeout, I18nService, $interpolate, progressBarService) {

        // Checking for trim function since IE8 doesn't have it
        // If not a function, create tirm with RegEx to mimic native trim
        if (typeof String.prototype.trim !== 'function') {
          String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
          };
        }

        //angular 1.2 doesn't support attributes ending in "-start", so we're
        //supporting both "autostart" and "auto-start" as a solution for
        //backward and forward compatibility.
        $scope.autoStart = $attrs.autoStart || $attrs.autostart;

        $scope.language = $scope.language || 'en';
        $scope.fallback = $scope.fallback || 'en';

        //allow to change the language of the directive while already launched
        $scope.$watch('language', function(newVal, oldVal) {
          if(newVal !== undefined) {
            i18nService.init(newVal, $scope.fallback);
          }
        });

        //init momentJS i18n, default english
        var i18nService = new I18nService();
        i18nService.init($scope.language, $scope.fallback);

        //progress bar
        $scope.displayProgressBar = 0;
        $scope.displayProgressActive = 'active'; //Bootstrap active effect for progress bar

        if ($element.html().trim().length === 0) {
          $element.append($compile('' + $interpolate.startSymbol() + 'millis' + $interpolate.endSymbol() + '')($scope));
        } else {
          $element.append($compile($element.contents())($scope));
        }

        $scope.startTime = null;
        $scope.endTime = null;
        $scope.timeoutId = null;
        $scope.countdown = angular.isNumber($scope.countdownattr) && parseInt($scope.countdownattr, 10) >= 0 ? parseInt($scope.countdownattr, 10) : undefined;
        $scope.isRunning = false;

        $scope.$on('timer-start', function () {
          $scope.start();
        });

        $scope.$on('timer-resume', function () {
          $scope.resume();
        });

        $scope.$on('timer-stop', function () {
          $scope.stop();
        });

        $scope.$on('timer-clear', function () {
          $scope.clear();
        });

        $scope.$on('timer-reset', function () {
          $scope.reset();
        });

        $scope.$on('timer-set-countdown', function (e, countdown) {
          $scope.countdown = countdown;
        });

        function resetTimeout() {
          if ($scope.timeoutId) {
            clearTimeout($scope.timeoutId);
          }
        }

        $scope.$watch('startTimeAttr', function(newValue, oldValue) {
          if (newValue !== oldValue && $scope.isRunning) {
            $scope.start();
          }
        });

        $scope.$watch('endTimeAttr', function(newValue, oldValue) {
          if (newValue !== oldValue && $scope.isRunning) {
            $scope.start();
          }
        });

        $scope.start = function () {
          $scope.startTime = $scope.startTimeAttr ? moment($scope.startTimeAttr) : moment();
          $scope.endTime = $scope.endTimeAttr ? moment($scope.endTimeAttr) : null;
          if (!angular.isNumber($scope.countdown)) {
            $scope.countdown = angular.isNumber($scope.countdownattr) && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
          }
          resetTimeout();
          tick();
          $scope.isRunning = true;
          $scope.$emit('timer-started', {
            timeoutId: $scope.timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $scope.resume = function () {
          resetTimeout();
          if ($scope.countdownattr) {
            $scope.countdown += 1;
          }
          $scope.startTime = moment().diff((moment($scope.stoppedTime).diff(moment($scope.startTime))));
          tick();
          $scope.isRunning = true;
          $scope.$emit('timer-started', {
            timeoutId: $scope.timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $scope.stop = $scope.pause = function () {
          var timeoutId = $scope.timeoutId;
          $scope.clear();
          $scope.$emit('timer-stopped', {
            timeoutId: timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $scope.clear = function () {
          // same as stop but without the event being triggered
          $scope.stoppedTime = moment();
          resetTimeout();
          $scope.timeoutId = null;
          $scope.isRunning = false;
        };

        $scope.reset = function () {
          $scope.startTime = $scope.startTimeAttr ? moment($scope.startTimeAttr) : moment();
          $scope.endTime = $scope.endTimeAttr ? moment($scope.endTimeAttr) : null;
          $scope.countdown = angular.isNumber($scope.countdownattr) && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
          resetTimeout();
          tick();
          $scope.isRunning = false;
          $scope.clear();
          $scope.$emit('timer-reset', {
            timeoutId: timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $element.bind('$destroy', function () {
          resetTimeout();
          $scope.isRunning = false;
        });

        function calculateTimeUnits() {
          var timeUnits = {}; //will contains time with units

          if ($attrs.startTime !== undefined){
            $scope.millis = moment().diff(moment($scope.startTimeAttr));
          }

          timeUnits = i18nService.getTimeUnits($scope.millis);

          // compute time values based on maxTimeUnit specification
          if (!$scope.maxTimeUnit || $scope.maxTimeUnit === 'day') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
            $scope.days = Math.floor((($scope.millis / (3600000)) / 24));
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'second') {
            $scope.seconds = Math.floor($scope.millis / 1000);
            $scope.minutes = 0;
            $scope.hours = 0;
            $scope.days = 0;
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'minute') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor($scope.millis / 60000);
            $scope.hours = 0;
            $scope.days = 0;
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'hour') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor($scope.millis / 3600000);
            $scope.days = 0;
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'month') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
            $scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
            $scope.months = Math.floor((($scope.millis / (3600000)) / 24) / 30);
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'year') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
            $scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
            $scope.months = Math.floor((($scope.millis / (3600000)) / 24 / 30) % 12);
            $scope.years = Math.floor(($scope.millis / (3600000)) / 24 / 365);
          }
          // plural - singular unit decision (old syntax, for backwards compatibility and English only, could be deprecated!)
          $scope.secondsS = ($scope.seconds === 1) ? '' : 's';
          $scope.minutesS = ($scope.minutes === 1) ? '' : 's';
          $scope.hoursS = ($scope.hours === 1) ? '' : 's';
          $scope.daysS = ($scope.days === 1)? '' : 's';
          $scope.monthsS = ($scope.months === 1)? '' : 's';
          $scope.yearsS = ($scope.years === 1)? '' : 's';

          // new plural-singular unit decision functions (for custom units and multilingual support)
          $scope.secondUnit = timeUnits.seconds;
          $scope.minuteUnit = timeUnits.minutes;
          $scope.hourUnit = timeUnits.hours;
          $scope.dayUnit = timeUnits.days;
          $scope.monthUnit = timeUnits.months;
          $scope.yearUnit = timeUnits.years;

          //add leading zero if number is smaller than 10
          $scope.sseconds = $scope.seconds < 10 ? '0' + $scope.seconds : $scope.seconds;
          $scope.mminutes = $scope.minutes < 10 ? '0' + $scope.minutes : $scope.minutes;
          $scope.hhours = $scope.hours < 10 ? '0' + $scope.hours : $scope.hours;
          $scope.ddays = $scope.days < 10 ? '0' + $scope.days : $scope.days;
          $scope.mmonths = $scope.months < 10 ? '0' + $scope.months : $scope.months;
          $scope.yyears = $scope.years < 10 ? '0' + $scope.years : $scope.years;

        }

        //determine initial values of time units and add AddSeconds functionality
        if ($scope.countdownattr) {
          $scope.millis = $scope.countdownattr * 1000;

          $scope.addCDSeconds = function (extraSeconds) {
            $scope.countdown += extraSeconds;
            if (!$scope.isRunning) {
              $scope.start();
            }
          };

          $scope.$on('timer-add-cd-seconds', function (e, extraSeconds) {
             $scope.addCDSeconds(extraSeconds);
          });

          $scope.$on('timer-set-countdown-seconds', function (e, countdownSeconds) {
            if (!$scope.isRunning) {
              $scope.clear();
            }

            $scope.countdown = countdownSeconds;
            $scope.millis = countdownSeconds * 1000;
            calculateTimeUnits();
          });
        } else {
          $scope.millis = 0;
        }
        calculateTimeUnits();

        var tick = function tick() {
          var typeTimer = null; // countdown or endTimeAttr
          $scope.millis = moment().diff($scope.startTime);
          var adjustment = $scope.millis % 1000;

          if ($scope.endTimeAttr) {
            typeTimer = $scope.endTimeAttr;
            $scope.millis = moment($scope.endTime).diff(moment());
            adjustment = $scope.interval - $scope.millis % 1000;
          }

          if ($scope.countdownattr) {
            typeTimer = $scope.countdownattr;
            $scope.millis = $scope.countdown * 1000;
          }

          if ($scope.millis < 0) {
            $scope.stop();
            $scope.millis = 0;
            calculateTimeUnits();
            if($scope.finishCallback) {
              $scope.$eval($scope.finishCallback);
            }
            return;
          }
          calculateTimeUnits();

          //We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5
          $scope.timeoutId = setTimeout(function () {
              tick();
              // since you choose not to use $timeout, at least preserve angular cycle two way data binding
              // by calling $scope.$apply() instead of $scope.$digest()
              $scope.$apply();
          }, $scope.interval - adjustment);

          $scope.$emit('timer-tick', {
            timeoutId: $scope.timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });

          if ($scope.countdown > 0) {
            $scope.countdown--;
          }
          else if ($scope.countdown <= 0) {
            $scope.stop();
            if($scope.finishCallback) {
              $scope.$eval($scope.finishCallback);
            }
          }

          if(typeTimer !== null){
            //calculate progress bar
            $scope.progressBar = progressBarService.calculateProgressBar($scope.startTime, $scope.millis, $scope.endTime, $scope.countdownattr);

            if($scope.progressBar === 100){
              $scope.displayProgressActive = ''; //No more Bootstrap active effect
            }
          }
        };

        if ($scope.autoStart === undefined || $scope.autoStart === true) {
          $scope.start();
        }
      }]
    };
  }])
  .directive('timerControls', function() {
    return {
      restrict: 'EA',
      scope: true,
      controller: ['$scope', function($scope) {
        $scope.timerStatus = "reset";
        $scope.$on('timer-started', function() {
          $scope.timerStatus = "started";
        });
        $scope.$on('timer-stopped', function() {
          $scope.timerStatus = "stopped";
        });
        $scope.$on('timer-reset', function() {
          $scope.timerStatus = "reset";
        });
        $scope.timerStart = function() {
          $scope.$broadcast('timer-start');
        };
        $scope.timerStop = function() {
          $scope.$broadcast('timer-stop');
        };
        $scope.timerResume = function() {
          $scope.$broadcast('timer-resume');
        };
        $scope.timerToggle = function() {
          switch ($scope.timerStatus) {
            case "started":
              $scope.timerStop();
              break;
            case "stopped":
              $scope.timerResume();
              break;
            case "reset":
              $scope.timerStart();
              break;
          }
        };
        $scope.timerAddCDSeconds = function(extraSeconds) {
          $scope.$broadcast('timer-add-cd-seconds', extraSeconds);
        };
      }]
    };
  });

/* commonjs package manager support (eg componentjs) */
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
  module.exports = timerModule;
}
<commit_msg>fixing undeclared timeoutId error in reset<commit_after>var timerModule = angular.module('timer', [])
  .directive('timer', ['$compile', function ($compile) {
    return  {
      restrict: 'EA',
      replace: false,
      scope: {
        interval: '=interval',
        startTimeAttr: '=startTime',
        endTimeAttr: '=endTime',
        countdownattr: '=countdown',
        finishCallback: '&finishCallback',
        autoStart: '&autoStart',
        language: '@?',
        fallback: '@?',
        maxTimeUnit: '=',
        seconds: '=?',
        minutes: '=?',
        hours: '=?',
        days: '=?',
        months: '=?',
        years: '=?',
        secondsS: '=?',
        minutesS: '=?',
        hoursS: '=?',
        daysS: '=?',
        monthsS: '=?',
        yearsS: '=?'
      },
      controller: ['$scope', '$element', '$attrs', '$timeout', 'I18nService', '$interpolate', 'progressBarService', function ($scope, $element, $attrs, $timeout, I18nService, $interpolate, progressBarService) {

        // Checking for trim function since IE8 doesn't have it
        // If not a function, create tirm with RegEx to mimic native trim
        if (typeof String.prototype.trim !== 'function') {
          String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
          };
        }

        //angular 1.2 doesn't support attributes ending in "-start", so we're
        //supporting both "autostart" and "auto-start" as a solution for
        //backward and forward compatibility.
        $scope.autoStart = $attrs.autoStart || $attrs.autostart;

        $scope.language = $scope.language || 'en';
        $scope.fallback = $scope.fallback || 'en';

        //allow to change the language of the directive while already launched
        $scope.$watch('language', function(newVal, oldVal) {
          if(newVal !== undefined) {
            i18nService.init(newVal, $scope.fallback);
          }
        });

        //init momentJS i18n, default english
        var i18nService = new I18nService();
        i18nService.init($scope.language, $scope.fallback);

        //progress bar
        $scope.displayProgressBar = 0;
        $scope.displayProgressActive = 'active'; //Bootstrap active effect for progress bar

        if ($element.html().trim().length === 0) {
          $element.append($compile('' + $interpolate.startSymbol() + 'millis' + $interpolate.endSymbol() + '')($scope));
        } else {
          $element.append($compile($element.contents())($scope));
        }

        $scope.startTime = null;
        $scope.endTime = null;
        $scope.timeoutId = null;
        $scope.countdown = angular.isNumber($scope.countdownattr) && parseInt($scope.countdownattr, 10) >= 0 ? parseInt($scope.countdownattr, 10) : undefined;
        $scope.isRunning = false;

        $scope.$on('timer-start', function () {
          $scope.start();
        });

        $scope.$on('timer-resume', function () {
          $scope.resume();
        });

        $scope.$on('timer-stop', function () {
          $scope.stop();
        });

        $scope.$on('timer-clear', function () {
          $scope.clear();
        });

        $scope.$on('timer-reset', function () {
          $scope.reset();
        });

        $scope.$on('timer-set-countdown', function (e, countdown) {
          $scope.countdown = countdown;
        });

        function resetTimeout() {
          if ($scope.timeoutId) {
            clearTimeout($scope.timeoutId);
          }
        }

        $scope.$watch('startTimeAttr', function(newValue, oldValue) {
          if (newValue !== oldValue && $scope.isRunning) {
            $scope.start();
          }
        });

        $scope.$watch('endTimeAttr', function(newValue, oldValue) {
          if (newValue !== oldValue && $scope.isRunning) {
            $scope.start();
          }
        });

        $scope.start = function () {
          $scope.startTime = $scope.startTimeAttr ? moment($scope.startTimeAttr) : moment();
          $scope.endTime = $scope.endTimeAttr ? moment($scope.endTimeAttr) : null;
          if (!angular.isNumber($scope.countdown)) {
            $scope.countdown = angular.isNumber($scope.countdownattr) && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
          }
          resetTimeout();
          tick();
          $scope.isRunning = true;
          $scope.$emit('timer-started', {
            timeoutId: $scope.timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $scope.resume = function () {
          resetTimeout();
          if ($scope.countdownattr) {
            $scope.countdown += 1;
          }
          $scope.startTime = moment().diff((moment($scope.stoppedTime).diff(moment($scope.startTime))));
          tick();
          $scope.isRunning = true;
          $scope.$emit('timer-started', {
            timeoutId: $scope.timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $scope.stop = $scope.pause = function () {
          var timeoutId = $scope.timeoutId;
          $scope.clear();
          $scope.$emit('timer-stopped', {
            timeoutId: timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $scope.clear = function () {
          // same as stop but without the event being triggered
          $scope.stoppedTime = moment();
          resetTimeout();
          $scope.timeoutId = null;
          $scope.isRunning = false;
        };

        $scope.reset = function () {
          $scope.startTime = $scope.startTimeAttr ? moment($scope.startTimeAttr) : moment();
          $scope.endTime = $scope.endTimeAttr ? moment($scope.endTimeAttr) : null;
          $scope.countdown = angular.isNumber($scope.countdownattr) && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
          resetTimeout();
          tick();
          $scope.isRunning = false;
          $scope.clear();
          $scope.$emit('timer-reset', {
            timeoutId: $scope.timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });
        };

        $element.bind('$destroy', function () {
          resetTimeout();
          $scope.isRunning = false;
        });

        function calculateTimeUnits() {
          var timeUnits = {}; //will contains time with units

          if ($attrs.startTime !== undefined){
            $scope.millis = moment().diff(moment($scope.startTimeAttr));
          }

          timeUnits = i18nService.getTimeUnits($scope.millis);

          // compute time values based on maxTimeUnit specification
          if (!$scope.maxTimeUnit || $scope.maxTimeUnit === 'day') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
            $scope.days = Math.floor((($scope.millis / (3600000)) / 24));
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'second') {
            $scope.seconds = Math.floor($scope.millis / 1000);
            $scope.minutes = 0;
            $scope.hours = 0;
            $scope.days = 0;
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'minute') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor($scope.millis / 60000);
            $scope.hours = 0;
            $scope.days = 0;
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'hour') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor($scope.millis / 3600000);
            $scope.days = 0;
            $scope.months = 0;
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'month') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
            $scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
            $scope.months = Math.floor((($scope.millis / (3600000)) / 24) / 30);
            $scope.years = 0;
          } else if ($scope.maxTimeUnit === 'year') {
            $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
            $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
            $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
            $scope.days = Math.floor((($scope.millis / (3600000)) / 24) % 30);
            $scope.months = Math.floor((($scope.millis / (3600000)) / 24 / 30) % 12);
            $scope.years = Math.floor(($scope.millis / (3600000)) / 24 / 365);
          }
          // plural - singular unit decision (old syntax, for backwards compatibility and English only, could be deprecated!)
          $scope.secondsS = ($scope.seconds === 1) ? '' : 's';
          $scope.minutesS = ($scope.minutes === 1) ? '' : 's';
          $scope.hoursS = ($scope.hours === 1) ? '' : 's';
          $scope.daysS = ($scope.days === 1)? '' : 's';
          $scope.monthsS = ($scope.months === 1)? '' : 's';
          $scope.yearsS = ($scope.years === 1)? '' : 's';

          // new plural-singular unit decision functions (for custom units and multilingual support)
          $scope.secondUnit = timeUnits.seconds;
          $scope.minuteUnit = timeUnits.minutes;
          $scope.hourUnit = timeUnits.hours;
          $scope.dayUnit = timeUnits.days;
          $scope.monthUnit = timeUnits.months;
          $scope.yearUnit = timeUnits.years;

          //add leading zero if number is smaller than 10
          $scope.sseconds = $scope.seconds < 10 ? '0' + $scope.seconds : $scope.seconds;
          $scope.mminutes = $scope.minutes < 10 ? '0' + $scope.minutes : $scope.minutes;
          $scope.hhours = $scope.hours < 10 ? '0' + $scope.hours : $scope.hours;
          $scope.ddays = $scope.days < 10 ? '0' + $scope.days : $scope.days;
          $scope.mmonths = $scope.months < 10 ? '0' + $scope.months : $scope.months;
          $scope.yyears = $scope.years < 10 ? '0' + $scope.years : $scope.years;

        }

        //determine initial values of time units and add AddSeconds functionality
        if ($scope.countdownattr) {
          $scope.millis = $scope.countdownattr * 1000;

          $scope.addCDSeconds = function (extraSeconds) {
            $scope.countdown += extraSeconds;
            if (!$scope.isRunning) {
              $scope.start();
            }
          };

          $scope.$on('timer-add-cd-seconds', function (e, extraSeconds) {
             $scope.addCDSeconds(extraSeconds);
          });

          $scope.$on('timer-set-countdown-seconds', function (e, countdownSeconds) {
            if (!$scope.isRunning) {
              $scope.clear();
            }

            $scope.countdown = countdownSeconds;
            $scope.millis = countdownSeconds * 1000;
            calculateTimeUnits();
          });
        } else {
          $scope.millis = 0;
        }
        calculateTimeUnits();

        var tick = function tick() {
          var typeTimer = null; // countdown or endTimeAttr
          $scope.millis = moment().diff($scope.startTime);
          var adjustment = $scope.millis % 1000;

          if ($scope.endTimeAttr) {
            typeTimer = $scope.endTimeAttr;
            $scope.millis = moment($scope.endTime).diff(moment());
            adjustment = $scope.interval - $scope.millis % 1000;
          }

          if ($scope.countdownattr) {
            typeTimer = $scope.countdownattr;
            $scope.millis = $scope.countdown * 1000;
          }

          if ($scope.millis < 0) {
            $scope.stop();
            $scope.millis = 0;
            calculateTimeUnits();
            if($scope.finishCallback) {
              $scope.$eval($scope.finishCallback);
            }
            return;
          }
          calculateTimeUnits();

          //We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5
          $scope.timeoutId = setTimeout(function () {
              tick();
              // since you choose not to use $timeout, at least preserve angular cycle two way data binding
              // by calling $scope.$apply() instead of $scope.$digest()
              $scope.$apply();
          }, $scope.interval - adjustment);

          $scope.$emit('timer-tick', {
            timeoutId: $scope.timeoutId,
            millis: $scope.millis,
            seconds: $scope.seconds,
            minutes: $scope.minutes,
            hours: $scope.hours,
            days: $scope.days
          });

          if ($scope.countdown > 0) {
            $scope.countdown--;
          }
          else if ($scope.countdown <= 0) {
            $scope.stop();
            if($scope.finishCallback) {
              $scope.$eval($scope.finishCallback);
            }
          }

          if(typeTimer !== null){
            //calculate progress bar
            $scope.progressBar = progressBarService.calculateProgressBar($scope.startTime, $scope.millis, $scope.endTime, $scope.countdownattr);

            if($scope.progressBar === 100){
              $scope.displayProgressActive = ''; //No more Bootstrap active effect
            }
          }
        };

        if ($scope.autoStart === undefined || $scope.autoStart === true) {
          $scope.start();
        }
      }]
    };
  }])
  .directive('timerControls', function() {
    return {
      restrict: 'EA',
      scope: true,
      controller: ['$scope', function($scope) {
        $scope.timerStatus = "reset";
        $scope.$on('timer-started', function() {
          $scope.timerStatus = "started";
        });
        $scope.$on('timer-stopped', function() {
          $scope.timerStatus = "stopped";
        });
        $scope.$on('timer-reset', function() {
          $scope.timerStatus = "reset";
        });
        $scope.timerStart = function() {
          $scope.$broadcast('timer-start');
        };
        $scope.timerStop = function() {
          $scope.$broadcast('timer-stop');
        };
        $scope.timerResume = function() {
          $scope.$broadcast('timer-resume');
        };
        $scope.timerToggle = function() {
          switch ($scope.timerStatus) {
            case "started":
              $scope.timerStop();
              break;
            case "stopped":
              $scope.timerResume();
              break;
            case "reset":
              $scope.timerStart();
              break;
          }
        };
        $scope.timerAddCDSeconds = function(extraSeconds) {
          $scope.$broadcast('timer-add-cd-seconds', extraSeconds);
        };
      }]
    };
  });

/* commonjs package manager support (eg componentjs) */
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
  module.exports = timerModule;
}
<|endoftext|>


<commit_before>module.exports = function(expect, eventEmitter, validCivo, invalidCivo, civoStub) {
  describe('listLoadBalancers()', () => {
    it('auto fail', (done) => {
      done(new Error('force fail'));
    })
  });
  describe('createLoadBalancers()', () => {
    it('auto fail', (done) => {
      done(new Error('force fail'));
    })
  });
  describe('updateLoadBalancers()', () => {
    it('auto fail', (done) => {
      done(new Error('force fail'));
    })
  });
  describe('deleteLoadBalancers()', () => {
    it('auto fail', (done) => {
      done(new Error('force fail'));
    })
  });
}

// module.exports = function(expect, eventEmitter, validCivo, invalidCivo, civoStub) {
//   describe('listDomains()', () => {
//     it('valid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.listDomains()
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(200, 'returned status should be 200');
//         expect(request.method).to.be.equal('GET', 'listDomains() should be a GET request');
//         expect(request.url).to.be.equal('/dns', 'listDomains() should call "/dns" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         expect(Object.keys(request.params)).to.have.lengthOf(0, 'No params should be used');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.responses.getDomainNames.response), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         invalidCivo.listDomains()
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(401, 'returned status should be 401 unauthorised');
//         expect(request.method).to.be.equal('GET', 'listDomains() should be a GET request');
//         expect(request.url).to.be.equal('/dns', 'listDomains() should call "/dns" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         expect(Object.keys(request.params)).to.have.lengthOf(0, 'No params should be used');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.authentication), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//   });
//   describe('createDomain()', () => {
//     it('valid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.createDomain('test.com')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(200, 'returned status should be 200');
//         expect(request.method).to.be.equal('POST', 'createDomain() should be a POST request');
//         expect(request.url).to.be.equal('/dns', 'createDomain() should call "/dns" endpoint');
//         const bodyKeys = Object.keys(request.body);
//         expect(bodyKeys).to.have.lengthOf(1, '1 key of body data should be recived');
//         expect(bodyKeys).to.include('name', 'expects body to contain name');
//         expect(request.body.name).to.be.equal('test.com', 'the "name" body field did not match');
//         expect(Object.keys(request.params)).to.have.lengthOf(0, 'No params should be used');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.responses.postDomainNames.response), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         invalidCivo.createDomain('test.com')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(401, 'returned status should be 401 unauthorised');
//         expect(request.method).to.be.equal('POST', 'createDomain() should be a POST request');
//         expect(request.url).to.be.equal('/dns', 'createDomain() should call "/dns" endpoint');
//         const bodyKeys = Object.keys(request.body);
//         expect(bodyKeys).to.have.lengthOf(1, '1 key of body data should be recived');
//         expect(bodyKeys).to.include('name', 'expects body to contain name');
//         expect(request.body.name).to.be.equal('test.com', 'the "name" body field did not match');
//         expect(Object.keys(request.params)).to.have.lengthOf(0, 'No params should be used');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.authentication), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid name', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.createDomain()
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(500, 'returned status should be 500 server error');
//         expect(request.method).to.be.equal('POST', 'createDomain() should be a POST request');
//         expect(request.url).to.be.equal('/dns', 'createDomain() should call "/dns" endpoint');
//         const bodyKeys = Object.keys(request.body);
//         expect(Object.keys(request.params)).to.have.lengthOf(0, 'No params should be used');
//         expect(bodyKeys).to.have.lengthOf(0, 'no body data should be recived');
//         expect(bodyKeys).to.not.include('name', 'expects no label to be sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.invalidName), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//   });
//   describe('deleteDomain()', () => {
//     it('valid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.deleteDomain('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(202, 'returned status should be 202');
//         expect(request.method).to.be.equal('DELETE', 'deleteDomain() should be a DELETE request');
//         expect(request.url).to.be.equal('/dns', 'deleteDomain() should call "/dns" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'no keys of body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.responses.deleteDomainNames.response), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         invalidCivo.deleteDomain('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(401, 'returned status should be 401 unauthorised');
//         expect(request.method).to.be.equal('DELETE', 'deleteDomain() should be a DELETE request');
//         expect(request.url).to.be.equal('/dns', 'deleteDomain() should call "/dns" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'no keys of body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.authentication), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid id', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.deleteDomain()
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(500, 'returned status should be 500 server error');
//         expect(request.method).to.be.equal('DELETE', 'deleteDomain() should be a DELETE request');
//         expect(request.url).to.be.equal('/dns', 'deleteDomain() should call "/dns" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'no keys of body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('undefined', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.invalidId), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//   });

//   describe('listDomainRecords()', () => {
//     it('valid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.listDomainRecords('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(200, 'returned status should be 200');
//         expect(request.method).to.be.equal('GET', 'listDomainRecords() should be a GET request');
//         expect(request.url).to.be.equal('/dns/records', 'listDomainRecords() should call "/dns/:id/records" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.responses.getDomainNames.recordsresponse), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         invalidCivo.listDomainRecords('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(401, 'returned status should be 401 unauthorised');
//         expect(request.method).to.be.equal('GET', 'listDomainRecords() should be a GET request');
//         expect(request.url).to.be.equal('/dns/records', 'listDomainRecords() should call "/dns/:id/records" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.authentication), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid id', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.listDomainRecords()
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(500, 'returned status should be 500 server error');
//         expect(request.method).to.be.equal('GET', 'listDomainRecords() should be a GET request');
//         expect(request.url).to.be.equal('/dns/records', 'listDomainRecords() should call "/dns/:id/records" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'no keys of body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('undefined', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.invalidId), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//   });
//   describe('createDomainRecord()', () => {
//     it('valid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.createDomainRecord('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'a', '@', '0.0.0.0', '10', '3600')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(200, 'returned status should be 200 ok');
//         expect(request.method).to.be.equal('POST', 'createDomainRecord() should be a POST request');
//         expect(request.url).to.be.equal('/dns/records', 'createDomainRecord() should call "/dns/:id/records" endpoint');
//         const bodyKeys = Object.keys(request.body);
//         expect(bodyKeys).to.have.lengthOf(5, '5 body data should be recived');
//         expect(request.body).to.have.all.keys('type', 'name', 'value', 'priority', 'ttl');
//         expect(request.body.type).to.be.equal('a');
//         expect(request.body.name).to.be.equal('@');
//         expect(request.body.value).to.be.equal('0.0.0.0');
//         expect(request.body.priority).to.be.equal('10');
//         expect(request.body.ttl).to.be.equal('3600');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.responses.postDomainNames.recordresponse), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         invalidCivo.createDomainRecord('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'a', '@', '0.0.0.0', '10', '3600')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(401, 'returned status should be 401 unauthorised');
//         expect(request.method).to.be.equal('POST', 'createDomainRecord() should be a POST request');
//         expect(request.url).to.be.equal('/dns/records', 'createDomainRecord() should call "/dns/:id/records" endpoint');
//         const bodyKeys = Object.keys(request.body);
//         expect(bodyKeys).to.have.lengthOf(5, '5 body data should be recived');
//         expect(request.body).to.have.all.keys('type', 'name', 'value', 'priority', 'ttl');
//         expect(request.body.type).to.be.equal('a');
//         expect(request.body.name).to.be.equal('@');
//         expect(request.body.value).to.be.equal('0.0.0.0');
//         expect(request.body.priority).to.be.equal('10');
//         expect(request.body.ttl).to.be.equal('3600');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.authentication), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('missing optionals', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.createDomainRecord('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'a', '@', '0.0.0.0')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(200, 'returned status should be 200 ok');
//         expect(request.method).to.be.equal('POST', 'createDomainRecord() should be a POST request');
//         expect(request.url).to.be.equal('/dns/records', 'createDomainRecord() should call "/dns/:id/records" endpoint');
//         const bodyKeys = Object.keys(request.body);
//         expect(bodyKeys).to.have.lengthOf(3, '3 body data should be recived');
//         expect(request.body).to.have.all.keys('type', 'name', 'value');
//         expect(request.body.type).to.be.equal('a');
//         expect(request.body.name).to.be.equal('@');
//         expect(request.body.value).to.be.equal('0.0.0.0');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.responses.postDomainNames.recordresponse), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid id', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.createDomainRecord()
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(500, 'returned status should be 500 server error');
//         expect(request.method).to.be.equal('POST', 'createDomainRecord() should be a POST request');
//         expect(request.url).to.be.equal('/dns/records', 'createDomainRecord() should call "/dns/:id/records" endpoint');
//         const bodyKeys = Object.keys(request.body);
//         expect(bodyKeys).to.have.lengthOf(0, 'no body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(1, '1 parameter should be used');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('undefined', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.invalidId), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//   });
//   describe('deleteDomainRecord()', () => {
//     it('valid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.deleteDomainRecord('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(202, 'returned status should be 202 accepted');
//         expect(request.method).to.be.equal('DELETE', 'deleteDomainRecord() should be a DELETE request');
//         expect(request.url).to.be.equal('/dns/records', 'deleteDomainRecord() should call "/dns/:id/records" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(2, '2 parameter should be used');
//         expect(paramKeys).to.include('domain_id', 'expects parameters to specify an id');
//         expect(request.params.domain_id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.responses.deleteDomainNames.recordresponse), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid auth', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         invalidCivo.deleteDomainRecord('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(401, 'returned status should be 401 unauthorised');
//         expect(request.method).to.be.equal('DELETE', 'deleteDomainRecord() should be a DELETE request');
//         expect(request.url).to.be.equal('/dns/records', 'deleteDomainRecord() should call "/dns/:id/records" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(2, '2 parameter should be used');
//         expect(paramKeys).to.include('domain_id', 'expects parameters to specify an id');
//         expect(request.params.domain_id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.authentication), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid id', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.deleteDomainRecord('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx')
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(500, 'returned status should be 500 server error');
//         expect(request.method).to.be.equal('DELETE', 'deleteDomainRecord() should be a DELETE request');
//         expect(request.url).to.be.equal('/dns/records', 'deleteDomainRecord() should call "/dns/:id/records" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(2, '2 parameter should be used');
//         expect(paramKeys).to.include('domain_id', 'expects parameters to specify an id');
//         expect(request.params.domain_id).to.be.equal('xxxxxxxx-xxxx-4xxx-4xxx-xxxxxxxxxxxx', 'received id parameter was not the same as sent');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('undefined', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.invalidId), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//     it('invalid domain_id', (done) => {
//       Promise.all([
//         eventEmitter.once('received'),
//         validCivo.deleteDomainRecord()
//       ]).then((data) => {
//         const request = data[0][0];
//         const response = data[1];
//         expect(request.status).to.be.equal(500, 'returned status should be 500 server error');
//         expect(request.method).to.be.equal('DELETE', 'deleteDomainRecord() should be a DELETE request');
//         expect(request.url).to.be.equal('/dns/records', 'deleteDomainRecord() should call "/dns/:id/records" endpoint');
//         expect(Object.keys(request.body)).to.have.lengthOf(0, 'No body data should be recived');
//         const paramKeys = Object.keys(request.params);
//         expect(paramKeys).to.have.lengthOf(2, '2 parameter should be used');
//         expect(paramKeys).to.include('domain_id', 'expects parameters to specify an id');
//         expect(request.params.domain_id).to.be.equal('undefined', 'received id parameter was not the same as sent');
//         expect(paramKeys).to.include('id', 'expects parameters to specify an id');
//         expect(request.params.id).to.be.equal('undefined', 'received id parameter was not the same as sent');
//         expect(JSON.stringify(response)).to.be.equal(JSON.stringify(civoStub.errors.invalidId), 'correct response was not returned');
//         done();
//       }).catch((err) => {
//         done(err);
//       });
//     });
//   });
// };<commit_msg>removing old tests<commit_after><|endoftext|>


<commit_before>(function() {
    'use strict';

    angular.module('Pager', [])
    .directive('pager', [function () {
        var definition = {
            restrict: 'A',
            scope: { currentPage: '=', totalPages: '=', maxPagesToDisplay: '@', pageChanged: '&' },
            replace: true,
            templateUrl: 'pager.tpl.html',

            link: function (scope, iElement, iAttrs) {
                scope.changed = function (newPage) {
                    if(!newPage)
                        return;

                    console.log(newPage);
                    scope.pageChanged({ pageNum: newPage });
                };

                scope.$watch('currentPage', updateCurrentPage);
                scope.$watch('totalPages', updateTotalPages);
                scope.$watch('maxPagesToDisplay', updateMaxPages);

                function updateTotalPages(totalPages)
                {
                    updatePages(scope.currentPage, totalPages, scope.maxPagesToDisplay);
                }

                function updateCurrentPage(currentPage)
                {
                    updatePages(currentPage, scope.totalPages, scope.maxPagesToDisplay);
                }

                function updateMaxPages(maxPages)
                {
                    updatePages(scope.currentPage, scope.totalPages, maxPages);
                }

                function updatePages(currentPage, totalPages, maxPages)
                {
                    var pages = [];
                    currentPage = parseInt(currentPage);
                    var pagesLeft = totalPages - currentPage;
                    var pagesAfterCurrent = Math.min(totalPages - currentPage, maxPages);
                    var pagesBeforeCurrent = Math.max(0, maxPages - pagesAfterCurrent);

                    var start = currentPage - pagesBeforeCurrent;
                    var end = currentPage + pagesAfterCurrent;

                    scope.hasPreBuffer = start !== 0;
                    scope.hasPostBuffer = end !== totalPages;

                    for(var i = start; i < end; i++)
                    {
                        pages.push({pageNumber: i, isCurrent: i == currentPage });
                    }
                    scope.pages = pages;
                }
            }
        };
        return definition;
    }]);
})();
<commit_msg>Cleanup<commit_after>(function() {
    'use strict';

    angular.module('Pager', [])
    .directive('pager', [function () {
        var definition = {
            restrict: 'A',
            scope: { currentPage: '=', totalPages: '=', maxPagesToDisplay: '@', pageChanged: '&' },
            replace: true,
            templateUrl: 'pager.tpl.html',

            link: function (scope, iElement, iAttrs) {
                scope.changed = function (newPage) {
                    if(!newPage)
                        return;

                    scope.pageChanged({ pageNum: newPage });
                };

                scope.$watch('currentPage', updateCurrentPage);
                scope.$watch('totalPages', updateTotalPages);
                scope.$watch('maxPagesToDisplay', updateMaxPages);

                function updateTotalPages(totalPages)
                {
                    updatePages(scope.currentPage, totalPages, scope.maxPagesToDisplay);
                }

                function updateCurrentPage(currentPage)
                {
                    updatePages(currentPage, scope.totalPages, scope.maxPagesToDisplay);
                }

                function updateMaxPages(maxPages)
                {
                    updatePages(scope.currentPage, scope.totalPages, maxPages);
                }

                function updatePages(currentPage, totalPages, maxPages)
                {
                    var pages = [];
                    currentPage = parseInt(currentPage);
                    var pagesLeft = totalPages - currentPage;
                    var pagesAfterCurrent = Math.min(totalPages - currentPage, maxPages);
                    var pagesBeforeCurrent = Math.max(0, maxPages - pagesAfterCurrent);

                    var start = currentPage - pagesBeforeCurrent;
                    var end = currentPage + pagesAfterCurrent;

                    scope.hasPreBuffer = start !== 0;
                    scope.hasPostBuffer = end !== totalPages;

                    for(var i = start; i < end; i++)
                    {
                        pages.push({pageNumber: i, isCurrent: i == currentPage });
                    }
                    scope.pages = pages;
                }
            }
        };
        return definition;
    }]);
})();
<|endoftext|>


<commit_before>/**
 * Date Range Field
 *
 * @class Hatimeria.core.field.DateRangeField
 * @extends Ext.form.field.Basic
 */
(function() {

    Ext.define('Hatimeria.core.field.DateRangeField', {
        extend: 'Ext.form.field.Picker',

        /**
         * @cfg {Object} value
         */
        value: {
            from: new Date,
            to: new Date
        },

        /**
         * Default width
         *
         * @cfg {Number} width
         */
        width: 170,

        /**
         * @cfg {String} format corresponding to Ext.util.Format.date()
         */
        format: 'd/m/Y',

        /**
         * @private
         * @property {Array}
         */
        rangeBoilerplates: [
            {key: 'today',   value: 'Dzisiejsze'},
            {key: 'week',    value: 'Z ostatniego tygodnia'},
            {key: 'twoweek', value: 'Z ostatnich dwóch tygodni'},
            {key: 'month',   value: 'Z ostatniego miesiąca'},
            {key: 'year',    value: 'Z ostatniego roku'}
        ],

        pickerAlign: 'bl',

        /**
         * @private
         */
        matchFieldWidth: false,

        constructor: function(cfg)
        {
            var config = {
            };
            Ext.apply(config, cfg || {});
            this.callParent([config]);
        },

        /**
         * Converts string to value Object
         *
         * @param {String} value
         * @private
         */
        dateRangeToObject: function(value)
        {
            var dates = value.split(/\s+\-\s+/);
            var date = {
                from: this.convertToDate(dates[0]),
                to: this.convertToDate(dates[1])
            }

            return date;
        },

        /**
         * String to object {Date}
         *
         * @param {String}
         * @return {Date}
         */
        convertToDate: function(value)
        {
            if (typeof value == 'object')
            {
                if (value instanceof Date)
                {
                    return value;
                }
                else
                {
                    throw new Error('Object must be instance of Date');
                }
            }
            else
            {
                return Ext.Date.parse(value, this.format);
            }
        },

        /**
         * Guess!
         *
         * @param {Object}
         */
        setValue: function(value)
        {
            var defaultValue = {
                from: new Date,
                to: new Date
            };

            if (!Ext.isObject(value))
            {
                value = this.defaultValue;
            }

            value = Ext.apply(defaultValue, value);
            value.from = this.convertToDate(value.from);
            value.to = this.convertToDate(value.to);
            this.lastValue = value;

            return this.callParent([value]);
        },

        /**
         * @param {String} value Must be {from: {Date}, to: {Date}}
         * @return {String}
         */
        valueToRaw: function(value)
        {
            var strFrom = Ext.Date.format(value.from, this.format);
            var strTo = Ext.Date.format(value.to, this.format);

            return strFrom + ' - ' + strTo;
        },

        /**
         * Conversion from text to object
         *
         * @param {String}
         * @return {Object}
         */
        rawToValue: function(value)
        {
            return this.dateRangeToObject(value);
        },

        /**
         * Check if dates are equal
         *
         * @return {Boolean}
         */
        isEqualRangeDate: function(newVal, oldVal)
        {
            return Ext.JSON.encode(newVal) == Ext.JSON.encode(oldVal);
        },

        /**
         * Check if value changed
         *
         * @param {Boolean} force optional to force event
         */
        checkChange: function(force) {
            if (!this.suspendCheckChange) {
                var me = this,
                    newVal = me.getValue(),
                    oldVal = me.lastValue;
                if ((!me.isEqualRangeDate(newVal, oldVal) || force) && !me.isDestroyed) {
                    me.lastValue = newVal;
                    me.fireEvent('change', me, newVal, oldVal);
                    me.onChange(newVal, oldVal);
                }
            }
        },

        /**
         * Creates instance of picker
         */
        createPicker: function()
        {
            var _this = this;
            var picker = Ext.create('Ext.container.Container', {
                floating: true,
                border: 0,
                width: 405,
                height: 260,
                hidden: true,
                padding: 5,
                ownerCt: this.ownerCt,
                pickerField: this,
                layout: 'auto',
                items: [
                    {
                        itemId: 'boilerplates-combobox',
                        xtype: 'combobox',
                        margin: '10 0 0 10',
                        store: Ext.create('Ext.data.Store', {
                            fields: ['key', 'value'],
                            data: this.rangeBoilerplates
                        }),
                        editable: false,
                        fieldLabel: 'Wybierz przedział',
                        valueField: 'key',
                        displayField: 'value'
                    },
                    {
                        xtype: 'panel',
                        layout: 'hbox',
                        itemId: 'pickers-panel',
                        border: 0,
                        defaults: {margin: 5},
                        items: [
                            Ext.create('Ext.picker.Date', {
                                itemId: 'picker-from',
                                format: this.format,
                                handler: function(picker, date) {
                                    _this.onDateSelect('from', date);
                                }
                            }),
                            Ext.create('Ext.picker.Date', {
                                itemId: 'picker-to',
                                format: this.format,
                                handler: function(picker, date) {
                                    _this.onDateSelect('to', date)
                                }
                            })
                        ]
                    }
                ]
            });

            this.picker = picker;

            return this.picker;
        },

        /**
         * Apply date values to pickers
         *
         * @param {Object} value {from:Date, to:Date}
         */
        applyToPicker: function(value)
        {
            if (this.picker)
            {
                this.picker.down('#picker-from').setValue(value.from);
                this.picker.down('#picker-to').setValue(value.to);
            }
        },

        /**
         * Event: react on expanding picker
         */
        onExpand: function()
        {
            this.applyToPicker(this.value);
        },

        /**
         * Apply new date
         *
         * @param {String} type
         * @param {Date} date
         */
        onDateSelect: function(type, date)
        {
            this.value[type] = date;
            this.setValue(this.value);
            this.checkChange(true);
        },

        /**
         * Validator for raw date range
         *
         * @return {Boolean}
         */
        isRawDateRangeValid: function(value)
        {
            value = this.dateRangeToObject(value);

            return (value.from && value.to);
        },

        /**
         * Validate raw value
         *
         * @return {Boolean}/{String}
         */
        validator: function(value)
        {
            if (!this.isRawDateRangeValid(value))
            {
                return "Daty są w nieprawidłowym formacie!";
            }

            return true;
        }

    });

})();
<commit_msg>DateRangeField Beta.<commit_after>/**
 * Date Range Field
 *
 * @class Hatimeria.core.field.DateRangeField
 * @extends Ext.form.field.Basic
 */
(function() {

    Ext.define('Hatimeria.core.field.DateRangeField', {
        extend: 'Ext.form.field.Picker',

        /**
         * @cfg {Object} value
         */
        value: {
            from: new Date,
            to: new Date
        },

        /**
         * Type of data which will be returned ("object"/"string"/"d/m/Y")
         *
         * @cfg {String} returnFormat
         */
        returnFormat: 'string',

        /**
         * Default width
         *
         * @cfg {Number} width
         */
        width: 170,

        /**
         * @cfg {String} format corresponding to Ext.util.Format.date()
         */
        format: 'd/m/Y',

        /**
         * @private
         * @property {Array}
         */
        rangeBoilerplates: [
            {key: 'today',   value: 'Dzisiejsze'},
            {key: 'week',    value: 'Z ostatniego tygodnia'},
            {key: 'twoweek', value: 'Z ostatnich dwóch tygodni'},
            {key: 'month',   value: 'Z ostatniego miesiąca'},
            {key: 'year',    value: 'Z ostatniego roku'}
        ],

        pickerAlign: 'bl',

        /**
         * @private
         */
        matchFieldWidth: false,

        constructor: function(cfg)
        {
            var config = {
            };
            Ext.apply(config, cfg || {});
            this.callParent([config]);
        },

        /**
         * Converts string to value Object
         *
         * @param {String} value
         * @private
         */
        dateRangeToObject: function(value)
        {
            var dates = value.split(/\s+\-\s+/);
            var date = {
                from: this.convertToDate(dates[0]),
                to: this.convertToDate(dates[1])
            }

            return date;
        },

        /**
         * String to object {Date}
         *
         * @param {String}
         * @return {Date}
         */
        convertToDate: function(value)
        {
            if (typeof value == 'object')
            {
                if (value instanceof Date)
                {
                    return value;
                }
                else
                {
                    throw new Error('Object must be instance of Date');
                }
            }
            else
            {
                return Ext.Date.parse(value, this.format);
            }
        },

        /**
         * Guess!
         *
         * @param {Object}
         */
        setValue: function(value)
        {
            var defaultValue = {
                from: new Date,
                to: new Date
            };

            if (!Ext.isObject(value))
            {
                value = this.defaultValue;
            }

            value = Ext.apply(defaultValue, value);
            value.from = this.convertToDate(value.from);
            value.to = this.convertToDate(value.to);
            this.lastValue = value;

            return this.callParent([value]);
        },

        /**
         * @param {String} value Must be {from: {Date}, to: {Date}}
         * @return {String}
         */
        valueToRaw: function(value)
        {
            var strFrom = Ext.Date.format(value.from, this.format);
            var strTo = Ext.Date.format(value.to, this.format);

            return strFrom + ' - ' + strTo;
        },

        /**
         * Conversion from text to object
         *
         * @param {String}
         * @return {Object}
         */
        rawToValue: function(value)
        {
            return this.dateRangeToObject(value);
        },

        /**
         * Check if dates are equal
         *
         * @return {Boolean}
         */
        isEqualRangeDate: function(newVal, oldVal)
        {
            return Ext.JSON.encode(newVal) == Ext.JSON.encode(oldVal);
        },

        /**
         * Check if value changed
         *
         * @param {Boolean} force optional to force event
         */
        checkChange: function(force)
        {
            if (!this.suspendCheckChange)
            {
                var me = this,
                    newVal = me.getValue(),
                    oldVal = me.lastValue;

                if (!this.isDateRangeValid(newVal))
                {
                    me.onChange(newVal, oldVal);
                    return false;
                }

                if ((!me.isEqualRangeDate(newVal, oldVal) || force) && !me.isDestroyed)
                {
                    me.lastValue = newVal;
                    var newValFormatted = me.getUnifiedReturnValue(newVal);
                    var oldValFormatted = me.getUnifiedReturnValue(oldVal);
                    me.fireEvent('change', me, newValFormatted, oldValFormatted);
                    me.onChange(newVal, oldVal);
                }
            }
        },

        /**
         * Creates instance of picker
         */
        createPicker: function()
        {
            var _this = this;
            var picker = Ext.create('Ext.container.Container', {
                floating: true,
                border: 0,
                width: 405,
                height: 260,
                hidden: true,
                padding: 5,
                ownerCt: this.ownerCt,
                pickerField: this,
                layout: 'auto',
                items: [
                    {
                        itemId: 'boilerplates-combobox',
                        xtype: 'combobox',
                        margin: '10 0 0 10',
                        store: Ext.create('Ext.data.Store', {
                            fields: ['key', 'value'],
                            data: this.rangeBoilerplates
                        }),
                        editable: false,
                        fieldLabel: 'Wybierz przedział',
                        valueField: 'key',
                        displayField: 'value'
                    },
                    {
                        xtype: 'panel',
                        layout: 'hbox',
                        itemId: 'pickers-panel',
                        border: 0,
                        defaults: {margin: 5},
                        items: [
                            Ext.create('Ext.picker.Date', {
                                itemId: 'picker-from',
                                format: this.format,
                                handler: function(picker, date) {
                                    _this.onDateSelect('from', date);
                                }
                            }),
                            Ext.create('Ext.picker.Date', {
                                itemId: 'picker-to',
                                format: this.format,
                                handler: function(picker, date) {
                                    _this.onDateSelect('to', date)
                                }
                            })
                        ]
                    }
                ]
            });

            this.picker = picker;

            return this.picker;
        },

        /**
         * Apply date values to pickers
         *
         * @param {Object} value {from:Date, to:Date}
         */
        applyToPicker: function(value)
        {
            if (this.picker)
            {
                this.picker.down('#picker-from').setValue(value.from);
                this.picker.down('#picker-to').setValue(value.to);
            }
        },

        /**
         * Event: react on expanding picker
         */
        onExpand: function()
        {
            this.applyToPicker(this.value);
        },

        /**
         * Apply new date
         *
         * @param {String} type
         * @param {Date} date
         */
        onDateSelect: function(type, date)
        {
            this.value[type] = date;
            this.setValue(this.value);
            this.checkChange(true);
        },

        /**
         * Validator for raw date range
         *
         * @return {Boolean}
         */
        isRawDateRangeValid: function(value)
        {
            value = this.dateRangeToObject(value);

            return (value.from && value.to);
        },

        /**
         * Check if date range object is valid
         *
         * @param {Object} value
         * @return {Boolean}
         */
        isDateRangeValid: function(value)
        {
            return value.from && value.to && typeof value.from.getDate == 'function' && typeof value.to.getDate == 'function' ;
        },

        /**
         * Validate raw value
         *
         * @return {Boolean}/{String}
         */
        validator: function(value)
        {
            if (!this.isRawDateRangeValid(value))
            {
                return "Daty są w nieprawidłowym formacie!";
            }

            return true;
        },

        /**
         * Convert declared output format
         *
         * @param {Object} value Must be {from:Date, to:Date}
         * @return {Object}
         */
        getUnifiedReturnValue: function(value)
        {
            if (this.returnFormat == 'object')
            {
                return value;
            }

            var format = (this.returnFormat == 'string') ? this.format : this.returnFormat;

            return {
                from: Ext.Date.format(value.from, format),
                  to: Ext.Date.format(value.to, format)
            };
        },

        /**
         * Submit output
         *
         * @return {Object}
         */
        getSubmitValue: function()
        {
            return this.getUnifiedReturnValue(this.value);
        }

    });

})();
<|endoftext|>