<commit_before>/*
 * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
 */

/**
 * @class crm.Views.Activity.List
 *
 * @extends argos.List
 * @mixins crm.Views._RightDrawerListMixin
 * @mixins crm.Views._CardLayoutListMixin
 *
 * @requires argos.List
 * @requires argos.Utility
 * @requires argos.Convert
 * @requires argos.ErrorManager
 * @requires crm.Action
 * @requires crm.Environment
 * @requires crm.Format
 * @requires crm.Views._CardLayoutListMixin
 * @requires crm.Views._RightDrawerListMixin
 *
 */
define('crm/Views/Activity/List', [
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/connect',
    'dojo/string',
    'dojo/query',
    'dojo/dom-class',
    '../_RightDrawerListMixin',
    'argos/List',
    '../_CardLayoutListMixin',
    '../../Format',
    'argos/Utility',
    'argos/Convert',
    '../../Action',
    '../../Environment',
    'argos/ErrorManager',
    'moment'
], function(
    declare,
    lang,
    connect,
    string,
    query,
    domClass,
    _RightDrawerListMixin,
    List,
    _CardLayoutListMixin,
    format,
    Utility,
    convert,
    action,
    environment,
    ErrorManager,
    moment
) {

    var __class = declare('crm.Views.Activity.List', [List, _RightDrawerListMixin, _CardLayoutListMixin], {
        // Localization
        allDayText: 'All day',
        completeActivityText: 'Complete',
        callText: 'Call',
        calledText: 'Called',
        addAttachmentActionText: 'Add Attachment',
        overdueText: 'overdue',
        alarmText: 'alarm',
        touchedText: 'touched',
        importantText: 'important',
        recurringText: 'recurring',

        //Card View
        itemIcon: 'content/images/icons/man_1.png',

        //Templates
        //Card View
        itemRowContainerTemplate: new Simplate([
            '
',
               '{%! $$.itemRowContentTemplate %}',
            '
'
        ]),
        activityTimeTemplate: new Simplate([
            '{% if ($$.isTimelessToday($)) { %}',
                '{%: $$.allDayText %}',
            '{% } else { %}',
                '{%: crm.Format.relativeDate($.StartDate, argos.Convert.toBoolean($.Timeless)) %}',
            '{% } %}'
        ]),
        itemTemplate: new Simplate([
            '
',
                '{%: $.Description %}',
            '
',
            '
',
                '{%! $$.activityTimeTemplate %}',
            '
',
            '
{%! $$.nameTemplate %}
'
        ]),
        nameTemplate: new Simplate([
            '{% if ($.ContactName) { %}',
            '{%: $.ContactName %} | {%: $.AccountName %}',
            '{% } else if ($.AccountName) { %}',
            '{%: $.AccountName %}',
            '{% } else { %}',
            '{%: $.LeadName %}',
            '{% } %}'
        ]),
        activityIndicatorIconByType: {
            'atToDo': 'fa fa-list-ul',
            'atPhoneCall': 'fa fa-phone',
            'atAppointment': 'fa fa-calendar-o',
            'atLiterature': 'fa fa-book',
            'atPersonal': 'fa fa-check-square-o',
            'atQuestion': 'fa fa-question-circle',
            'atNote': 'fa fa-file-text-o',
            'atEMail': 'fa fa-envelope'
        },
        activityTypeText: {
            'atToDo': 'To-Do',
            'atPhoneCall': 'Phone Call',
            'atAppointment': 'Meeting',
            'atLiterature': 'Lit Request',
            'atPersonal': 'Personal',
            'atQuestion': 'Question',
            'atNote': 'Note',
            'atEMail': 'Email'
        },
        //Localization
        titleText: 'Activities',

        //View Properties
        id: 'activity_list',
        security: null, //'Entities/Activity/View',
        iconClass: 'fa fa-check-square-o fa-lg',
        detailView: 'activity_detail',
        insertView: 'activity_types_list',
        historyEditView: 'history_edit',
        enableActions: true,
        queryOrderBy: 'StartDate desc',
        querySelect: [
            'Description',
            'StartDate',
            'Type',
            'AccountId',
            'AccountName',
            'ContactId',
            'ContactName',
            'PhoneNumber',
            'LeadId',
            'LeadName',
            'TicketId',
            'OpportunityId',
            'Leader',
            'UserId',
            'Timeless',
            'Alarm',
            'Priority',
            'ModifyDate',
            'RecurrenceState',
            'Recurring'
        ],
        queryInclude: [
            '$descriptors'
        ],
        resourceKind: 'activities',
        contractName: 'system',
        pageSize: 105,

        hashTagQueries: {
            'alarm': 'Alarm eq true',
            'recurring': 'Recurring eq true',
            'timeless': 'Timeless eq true',
            'yesterday': function() {
                var now, yesterdayStart, yesterdayEnd, query;

                now = moment();

                yesterdayStart = now.clone().subtract(1, 'days').startOf('day');
                yesterdayEnd = yesterdayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(yesterdayStart.toDate()),
                        convert.toIsoStringFromDate(yesterdayEnd.toDate()),
                        yesterdayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        yesterdayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'today': function() {
                var now, todayStart, todayEnd, query;

                now = moment();

                todayStart = now.clone().startOf('day');
                todayEnd = todayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(todayStart.toDate()),
                        convert.toIsoStringFromDate(todayEnd.toDate()),
                        todayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        todayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'this-week': function() {
                var now, weekStartDate, weekEndDate, query;

                now = moment();

                weekStartDate = now.clone().startOf('week');
                weekEndDate = weekStartDate.clone().endOf('week');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(weekStartDate.toDate()),
                        convert.toIsoStringFromDate(weekEndDate.toDate()),
                        weekStartDate.format('YYYY-MM-DDT00:00:00[Z]'),
                        weekEndDate.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            }
        },
        hashTagQueriesText: {
            'alarm': 'alarm',
            'recurring': 'recurring',
            'timeless': 'timeless',
            'today': 'today',
            'this-week': 'this-week',
            'yesterday': 'yesterday'
        },
        defaultSearchTerm: function() {
            if (App.enableHashTags) {
                return '#' + this.hashTagQueriesText['this-week'];
            }

            return '';
        },
        formatSearchQuery: function(searchQuery) {
            return string.substitute('upper(Description) like "%${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
        },
        formatDateTime: function(dateTime) {
            return 'StartTime';
        },
        getItemActionKey: function(entry) {
            return entry.$key;
        },
        getItemDescriptor: function(entry) {
            return entry.$descriptor;
        },
        createIndicatorLayout: function() {
            return this.itemIndicators || (this.itemIndicators = [{
                id: 'alarm',
                cls: 'fa fa-bell-o fa-lg',
                label: this.alarmText,
                onApply: function(entry, parent) {
                    this.isEnabled = parent.hasAlarm(entry);
                }
                }, {
                    id: 'touched',
                    cls: 'fa fa-hand-o-up fa-lg',
                    label: this.touchedText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.hasBeenTouched(entry);
                    }
                }, {
                    id: 'important',
                    cls: 'fa fa-exclamation fa-lg',
                    label: this.importantText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isImportant(entry);
                    }
                },  {
                    id: 'recurring',
                    cls: 'fa fa-refresh fa-lg',
                    label: this.recurringText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isRecurring(entry, this);
                    }
                }, {
                    id: 'overdue',
                    cls: 'fa fa-exclamation-circle fa-lg',
                    label: this.overdueText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isOverdue(entry);
                    }
                }
            ]);
        },
        hasBeenTouched: function(entry) {
            var modifiedDate, currentDate, weekAgo;
            if (entry['ModifyDate']) {
                modifiedDate = moment(convert.toDateFromString(entry['ModifyDate']));
                currentDate = moment().endOf('day');
                weekAgo = moment().subtract(1, 'weeks');

                return modifiedDate.isAfter(weekAgo) &&
                    modifiedDate.isBefore(currentDate);
            }
            return false;
        },
        isImportant: function(entry) {
            if (entry['Priority']) {
                if (entry['Priority'] === 'High') {
                    return true;
                }
            }
            return false;
        },
        isOverdue: function(entry) {
            var startDate, currentDate, seconds, mins, days;
            if (entry['StartDate']) {
                startDate = convert.toDateFromString(entry['StartDate']);
                currentDate = new Date();
                seconds = Math.round((currentDate - startDate) / 1000);
                mins = seconds / 60;
                if (mins >= 1) {
                    return true;
                }
            }
            return false;
        },
        isTimelessToday: function(entry) {
            if (!entry || !entry.Timeless) {
                return false;
            }

            var start = moment(entry.StartDate);
            return this._isTimelessToday(start);
        },
        _isTimelessToday: function(start) {
            // Start is UTC, convert it to local time so we can compare it against "now"
            start.add({ minutes: start.zone() });
            return start.isAfter(moment().startOf('day')) && start.isBefore(moment().endOf('day'));
        },
        isRecurring: function(entry) {
            if (entry['RecurrenceState']) {
                if (entry['RecurrenceState'] === 'rstOccurrence') {
                    return true;
                }
            }
            return false;
        },
        hasAlarm: function(entry) {
            if (entry['Alarm'] === true) {
                return true;
            }
            return false;
        },
        getItemIconClass: function(entry) {
            var type = entry && entry.Type;
            return this._getItemIconClass(type);
        },
        _getItemIconClass: function(type) {
            var cls = this.activityIndicatorIconByType[type];
            if (cls) {
                cls = cls + ' fa-2x';
            }

            return cls;
        },
        createActionLayout: function() {
           return this.actions || (this.actions = [{
               id: 'complete',
               cls: 'fa fa-check-square fa-2x',
               label: this.completeActivityText,
               enabled: function(action, selection) {
                   var recur, entry = selection && selection.data;
                   if (!entry) {
                       return false;
                   }
                   recur = false;
                   if (entry['RecurrenceState'] === 'rstOccurrence') {
                       recur = true;
                   }

                   return entry['Leader']['$key'] === App.context['user']['$key'] && !recur;
               },
               fn: (function(action, selection) {
                   var entry;

                   entry = selection && selection.data && selection.data;

                   entry['CompletedDate'] = new Date();
                   entry['Result'] = 'Complete';

                   environment.refreshActivityLists();
                   this.completeActivity(entry);

               }).bindDelegate(this)
           }, {
               id: 'call',
               cls: 'fa fa-phone-square fa-2x',
               label: this.callText,
               enabled: function(action, selection) {
                   var entry;
                   entry = selection && selection.data;
                   return entry && entry.PhoneNumber;
               },
               fn: function(action, selection) {
                   var entry, phone;
                   entry = selection && selection.data;
                   phone = entry && entry.PhoneNumber;
                   if (phone) {
                       this.recordCallToHistory(function() {
                           App.initiateCall(phone);
                       }.bindDelegate(this), entry);
                   }
               }.bindDelegate(this)
           }, {
               id: 'addAttachment',
               cls: 'fa fa-paperclip fa-2x',
               label: this.addAttachmentActionText,
               fn: action.addAttachment.bindDelegate(this)
           }]
           );
        },
        recordCallToHistory: function(complete, entry) {
           var tempEntry = {
               '$name': 'History',
               'Type': 'atPhoneCall',
               'ContactName': entry['ContactName'],
               'ContactId': entry['ContactId'],
               'AccountName': entry['AccountName'],
               'AccountId': entry['AccountId'],
               'Description': string.substitute("${0} ${1}", [this.calledText, (entry['ContactName'] || '')]),
               'UserId': App.context && App.context.user['$key'],
               'UserName': App.context && App.context.user['UserName'],
               'Duration': 15,
               'CompletedDate': (new Date())
           };

           this.navigateToHistoryInsert('atPhoneCall', tempEntry, complete);
        },
        navigateToHistoryInsert: function(type, entry, complete) {
           var view = App.getView(this.historyEditView);
           if (view) {
               environment.refreshActivityLists();
               view.show({
                   title: this.activityTypeText[type],
                   template: {},
                   entry: entry,
                   insert: true
               }, {
                   complete: complete
               });
           }
        },
        completeActivity: function(entry) {
           var completeActivity, request, completeActivityEntry;

           completeActivityEntry = {
               "$name": "ActivityComplete",
               "request": {
                   "entity": { '$key': entry['$key'] },
                   "ActivityId": entry['$key'],
                   "userId": entry['Leader']['$key'],
                   "result": entry['Result'],
                   "completeDate": entry['CompletedDate']
               }
           };

           request = new Sage.SData.Client.SDataServiceOperationRequest(this.getService())
               .setResourceKind('activities')
               .setContractName('system')
               .setOperationName('Complete');

           request.execute(completeActivityEntry, {
               success: function() {
                   connect.publish('/app/refresh', [{
                       resourceKind: 'history'
                   }]);

                   this.clear();
                   this.refresh();
               },
               failure: this.onRequestFailure,
               scope: this
           });
        },
        onRequestFailure: function(response, o) {
           ErrorManager.addError(response, o, {}, 'failure');
        }
    });

    lang.setObject('Mobile.SalesLogix.Views.Activity.List', __class);
    return __class;
});

<commit_msg>Changed localization string.<commit_after>/*
 * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
 */

/**
 * @class crm.Views.Activity.List
 *
 * @extends argos.List
 * @mixins crm.Views._RightDrawerListMixin
 * @mixins crm.Views._CardLayoutListMixin
 *
 * @requires argos.List
 * @requires argos.Utility
 * @requires argos.Convert
 * @requires argos.ErrorManager
 * @requires crm.Action
 * @requires crm.Environment
 * @requires crm.Format
 * @requires crm.Views._CardLayoutListMixin
 * @requires crm.Views._RightDrawerListMixin
 *
 */
define('crm/Views/Activity/List', [
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/connect',
    'dojo/string',
    'dojo/query',
    'dojo/dom-class',
    '../_RightDrawerListMixin',
    'argos/List',
    '../_CardLayoutListMixin',
    '../../Format',
    'argos/Utility',
    'argos/Convert',
    '../../Action',
    '../../Environment',
    'argos/ErrorManager',
    'moment'
], function(
    declare,
    lang,
    connect,
    string,
    query,
    domClass,
    _RightDrawerListMixin,
    List,
    _CardLayoutListMixin,
    format,
    Utility,
    convert,
    action,
    environment,
    ErrorManager,
    moment
) {

    var __class = declare('crm.Views.Activity.List', [List, _RightDrawerListMixin, _CardLayoutListMixin], {
        // Localization
        allDayText: 'Timeless',
        completeActivityText: 'Complete',
        callText: 'Call',
        calledText: 'Called',
        addAttachmentActionText: 'Add Attachment',
        overdueText: 'overdue',
        alarmText: 'alarm',
        touchedText: 'touched',
        importantText: 'important',
        recurringText: 'recurring',

        //Card View
        itemIcon: 'content/images/icons/man_1.png',

        //Templates
        //Card View
        itemRowContainerTemplate: new Simplate([
            '
',
               '{%! $$.itemRowContentTemplate %}',
            '
'
        ]),
        activityTimeTemplate: new Simplate([
            '{% if ($$.isTimelessToday($)) { %}',
                '{%: $$.allDayText %}',
            '{% } else { %}',
                '{%: crm.Format.relativeDate($.StartDate, argos.Convert.toBoolean($.Timeless)) %}',
            '{% } %}'
        ]),
        itemTemplate: new Simplate([
            '
',
                '{%: $.Description %}',
            '
',
            '
',
                '{%! $$.activityTimeTemplate %}',
            '
',
            '
{%! $$.nameTemplate %}
'
        ]),
        nameTemplate: new Simplate([
            '{% if ($.ContactName) { %}',
            '{%: $.ContactName %} | {%: $.AccountName %}',
            '{% } else if ($.AccountName) { %}',
            '{%: $.AccountName %}',
            '{% } else { %}',
            '{%: $.LeadName %}',
            '{% } %}'
        ]),
        activityIndicatorIconByType: {
            'atToDo': 'fa fa-list-ul',
            'atPhoneCall': 'fa fa-phone',
            'atAppointment': 'fa fa-calendar-o',
            'atLiterature': 'fa fa-book',
            'atPersonal': 'fa fa-check-square-o',
            'atQuestion': 'fa fa-question-circle',
            'atNote': 'fa fa-file-text-o',
            'atEMail': 'fa fa-envelope'
        },
        activityTypeText: {
            'atToDo': 'To-Do',
            'atPhoneCall': 'Phone Call',
            'atAppointment': 'Meeting',
            'atLiterature': 'Lit Request',
            'atPersonal': 'Personal',
            'atQuestion': 'Question',
            'atNote': 'Note',
            'atEMail': 'Email'
        },
        //Localization
        titleText: 'Activities',

        //View Properties
        id: 'activity_list',
        security: null, //'Entities/Activity/View',
        iconClass: 'fa fa-check-square-o fa-lg',
        detailView: 'activity_detail',
        insertView: 'activity_types_list',
        historyEditView: 'history_edit',
        enableActions: true,
        queryOrderBy: 'StartDate desc',
        querySelect: [
            'Description',
            'StartDate',
            'Type',
            'AccountId',
            'AccountName',
            'ContactId',
            'ContactName',
            'PhoneNumber',
            'LeadId',
            'LeadName',
            'TicketId',
            'OpportunityId',
            'Leader',
            'UserId',
            'Timeless',
            'Alarm',
            'Priority',
            'ModifyDate',
            'RecurrenceState',
            'Recurring'
        ],
        queryInclude: [
            '$descriptors'
        ],
        resourceKind: 'activities',
        contractName: 'system',
        pageSize: 105,

        hashTagQueries: {
            'alarm': 'Alarm eq true',
            'recurring': 'Recurring eq true',
            'timeless': 'Timeless eq true',
            'yesterday': function() {
                var now, yesterdayStart, yesterdayEnd, query;

                now = moment();

                yesterdayStart = now.clone().subtract(1, 'days').startOf('day');
                yesterdayEnd = yesterdayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(yesterdayStart.toDate()),
                        convert.toIsoStringFromDate(yesterdayEnd.toDate()),
                        yesterdayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        yesterdayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'today': function() {
                var now, todayStart, todayEnd, query;

                now = moment();

                todayStart = now.clone().startOf('day');
                todayEnd = todayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(todayStart.toDate()),
                        convert.toIsoStringFromDate(todayEnd.toDate()),
                        todayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        todayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'this-week': function() {
                var now, weekStartDate, weekEndDate, query;

                now = moment();

                weekStartDate = now.clone().startOf('week');
                weekEndDate = weekStartDate.clone().endOf('week');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(weekStartDate.toDate()),
                        convert.toIsoStringFromDate(weekEndDate.toDate()),
                        weekStartDate.format('YYYY-MM-DDT00:00:00[Z]'),
                        weekEndDate.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            }
        },
        hashTagQueriesText: {
            'alarm': 'alarm',
            'recurring': 'recurring',
            'timeless': 'timeless',
            'today': 'today',
            'this-week': 'this-week',
            'yesterday': 'yesterday'
        },
        defaultSearchTerm: function() {
            if (App.enableHashTags) {
                return '#' + this.hashTagQueriesText['this-week'];
            }

            return '';
        },
        formatSearchQuery: function(searchQuery) {
            return string.substitute('upper(Description) like "%${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
        },
        formatDateTime: function(dateTime) {
            return 'StartTime';
        },
        getItemActionKey: function(entry) {
            return entry.$key;
        },
        getItemDescriptor: function(entry) {
            return entry.$descriptor;
        },
        createIndicatorLayout: function() {
            return this.itemIndicators || (this.itemIndicators = [{
                id: 'alarm',
                cls: 'fa fa-bell-o fa-lg',
                label: this.alarmText,
                onApply: function(entry, parent) {
                    this.isEnabled = parent.hasAlarm(entry);
                }
                }, {
                    id: 'touched',
                    cls: 'fa fa-hand-o-up fa-lg',
                    label: this.touchedText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.hasBeenTouched(entry);
                    }
                }, {
                    id: 'important',
                    cls: 'fa fa-exclamation fa-lg',
                    label: this.importantText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isImportant(entry);
                    }
                },  {
                    id: 'recurring',
                    cls: 'fa fa-refresh fa-lg',
                    label: this.recurringText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isRecurring(entry, this);
                    }
                }, {
                    id: 'overdue',
                    cls: 'fa fa-exclamation-circle fa-lg',
                    label: this.overdueText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isOverdue(entry);
                    }
                }
            ]);
        },
        hasBeenTouched: function(entry) {
            var modifiedDate, currentDate, weekAgo;
            if (entry['ModifyDate']) {
                modifiedDate = moment(convert.toDateFromString(entry['ModifyDate']));
                currentDate = moment().endOf('day');
                weekAgo = moment().subtract(1, 'weeks');

                return modifiedDate.isAfter(weekAgo) &&
                    modifiedDate.isBefore(currentDate);
            }
            return false;
        },
        isImportant: function(entry) {
            if (entry['Priority']) {
                if (entry['Priority'] === 'High') {
                    return true;
                }
            }
            return false;
        },
        isOverdue: function(entry) {
            var startDate, currentDate, seconds, mins, days;
            if (entry['StartDate']) {
                startDate = convert.toDateFromString(entry['StartDate']);
                currentDate = new Date();
                seconds = Math.round((currentDate - startDate) / 1000);
                mins = seconds / 60;
                if (mins >= 1) {
                    return true;
                }
            }
            return false;
        },
        isTimelessToday: function(entry) {
            if (!entry || !entry.Timeless) {
                return false;
            }

            var start = moment(entry.StartDate);
            return this._isTimelessToday(start);
        },
        _isTimelessToday: function(start) {
            // Start is UTC, convert it to local time so we can compare it against "now"
            start.add({ minutes: start.zone() });
            return start.isAfter(moment().startOf('day')) && start.isBefore(moment().endOf('day'));
        },
        isRecurring: function(entry) {
            if (entry['RecurrenceState']) {
                if (entry['RecurrenceState'] === 'rstOccurrence') {
                    return true;
                }
            }
            return false;
        },
        hasAlarm: function(entry) {
            if (entry['Alarm'] === true) {
                return true;
            }
            return false;
        },
        getItemIconClass: function(entry) {
            var type = entry && entry.Type;
            return this._getItemIconClass(type);
        },
        _getItemIconClass: function(type) {
            var cls = this.activityIndicatorIconByType[type];
            if (cls) {
                cls = cls + ' fa-2x';
            }

            return cls;
        },
        createActionLayout: function() {
           return this.actions || (this.actions = [{
               id: 'complete',
               cls: 'fa fa-check-square fa-2x',
               label: this.completeActivityText,
               enabled: function(action, selection) {
                   var recur, entry = selection && selection.data;
                   if (!entry) {
                       return false;
                   }
                   recur = false;
                   if (entry['RecurrenceState'] === 'rstOccurrence') {
                       recur = true;
                   }

                   return entry['Leader']['$key'] === App.context['user']['$key'] && !recur;
               },
               fn: (function(action, selection) {
                   var entry;

                   entry = selection && selection.data && selection.data;

                   entry['CompletedDate'] = new Date();
                   entry['Result'] = 'Complete';

                   environment.refreshActivityLists();
                   this.completeActivity(entry);

               }).bindDelegate(this)
           }, {
               id: 'call',
               cls: 'fa fa-phone-square fa-2x',
               label: this.callText,
               enabled: function(action, selection) {
                   var entry;
                   entry = selection && selection.data;
                   return entry && entry.PhoneNumber;
               },
               fn: function(action, selection) {
                   var entry, phone;
                   entry = selection && selection.data;
                   phone = entry && entry.PhoneNumber;
                   if (phone) {
                       this.recordCallToHistory(function() {
                           App.initiateCall(phone);
                       }.bindDelegate(this), entry);
                   }
               }.bindDelegate(this)
           }, {
               id: 'addAttachment',
               cls: 'fa fa-paperclip fa-2x',
               label: this.addAttachmentActionText,
               fn: action.addAttachment.bindDelegate(this)
           }]
           );
        },
        recordCallToHistory: function(complete, entry) {
           var tempEntry = {
               '$name': 'History',
               'Type': 'atPhoneCall',
               'ContactName': entry['ContactName'],
               'ContactId': entry['ContactId'],
               'AccountName': entry['AccountName'],
               'AccountId': entry['AccountId'],
               'Description': string.substitute("${0} ${1}", [this.calledText, (entry['ContactName'] || '')]),
               'UserId': App.context && App.context.user['$key'],
               'UserName': App.context && App.context.user['UserName'],
               'Duration': 15,
               'CompletedDate': (new Date())
           };

           this.navigateToHistoryInsert('atPhoneCall', tempEntry, complete);
        },
        navigateToHistoryInsert: function(type, entry, complete) {
           var view = App.getView(this.historyEditView);
           if (view) {
               environment.refreshActivityLists();
               view.show({
                   title: this.activityTypeText[type],
                   template: {},
                   entry: entry,
                   insert: true
               }, {
                   complete: complete
               });
           }
        },
        completeActivity: function(entry) {
           var completeActivity, request, completeActivityEntry;

           completeActivityEntry = {
               "$name": "ActivityComplete",
               "request": {
                   "entity": { '$key': entry['$key'] },
                   "ActivityId": entry['$key'],
                   "userId": entry['Leader']['$key'],
                   "result": entry['Result'],
                   "completeDate": entry['CompletedDate']
               }
           };

           request = new Sage.SData.Client.SDataServiceOperationRequest(this.getService())
               .setResourceKind('activities')
               .setContractName('system')
               .setOperationName('Complete');

           request.execute(completeActivityEntry, {
               success: function() {
                   connect.publish('/app/refresh', [{
                       resourceKind: 'history'
                   }]);

                   this.clear();
                   this.refresh();
               },
               failure: this.onRequestFailure,
               scope: this
           });
        },
        onRequestFailure: function(response, o) {
           ErrorManager.addError(response, o, {}, 'failure');
        }
    });

    lang.setObject('Mobile.SalesLogix.Views.Activity.List', __class);
    return __class;
});

<|endoftext|>


<commit_before>const ArcGISPlugin = require("arcgis-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: {
    index: "./src/index.tsx"
  },
  output: {
    filename: "[name].bundle.js",
    publicPath: ""
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        options: {
          transpileOnly: true
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: false }
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(["dist"]),
    new ArcGISPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html",
      chunksSortMode: "none"
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ],
  resolve: {
    modules: [path.resolve(__dirname, "/src"), "node_modules/"],
    extensions: [".ts", ".tsx", ".js", ".scss"]
  },
  externals: [
    (context, request, callback) => {
      if (/pe-wasm$/.test(request)) {
        return callback(null, "amd " + request);
      }
      callback();
    }
  ],
  node: {
    process: false,
    global: false
  }
};
<commit_msg>fix typo<commit_after>const ArcGISPlugin = require("@arcgis/webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: {
    index: "./src/index.tsx"
  },
  output: {
    filename: "[name].bundle.js",
    publicPath: ""
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        options: {
          transpileOnly: true
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: false }
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(["dist"]),
    new ArcGISPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html",
      chunksSortMode: "none"
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ],
  resolve: {
    modules: [path.resolve(__dirname, "/src"), "node_modules/"],
    extensions: [".ts", ".tsx", ".js", ".scss"]
  },
  externals: [
    (context, request, callback) => {
      if (/pe-wasm$/.test(request)) {
        return callback(null, "amd " + request);
      }
      callback();
    }
  ],
  node: {
    process: false,
    global: false
  }
};
<|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');
var crudBox = require('./crudBox.js');

var CrudList = React.createClass({

  handleUpdate: function(id) {

   var problem = this.refs.problem.value.trim();
   var answer = ReactDOM.findDOMNode(this.refs.answer).value.trim();
   var type = ReactDOM.findDOMNode(this.refs.type).value.trim();
   var name = ReactDOM.findDOMNode(this.refs.name).value.trim();

   if (!problem) {
     return;
   }
   var data = ({problem: problem, answer: answer, name: name, type: type});
   console.log(data);
   $.ajax({
     url: '/api/exercises/' + id,
     dataType: 'json',
     data: data,
     type: 'PUT',
     success: function(poop) {
       console.log('Updating Exercise!', data, poop);
       document.location = '/post_exercise';
     },
     error: function(xhr, status, err) {
       console.log('Did not update!');
       console.error(this.props.url, status, err.toString());
     }.bind(this)
   });
 },

 getInitialState: function(){
   return {
     fltr: null
   };
 },

 toggle: function (id) {
   console.log(id);
   this.setState({
     fltr: id
   })
 },
 reToggle: function (id) {
   this.setState({
     fltr: null
   })
 },

 render: function() {

   var that = this;

   var renderUpdateForm = this.props.data.map(function(exercises) {

     if(exercises.name == that.state.fltr) {
       return (

Edit {exercises.name}

           <form>

                 Exercise Name
                 <textarea rows='1' type='text' ref='name' className='form-control'  defaultValue={exercises.name}/>

                 Exercise Type
                 <textarea rows='1' type='text' ref='type' className='form-control'  defaultValue={exercises.type}/>

                 Exercise Problem
                 <textarea rows='10' type='text' className='form-control' ref='problem' defaultValue={exercises.problem}/>

                 Exercise Answer
                 <textarea rows='10' type='text' ref='answer' className='form-control'  defaultValue={exercises.answer}/>

                 <button onClick={that.handleUpdate.bind(that, exercises._id)} type='submit' className='btn btn-default'> Submit {exercises.name}</button>

           </form>

       )
     }
   }.bind(that));

     var updateExerciseData = this.props.data.map(function(exercises){
       return(

               {exercises.name}
               <button onClick={that.toggle.bind(this, exercises.name)}></button>

       )
     });

     return(

            {renderUpdateForm}

{updateExerciseData}

      )
    }
  });

module.exports = CrudList;
<commit_msg>Delete works yo<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
var crudBox = require('./crudBox.js');

var CrudList = React.createClass({

  handleUpdate: function(id) {

   var problem = this.refs.problem.value.trim();
   var answer = this.refs.answer.value.trim();
   var type = this.refs.type.value.trim();
   var name = this.refs.name.value.trim();

   if (!problem) {
     return;
   }
   var data = ({problem: problem, answer: answer, name: name, type: type});
   console.log(data);
   $.ajax({
     url: '/api/exercises/' + id,
     dataType: 'json',
     data: data,
     type: 'PUT',
     success: function(poop) {
       console.log('Updating Exercise!', data, poop);
       document.location = '/post_exercise';
     },
     error: function(xhr, status, err) {
       console.log('Did not update!');
       console.error(this.props.url, status, err.toString());
     }.bind(this)
   });
 },

 deleteExercise: function(id) {

  var areYouSure = confirm("Are you sure that you want to delete this exercise?");
  if (areYouSure == true){
    $.ajax({
       url: '/api/exercises/' + id,
       dataType: 'json',
       type: 'DELETE',
       success: function() {
         console.log('DELETING Exercise!');
         document.location = '/post_exercise';
       }.bind(this),
       error: function(xhr, status, err) {
         console.log('Did not update!');
         console.error(this.props.url, status, err.toString());
       }.bind(this)
    });
  }
 },

 getInitialState: function(){
   return {
     fltr: null
   };
 },

 toggle: function (id) {
   console.log(id);
   this.setState({
     fltr: id
   })
 },
 reToggle: function (id) {
   this.setState({
     fltr: null
   })
 },

 render: function() {

   var that = this;

   var renderUpdateForm = this.props.data.map(function(exercises) {

     if(exercises.name == that.state.fltr) {
       return (

Edit {exercises.name}

           <form>

                 Exercise Name
                 <textarea rows='1' type='text' ref='name' className='form-control'  defaultValue={exercises.name}/>

                 Exercise Type
                 <textarea rows='1' type='text' ref='type' className='form-control'  defaultValue={exercises.type}/>

                 Exercise Problem
                 <textarea rows='10' type='text' className='form-control' ref='problem' defaultValue={exercises.problem}/>

                 Exercise Answer
                 <textarea rows='10' type='text' ref='answer' className='form-control'  defaultValue={exercises.answer}/>

                 <button onClick={that.handleUpdate.bind(that, exercises._id)} type='submit' className='btn btn-default'> Submit {exercises.name}</button>

           </form>

       )
     }
   }.bind(that));

     var updateExerciseData = this.props.data.map(function(exercises){
       return(

               {exercises.name}
               <button onClick={that.toggle.bind(this, exercises.name)}></button>
               <button onClick={that.deleteExercise.bind(this, exercises._id)}></button>

       )
     });

     return(

            {renderUpdateForm}

{updateExerciseData}

      )
    }
  });

module.exports = CrudList;
<|endoftext|>


<commit_before>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 *
 * Google CDN, Latest jQuery
 * To use the default WordPress version of jQuery, go to lib/config.php and
 * remove or comment out: add_theme_support('jquery-cdn');
 * ======================================================================== */

(function($) {

// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Roots = {
  // All pages
  common: {
    init: function() {
      // JavaScript to be fired on all pages

      //Page load
      jQuery(window).load(function () {

          $('#msg-loading').delay(300).fadeOut('slow');
          $('#preloader').delay(300).fadeOut('slow');
          $('body').delay(300).css("overflow","visible");

      }); //End page load

      //Document Ready
      $(document).ready(function() {

        //buttons
            //Link Open
            $('a.leave, .navbar a, .content-info a').click( function() {
              $("#preloader").fadeIn(300);
              $('body').delay(300).css("overflow","hidden");
              window.location = $(this).attr("href");
            });
            //Search Open
            function searchOpen() {
              $("#preloader").fadeIn(300);
              $("#searcher").css('opacity', 1);
              $("#loader").css('opacity', 0);
              $('body').delay(300).css("overflow","hidden");
              return false;
            }
            $('span.search-open').click(searchOpen);
            //Search Close
            function searchClose() {
              $("#preloader").fadeOut(300);
              $("#searcher").css("opacity", 0);
              $('body').delay(300).css("overflow","visible");
              $("#loader").delay(600).fadeIn(0);
              return false;
            }
            $('span.search-close').click(searchClose);
        //Lazy Load
        $("img.lazy").unveil(200, function() {
          $(this).load(function() {
            this.style.opacity = 1;
          });
        });
        // jQuery to collapse the navbar on scroll
        $(window).scroll(function() {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //Same height
        $('.fix-height').matchHeight();

        //Sharing button
        var completed = 0;
        var windowLocation = window.location.href.replace(window.location.hash, '');

            //facebook
            function facebookShare() {
              window.open('https://www.facebook.com/sharer/sharer.php?u=' + windowLocation, "facebookWindow", "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0");
              return false;
            }
            $('.facebook-share').click(facebookShare);
            //Google Plus
            function googlePlusShare() {
              window.open('https://plus.google.com/share?url=' + windowLocation, "googlePlusWindow", "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0");
              return false;
            }
            $('.google-plus-share').click(googlePlusShare);
            //Twitter
            function twitterShare() {
            var $pageTitle = encodeURIComponent($("h1").text());
            window.open('http://twitter.com/intent/tweet?text=' + $pageTitle + ' ' + windowLocation, "twitterWindow", "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0");
              return false;
            }
            $('.twitter-share').click(twitterShare);

        //affix
        $('.ff-affix').affix({
          offset: {
            top: 140,
            bottom: function() {
              return  (this.bottom = $('#comments').outerHeight(true) );
            }
          }
        });

        //Fancybox
        $("a[rel^='prettyPhoto']").prettyPhoto({
          animation_speed: 'slow', /* fast/slow/normal */
          slideshow: 5000, /* false OR interval time in ms */
          autoplay_slideshow: false, /* true/false */
          opacity: 0.80, /* Value between 0 and 1 */
          show_title: false, /* true/false */
          allow_resize: true, /* Resize the photos bigger than viewport. true/false */
          default_width: 500,
          default_height: 344,
          counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
          theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
          horizontal_padding: 20, /* The padding on each side of the picture */
          wmode: 'opaque', /* Set the flash wmode attribute */
          modal: false, /* If set to true, only the close button will close the window */
          deeplinking: true, /* Allow prettyPhoto to update the url to enable deeplinking. */
          overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
          keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
          changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
          callback: function(){}, /* Called when prettyPhoto is closed */
          ie6_fallback: true,
          social_tools: false /* html or false to disable */
      });

	  }); //End document ready

    }
  },
  // Home page
  home: {
    init: function() {
      // JavaScript to be fired on the home page
      $(document).ready(function() {

        //random color
        $(".b-wrapper").each(function() {
          var colors = Please.make_color({
            colors_returned: 4,
            hue: 12, //set your hue manually
          });
          var rand = Math.floor(Math.random()*colors.length);
          $(this).css("background-color", colors[rand]);
        });
        //slide carousel
        $('.slide_carousel').each(function() {
          $(this).slick({
            centerMode: true,
            centerPadding: '20px',
            slidesToShow: 3,
            lazyLoad: 'ondemand',
            responsive: [
              {
                breakpoint: 768,
                settings: {
                  arrows: false,
                  centerMode: true,
                  centerPadding: '',
                  slidesToShow: 2
                }
              },
              {
                breakpoint: 480,
                settings: {
                  arrows: false,
                  centerMode: true,
                  centerPadding: '',
                  slidesToShow: 1
                }
              }
            ],
          });
        });
        //slide intro
        $('.slide_intro').each(function() {
          $(this).slick({
            dots: true,
            lazyLoad: 'ondemand',
          });
        });

      }); // End document ready
    }
  },
  // About us page, note the change from about-us to about_us.
  about_us: {
    init: function() {
      // JavaScript to be fired on the about us page
    }
  }
};

// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
  fire: function(func, funcname, args) {
    var namespace = Roots;
    funcname = (funcname === undefined) ? 'init' : funcname;
    if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') {
      namespace[func][funcname](args);
    }
  },
  loadEvents: function() {
    UTIL.fire('common');

    $.each(document.body.className.replace(/-/g, '_').split(/\s+/),function(i,classnm) {
      UTIL.fire(classnm);
    });
  }
};

$(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<commit_msg>Removed delay from leave button<commit_after>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 *
 * Google CDN, Latest jQuery
 * To use the default WordPress version of jQuery, go to lib/config.php and
 * remove or comment out: add_theme_support('jquery-cdn');
 * ======================================================================== */

(function($) {

// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Roots = {
  // All pages
  common: {
    init: function() {
      // JavaScript to be fired on all pages

      //Page load
      jQuery(window).load(function () {

          $('#msg-loading').delay(300).fadeOut('slow');
          $('#preloader').delay(300).fadeOut('slow');
          $('body').delay(300).css("overflow","visible");

      }); //End page load

      //Document Ready
      $(document).ready(function() {

        //buttons
            //Link Open
            $('a.leave, .navbar a, .content-info a').click( function() {
              $("#preloader").fadeIn(300);
              $('body').css("overflow","hidden");
              window.location = $(this).attr("href");
            });
            //Search Open
            function searchOpen() {
              $("#preloader").fadeIn(300);
              $("#searcher").css('opacity', 1);
              $("#loader").css('opacity', 0);
              $('body').delay(300).css("overflow","hidden");
              return false;
            }
            $('span.search-open').click(searchOpen);
            //Search Close
            function searchClose() {
              $("#preloader").fadeOut(300);
              $("#searcher").css("opacity", 0);
              $('body').delay(300).css("overflow","visible");
              $("#loader").delay(600).fadeIn(0);
              return false;
            }
            $('span.search-close').click(searchClose);
        //Lazy Load
        $("img.lazy").unveil(200, function() {
          $(this).load(function() {
            this.style.opacity = 1;
          });
        });
        // jQuery to collapse the navbar on scroll
        $(window).scroll(function() {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //Same height
        $('.fix-height').matchHeight();

        //Sharing button
        var completed = 0;
        var windowLocation = window.location.href.replace(window.location.hash, '');

            //facebook
            function facebookShare() {
              window.open('https://www.facebook.com/sharer/sharer.php?u=' + windowLocation, "facebookWindow", "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0");
              return false;
            }
            $('.facebook-share').click(facebookShare);
            //Google Plus
            function googlePlusShare() {
              window.open('https://plus.google.com/share?url=' + windowLocation, "googlePlusWindow", "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0");
              return false;
            }
            $('.google-plus-share').click(googlePlusShare);
            //Twitter
            function twitterShare() {
            var $pageTitle = encodeURIComponent($("h1").text());
            window.open('http://twitter.com/intent/tweet?text=' + $pageTitle + ' ' + windowLocation, "twitterWindow", "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0");
              return false;
            }
            $('.twitter-share').click(twitterShare);

        //affix
        $('.ff-affix').affix({
          offset: {
            top: 140,
            bottom: function() {
              return  (this.bottom = $('#comments').outerHeight(true) );
            }
          }
        });

        //Fancybox
        $("a[rel^='prettyPhoto']").prettyPhoto({
          animation_speed: 'slow', /* fast/slow/normal */
          slideshow: 5000, /* false OR interval time in ms */
          autoplay_slideshow: false, /* true/false */
          opacity: 0.80, /* Value between 0 and 1 */
          show_title: false, /* true/false */
          allow_resize: true, /* Resize the photos bigger than viewport. true/false */
          default_width: 500,
          default_height: 344,
          counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
          theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
          horizontal_padding: 20, /* The padding on each side of the picture */
          wmode: 'opaque', /* Set the flash wmode attribute */
          modal: false, /* If set to true, only the close button will close the window */
          deeplinking: true, /* Allow prettyPhoto to update the url to enable deeplinking. */
          overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
          keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
          changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
          callback: function(){}, /* Called when prettyPhoto is closed */
          ie6_fallback: true,
          social_tools: false /* html or false to disable */
      });

	  }); //End document ready

    }
  },
  // Home page
  home: {
    init: function() {
      // JavaScript to be fired on the home page
      $(document).ready(function() {

        //random color
        $(".b-wrapper").each(function() {
          var colors = Please.make_color({
            colors_returned: 4,
            hue: 12, //set your hue manually
          });
          var rand = Math.floor(Math.random()*colors.length);
          $(this).css("background-color", colors[rand]);
        });
        //slide carousel
        $('.slide_carousel').each(function() {
          $(this).slick({
            centerMode: true,
            centerPadding: '20px',
            slidesToShow: 3,
            lazyLoad: 'ondemand',
            responsive: [
              {
                breakpoint: 768,
                settings: {
                  arrows: false,
                  centerMode: true,
                  centerPadding: '',
                  slidesToShow: 2
                }
              },
              {
                breakpoint: 480,
                settings: {
                  arrows: false,
                  centerMode: true,
                  centerPadding: '',
                  slidesToShow: 1
                }
              }
            ],
          });
        });
        //slide intro
        $('.slide_intro').each(function() {
          $(this).slick({
            dots: true,
            lazyLoad: 'ondemand',
          });
        });

      }); // End document ready
    }
  },
  // About us page, note the change from about-us to about_us.
  about_us: {
    init: function() {
      // JavaScript to be fired on the about us page
    }
  }
};

// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
  fire: function(func, funcname, args) {
    var namespace = Roots;
    funcname = (funcname === undefined) ? 'init' : funcname;
    if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') {
      namespace[func][funcname](args);
    }
  },
  loadEvents: function() {
    UTIL.fire('common');

    $.each(document.body.className.replace(/-/g, '_').split(/\s+/),function(i,classnm) {
      UTIL.fire(classnm);
    });
  }
};

$(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<|endoftext|>


<commit_before>// --------------------------------------------------
// Decoy app init and events
// --------------------------------------------------
define(function (require) {

	// Dependencies
	var $ = require('jquery')
		, _ = require('underscore')
		, Backbone = require('backbone')
		, FastClick = require('fastclick')
		, Affixable = require('./modules/affixable')
		, LocalizeCompare = require('./localize/compare')
		, manifest = require('./modules/manifest')
		, bootstrap = require('bootstrap')
		, console = require('bkwld/console')
		, csrf = require('bkwld/csrf')
		, jqv = require('bkwld/jquery-views')
	;

	// Modules that add mojo globally
	require('./modules/datepicker'); // Init datepickers created with Former::date()
	require('./modules/timepicker'); // Init datepickers created with Former::time()
	require('./modules/datetimepicker'); // Init datepickers created with Former::datetime()
	require('./modules/auto-toggleable'); // Scan make for attributes that enable toggling
	require('./modules/chicken-switch').register(); // Enable chicken switches on delete
	var wysiwyg = require('./wysiwyg/factory');

	// Private static vars
	var app = _.extend({}, Backbone.Events),
		$body = $('body'),
		$doc = $(document);

	// --------------------------------------------------
	// Pre-ready init

	// Disable # links because they're not links silly
	$doc.on('click', '[href="#"]', false);

	// Enable fast click
	FastClick.attach(document.body);

	// --------------------------------------------------
	// Configure Backbone

	// Massage attribtues of the sync process
	var oldSync = Backbone.sync;
	Backbone.sync = function(method, model, options){

		// If there is a 'whitelist' attribute on the model and it's
		// an array, delete all attributes except for the ones from the
		// whitelist
		if (model.whitelist && _.isArray(model.whitelist)) {

			// Add id by default, needed in Backbone 1.1.1
			if (!_.contains(model.whitelist, 'id')) model.whitelist.push('id');

			// Don't operate on the real model.  But, for whatever reason, the
			// collection didn't get brought along on the clone, so do that manually
			var oldModel = model;
			model = oldModel.clone();
			model.collection = oldModel.collection;

			// Remove attribtues
			_.each(model.attributes, function(value, key, list) {
				if (!_.contains(oldModel.whitelist, key)) delete model.attributes[key];
			});
		}

		// Finish up with the traditional sync
		return oldSync(method, model, options);
	};

	// Find all valid data-js-views and create them.  A data-js-view tag may specify
	// multiple backbone views by seperating them with a space
	app.initalizeViews = function(manifest) {
		_.each($body.find('[data-js-view]'), function (elem) {
			var views = $(elem).attr('data-js-view').split(' ');
			_.each(views, function(identifier) {
				var view = manifest[identifier];
				if (view) new view({ el: elem, app: app });
			});
		});
	};

	// Newer style view declaration
	$('body.elements.field #main').views(require('./elements/field'));
	$('body.elements.index .tab-sidebar').views(require('./views/tab-sidebar'));
	$('body > .sidebar').views(Sidebar); // The nav sidebar
	if ($('.form-group.compare').length) $('.related-left-col .form-group').views(LocalizeCompare);
	$('.admin-permissions').views(require('./views/admin-permissions'));

	// Launch change modal
	var changes_modal = require('./modules/changes-modal');
	$('.changes-modal-link').on('click', changes_modal.open);

	// --------------------------------------------------
	// DOM ready
	app.on('ready', function () {

		// Initalize views
		app.initalizeViews(manifest);

		// Add "Required" icons to file input fields where we're manually applying
		// a required class with Former, which puts it on the input rather than the control group.  We
		// want these fields to look required but not actually be enforced by the browser.
		var required_html = ' ';
		$('input.required, textarea.required').closest('.form-group').find('.control-label').append(required_html);

		// And "Help" icons
		// Disabled cause I'm not sure we really want this
		// $('.help-block').prepend(' ');

		// Enable bootstrap tooltips
		$body.find('.js-tooltip').tooltip({
			animation: false,
			html: true,
			container: '#main' // Add them out here to prevent some z-index issues
		});

		// Turn WYSIWYGs on.
		wysiwyg.init('textarea.wysiwyg');

		// Enable affix globally
		$('.affixable').views(Affixable);

	});

	// Return public module
	return app;
});
<commit_msg>Fixing sidebar require<commit_after>// --------------------------------------------------
// Decoy app init and events
// --------------------------------------------------
define(function (require) {

	// Dependencies
	var $ = require('jquery')
		, _ = require('lodash')
		, Backbone = require('backbone')
		, FastClick = require('fastclick')
		, Affixable = require('./modules/affixable')
		, Sidebar = require('./modules/sidebar')
		, LocalizeCompare = require('./localize/compare')
		, manifest = require('./modules/manifest')
		, bootstrap = require('bootstrap')
		, console = require('bkwld/console')
		, csrf = require('bkwld/csrf')
		, jqv = require('bkwld/jquery-views')
	;

	// Modules that add mojo globally
	require('./modules/datepicker'); // Init datepickers created with Former::date()
	require('./modules/timepicker'); // Init datepickers created with Former::time()
	require('./modules/datetimepicker'); // Init datepickers created with Former::datetime()
	require('./modules/auto-toggleable'); // Scan make for attributes that enable toggling
	require('./modules/chicken-switch').register(); // Enable chicken switches on delete
	var wysiwyg = require('./wysiwyg/factory');

	// Private static vars
	var app = _.extend({}, Backbone.Events),
		$body = $('body'),
		$doc = $(document);

	// --------------------------------------------------
	// Pre-ready init

	// Disable # links because they're not links silly
	$doc.on('click', '[href="#"]', false);

	// Enable fast click
	FastClick.attach(document.body);

	// --------------------------------------------------
	// Configure Backbone

	// Massage attribtues of the sync process
	var oldSync = Backbone.sync;
	Backbone.sync = function(method, model, options){

		// If there is a 'whitelist' attribute on the model and it's
		// an array, delete all attributes except for the ones from the
		// whitelist
		if (model.whitelist && _.isArray(model.whitelist)) {

			// Add id by default, needed in Backbone 1.1.1
			if (!_.contains(model.whitelist, 'id')) model.whitelist.push('id');

			// Don't operate on the real model.  But, for whatever reason, the
			// collection didn't get brought along on the clone, so do that manually
			var oldModel = model;
			model = oldModel.clone();
			model.collection = oldModel.collection;

			// Remove attribtues
			_.each(model.attributes, function(value, key, list) {
				if (!_.contains(oldModel.whitelist, key)) delete model.attributes[key];
			});
		}

		// Finish up with the traditional sync
		return oldSync(method, model, options);
	};

	// Find all valid data-js-views and create them.  A data-js-view tag may specify
	// multiple backbone views by seperating them with a space
	app.initalizeViews = function(manifest) {
		_.each($body.find('[data-js-view]'), function (elem) {
			var views = $(elem).attr('data-js-view').split(' ');
			_.each(views, function(identifier) {
				var view = manifest[identifier];
				if (view) new view({ el: elem, app: app });
			});
		});
	};

	// Newer style view declaration
	$('body.elements.field #main').views(require('./elements/field'));
	$('body.elements.index .tab-sidebar').views(require('./views/tab-sidebar'));
	$('body > .sidebar').views(Sidebar); // The nav sidebar
	if ($('.form-group.compare').length) $('.related-left-col .form-group').views(LocalizeCompare);
	$('.admin-permissions').views(require('./views/admin-permissions'));

	// Launch change modal
	var changes_modal = require('./modules/changes-modal');
	$('.changes-modal-link').on('click', changes_modal.open);

	// --------------------------------------------------
	// DOM ready
	app.on('ready', function () {

		// Initalize views
		app.initalizeViews(manifest);

		// Add "Required" icons to file input fields where we're manually applying
		// a required class with Former, which puts it on the input rather than the control group.  We
		// want these fields to look required but not actually be enforced by the browser.
		var required_html = ' ';
		$('input.required, textarea.required').closest('.form-group').find('.control-label').append(required_html);

		// And "Help" icons
		// Disabled cause I'm not sure we really want this
		// $('.help-block').prepend(' ');

		// Enable bootstrap tooltips
		$body.find('.js-tooltip').tooltip({
			animation: false,
			html: true,
			container: '#main' // Add them out here to prevent some z-index issues
		});

		// Turn WYSIWYGs on.
		wysiwyg.init('textarea.wysiwyg');

		// Enable affix globally
		$('.affixable').views(Affixable);

	});

	// Return public module
	return app;
});
<|endoftext|>


<commit_before>const gulp = require('gulp');
const maps = require('gulp-sourcemaps');
const webpack = require('webpack-stream');
const eslint = require('gulp-eslint');

var lintFiles = ['**/*.js', '!node_modules/**', '!build/**', '!**/*spec.js',
'!**/*test.js', '!test/**bundle.**'];
var statFiles = ['app/**/*.html'];

gulp.task('static:dev', () => {
  gulp.src(statFiles)
    .pipe(gulp.dest('./build'));
});

gulp.task('sass:dev', () => {
  gulp.src('app/scss/*.scss')
    .pipe(maps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(maps.write('./'))
    .pipe(gulp.dest('./build'));
});

gulp.task('lint:dev', () => {
  return gulp.src(lintFiles)
    .pipe(eslint)
    .pipe(eslint.format());
});

gulp.task('lint', ['lint:dev']);
gulp.task('build', ['sass:dev', 'static:dev']);
<commit_msg>edit gulpfile<commit_after>const gulp = require('gulp');
const sass = require('gulp-sass');
const maps = require('gulp-sourcemaps');
const protractor = require('gulp-protractor').protractor;
const cp = require('child_process');
const webpack = require('webpack-stream');
const eslint = require('gulp-eslint');
const mongoose = require('mongoose');
const mongoUri = 'mongodb://localhost/bands_test';

var lintFiles = ['**/*.js', '!node_modules/**', '!build/**', '!**/*spec.js',
'!**/*test.js', '!test/**bundle.**', '!*.conf.js'];
var statFiles = ['app/**/*.html'];
var children = [];

function killcp() {
  children.forEach((child) => {
    child.kill('SIGTERM');
  });
}

// gulp.task('sass:dev', () => {
//   gulp.src('app/scss/*.scss')
//     .pipe(maps.init())
//     .pipe(sass().on('error', sass.logError))
//     .pipe(maps.write('./'))
//     .pipe(gulp.dest('./build'));
// });

gulp.task('webpack:dev', () => {
  gulp.src('app/js/entry.js')
    .pipe(webpack( {
      devtool: 'source-map',
      output: {
        filename: 'bundle.js'
      }
    }))
    .pipe(gulp.dest('./build'));
});

// gulp.task('webpack:test', () => {
//   return gulp.src('test/unit/entry.js')
//     .pipe(webpack({
//       devtool: 'source-map',
//       output: {
//         filename: 'bundle.js'
//       },
//       module: {
//         loaders: [
//           {
//             test: /\.html$/,
//             loader: 'html'
//           }
//         ]
//       }
//     }))
//     .pipe(gulp.dest('test/'));
// });
//
// gulp.task('webpack:protractor', () => {
//   gulp.src('test/integration/**.js')
//     .pipe(webpack( {
//       devtool: 'source-map',
//       output: {
//         filename: 'pro_bundle.js'
//       }
//     }))
//     .pipe(gulp.dest('./test'));
// });

gulp.task('static:dev', () => {
  gulp.src(statFiles)
    .pipe(gulp.dest('./build'));
});

// gulp.task('mongoDB:test', (done) => {
//   children.push(cp.spawn('mongod'));
//   setTimeout(done, 1000);
// });
//
// gulp.task('dropDb:test', ['mongoDB:test'], (done) => {
//   mongoose.connect(mongoUri, () => {
//     mongoose.connection.db.dropDatabase(() => {
//       mongoose.disconnect(done);
//     });
//   });
// });
//
// gulp.task('startservers:test', (done) => {
//   children.push(cp.fork('server.js'));
//   children.push(cp.fork('../server/server.js', [], { env: { MONGODB_URI: mongoUri } } ));
//   children.push(cp.spawn('webdriver-manager', ['start']));
//   setTimeout(done, 1000);
// });
//
// gulp.task('protractor:test', ['build', 'startservers:test', 'dropDb:test'], () => {
//   gulp.src('test/integration/**/*spec.js')
//     .pipe(protractor({
//       configFile: 'test/integration/config.js'
//     }))
//     .on('end', () => {
//       killcp();
//     })
//     .on('error', () => {
//       killcp();
//     });
// });

gulp.task('lint:dev', () => {
  return gulp.src(lintFiles)
    .pipe(eslint())
    .pipe(eslint.format());
});

// gulp.task('sass', ['sass:dev']);
// gulp.task('sass:watch', () => {
//   gulp.watch('./*scss', ['sass:dev']);
// });
// gulp.task('test', ['protractor:test', 'webpack:protractor']);
gulp.task('build', ['webpack:dev', 'static:dev']);
gulp.task('lint', ['lint:dev']);
//gulp.task('default', ['build', 'lint', 'test']);
<|endoftext|>


<commit_before>// reading time
(function ($) {
  "use strict";
  $(document).ready(function(){
    $(".post-content").fitVids();
    // Calculates Reading Time
    $('.post-content').readingTime({
      readingTimeTarget: '.post-reading-time',
      wordCountTarget: '.post-word-count',
    });
    // Creates Captions from Alt tags
    $(".post-content img").each(function() {
      // Let's put a caption if there is one
      if($(this).attr("alt"))
        $(this).wrap('

')
      .after('
'+$(this).attr("alt")+'
');
    });
  });
}(jQuery));

// transformation for article image
(function ($) {
  "use strict";
  $(document).ready(function(){
    var $window = $(window),
    $image = $('.post-image-image');
    $window.on('scroll', function() {
      var top = $window.scrollTop();
      if (top < 0 || top > 1500) { return; }
      $image
      .css('transform', 'translate3d(0px, '+top/3+'px, 0px)')
      .css('opacity', 1-Math.max(top/700, 0));
    });
    $window.trigger('scroll');
    $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 500);
            return false;
          }
        }
      });
    });
  });
}(jQuery));

// transformation for frontpage image
(function ($) {
  "use strict";
  $(document).ready(function(){
    var $window = $(window),
    $image = $('.teaserimage-image');
    $window.on('scroll', function() {
      var top = $window.scrollTop();
      if (top < 0 || top > 1500) { return; }
      $image
      .css('transform', 'translate3d(0px, '+top/3+'px, 0px)')
      .css('opacity', 1-Math.max(top/700, 0));
    });
    $window.trigger('scroll');
  });
}(jQuery));

// resize article image
(function ($) {
  "use strict";
  function arrangeItems(height) {
    var $teaserImage = $('.teaserimage'),
    $content = $('.post-content'),
    $articleImage = $('.post-image-image'),
    $articleImageContainer = $('.article-image'),
    $postReading = $('.post-reading');

    $teaserImage.height(height - 200);
    $articleImage.height(height);
    $articleImageContainer.height(height);
    if ($articleImageContainer.length) {
      $content.css('padding-top', height + 'px');
    }
    $postReading.css('top', (height - 36) + 'px');
  };
  $(document).ready(function(){
    arrangeItems($(window).height());
    // initial orientation mode
    var $portraitMode = $(window).height() > $(window).width();
    // listen to resize events
    $(window).resize(function() {
      if (isMobile.any) {
        // on mobile only resize when orientation change
        var $currentMode = $(window).height() > $(window).width();
        if($portraitMode != $currentMode){
          // toggle mode
          $portraitMode = $currentMode;
          arrangeItems($(window).height());
        }
      } else {
        arrangeItems($(window).height());
      }
    });
  });
}(jQuery));<commit_msg>open all external links in a new tab<commit_after>// reading time
(function ($) {
  "use strict";
  $(document).ready(function(){
    $(".post-content").fitVids();
    // Calculates Reading Time
    $('.post-content').readingTime({
      readingTimeTarget: '.post-reading-time',
      wordCountTarget: '.post-word-count',
    });
    // Creates Captions from Alt tags
    $(".post-content img").each(function() {
      // Let's put a caption if there is one
      if($(this).attr("alt"))
        $(this).wrap('

')
      .after('
'+$(this).attr("alt")+'
');
    });
  });
}(jQuery));

// transformation for article image
(function ($) {
  "use strict";
  $(document).ready(function(){
    var $window = $(window),
    $image = $('.post-image-image');
    $window.on('scroll', function() {
      var top = $window.scrollTop();
      if (top < 0 || top > 1500) { return; }
      $image
      .css('transform', 'translate3d(0px, '+top/3+'px, 0px)')
      .css('opacity', 1-Math.max(top/700, 0));
    });
    $window.trigger('scroll');
    $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 500);
            return false;
          }
        }
      });
    });
  });
}(jQuery));

// transformation for frontpage image
(function ($) {
  "use strict";
  $(document).ready(function(){
    var $window = $(window),
    $image = $('.teaserimage-image');
    $window.on('scroll', function() {
      var top = $window.scrollTop();
      if (top < 0 || top > 1500) { return; }
      $image
      .css('transform', 'translate3d(0px, '+top/3+'px, 0px)')
      .css('opacity', 1-Math.max(top/700, 0));
    });
    $window.trigger('scroll');
  });
}(jQuery));

// resize article image
(function ($) {
  "use strict";
  function arrangeItems(height) {
    var $teaserImage = $('.teaserimage'),
    $content = $('.post-content'),
    $articleImage = $('.post-image-image'),
    $articleImageContainer = $('.article-image'),
    $postReading = $('.post-reading');

    $teaserImage.height(height - 200);
    $articleImage.height(height);
    $articleImageContainer.height(height);
    if ($articleImageContainer.length) {
      $content.css('padding-top', height + 'px');
    }
    $postReading.css('top', (height - 36) + 'px');
  };
  $(document).ready(function(){
    arrangeItems($(window).height());
    // initial orientation mode
    var $portraitMode = $(window).height() > $(window).width();
    // listen to resize events
    $(window).resize(function() {
      if (isMobile.any) {
        // on mobile only resize when orientation change
        var $currentMode = $(window).height() > $(window).width();
        if($portraitMode != $currentMode){
          // toggle mode
          $portraitMode = $currentMode;
          arrangeItems($(window).height());
        }
      } else {
        arrangeItems($(window).height());
      }
    });
  });
}(jQuery));

// open new tab for all external links
(function ($) {
  "use strict";
  $(document.links).filter(function() {
    return this.hostname != window.location.hostname;
  }).attr('target', '_blank');
}(jQuery));<|endoftext|>


<commit_before>'use strict';

var should = require('should');
var gutil = require('gulp-util');
var stylus = require('../');
var fs = require('fs');

require('mocha');

describe('gulp-stylus', function(){
	it('should render stylus .styl to CSS .css', function(done){
		var stream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/expected/normal.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();

	});

	it ('should compress when called', function(done){
		var stream = stylus({compress: true});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/compressed.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should import other .styl files', function(done){
		var stream = stylus({import: __dirname + '/fixtures/one.styl'});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/imported.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should define variables in .styl files', function(done){
		var stream = stylus({define: {'white': '#fff'}});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/define.styl',
			contents: fs.readFileSync('test/fixtures/define.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/define.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it('should skip css files', function(done){
		var stream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/ie8.css',
			contents: fs.readFileSync('test/fixtures/ie8.css')
		});

		stream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/fixtures/ie8.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();

	});

	it('should throw on parse error', function(done){
		var stream = stylus();

		var file = 'test/fixtures/error.styl';

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: file,
			contents: fs.readFileSync(file)
		});

		stream.on('error', function(err) {
			should.exist(err);
			err.name.toString().should.match(/ParseError/);
			done();
		});
    stream.write(fakeFile);
    stream.end();

  });

	it ('should import nested and reverse recursive files', function(done){
		var stream = stylus();
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/import.styl',
			contents: fs.readFileSync('test/fixtures/import.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/expected/import.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();
	});

it ('should generate sourcemaps', function(done){
	var stream = stylus({ sourcemap: true });

	var fakeFile = new gutil.File({
		base: 'test/fixtures',
		cwd: 'test/',
		path: 'test/fixtures/normal.styl',
		contents: fs.readFileSync('test/fixtures/normal.styl')
	});

	stream.on('data', function(newFile) {
		should.exist(newFile);
		should.exist(newFile.contents);
		String(newFile.contents).should.equal(fs.readFileSync('test/expected/normal.css', 'utf8'));
		should.exist(newFile.sourceMap);
		newFile.sourceMap.version.should.equal(3)
		newFile.sourceMap.mappings.length.should.be.above(1)
		done();
	});

	stream.write(fakeFile);
	stream.end();

});

});
<commit_msg>add gulp-surcemap test<commit_after>'use strict';

var should = require('should');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var stylus = require('../');
var fs = require('fs');

require('mocha');

describe('gulp-stylus', function(){
	it('should render stylus .styl to CSS .css', function(done){
		var stream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/expected/normal.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();

	});

	it ('should compress when called', function(done){
		var stream = stylus({compress: true});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			var fixture = fs.readFileSync('test/expected/compressed.css', 'utf8');
			String(newFile.contents).should.equal(fixture);
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should import other .styl files', function(done){
		var stream = stylus({import: __dirname + '/fixtures/one.styl'});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/imported.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should define variables in .styl files', function(done){
		var stream = stylus({define: {'white': '#fff'}});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/define.styl',
			contents: fs.readFileSync('test/fixtures/define.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/define.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it('should skip css files', function(done){
		var stream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/ie8.css',
			contents: fs.readFileSync('test/fixtures/ie8.css')
		});

		stream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/fixtures/ie8.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();

	});

	it('should throw on parse error', function(done){
		var stream = stylus();

		var file = 'test/fixtures/error.styl';

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: file,
			contents: fs.readFileSync(file)
		});

		stream.on('error', function(err) {
			should.exist(err);
			err.name.toString().should.match(/ParseError/);
			done();
		});
    stream.write(fakeFile);
    stream.end();

  });

	it ('should import nested and reverse recursive files', function(done){
		var stream = stylus();
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/import.styl',
			contents: fs.readFileSync('test/fixtures/import.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/expected/import.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();
	});

	it ('should generate sourcemaps', function(done){
		var stream = stylus({sourcemap: true});

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/expected/normal.css', 'utf8'));
			should.exist(newFile.sourceMap);
			newFile.sourceMap.version.should.equal(3);
			newFile.sourceMap.mappings.length.should.be.above(1);
			done();
		});

		stream.write(fakeFile);
		stream.end();

	});

	it ('should generate sourcemaps with gulp-sourcemaps', function(done){
		var stream = sourcemaps.init();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.write(fakeFile);
		stream.pipe(stylus())
		  .on('error', done)
		  .on('data', function(newFile) {
				should.exist(newFile);
				should.exist(newFile.contents);
				String(newFile.contents).should.equal(fs.readFileSync('test/expected/normal.css', 'utf8'));
				should.exist(newFile.sourceMap);
				newFile.sourceMap.version.should.equal(3);
				newFile.sourceMap.mappings.length.should.be.above(1);
				done();
			});

		stream.end();

	});

});
<|endoftext|>


<commit_before>var path = require('path');
var exec = require('child_process').exec;
var url = require('url');

var gulp = require('gulp');
var gutil = require('gulp-util');
var nano = require('gulp-cssnano');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var cache = require('gulp-cached');
var express = require('express');
var proxy = require('express-http-proxy');
var webpack = require('webpack');
var through = require('through2');
var br = require('brotli');

function brotli(opts) {
  return through.obj(function(file, enc, callback) {
    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('brotli', 'Streams not supported'));
    } else if (file.isBuffer()) {
      file.path += '.br';
      file.contents = new Buffer(br.compress(file.contents, opts).buffer);
      return callback(null, file);
    }
  });
}

gulp.task('css', function() {
  return gulp.src(['src/css/fonts.css', 'src/css/fontello.css', 'src/css/style.css'])
    .pipe(concat('bundle.css'))
    .pipe(autoprefixer())
    .pipe(nano())
    .pipe(gulp.dest('dist'));
});

gulp.task('js', function(cb) {
  var config = require('./webpack.config.prod.js');
  var compiler = webpack(config);

  process.env['NODE_ENV'] = 'production';

  compiler.run(function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);

    gutil.log('[webpack]', stats.toString({
      colors: true
    }));

    if (stats.hasErrors()) process.exit(1);

    cb();
  });
});

gulp.task('fonts', function() {
  return gulp.src('src/font/*')
    .pipe(gulp.dest('dist/font'));
});

gulp.task('fonts:woff', function() {
  return gulp.src('src/font/*(*.woff|*.woff2)')
    .pipe(gulp.dest('dist/br/font'));
});

gulp.task('config', function() {
  return gulp.src('../config.default.toml')
    .pipe(gulp.dest('dist/br'));
});

function compress() {
  return gulp.src(['dist/**/!(*.br|*.woff|*.woff2)', '!dist/{br,br/**}'])
    .pipe(brotli({ quality: 11 }))
    .pipe(gulp.dest('dist/br'));
}

gulp.task('compress', ['css', 'js', 'fonts'], compress);
gulp.task('compress:dev', ['css', 'fonts'], compress);

gulp.task('bindata', ['compress', 'config'], function(cb) {
  exec('go-bindata -nomemcopy -nocompress -pkg assets -o ../assets/bindata.go -prefix "dist/br" dist/br/...', cb);
});

gulp.task('bindata:dev', ['compress:dev', 'config'], function(cb) {
  exec('go-bindata -debug -pkg assets -o ../assets/bindata.go -prefix "dist/br" dist/br/...', cb);
});

gulp.task('dev', ['css', 'fonts', 'fonts:woff', 'config', 'compress:dev', 'bindata:dev'], function() {
  gulp.watch('src/css/*.css', ['css']);

  var config = require('./webpack.config.dev.js');
  var compiler = webpack(config);
  var app = express();

  app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
  }));

  app.use(require('webpack-hot-middleware')(compiler));

  app.use('/', express.static('dist'));

  app.use('*', proxy('localhost:1337', {
    forwardPath: function(req, res) {
      return url.parse(req.url).path;
    }
  }));

  app.listen(3000, function (err) {
    if (err) {
      console.log(err);
      return;
    }

    console.log('Listening at http://localhost:3000');
  });
});

gulp.task('build', ['css', 'js', 'fonts', 'fonts:woff', 'config', 'compress', 'bindata']);

gulp.task('default', ['dev']);
<commit_msg>Return req.originalUrl from gulpfile proxy<commit_after>var path = require('path');
var exec = require('child_process').exec;
var url = require('url');

var gulp = require('gulp');
var gutil = require('gulp-util');
var nano = require('gulp-cssnano');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var cache = require('gulp-cached');
var express = require('express');
var proxy = require('express-http-proxy');
var webpack = require('webpack');
var through = require('through2');
var br = require('brotli');

function brotli(opts) {
  return through.obj(function(file, enc, callback) {
    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('brotli', 'Streams not supported'));
    } else if (file.isBuffer()) {
      file.path += '.br';
      file.contents = new Buffer(br.compress(file.contents, opts).buffer);
      return callback(null, file);
    }
  });
}

gulp.task('css', function() {
  return gulp.src(['src/css/fonts.css', 'src/css/fontello.css', 'src/css/style.css'])
    .pipe(concat('bundle.css'))
    .pipe(autoprefixer())
    .pipe(nano())
    .pipe(gulp.dest('dist'));
});

gulp.task('js', function(cb) {
  var config = require('./webpack.config.prod.js');
  var compiler = webpack(config);

  process.env['NODE_ENV'] = 'production';

  compiler.run(function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);

    gutil.log('[webpack]', stats.toString({
      colors: true
    }));

    if (stats.hasErrors()) process.exit(1);

    cb();
  });
});

gulp.task('fonts', function() {
  return gulp.src('src/font/*')
    .pipe(gulp.dest('dist/font'));
});

gulp.task('fonts:woff', function() {
  return gulp.src('src/font/*(*.woff|*.woff2)')
    .pipe(gulp.dest('dist/br/font'));
});

gulp.task('config', function() {
  return gulp.src('../config.default.toml')
    .pipe(gulp.dest('dist/br'));
});

function compress() {
  return gulp.src(['dist/**/!(*.br|*.woff|*.woff2)', '!dist/{br,br/**}'])
    .pipe(brotli({ quality: 11 }))
    .pipe(gulp.dest('dist/br'));
}

gulp.task('compress', ['css', 'js', 'fonts'], compress);
gulp.task('compress:dev', ['css', 'fonts'], compress);

gulp.task('bindata', ['compress', 'config'], function(cb) {
  exec('go-bindata -nomemcopy -nocompress -pkg assets -o ../assets/bindata.go -prefix "dist/br" dist/br/...', cb);
});

gulp.task('bindata:dev', ['compress:dev', 'config'], function(cb) {
  exec('go-bindata -debug -pkg assets -o ../assets/bindata.go -prefix "dist/br" dist/br/...', cb);
});

gulp.task('dev', ['css', 'fonts', 'fonts:woff', 'config', 'compress:dev', 'bindata:dev'], function() {
  gulp.watch('src/css/*.css', ['css']);

  var config = require('./webpack.config.dev.js');
  var compiler = webpack(config);
  var app = express();

  app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
  }));

  app.use(require('webpack-hot-middleware')(compiler));

  app.use('/', express.static('dist'));

  app.use('*', proxy('localhost:1337', {
    forwardPath: function(req, res) {
      return req.originalUrl;
    }
  }));

  app.listen(3000, function (err) {
    if (err) {
      console.log(err);
      return;
    }

    console.log('Listening at http://localhost:3000');
  });
});

gulp.task('build', ['css', 'js', 'fonts', 'fonts:woff', 'config', 'compress', 'bindata']);

gulp.task('default', ['dev']);
<|endoftext|>