<commit_before>(function() {

	var initMasonry = function() {
		$(".preview-list").imagesLoaded(function() {
			var gutterWidth = 2;

			var one_column_threshold = 450;
			var two_column_threshold = 340;

			console.log("Previews loaded.");

			$(".preview-list").fadeIn("fast");
			$(".preview-list").masonry({
				itemSelector: ".preview",
				gutterWidth: gutterWidth,
				isAnimated: false,
				columnWidth: function(containerWidth) {
					var one_column_width = containerWidth;
					var two_column_width = Math.floor((containerWidth - gutterWidth) / 2);
					var three_column_width = Math.floor((containerWidth - 2 * gutterWidth) / 3);

					if (one_column_width <= one_column_threshold) {
						box_width = one_column_width;
					} else if (two_column_width <= two_column_threshold) {
						box_width = two_column_width;
					} else {
						box_width = three_column_width;
					}
					$(".preview > div").width(box_width);

					if (box_width != one_column_width) {
						$(".featured-box").width(box_width * 2 + gutterWidth);
					}

					return box_width;
				}
			});
		});
	};

	var initPreviewClickHandler = function() {
		$(".preview").click(function(event) {
			window.location.href = $(event.currentTarget).attr("id").split("preview-")[1];
		});
	};

	var initInfiniteScroll = function() {
		$(".preview-list").infinitescroll({
			navSelector  : ".pagination-links",
			nextSelector : ".pagination-links .next_page",
			itemSelector : ".preview",
			bufferPx : 500,
			loading : {
				img : "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==", // transparent 1x1 gif
				msgText : "",
				finishedMsg : ""
			}},
			function(newElements) {
				$(newElements).css({opacity: 0});
				$(newElements).imagesLoaded(function() {
					$(newElements).animate({opacity: 1}, "fast", function() {
						$(newElements).css("opacity", "");
					});
					$(".preview-list").masonry("reload");
				});
			}
		);

		// trigger the first retrieval, even before the user starts scrolling
		$(".preview-list").infinitescroll("retrieve");
	}

	$(document).ready(function() {
		if ($(".photo-stream-page").length) {
			initMasonry();
			initPreviewClickHandler();
			initInfiniteScroll();
		}
	});
}
)();<commit_msg>Add onClick functionality to newly added previews from infinite scroll.<commit_after>(function() {

	var initMasonry = function() {
		$(".preview-list").imagesLoaded(function() {
			var gutterWidth = 2;

			var one_column_threshold = 450;
			var two_column_threshold = 340;

			console.log("Previews loaded.");

			$(".preview-list").fadeIn("fast");
			$(".preview-list").masonry({
				itemSelector: ".preview",
				gutterWidth: gutterWidth,
				isAnimated: false,
				columnWidth: function(containerWidth) {
					var one_column_width = containerWidth;
					var two_column_width = Math.floor((containerWidth - gutterWidth) / 2);
					var three_column_width = Math.floor((containerWidth - 2 * gutterWidth) / 3);

					if (one_column_width <= one_column_threshold) {
						box_width = one_column_width;
					} else if (two_column_width <= two_column_threshold) {
						box_width = two_column_width;
					} else {
						box_width = three_column_width;
					}
					$(".preview > div").width(box_width);

					if (box_width != one_column_width) {
						$(".featured-box").width(box_width * 2 + gutterWidth);
					}

					return box_width;
				}
			});
		});
	};

	var navigateToEntry = function(preview) {
		window.location.href = preview.attr("id").split("preview-")[1];
	}

	var initPreviewClickHandler = function() {
		$(".preview").click(function(event) {
			navigateToEntry($(event.currentTarget));
		});
	};

	var initInfiniteScroll = function() {
		$(".preview-list").infinitescroll({
			navSelector  : ".pagination-links",
			nextSelector : ".pagination-links .next_page",
			itemSelector : ".preview",
			bufferPx : 500,
			loading : {
				img : "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==", // transparent 1x1 gif
				msgText : "",
				finishedMsg : ""
			}},
			function(newElements) {
				$(newElements).css({opacity: 0});
				$(newElements).click(function(event) {
					navigateToEntry($(event.currentTarget));
				});
				$(newElements).imagesLoaded(function() {
					$(newElements).animate({opacity: 1}, "fast", function() {
						$(newElements).css("opacity", "");
					});
					$(".preview-list").masonry("reload");
				});
			}
		);

		// trigger the first retrieval, even before the user starts scrolling
		$(".preview-list").infinitescroll("retrieve");
	}

	$(document).ready(function() {
		if ($(".photo-stream-page").length) {
			initMasonry();
			initPreviewClickHandler();
			initInfiniteScroll();
		}
	});
}
)();<|endoftext|>


<commit_before>H5.PlayerControls = (function (Event, Array) {
    "use strict";

    function createGamePadControls() {
        return createControls(Event.GAME_PAD);
    }

    function createKeyBoardControls() {
        return createControls(Event.KEY_BOARD);
    }

    function createControls(event) {

        var unsubscribe;
        var commands = [];

        return {
            add: function (keyCode) {

                var command = {
                    code: keyCode,
                    isPressed: false
                };

                commands.push(command);

                return {
                    or: function (keyCode) {
                        if (command.or === undefined) {
                            command.or = keyCode;
                        } else if (command.or instanceof Array) {
                            command.or.push(keyCode);
                        } else {
                            command.or = [command.or, keyCode];
                        }
                    },
                    onDown: function (callback, self) {
                        if (self) {
                            command.onDown = callback.bind(self);
                        } else {
                            command.onDown = callback;
                        }
                    },
                    onUp: function (callback, self) {
                        if (self) {
                            command.onUp = callback.bind(self);
                        } else {
                            command.onUp = callback;
                        }
                    },
                    remove: function () {
                        commands.splice(commands.indexOf(command), 1);
                    }
                }
            },

            register: function (events) {
                var eventId = events.subscribe(event, function (inputType) {
                    commands.forEach(function (command) {
                        var isPressed;
                        if (command.or && command.or instanceof Array) {
                            isPressed = inputType.isPressed(command.code) || command.or.some(function (code) {
                                    return inputType.isPressed(code);
                                });
                        } else if (command.or) {
                            isPressed = inputType.isPressed(command.code) || inputType.isPressed(command.or);
                        } else {
                            isPressed = inputType.isPressed(command.code);
                        }

                        if (isPressed && !command.isPressed) {
                            command.isPressed = true;
                            if (command.onDown) command.onDown();

                        } else if (!isPressed && command.isPressed) {
                            command.isPressed = false;
                            if (command.onUp) command.onUp();
                        }
                    });
                });

                unsubscribe = function () {
                    events.unsubscribe(eventId);
                    unsubscribe = undefined;
                };
            },

            cancel: function () {
                if (unsubscribe) unsubscribe();
            }
        }
    }

    return {
        getGamePad: createGamePadControls,
        getKeyBoard: createKeyBoardControls
    }
})(H5.Event, Array);<commit_msg>fix chaining #core<commit_after>H5.PlayerControls = (function (Event, Array) {
    "use strict";

    function createGamePadControls() {
        return createControls(Event.GAME_PAD);
    }

    function createKeyBoardControls() {
        return createControls(Event.KEY_BOARD);
    }

    function createControls(event) {

        var unsubscribe;
        var commands = [];

        return {
            add: function (keyCode) {

                var command = {
                    code: keyCode,
                    isPressed: false
                };

                commands.push(command);

                return {
                    or: function (keyCode) {
                        if (command.or === undefined) {
                            command.or = keyCode;
                        } else if (command.or instanceof Array) {
                            command.or.push(keyCode);
                        } else {
                            command.or = [command.or, keyCode];
                        }

                        return this;
                    },
                    onDown: function (callback, self) {
                        if (self) {
                            command.onDown = callback.bind(self);
                        } else {
                            command.onDown = callback;
                        }

                        return this;
                    },
                    onUp: function (callback, self) {
                        if (self) {
                            command.onUp = callback.bind(self);
                        } else {
                            command.onUp = callback;
                        }

                        return this;
                    },
                    remove: function () {
                        commands.splice(commands.indexOf(command), 1);

                        return this;
                    }
                }
            },

            register: function (events) {
                var eventId = events.subscribe(event, function (inputType) {
                    commands.forEach(function (command) {
                        var isPressed;
                        if (command.or && command.or instanceof Array) {
                            isPressed = inputType.isPressed(command.code) || command.or.some(function (code) {
                                    return inputType.isPressed(code);
                                });
                        } else if (command.or) {
                            isPressed = inputType.isPressed(command.code) || inputType.isPressed(command.or);
                        } else {
                            isPressed = inputType.isPressed(command.code);
                        }

                        if (isPressed && !command.isPressed) {
                            command.isPressed = true;
                            if (command.onDown) command.onDown();

                        } else if (!isPressed && command.isPressed) {
                            command.isPressed = false;
                            if (command.onUp) command.onUp();
                        }
                    });
                });

                unsubscribe = function () {
                    events.unsubscribe(eventId);
                    unsubscribe = undefined;
                };

                return this;
            },

            cancel: function () {
                if (unsubscribe) unsubscribe();

                return this;
            }
        }
    }

    return {
        getGamePad: createGamePadControls,
        getKeyBoard: createKeyBoardControls
    }
})(H5.Event, Array);<|endoftext|>


<commit_before>var React = require('react');
var router = require('react-router-dom');
var Link = router.Link;
var Route = router.Route;

var helpers = require('../utils/helpers');

var Dashboard = React.createClass({

	getInitialState: function() {
		return {
			userPods: []
		};
	},

	/*
	componentDidMount: function() {
		this.setState({userPods: []});
	  	// Grab all of the user's pods from the database & display
	  	helpers.getPods().then(function(userPods) {
	      this.setState({ userPods: userPods.data })
	      console.log("User's pods ", userPods.data)
	    }.bind(this));
	},

	renderEmpty: function() {
	    return (

	            You haven't joined any Pods yet!

	    );
	},

	renderPods: function() {
		console.log('state', this.state);
	    return this.state.userPods.map(function(pod, index) {
	      return (

	                {pod.title}

	                  <button className="btn btn-default ">Go to Pod</button>

Description: {pod.description}

	      )
	    });
	},
	*/

	// handleClick: function() {
	// 	event.preventDefault();
 //    this.props.searchTerm(this.state.title, this.state.icon, this.state.description, this.state.members);
 //    this.setState({title:'', icon: '', description: '', members: []}); //leave interest out for now
 //    this.setState({displayResults: true});

 //    db.Pod.save({title: this.state.title, icon: this.state.icon, description: this.state.description, members: this.state.members});
 //    // redirect to login page
 //    res.redirect('/create', function(req, res) {
 //      res.render('index'); // goes back to the index for createPod
 //    });

	// }

	render: function() {
		return (

Your Pods

PODS GO HERE

You

Name

Pods

podname

podname

										<button id="create-btn" className="btn btn-default btn-round-sm btn-sm">Create New Pod!</button>

		);
	}
});

module.exports = Dashboard;
<commit_msg>adds a render empty or render pods function<commit_after>var React = require('react');
var router = require('react-router-dom');
var Link = router.Link;
var Route = router.Route;

var helpers = require('../utils/helpers');

var Dashboard = React.createClass({

	getInitialState: function() {
		return {
			userPods: []
		};
	},

	componentDidMount: function() {
		this.setState({userPods: []});
	  	// Grab all of the user's pods from the database & display
	  	helpers.getPods().then(function(userPods) {
	      this.setState({ userPods: userPods.data })
	      console.log("User's pods ", userPods.data)
	    }.bind(this));
	},

	renderEmpty: function() {
	    return (

	            You haven't joined any Pods yet!

	    );
	},

	renderPods: function() {
		console.log('state', this.state);
	    return this.state.userPods.map(function(pod, index) {
	      return (

	                {pod.title}

	                  <button className="btn btn-default ">Go to Pod</button>

Description: {pod.description}

	      )
	    });
	},

	render: function() {
		return (

Your Pods

							{this.renderPods}

You

Name

Pods

podname

podname

										<button id="create-btn" className="btn btn-default btn-round-sm btn-sm">Create New Pod!</button>

		);
	}
});

module.exports = Dashboard;
<|endoftext|>


<commit_before>var models = require('../models'),
  async = require('async')

var userSerializer = {
  select: ['id', 'username', 'info'],
  info: { select: ['screenName'] }
}

exports.addRoutes = function(app) {
  app.get('/v1/top/:category', function(req, res) {
    models.Stats.getTopUserIdsWithScores(req.params.category, function(err, userIdsWithScores) {
      if (err || !userIdsWithScores)
        return res.jsonp(err, 422)

      var userIdsScores = {}
      var userIds = []
      for(var i=0; i<userIdsWithScores.length; i+=2) {
        userIdsScores[userIdsWithScores[i]] = userIdsWithScores[i+1]
        userIds.push(userIdsWithScores[i])
      }

      // FIXME: refactor to map function
      var users = []
      async.forEach(userIds, function(userId, callback) {
        models.User.findById(userId, function(err, user) {
          // NOTE: this user does not exist anymore, e.g. was deleted or
          // database is broken
          if (!user)
            return callback(null)

          user.toJSON(userSerializer, function(err, json) {
            if (!json)
              return callback(err)

            json.score = userIdsScores[userId]
            users.push(json)
            callback(null)
          })
        })
      }, function(err) {
        if (err)
          return res.jsonp(err, 422)

        res.jsonp(users)
      })
    })
  })
}
<commit_msg>Replaces old serializers with new on stats route.<commit_after>var models = require('../models')
  , async = require('async')
  , UserSerializer = models.UserSerializer;

var userSerializer = {
  select: ['id', 'username', 'info'],
  info: { select: ['screenName'] }
}

exports.addRoutes = function(app) {
  app.get('/v1/top/:category', function(req, res) {
    models.Stats.getTopUserIdsWithScores(req.params.category, function(err, userIdsWithScores) {
      if (err || !userIdsWithScores)
        return res.jsonp(err, 422)

      var userIdsScores = {}
      var userIds = []
      for(var i=0; i<userIdsWithScores.length; i+=2) {
        userIdsScores[userIdsWithScores[i]] = userIdsWithScores[i+1]
        userIds.push(userIdsWithScores[i])
      }

      // FIXME: refactor to map function
      var users = []
      async.forEach(userIds, function(userId, callback) {
        models.User.findById(userId, function(err, user) {
          // NOTE: this user does not exist anymore, e.g. was deleted or
          // database is broken
          if (!user)
            return callback(null)

          new UserSerializer(user).toJSON(function(err, json) {
            if (!json)
              return callback(err);

            json.score = userIdsScores[userId];
            users.push(json);
            callback(null);
          });
        })
      }, function(err) {
        if (err)
          return res.jsonp(err, 422)

        res.jsonp(users)
      })
    })
  })
}
<|endoftext|>


<commit_before>var karmaBaseConf = require('./karma.base.conf')

var browsers = {
  sl_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'Windows 10',
    version: '50.0'
  },
  sl_firefox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'Windows 10',
    version: '46.0'
  },
  sl_ie_11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 10',
    version: '11.103'
  },
  sl_edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10',
    version: '13.10586'
  }
}

module.exports = function (config) {
  karmaBaseConf.plugins.push(require('karma-sauce-launcher'))
  karmaBaseConf.reporters.push('saucelabs')
  karmaBaseConf.logLevel = config.LOG_DEBUG
  karmaBaseConf.customLaunchers = browsers
  karmaBaseConf.captureTimeout = 200000
  karmaBaseConf.browserDisconnectTolerance = 3
  karmaBaseConf.browserNoActivityTimeout = 20000
  karmaBaseConf.concurrency = 5
  karmaBaseConf.browsers = Object.keys(browsers)
  karmaBaseConf.sauceLabs = {
    // Should be false for running on travis, as travis already starts its own
    // sauce connect
    startConnect: false,
    // https://github.com/karma-runner/karma-sauce-launcher/issues/73
    tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
  }

  config.set(karmaBaseConf)
}
<commit_msg>fix: increase browserNoActivityTimeout for Karma<commit_after>var karmaBaseConf = require('./karma.base.conf')

var browsers = {
  sl_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'Windows 10',
    version: '50.0'
  },
  sl_firefox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'Windows 10',
    version: '46.0'
  },
  sl_ie_11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 10',
    version: '11.103'
  },
  sl_edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10',
    version: '13.10586'
  }
}

module.exports = function (config) {
  karmaBaseConf.plugins.push(require('karma-sauce-launcher'))
  karmaBaseConf.reporters.push('saucelabs')
  karmaBaseConf.logLevel = config.LOG_DEBUG
  karmaBaseConf.customLaunchers = browsers
  karmaBaseConf.captureTimeout = 200000
  karmaBaseConf.browserDisconnectTolerance = 3
  karmaBaseConf.browserNoActivityTimeout = 30000
  karmaBaseConf.concurrency = 5
  karmaBaseConf.browsers = Object.keys(browsers)
  karmaBaseConf.sauceLabs = {
    // Should be false for running on travis, as travis already starts its own
    // sauce connect
    startConnect: false,
    // https://github.com/karma-runner/karma-sauce-launcher/issues/73
    tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
  }

  config.set(karmaBaseConf)
}
<|endoftext|>


<commit_before>'use strict';

angular.module('wuw.czErrorMessage', [])

.controller('czErrorMessageCtrl', ['$scope', '$ionicSlideBoxDelegate', '$timeout', function($scope, $ionicSlideBoxDelegate, $timeout) {

    var el;

    this.init = function(element) {
        el = angular.element(element);
        $scope.hide(); // the error message is hidden by default
    };

    $scope.hide = function() {
        el.removeClass("czMessageBox-rolldown");
        el.addClass("czMessageBox-rollup");
        $scope.visible = false;
    };

    $scope.show = function() {
        $ionicSlideBoxDelegate.slide(1,10);
        el.removeClass("czMessageBox-rollup");
        el.addClass("czMessageBox-rolldown");
    };

    $scope.$on('czErrorMessage.show', function(event, args) {
        $scope.show();
    });

    $scope.$on('czErrorMessage.hide', function(event, args) {
        $scope.hide();
    });

    $scope.slideHasChanged = function($index) {
        if ($index !== 1) {
            $scope.hide();
        }
    };
}])

.directive('czErrorMessage', function () {
    return {
        restrict: 'E',
        controller: 'czErrorMessageCtrl',
        template:
                    '<ion-slide-box class="czMessageBox czMessageBox-rollup" show-pager="false" on-slide-changed="slideHasChanged($index)">' +
                        '<ion-slide>' +
                            '
' +
                        '</ion-slide>' +
                        '<ion-slide>' +
                            '<ion-scroll direction="x" scrollbar-x="false">'+
                                '<ng-transclude></ng-transclude>'+
                            '</ion-scroll>'+
                        '</ion-slide>'+
                        '<ion-slide>'+
                            '
'+
                        '</ion-slide>'+
                    '</ion-slide-box>',
        transclude: true,
        scope: {
        },
        link: function(scope, element, attrs, czErrorMessageCtrl) {
            czErrorMessageCtrl.init(element[0].children[0]);
        }
    };
});
<commit_msg>czErrorMessage: don't mix up with sidemenu<commit_after>'use strict';

angular.module('wuw.czErrorMessage', [])

.controller('czErrorMessageCtrl', ['$scope', '$ionicSlideBoxDelegate', '$ionicSideMenuDelegate', '$timeout', function($scope, $ionicSlideBoxDelegate, $ionicSideMenuDelegate, $timeout) {

    var el;

    this.init = function(element) {
        el = angular.element(element);
        $scope.hide(); // the error message is hidden by default
    };

    $scope.hide = function() {
        el.removeClass("czMessageBox-rolldown");
        el.addClass("czMessageBox-rollup");
        $scope.visible = false;
    };

    $scope.show = function() {
        $ionicSlideBoxDelegate.slide(1,10);
        el.removeClass("czMessageBox-rollup");
        el.addClass("czMessageBox-rolldown");
    };

    $scope.$on('czErrorMessage.show', function(event, args) {
        $scope.show();
    });

    $scope.$on('czErrorMessage.hide', function(event, args) {
        $scope.hide();
    });

    $scope.slideHasChanged = function($index) {
        if ($index !== 1) {
            $scope.hide();
        }
    };

    // When sliding the error messag away, don't influence the side menu
    $scope.$on('$ionicView.enter', function(){
        $ionicSideMenuDelegate.canDragContent(false);
    });

    $scope.$on('$ionicView.leave', function(){
        $ionicSideMenuDelegate.canDragContent(true);
    });
}])

.directive('czErrorMessage', function () {
    return {
        restrict: 'E',
        controller: 'czErrorMessageCtrl',
        template:
                    '<ion-slide-box class="czMessageBox czMessageBox-rollup" show-pager="false" on-slide-changed="slideHasChanged($index)">' +
                        '<ion-slide>' +
                            '
' +
                        '</ion-slide>' +
                        '<ion-slide>' +
                            '<ion-scroll direction="x" scrollbar-x="false">'+
                                '<ng-transclude></ng-transclude>'+
                            '</ion-scroll>'+
                        '</ion-slide>'+
                        '<ion-slide>'+
                            '
'+
                        '</ion-slide>'+
                    '</ion-slide-box>',
        transclude: true,
        scope: {
        },
        link: function(scope, element, attrs, czErrorMessageCtrl) {
            czErrorMessageCtrl.init(element[0].children[0]);
        }
    };
});
<|endoftext|>


<commit_before>'use strict';
const baseModel = require('./baseModel');

/**
 * Comments model
 */
class Comments extends baseModel{

    /**
     * Call parent and define schema
     */
    constructor(){
        super('comments');

        let Schema = this.db.Schema;
        this.schema = new Schema({
            content     : String,
            targetUser  : {type : Schema.Types.ObjectId, ref: 'users'},
            createdBy   : {type: Schema.Types.ObjectId, ref : 'users'},
            created     : { type: Date, default: Date.now }
        });

    }

    findComments(userId, callback){

        this.getMongooseModel().find({targetUser : userId},null, {sort: {created : -1}}).populate({
            path: 'createdBy',
            model: 'users',
            select: {
                username: 1,
                firstName: 1,
                lastName: 1
            }
        }).exec(callback);
    }

    findComment(commentId, callback){
        this.getMongooseModel().findOne({_id : commentId}, null, {sort: {created : -1}}).populate({
            path: 'createdBy',
            model: 'users',
            select: {
                username: 1,
                firstName: 1,
                lastName: 1,
                email: 1,
            }
        }).populate({
            path: 'targetUser',
            model: 'users',
            select: {
                username: 1,
                firstName: 1,
                lastName: 1,
                email: 1,
            }
        })
            .exec(callback);
    }

}

module.exports = new Comments();<commit_msg>fix avatar display in comment bloc<commit_after>'use strict';
const baseModel = require('./baseModel');

/**
 * Comments model
 */
class Comments extends baseModel{

    /**
     * Call parent and define schema
     */
    constructor(){
        super('comments');

        let Schema = this.db.Schema;
        this.schema = new Schema({
            content     : String,
            targetUser  : {type : Schema.Types.ObjectId, ref: 'users'},
            createdBy   : {type: Schema.Types.ObjectId, ref : 'users'},
            created     : { type: Date, default: Date.now }
        });

    }

    findComments(userId, callback){

        this.getMongooseModel().find({targetUser : userId},null, {sort: {created : -1}}).populate({
            path: 'createdBy',
            model: 'users',
            select: {
                username: 1,
                firstName: 1,
                avatar : 1,
                lastName: 1
            }
        }).exec(callback);
    }

    findComment(commentId, callback){
        this.getMongooseModel().findOne({_id : commentId}, null, {sort: {created : -1}}).populate({
            path: 'createdBy',
            model: 'users',
            select: {
                username: 1,
                firstName: 1,
                lastName: 1,
                avatar: 1,
                email: 1,
            }
        }).populate({
            path: 'targetUser',
            model: 'users',
            select: {
                username: 1,
                firstName: 1,
                lastName: 1,
                avatar: 1,
                email: 1,
            }
        })
            .exec(callback);
    }

}

module.exports = new Comments();<|endoftext|>


<commit_before>define([
  'angular',
  'text!./cam-tasklist-task.html',
  'jquery'
], function(
  angular,
  template,
  jquery
) {
  'use strict';

  var TaskErrorManager = (function() {

    function TaskErrorManager() {

      this.errorProvider = null;

    }

    return TaskErrorManager;

  })();

  return [ function() {

    return {
      restrict: 'A',
      scope: {
        tasklistData: '='
      },

      template: template,

      controller : [
        '$scope',
        '$q',
        '$location',
        '$translate',
        'Notifications',
        'camAPI',
        'Views',
        'search',
      function(
        $scope,
        $q,
        $location,
        $translate,
        Notifications,
        camAPI,
        Views,
        search
      ) {

        // setup /////////////////////////////////////////////////////////////////////

        var Task = camAPI.resource('task');

        var taskData = $scope.taskData = $scope.tasklistData.newChild($scope);

        // error handling //////////////////////////////////////////////////////////////

        function errorNotification(src, err) {
          $translate(src).then(function(translated) {
            Notifications.addError({
              status: translated,
              message: (err ? err.message : ''),
              exclusive: true,
              scope: $scope
            });
          });
        }

        $scope.errorHandler = function (status, err) {
          var _status = enhanceErrorMessage(err.message);

          if(_status === 'TASK_NOT_EXIST' || _status === 'INSTANCE_SUSPENDED') {
            return $translate(_status).then(function(translated) {
              err.message = translated;
              errorNotification(status, err);
              clearTask(true);
            });

          }
          else {
            errorNotification(status, err);
          }

        };

        function enhanceErrorMessage(msg) {
          if (msg) {
            if(msg.indexOf('task is null') !== -1 || msg.indexOf('No matching task') !== -1) {
              // task does not exist (e.g. completed by someone else)
              return 'TASK_NOT_EXIST';
            }
            else if(msg.indexOf('is suspended') !== -1) {
              // process instance is suspended
              return 'INSTANCE_SUSPENDED';
            }
          }
          return msg;
        }

        function clearTask(updateLocation) {

          if (updateLocation) {
            var search = $location.search() || {};

            delete search.task;
            delete search.detailsTab;

            // reseting the location leads that
            // the taskId will set to null and
            // the current selected task will
            // also be set to null, so that the
            // view gets clear
            $location.search(angular.copy(search));

          }
          else {
            // reset current select taskId to null
            taskData.set('taskId', { 'taskId' : null });
          }

          // list of tasks must be reloaded as
          // well: changed properties on this
          // task may cause the list to change
          taskData.changed('taskList');
        }

        $scope.$watch('taskState.$error', function (err) {
          if (err) {
            var src = enhanceErrorMessage(err.message);
            errorNotification(src, err);
            // pass false to not reset the search params!
            // in that case the history works properly.
            clearTask(false);
          }
        });

        // provider ///////////////////////////////////////////////////////////////////

        taskData.provide('assignee', ['task', function(task) {
          if (task) {
            if(task._embedded.identityLink) {
              for(var i = 0; i < task._embedded.identityLink.length; i++) {
                if(task._embedded.identityLink[i].type === 'assignee') {
                  if(task._embedded.identityLink[i]._embedded.user) {
                    return task._embedded.identityLink[i]._embedded.user[0];
                  } else {
                    return {id: task._embedded.identityLink[i].userId};
                  }

                }
              }
            }
          }
          return null;
        }]);

        taskData.provide('groups', ['task', function(task) {
          var groups = [];
          if (task) {
            if(task._embedded.identityLink) {
              for(var i = 0; i < task._embedded.identityLink.length; i++) {
                if(task._embedded.identityLink[i].type === 'candidate' && task._embedded.identityLink[i].groupId !== null) {
                  if(task._embedded.identityLink[i]._embedded.group) {
                    groups.push(task._embedded.identityLink[i]._embedded.group[0]);
                  } else {
                    groups.push({id: task._embedded.identityLink[i].groupId});
                  }
                }
              }
            }
          }
          return groups;
        }]);

        taskData.provide('isAssignee', ['assignee', function(assignee) {
          return !!assignee && assignee.id === $scope.$root.authentication.name;
        }]);

        taskData.provide('processDefinition', ['task', function (task) {
          if (!task || !task._embedded || !task._embedded.processDefinition) {
            return null;
          }
          return task._embedded.processDefinition[0];
        }]);

        taskData.provide('caseDefinition', ['task', function (task) {
          if (!task || !task._embedded || !task._embedded.caseDefinition) {
            return null;
          }
          return task._embedded.caseDefinition[0];
        }]);

        // observer ////////////////////////////////////////////////////////////////////////

        /**
         * expose current task as scope variable
         */
        $scope.taskState = taskData.observe('task', function(task) {
          $scope.task = task;
        });

        taskData.observe('isAssignee', function (isAssignee) {
          $scope.isAssignee = isAssignee;
        });

        // plugins //////////////////////////////////////////////////////////////

        $scope.taskVars = { read: [ 'task', 'taskData', 'errorHandler' ] };
        $scope.taskDetailTabs = Views.getProviders({ component: 'tasklist.task.detail' });

        $scope.selectedTaskDetailTab = $scope.taskDetailTabs[0];

        $scope.selectTaskDetailTab = function(tab) {
          $scope.selectedTaskDetailTab = tab;

          search.updateSilently({
            detailsTab: tab.id
          });
        };

        function setDefaultTaskDetailTab(tabs) {
          var selectedTabId = search().detailsTab;

          if (!tabs || !tabs.length) {
            return;
          }

          if (selectedTabId) {
            var provider = Views.getProvider({ component: 'tasklist.task.detail', id: selectedTabId });
            if (provider && tabs.indexOf(provider) != -1) {
              $scope.selectedTaskDetailTab = provider;
              return;
            }
          }

          search.updateSilently({
            detailsTab: null
          });

          $scope.selectedTaskDetailTab = tabs[0];
        }

        setDefaultTaskDetailTab($scope.taskDetailTabs);

        $scope.$on('$routeChanged', function() {
          setDefaultTaskDetailTab($scope.taskDetailTabs);
        });

      }]
    };
  }];
});

<commit_msg>fix(task/detail): adjust null check<commit_after>define([
  'angular',
  'text!./cam-tasklist-task.html',
  'jquery'
], function(
  angular,
  template,
  jquery
) {
  'use strict';

  var TaskErrorManager = (function() {

    function TaskErrorManager() {

      this.errorProvider = null;

    }

    return TaskErrorManager;

  })();

  return [ function() {

    return {
      restrict: 'A',
      scope: {
        tasklistData: '='
      },

      template: template,

      controller : [
        '$scope',
        '$q',
        '$location',
        '$translate',
        'Notifications',
        'camAPI',
        'Views',
        'search',
      function(
        $scope,
        $q,
        $location,
        $translate,
        Notifications,
        camAPI,
        Views,
        search
      ) {

        // setup /////////////////////////////////////////////////////////////////////

        var Task = camAPI.resource('task');

        var taskData = $scope.taskData = $scope.tasklistData.newChild($scope);

        // error handling //////////////////////////////////////////////////////////////

        function errorNotification(src, err) {
          $translate(src).then(function(translated) {
            Notifications.addError({
              status: translated,
              message: (err ? err.message : ''),
              exclusive: true,
              scope: $scope
            });
          });
        }

        $scope.errorHandler = function (status, err) {
          var _status = enhanceErrorMessage(err.message);

          if(_status === 'TASK_NOT_EXIST' || _status === 'INSTANCE_SUSPENDED') {
            return $translate(_status).then(function(translated) {
              err.message = translated;
              errorNotification(status, err);
              clearTask(true);
            });

          }
          else {
            errorNotification(status, err);
          }

        };

        function enhanceErrorMessage(msg) {
          if (msg) {
            if(msg.indexOf('task is null') !== -1 || msg.indexOf('No matching task') !== -1) {
              // task does not exist (e.g. completed by someone else)
              return 'TASK_NOT_EXIST';
            }
            else if(msg.indexOf('is suspended') !== -1) {
              // process instance is suspended
              return 'INSTANCE_SUSPENDED';
            }
          }
          return msg;
        }

        function clearTask(updateLocation) {

          if (updateLocation) {
            var search = $location.search() || {};

            delete search.task;
            delete search.detailsTab;

            // reseting the location leads that
            // the taskId will set to null and
            // the current selected task will
            // also be set to null, so that the
            // view gets clear
            $location.search(angular.copy(search));

          }
          else {
            // reset current select taskId to null
            taskData.set('taskId', { 'taskId' : null });
          }

          // list of tasks must be reloaded as
          // well: changed properties on this
          // task may cause the list to change
          taskData.changed('taskList');
        }

        $scope.$watch('taskState.$error', function (err) {
          if (err) {
            var src = enhanceErrorMessage(err.message);
            errorNotification(src, err);
            // pass false to not reset the search params!
            // in that case the history works properly.
            clearTask(false);
          }
        });

        // provider ///////////////////////////////////////////////////////////////////

        taskData.provide('assignee', ['task', function(task) {
          if (task && task._embedded) {
            if(task._embedded.identityLink) {
              for(var i = 0; i < task._embedded.identityLink.length; i++) {
                if(task._embedded.identityLink[i].type === 'assignee') {
                  if(task._embedded.identityLink[i]._embedded.user) {
                    return task._embedded.identityLink[i]._embedded.user[0];
                  } else {
                    return {id: task._embedded.identityLink[i].userId};
                  }

                }
              }
            }
          }
          return null;
        }]);

        taskData.provide('groups', ['task', function(task) {
          var groups = [];
          if (task && task._embedded) {
            if(task._embedded.identityLink) {
              for(var i = 0; i < task._embedded.identityLink.length; i++) {
                if(task._embedded.identityLink[i].type === 'candidate' && task._embedded.identityLink[i].groupId !== null) {
                  if(task._embedded.identityLink[i]._embedded.group) {
                    groups.push(task._embedded.identityLink[i]._embedded.group[0]);
                  } else {
                    groups.push({id: task._embedded.identityLink[i].groupId});
                  }
                }
              }
            }
          }
          return groups;
        }]);

        taskData.provide('isAssignee', ['assignee', function(assignee) {
          return !!assignee && assignee.id === $scope.$root.authentication.name;
        }]);

        taskData.provide('processDefinition', ['task', function (task) {
          if (!task || !task._embedded || !task._embedded.processDefinition) {
            return null;
          }
          return task._embedded.processDefinition[0];
        }]);

        taskData.provide('caseDefinition', ['task', function (task) {
          if (!task || !task._embedded || !task._embedded.caseDefinition) {
            return null;
          }
          return task._embedded.caseDefinition[0];
        }]);

        // observer ////////////////////////////////////////////////////////////////////////

        /**
         * expose current task as scope variable
         */
        $scope.taskState = taskData.observe('task', function(task) {
          $scope.task = task;
        });

        taskData.observe('isAssignee', function (isAssignee) {
          $scope.isAssignee = isAssignee;
        });

        // plugins //////////////////////////////////////////////////////////////

        $scope.taskVars = { read: [ 'task', 'taskData', 'errorHandler' ] };
        $scope.taskDetailTabs = Views.getProviders({ component: 'tasklist.task.detail' });

        $scope.selectedTaskDetailTab = $scope.taskDetailTabs[0];

        $scope.selectTaskDetailTab = function(tab) {
          $scope.selectedTaskDetailTab = tab;

          search.updateSilently({
            detailsTab: tab.id
          });
        };

        function setDefaultTaskDetailTab(tabs) {
          var selectedTabId = search().detailsTab;

          if (!tabs || !tabs.length) {
            return;
          }

          if (selectedTabId) {
            var provider = Views.getProvider({ component: 'tasklist.task.detail', id: selectedTabId });
            if (provider && tabs.indexOf(provider) != -1) {
              $scope.selectedTaskDetailTab = provider;
              return;
            }
          }

          search.updateSilently({
            detailsTab: null
          });

          $scope.selectedTaskDetailTab = tabs[0];
        }

        setDefaultTaskDetailTab($scope.taskDetailTabs);

        $scope.$on('$routeChanged', function() {
          setDefaultTaskDetailTab($scope.taskDetailTabs);
        });

      }]
    };
  }];
});

<|endoftext|>


<commit_before>'use strict';

var blueprint = require ('@onehilltech/blueprint')
  , mongodb = require ('@onehilltech/blueprint-mongodb')
  , ResourceController = mongodb.ResourceController
  , _ = require ('lodash')
  ;

var Message = require ('../models/Message')
  , User    = require ('../models/User')
  ;

function MessageController () {
  ResourceController.call (this, {name: 'message', model: Message});
}

MessageController.prototype.create = function () {
  var opts = {
    on: {
      preCreate: function (req, doc, callback) {
        doc.org_id = req.user.org_id;
        doc.sender = req.user.username;

        return callback(null, doc);
      }
    }
  };

  return mongodb.ResourceController.prototype.create.call (this, opts);
};

MessageController.prototype.getAll = function () {
  var opts = {
    on: {
      authorize: function (req, callback) {
        var role = req.user.role;

        if (role !== 'admin') {
          var queries = req.query;

          if (_.isEmpty (queries)) {
            return callback ('unauthorized');
          }

          var whitelist = ['sender', 'receiver'];

          for (var query in queries) {
            if (!_.includes (whitelist, query)) {
              return callback ('unauthorized query parameter');
            }
          }
        }

        return callback ();
      }
    }
  };

  return mongodb.ResourceController.prototype.getAll.call (this, opts);
};

blueprint.controller (MessageController, ResourceController);

module.exports = MessageController;<commit_msg>quick fail fast optimization in MessageController<commit_after>'use strict';

var blueprint = require ('@onehilltech/blueprint')
  , mongodb = require ('@onehilltech/blueprint-mongodb')
  , ResourceController = mongodb.ResourceController
  , _ = require ('lodash')
  ;

var Message = require ('../models/Message')
  , User    = require ('../models/User')
  ;

function MessageController () {
  ResourceController.call (this, {name: 'message', model: Message});
}

MessageController.prototype.create = function () {
  var opts = {
    on: {
      preCreate: function (req, doc, callback) {
        doc.org_id = req.user.org_id;
        doc.sender = req.user.username;

        return callback(null, doc);
      }
    }
  };

  return mongodb.ResourceController.prototype.create.call (this, opts);
};

MessageController.prototype.getAll = function () {
  var opts = {
    on: {
      authorize: function (req, callback) {
        var role = req.user.role;

        if (role === 'admin') {
          return callback ();
        }

        var queries = req.query;

        if (_.isEmpty (queries)) {
          return callback ('unauthorized');
        }

        var whitelist = ['sender', 'receiver'];
        for (var query in queries) {
          if (!_.includes (whitelist, query)) {
            return callback ('unauthorized query parameter');
          }
        }

        return callback ();
      }
    }
  };

  return mongodb.ResourceController.prototype.getAll.call (this, opts);
};

blueprint.controller (MessageController, ResourceController);

module.exports = MessageController;<|endoftext|>


<commit_before>(function($win, $doc) {
  'use strict';

  var document = $doc;
  var window = $win;

  window.Rplus = {
    ele: {
      html: document.documentElement,
      head: document.head || document.getElementsByTagName('head')[0]
    },
    ready: function (fn) {
      if (document.readyState !== 'loading'){
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    },
    ajaxGet: function ($path, $fn) {
      var ajax = new XMLHttpRequest();
      ajax.open('GET', $path, true);
      ajax.send();
      if ('function' === typeof $fn) {
        ajax.onload = function () {
          $fn({data: ajax.responseText});
        };
      }
    },
    getFBInfo: function ($noscriptEle) {
      var _allAttr = (function ($fbString) {
        return {
          arr: $fbString.match(/(?!\s)\w+?=".+?"/g),
          obj: {
            oriString: $fbString.trim(),
            tag: $fbString.match(/^\s+?<(\w+?)\s/)[1]
          }
        };
      })($noscriptEle.firstChild.data);

      for (var i = _allAttr.arr.length; i;) {
        i--;
        _allAttr._tmpArr = _allAttr.arr[i].match(/(\w+?)="(.+?)"/);
        _allAttr.obj[_allAttr._tmpArr[1]] = _allAttr._tmpArr[2];
      }

      return _allAttr.obj;
    },
    injectInline: function ($src, $specilOption) {
      $src.sourceAttr = {
        link: 'href',
        img: 'src'
      }[$src.tag];
      $src.sourceUrl = $src[$src.sourceAttr];

      var _cachedItem = $src.sourceUrl.split('/').reverse()[0];
      var _isSvgType = (/\.svg$/.test(_cachedItem));
      var localData = localStorage.getItem(_cachedItem);

      var injectHTML = function (inlineContent) {
        var div = document.createElement('div');
        div.innerHTML = inlineContent;

        if (document.readyState !== 'loading') {
          var _insertBeforeEle = ($specilOption && $specilOption.insertBefore) || Rplus.ele.body.childNodes[0];
          Rplus.ele.body.insertBefore(div, _insertBeforeEle);
        } else {
          Rplus.ele.head.appendChild(div);
        }
      };

      if (Rplus.hasCache && localData) {
        injectHTML(localData);
      } else if ($specilOption && $specilOption.insertTag) {
        injectHTML($src.oriString);
      } else {
        Rplus.ajaxGet($src.sourceUrl, function (response) {
          var inlineContent = response.data;

          if (!_isSvgType) {
            inlineContent = '<style>' + inlineContent + '</sctyle>';
          }

          localStorage.setItem(_cachedItem, inlineContent);

          if ($specilOption && $specilOption.cacheOnly) {
            return;
          }

          injectHTML(inlineContent);
        });
      }
    }
  };

  var Rplus = window.Rplus || {};

  // init Rplus.ele.body
  Rplus.ready(function () {
    Rplus.ele.body = document.body || document.getElementsByTagName('body')[0];
  });

  // check cache version
  ;(function ($ele, $lsItem) {
    var _latestVersion = $ele.getAttribute('data-' + $lsItem);
    var _cacheVersion = localStorage.getItem($lsItem);
    var _hasCache = (_cacheVersion === _latestVersion);

    if (!_hasCache || '#clear' === location.hash) {
      // forcely clear all localStorage data
      localStorage.clear();
      localStorage.setItem($lsItem, _latestVersion);
    }

    Rplus.hasCache = _hasCache;
  })(document.getElementById('js-version'), 'version');

  // init modernizr class for <html>, from cache or inject script callback
  ;(function ($eles, $lsItem) {
    var htmlClassName = localStorage.getItem($lsItem);

    if (Rplus.hasCache && htmlClassName) {
      // init html class
      $eles.html.className = htmlClassName;
    } else {
      var _injectJsEle = document.createElement('script');

      // save html className into localStorage after script loaded
      _injectJsEle.src = '//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js';
      _injectJsEle.addEventListener('load', function () {
        localStorage.setItem($lsItem, $eles.html.className);
      });

      $eles.head.appendChild(_injectJsEle);
    }
  })(Rplus.ele, 'modernizrAllClass');

  // init main style
  Rplus.injectInline(Rplus.getFBInfo(document.getElementById('js-main-style')), {insertTag: true});

})(window, document);
<commit_msg>加入 副檔名 資訊 至 fbinfo<commit_after>(function($win, $doc) {
  'use strict';

  var document = $doc;
  var window = $win;

  window.Rplus = {
    ele: {
      html: document.documentElement,
      head: document.head || document.getElementsByTagName('head')[0]
    },
    ready: function (fn) {
      if (document.readyState !== 'loading'){
        fn();
      } else {
        document.addEventListener('DOMContentLoaded', fn);
      }
    },
    ajaxGet: function ($path, $fn) {
      var ajax = new XMLHttpRequest();
      ajax.open('GET', $path, true);
      ajax.send();
      if ('function' === typeof $fn) {
        ajax.onload = function () {
          $fn({data: ajax.responseText});
        };
      }
    },
    getFBInfo: function ($noscriptEle) {
      var _allAttr = (function ($fbString) {
        return {
          arr: $fbString.match(/(?!\s)\w+?=".+?"/g),
          obj: {
            oriString: $fbString.trim(),
            tag: $fbString.match(/^\s+?<(\w+?)\s/)[1]
          }
        };
      })($noscriptEle.firstChild.data);

      for (var i = _allAttr.arr.length; i;) {
        i--;
        _allAttr._tmpArr = _allAttr.arr[i].match(/(\w+?)="(.+?)"/);
        _allAttr.obj[_allAttr._tmpArr[1]] = _allAttr._tmpArr[2];
      }

      return _allAttr.obj;
    },
    injectInline: function ($src, $specilOption) {
      $src.sourceAttr = {
        link: 'href',
        img: 'src'
      }[$src.tag];
      $src.sourceUrl = $src[$src.sourceAttr];
      $src.ext = $src.sourceUrl.split('.').reverse()[0];

      var _cachedItem = $src.sourceUrl.split('/').reverse()[0];
      var _isSvgType = ('svg' === $src.ext);
      var localData = localStorage.getItem(_cachedItem);

      var injectHTML = function (inlineContent) {
        var div = document.createElement('div');
        div.innerHTML = inlineContent;

        if (document.readyState !== 'loading') {
          var _insertBeforeEle = ($specilOption && $specilOption.insertBefore) || Rplus.ele.body.childNodes[0];
          Rplus.ele.body.insertBefore(div, _insertBeforeEle);
        } else {
          Rplus.ele.head.appendChild(div);
        }
      };

      if (Rplus.hasCache && localData) {
        injectHTML(localData);
      } else if ($specilOption && $specilOption.insertTag) {
        injectHTML($src.oriString);
      } else {
        Rplus.ajaxGet($src.sourceUrl, function (response) {
          var inlineContent = response.data;

          if (!_isSvgType) {
            inlineContent = '<style>' + inlineContent + '</sctyle>';
          }

          localStorage.setItem(_cachedItem, inlineContent);

          if ($specilOption && $specilOption.cacheOnly) {
            return;
          }

          injectHTML(inlineContent);
        });
      }
    }
  };

  var Rplus = window.Rplus || {};

  // init Rplus.ele.body
  Rplus.ready(function () {
    Rplus.ele.body = document.body || document.getElementsByTagName('body')[0];
  });

  // check cache version
  ;(function ($ele, $lsItem) {
    var _latestVersion = $ele.getAttribute('data-' + $lsItem);
    var _cacheVersion = localStorage.getItem($lsItem);
    var _hasCache = (_cacheVersion === _latestVersion);

    if (!_hasCache || '#clear' === location.hash) {
      // forcely clear all localStorage data
      localStorage.clear();
      localStorage.setItem($lsItem, _latestVersion);
    }

    Rplus.hasCache = _hasCache;
  })(document.getElementById('js-version'), 'version');

  // init modernizr class for <html>, from cache or inject script callback
  ;(function ($eles, $lsItem) {
    var htmlClassName = localStorage.getItem($lsItem);

    if (Rplus.hasCache && htmlClassName) {
      // init html class
      $eles.html.className = htmlClassName;
    } else {
      var _injectJsEle = document.createElement('script');

      // save html className into localStorage after script loaded
      _injectJsEle.src = '//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js';
      _injectJsEle.addEventListener('load', function () {
        localStorage.setItem($lsItem, $eles.html.className);
      });

      $eles.head.appendChild(_injectJsEle);
    }
  })(Rplus.ele, 'modernizrAllClass');

  // init main style
  Rplus.injectInline(Rplus.getFBInfo(document.getElementById('js-main-style')), {insertTag: true});

})(window, document);
<|endoftext|>


<commit_before>var Task = Backbone.Model.extend({
	initialize: function() {
		this.expectations = new Expectations();

		this.listenTo(this.expectations, 'all', this.completeIfExpectationsComplete);
	},

	defaults: {
		complete: false,
		title: 'No title',
		taskId: 0
	},

	validate: function(attributes){
	    if(attributes.title === undefined || attributes.taskId === undefined){
	        return "Remember to set a title and an id for your task.";
	    }
    },

	completeExpectation: function(expectation) {
		expectation.save({
			complete: true});

		this.completeIfExpectationsComplete();
	},

	completeIfEmpty: function() {
		this.save({
  			complete: this.isEmpty()
  		});
	},

	completeIfExpectationsComplete: function() {
		var self = this;
		this.save({
  			complete: self.expectationsAreComplete()
  		});
	},

	delete: function() {
		try {
			this.expectations.each((exp) => exp.destroy())
			this.destroy();
		} catch (err) {
			console.log(err);
		};
	},

	deleteExpectation: function(expectation) {
		if (typeof expectation === "number") expectation = this.getExpectation(expectation);
		this.expectations.destroy(expectation);
		this.completeIfEmpty();
	},

	editTitle: function(newTitle) {
		this.save({
			title: newTitle
		});
	},

	expectationIsComplete: function(expectation) {
		return expectation.get('complete');
	},

	expectationsAreComplete: function() {
		var self = this;
		var result = true;

		this.expectations.forEach(function(expectation) {
			if (!self.expectationIsComplete(expectation)) return result = false;
		});
		return result;
	},

	getExpectation: function(index) {
		return this.expectations.at(index);
	},

	isEmpty: function() {
		return !this.expectations.length;
	},

	logTasksAndExp: function() {
		var taskTitle = this.get('title');
		var text = '';
		var lineLength = 'EXPECTATIONS'.length + 10;

		text += ' --- TASK --- \n';
		text += this.get('title') + ' : ';
		if (this.get('complete')) text += 'complete'
		else text += 'todo';
		text += '\n';

		text += '\n';

		text += " --- EXPECTATIONS --- \n";
		this.expectations.each(function(expectation) {
			text += expectation.get('title') + ' : ';
			if (expectation.get('complete')) text += 'complete'
			else text += 'todo';
			text += '\n';
		});

		console.log(text);
	},

  	toggle: function() {
  		this.save({
  			complete: !this.get('complete')
  		});
  	}
});<commit_msg>Fix localStorage adds each task's exps from localStorage on initialize.<commit_after>var Task = Backbone.Model.extend({
	initialize: function() {
		var localExp = this.get('expectations');
		this.expectations = new Expectations();
		if (localExp) localExp.forEach((exp) => this.expectations.add(exp));

		this.listenTo(this.expectations, 'all', this.completeIfExpectationsComplete);
		this.listenTo(this.expectations, 'add', (expectation) => this.save({expectations: this.expectations}));
	},

	defaults: {
		complete: false,
		title: 'No title',
		taskId: 0
	},

	validate: function(attributes){
	    if(attributes.title === undefined || attributes.taskId === undefined){
	        return "Remember to set a title and an id for your task.";
	    }
    },

	completeIfEmpty: function() {
		this.save({
  			complete: this.isEmpty()
  		});
	},

	completeIfExpectationsComplete: function() {
		var self = this;
		this.save({
  			complete: self.expectationsAreComplete()
  		});
	},

	delete: function() {
		try {
			this.expectations.each((exp) => exp.destroy())
			this.destroy();
		} catch (err) {
			console.log(err);
		};
	},

	editTitle: function(newTitle) {
		this.save({
			title: newTitle
		});
	},

	expectationIsComplete: function(expectation) {
		return expectation.get('complete');
	},

	expectationsAreComplete: function() {
		var self = this;
		var result = true;

		this.expectations.forEach(function(expectation) {
			if (!self.expectationIsComplete(expectation)) return result = false;
		});
		return result;
	},

	getExpectation: function(index) {
		return this.expectations.at(index);
	},

	isEmpty: function() {
		return !this.expectations.length;
	},

	logTasksAndExp: function() {
		var taskTitle = this.get('title');
		var text = '';
		var lineLength = 'EXPECTATIONS'.length + 10;

		text += ' --- TASK --- \n';
		text += this.get('title') + ' : ';
		if (this.get('complete')) text += 'complete'
		else text += 'todo';
		text += '\n';

		text += '\n';

		text += " --- EXPECTATIONS --- \n";
		this.expectations.each(function(expectation) {
			text += expectation.get('title') + ' : ';
			if (expectation.get('complete')) text += 'complete'
			else text += 'todo';
			text += '\n';
		});

		console.log(text);
	},

  	toggle: function() {
  		this.save({
  			complete: !this.get('complete')
  		});
  	}
});<|endoftext|>


<commit_before>"use strict";

const uuid = require("uuid").v1,
	path = require("path"),
	config = require(path.join(__dirname, "..", "config.json")),
	cache = require(path.join(__dirname, "cache.js")),
	error = require(path.join(__dirname, "error.js")),
	load = require(path.join(__dirname, "load.js")),
	stores = require(path.join(__dirname, "stores.js")),
	jsonpatch = require("jsonpatch").apply_patch,
	iterate = require(path.join(__dirname, "iterate.js")),
	regex = require(path.join(__dirname, "regex.js")),
	collections = require(path.join(__dirname, "collections.js"));

/**
 * Collection delete handler
 *
 * @method collection_delete
 * @param  {Object} req  Client request
 * @param  {Object} res  Client response
 * @param  {String} user User ID
 * @param  {String} type Collection type
 * @param  {String} key  Record key
 * @return {Undefined}   undefined
 */
function del (req, res, user_id, type, key) {
	collections.remove(user_id + "_" + type);
	stores.get(type).del(key).then(() => {
		res.send(config.instruction.success);
	}, e => {
		error(req, res, e);
	});
}

/**
 * Collection update handler
 *
 * @method collection_update
 * @param  {Object} req  Client request
 * @param  {Object} res  Client response
 * @param  {String} luser User ID
 * @param  {String} type Collection type
 * @param  {String} key  Record key
 * @param  {Object} data Record data
 * @param  {Object} msg  [Optional] Instruction
 * @return {Undefined}   undefined
 */
function update (req, res, luser, type, key, data, msg) {
	collections.remove(luser + "_" + type);
	stores.get(type).set(key, data, false, req.method === "PUT").then(rec => {
		const output = {
			instruction: (msg || config.instruction.success).replace(/\:id/g, rec[0])
		};

		if (!regex.invite.test(req.url)) {
			output.id = rec[0];
		}

		res.send(output);
	}, e => {
		error(req, res, e);
	});
}

/**
 * Collection item handler
 *
 * @method collection_item
 * @param  {Object}   req   Client request
 * @param  {Object}   res   Client response
 * @param  {String}   type  Collection type
 * @param  {Function} fn    [Optional] PATCH/PUT validation
 * @param  {Object}   links [Optional] Hash of links (HATEOAS)
 * @return {Undefined}      undefined
 */
function item (req, res, type, fn, links) {
	const user = req.session.passport.user,
		id = req.body ? req.body[type.replace(regex.trailing_s, "") + "_id"] || req.url.replace(/.*\//, "") : req.url.replace(/.*\//, ""),
		method = req.method,
		admin = req.session.admin === true,
		rec = stores.get(type).get(id, true);

	let data;

	if (!rec || rec.user_id !== user.id && !admin) {
		res.error(404);
	} else if (method === "DELETE") {
		del(req, res, user.id, type, id);
	} else if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
		if (!admin) {
			delete rec.user_id;
		}

		if (links !== undefined) {
			iterate(links, (v, k) => {
				rec[k] = v.replace(/:id/g, id);
			});
		}

		res.send(rec);
	} else {
		if (method === "PATCH") {
			try {
				data = jsonpatch(rec, req.body);
			} catch (e) {
				return res.error(400, e);
			}

			data = load(type, data);
		} else {
			data = load(type, req.body);
		}

		data.user_id = user.id;

		fn(data, e => {
			if (e) {
				res.error(400, e);
			} else {
				update(req, res, user.id, type, id, data);
			}
		}, method);
	}

	return void 0;
}

/**
 * Reads a collection
 *
 * @method read
 * @param  {Object} req  Client request
 * @param  {Object} res  Client response
 * @param  {String} id   User ID
 * @param  {String} type Collection type
 * @return {Undefined}   undefined
 */
function read (req, res, id, type) {
	cache(id, type).then(data => {
		const instruction = config.instruction[type + "_create"];

		res.send(data.length > 0 ? data : instruction ? {instruction: instruction} : data);
	}, e => {
		error(req, res, e);
	});
}

/**
 * Collection handler
 *
 * @method all
 * @param  {Object}   req  Client request
 * @param  {Object}   res  Client response
 * @param  {String}   type Collection type
 * @param  {Function} fn   POST validation
 * @return {Undefined}     undefined
 */
function all (req, res, type, fn) {
	const id = req.session.passport.user.id;

	let data, nid;

	if (req.method === "POST") {
		data = load(type, req.body);
		nid = uuid();
		data.id = nid;
		data.user_id = id;

		fn(data, e => {
			if (e) {
				res.error(400, e);
			} else {
				update(req, res, id, type, nid, data, config.instruction[type + "_new"]);
			}
		});
	} else if (req.session.admin) {
		res.send(stores.get(type).dump());
	} else {
		read(req, res, id, type);
	}
}

module.exports = {
	all: all,
	item: item
};
<commit_msg>Moving content concern into `collection.read()`<commit_after>"use strict";

const uuid = require("uuid").v1,
	path = require("path"),
	config = require(path.join(__dirname, "..", "config.json")),
	cache = require(path.join(__dirname, "cache.js")),
	error = require(path.join(__dirname, "error.js")),
	load = require(path.join(__dirname, "load.js")),
	stores = require(path.join(__dirname, "stores.js")),
	jsonpatch = require("jsonpatch").apply_patch,
	iterate = require(path.join(__dirname, "iterate.js")),
	regex = require(path.join(__dirname, "regex.js")),
	collections = require(path.join(__dirname, "collections.js"));

/**
 * Collection delete handler
 *
 * @method collection_delete
 * @param  {Object} req  Client request
 * @param  {Object} res  Client response
 * @param  {String} user User ID
 * @param  {String} type Collection type
 * @param  {String} key  Record key
 * @return {Undefined}   undefined
 */
function del (req, res, user_id, type, key) {
	collections.remove(user_id + "_" + type);
	stores.get(type).del(key).then(() => {
		res.send(config.instruction.success);
	}, e => {
		error(req, res, e);
	});
}

/**
 * Collection update handler
 *
 * @method collection_update
 * @param  {Object} req  Client request
 * @param  {Object} res  Client response
 * @param  {String} luser User ID
 * @param  {String} type Collection type
 * @param  {String} key  Record key
 * @param  {Object} data Record data
 * @param  {Object} msg  [Optional] Instruction
 * @return {Undefined}   undefined
 */
function update (req, res, luser, type, key, data, msg) {
	collections.remove(luser + "_" + type);
	stores.get(type).set(key, data, false, req.method === "PUT").then(rec => {
		const output = {
			instruction: (msg || config.instruction.success).replace(/\:id/g, rec[0])
		};

		if (!regex.invite.test(req.url)) {
			output.id = rec[0];
		}

		res.send(output);
	}, e => {
		error(req, res, e);
	});
}

/**
 * Collection item handler
 *
 * @method collection_item
 * @param  {Object}   req   Client request
 * @param  {Object}   res   Client response
 * @param  {String}   type  Collection type
 * @param  {Function} fn    [Optional] PATCH/PUT validation
 * @param  {Object}   links [Optional] Hash of links (HATEOAS)
 * @return {Undefined}      undefined
 */
function item (req, res, type, fn, links) {
	const user = req.session.passport.user,
		id = req.body ? req.body[type.replace(regex.trailing_s, "") + "_id"] || req.url.replace(/.*\//, "") : req.url.replace(/.*\//, ""),
		method = req.method,
		admin = req.session.admin === true,
		rec = stores.get(type).get(id, true);

	let data;

	if (!rec || rec.user_id !== user.id && !admin) {
		res.error(404);
	} else if (method === "DELETE") {
		del(req, res, user.id, type, id);
	} else if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
		if (!admin) {
			delete rec.user_id;
		}

		if (links !== undefined) {
			iterate(links, (v, k) => {
				rec[k] = v.replace(/:id/g, id);
			});
		}

		res.send(rec);
	} else {
		if (method === "PATCH") {
			try {
				data = jsonpatch(rec, req.body);
			} catch (e) {
				return res.error(400, e);
			}

			data = load(type, data);
		} else {
			data = load(type, req.body);
		}

		data.user_id = user.id;

		fn(data, e => {
			if (e) {
				res.error(400, e);
			} else {
				update(req, res, user.id, type, id, data);
			}
		}, method);
	}

	return void 0;
}

/**
 * Reads a collection
 *
 * @method read
 * @param  {Object} req  Client request
 * @param  {Object} res  Client response
 * @param  {String} id   User ID
 * @param  {String} type Collection type
 * @return {Undefined}   undefined
 */
function read (req, res, id, type) {
	cache(id, type).then(data => {
		const instruction = config.instruction[type + "_create"];

		res.send(data.length > 0 ? data.map(i => {
			delete i.user_id;

			return i;
		}) : instruction ? {instruction: instruction} : data);
	}, e => {
		error(req, res, e);
	});
}

/**
 * Collection handler
 *
 * @method all
 * @param  {Object}   req  Client request
 * @param  {Object}   res  Client response
 * @param  {String}   type Collection type
 * @param  {Function} fn   POST validation
 * @return {Undefined}     undefined
 */
function all (req, res, type, fn) {
	const id = req.session.passport.user.id;

	let data, nid;

	if (req.method === "POST") {
		data = load(type, req.body);
		nid = uuid();
		data.id = nid;
		data.user_id = id;

		fn(data, e => {
			if (e) {
				res.error(400, e);
			} else {
				update(req, res, id, type, nid, data, config.instruction[type + "_new"]);
			}
		});
	} else if (req.session.admin) {
		res.send(stores.get(type).dump());
	} else {
		read(req, res, id, type);
	}
}

module.exports = {
	all: all,
	item: item
};
<|endoftext|>


<commit_before>var firebaseRef = new Firebase("https://boiling-heat-9947.firebaseio.com/");
var media = {};

function init(){
      $(function() {

                //set up webcam feed
                (function() {

                    var video = document.querySelector("#videoElement");

                    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

                    if (navigator.getUserMedia) {
                        navigator.getUserMedia({video: true, audio: true}, handleVideo, videoError);
                    }

                    function handleVideo(stream) {

                        video.src = window.URL.createObjectURL(stream);
                        video.volume = 0;

                    }

                    function videoError(e) {
                        console.log('error, no webcam support found');
                    }

                })();

                //Get and set washingtonPost content
                var washingtonPostData;
                $.ajax({
                 url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('http://feeds.washingtonpost.com/rss/blogs/rss_the-switch'),
                  dataType : 'json',
                  success  : function (data) {
                    console.log(data);
                    washingtonPostData = data;
                    var current = data.responseData.feed.entries[0];
                    $('.washingtonPostArticleTitle').html(current.title);
                    $('.washingtonPostArticleContent').html(current.contentSnippet);
                    $('.washingtonPostArticleAuthor').html(current.author);
                    console.log(current.publishedDate);
                    var res = current.publishedDate.slice(5,25);

                    //September abbreviation is Sept so it adds another character and requires special parsing
                    if (res.slice(3,6) === 'Sep') {
                      var month = 9;
                      var day = res.slice(0,2);
                      var year = res.slice(8,12);
                      var dayTime = res.slice(13,21);
                    }
                    console.log(res);
                    var day = res.slice(0,2);
                    console.log(day);
                    var month = res.slice(3,6);
                    console.log(month);
                    var year = res.slice(7,11);
                    console.log(year);
                    var dayTime = res.slice(12,20);
                    console.log(dayTime);

                  },
                  error : function(data){
                    console.log(data)
                  }
                });
                //get firebase info
                firebaseRef.once('value', function(snapshot) {

                    //use this function if you want to write firebase data easily. Note to add a slide copy object of type you wish to add and place in the order you want. make sure that order is ascending by number
                    /*
                    (function(){
                        firebaseRef.set({
                              1: {
                                    type: "logo",
                                    transitions: {
                                        entry: 'fade',
                                        exit: 'fade'
                                    },
                                    timing: {
                                        slideTime:5000 ,
                                        transitionTime: 2000,
                                    }
                              },
                              2: {
                                  type: "liveVideoOverlay",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      slideTime: 5000,
                                      transitionTime: 2000,
                                      audioFadeTime: 2000,
                                  },
                                  content: {
                                      overlay: 'Customer-driven software
 development for government
 and commercial enterprises.',
                                      overlayColor: '#FAFCFA',
                                  }
                              },
                              3: {
                                  type: "bioPanels",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      openFirstSection: 3000,
                                      openSection: 1000,
                                      sectionTime: 5000,
                                      transitionTime:1000,
                                  },
                                  content: {
                                      content: [{"name":"Jamil Evans","bio":"As President of Evans & Chambers Technology, Jamil Evans is charged with maintaining good relationships with stakeholders in the Federal Government and Intelligence Community. He manages the technical director of the company to ensure that EC's core competencies and innovations are aligned with our customer base. Jamil's uncommon mixture of hard-core technical expertise and strategic relationship management skills drive the company's winning results. Jamil is an expert in service oriented architectures (SOA), secure web service standards definition, and the design and implementation of mission-critical enterprise services and systems. Prior to founding Evans & Chambers Technology, Jamil served as a senior software engineer at Booz Allen Hamilton, providing vendor analysis and software development services to an Intelligence Community customer."},{"name":"Mary Sabatino","bio":"As a Program Manager for Evans & Chambers Technology, Mary Sabatino plays a key role in transforming customer requirements into application design and managing the resources needed to complete projects. She also works closely with development teams to keep the project within scope and to meet production and budget targets. She supports the entire Software Development Life Cycle, including requirements definition, functional design, development, system testing, documentation, training, implementation, maintenance, and customer support. Prior to working with EC, Mary managed projects with L-3 Communications and CACI to support complex information technology projects.  Mary finds it very rewarding to watch a design “come to life” in the form of a working application and her customers praise her dedication, thoroughness, and ability to go above and beyond to ensure that her projects are managed and executed efficiently."},{"name":"Ryan Gross","bio":"Ryan Gross joined Evans & Chambers Technology (EC) in November 2013. Before joining the team, he worked on a commercial project for EC, developing a workflow management tool built on Java using the Grails framework and utilizing a MySQL database. His previous experience in Java development and web development prepared him for his new role at EC as a Software Developer / Engineer I. Ryan enjoys the challenge of developing and enjoys the opportunity to work on projects that provide a positive impact."},{"name":"Vik David","bio":"Vik David is a Software Engineer for Evans & Chambers Technology's and has been working with EC since September 2010. Vik takes a lot of satisfaction in creating something that will help his clients in their jobs. His focus is on front-end technologies and he recently re-wrote and improved a widely-used dashboard report for his client."}],
                                  }
                              },
                              4: {
                                  type: "weather",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      slideTime: 10000,
                                      transitionTime: 2000,
                                  },
                                  content: {
                                      overlayColor: '#FAFCFA',
                                      zip: '20001'
                                  }
                              },
                              5: {
                                  type: "picture",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      slideTime: 10000,
                                      transitionTime: 2000,
                                  },
                                  content: {
                                      caption: "Photo caption goes here"
                                  },
                              }
                            });
                    })(); */

                    //holder array to specify slide order
                    var slideOrder = [];
                    //calculate total slideshow time
                    var totalTime = function() {
                        var time=2000;
                        snapshot.forEach(function(childSnapshot) {

                            var key = childSnapshot.val();
                            slideOrder.push(key.type); //fill in order array

                            if(key.type ==='logo' || key.type==='liveVideoOverlay' || key.type==='picture' || key.type==='staticVideoOverlay'){
                              time+= (key.timing.slideTime + key.timing.transitionTime);
                            } else if (key.type==='bioPanels'){
                              time+= (key.timing.openFirstSection + (key.timing.openSection*6) + (key.timing.sectionTime*6) + key.timing.transitionTime);
                          } else if(key.type==='weather'){ //if type is weather then add time same as others and get weather info from api
                              time+= (key.timing.slideTime + key.timing.transitionTime);
                              $.ajax({
                                 url: 'http://api.openweathermap.org/data/2.5/weather?zip='+ key.content.zip + ',us&units=imperial&APPID=8cbe87b8668498c44b0ade0ce19afd6b',
                                 data: {
                                    format: 'json'
                                 },
                                 error: function() {
                                    console.error("something went wrong with ajax call")
                                 },
                                 dataType: 'jsonp',
                                 success: function(data) {
                                    $('.weather p').html("
" + data.name + "
" + data.main.temp + "º | " +toCamelCase(data.weather[0].description));
                                 },
                                 type: 'GET'
                             });

                          }

                        });
                      return time;
                    };

                    // start interval
                    (function(){
                        setInterval(function(){
                            window[slideOrder[0]](snapshot.val(), slideOrder, 0);
                        }, totalTime());
                    })();

                    window[slideOrder[0]](snapshot.val(), slideOrder, 0); //pass slide1 the firebase data & array

                    preloadMedia(snapshot.val());

                }, function (err) { // throw error if get request fails
                    console.error(err);
                }

                );

            });
}

//Caches photos and videos immediately so media is loaded in time
function preloadMedia(slides){
media["fullScreen"] = [];

  for(i in slides){
    if(slides[i] != undefined){
      if(slides[i].type == "picture"){
        var image = new Image();
        image.src = slides[i].content.imageUrl;
        media["fullScreen"].push(image);
      }
      else if(slides[i].type == "staticVideoOverlay"){
        var video = new Image();
        video.src = slides[i].content.videoUrl;
        media["staticVideoOverlay"] = video;
      }
      else if(slides[i].type == "bioPanels"){
        for(k in slides[i].content.content){
          var imageCover = new Image();
          imageCover.src = slides[i].content.content[k].imageUrlCover;
          media["bioCover"+k] = imageCover;

          var imageContent = new Image();
          imageContent.src = slides[i].content.content[k].imageUrlContent;
          media["bioContent"+k] = imageContent;
        }
      }
    }
  }
}<commit_msg>UP-17 - moved preloadMedia call before load of first slide<commit_after>var firebaseRef = new Firebase("https://boiling-heat-9947.firebaseio.com/");
var media = {};

function init(){
      $(function() {

                //set up webcam feed
                (function() {

                    var video = document.querySelector("#videoElement");

                    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

                    if (navigator.getUserMedia) {
                        navigator.getUserMedia({video: true, audio: true}, handleVideo, videoError);
                    }

                    function handleVideo(stream) {

                        video.src = window.URL.createObjectURL(stream);
                        video.volume = 0;

                    }

                    function videoError(e) {
                        console.log('error, no webcam support found');
                    }

                })();

                //Get and set washingtonPost content
                var washingtonPostData;
                $.ajax({
                 url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('http://feeds.washingtonpost.com/rss/blogs/rss_the-switch'),
                  dataType : 'json',
                  success  : function (data) {
                    console.log(data);
                    washingtonPostData = data;
                    var current = data.responseData.feed.entries[0];
                    $('.washingtonPostArticleTitle').html(current.title);
                    $('.washingtonPostArticleContent').html(current.contentSnippet);
                    $('.washingtonPostArticleAuthor').html(current.author);
                    console.log(current.publishedDate);
                    var res = current.publishedDate.slice(5,25);

                    //September abbreviation is Sept so it adds another character and requires special parsing
                    if (res.slice(3,6) === 'Sep') {
                      var month = 9;
                      var day = res.slice(0,2);
                      var year = res.slice(8,12);
                      var dayTime = res.slice(13,21);
                    }
                    console.log(res);
                    var day = res.slice(0,2);
                    console.log(day);
                    var month = res.slice(3,6);
                    console.log(month);
                    var year = res.slice(7,11);
                    console.log(year);
                    var dayTime = res.slice(12,20);
                    console.log(dayTime);

                  },
                  error : function(data){
                    console.log(data)
                  }
                });
                //get firebase info
                firebaseRef.once('value', function(snapshot) {

                    //use this function if you want to write firebase data easily. Note to add a slide copy object of type you wish to add and place in the order you want. make sure that order is ascending by number
                    /*
                    (function(){
                        firebaseRef.set({
                              1: {
                                    type: "logo",
                                    transitions: {
                                        entry: 'fade',
                                        exit: 'fade'
                                    },
                                    timing: {
                                        slideTime:5000 ,
                                        transitionTime: 2000,
                                    }
                              },
                              2: {
                                  type: "liveVideoOverlay",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      slideTime: 5000,
                                      transitionTime: 2000,
                                      audioFadeTime: 2000,
                                  },
                                  content: {
                                      overlay: 'Customer-driven software
 development for government
 and commercial enterprises.',
                                      overlayColor: '#FAFCFA',
                                  }
                              },
                              3: {
                                  type: "bioPanels",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      openFirstSection: 3000,
                                      openSection: 1000,
                                      sectionTime: 5000,
                                      transitionTime:1000,
                                  },
                                  content: {
                                      content: [{"name":"Jamil Evans","bio":"As President of Evans & Chambers Technology, Jamil Evans is charged with maintaining good relationships with stakeholders in the Federal Government and Intelligence Community. He manages the technical director of the company to ensure that EC's core competencies and innovations are aligned with our customer base. Jamil's uncommon mixture of hard-core technical expertise and strategic relationship management skills drive the company's winning results. Jamil is an expert in service oriented architectures (SOA), secure web service standards definition, and the design and implementation of mission-critical enterprise services and systems. Prior to founding Evans & Chambers Technology, Jamil served as a senior software engineer at Booz Allen Hamilton, providing vendor analysis and software development services to an Intelligence Community customer."},{"name":"Mary Sabatino","bio":"As a Program Manager for Evans & Chambers Technology, Mary Sabatino plays a key role in transforming customer requirements into application design and managing the resources needed to complete projects. She also works closely with development teams to keep the project within scope and to meet production and budget targets. She supports the entire Software Development Life Cycle, including requirements definition, functional design, development, system testing, documentation, training, implementation, maintenance, and customer support. Prior to working with EC, Mary managed projects with L-3 Communications and CACI to support complex information technology projects.  Mary finds it very rewarding to watch a design “come to life” in the form of a working application and her customers praise her dedication, thoroughness, and ability to go above and beyond to ensure that her projects are managed and executed efficiently."},{"name":"Ryan Gross","bio":"Ryan Gross joined Evans & Chambers Technology (EC) in November 2013. Before joining the team, he worked on a commercial project for EC, developing a workflow management tool built on Java using the Grails framework and utilizing a MySQL database. His previous experience in Java development and web development prepared him for his new role at EC as a Software Developer / Engineer I. Ryan enjoys the challenge of developing and enjoys the opportunity to work on projects that provide a positive impact."},{"name":"Vik David","bio":"Vik David is a Software Engineer for Evans & Chambers Technology's and has been working with EC since September 2010. Vik takes a lot of satisfaction in creating something that will help his clients in their jobs. His focus is on front-end technologies and he recently re-wrote and improved a widely-used dashboard report for his client."}],
                                  }
                              },
                              4: {
                                  type: "weather",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      slideTime: 10000,
                                      transitionTime: 2000,
                                  },
                                  content: {
                                      overlayColor: '#FAFCFA',
                                      zip: '20001'
                                  }
                              },
                              5: {
                                  type: "picture",
                                  transitions: {
                                      entry: 'fade',
                                      exit: 'fade'
                                  },
                                  timing: {
                                      slideTime: 10000,
                                      transitionTime: 2000,
                                  },
                                  content: {
                                      caption: "Photo caption goes here"
                                  },
                              }
                            });
                    })(); */

                    //holder array to specify slide order
                    var slideOrder = [];
                    //calculate total slideshow time
                    var totalTime = function() {
                        var time=2000;
                        snapshot.forEach(function(childSnapshot) {

                            var key = childSnapshot.val();
                            slideOrder.push(key.type); //fill in order array

                            if(key.type ==='logo' || key.type==='liveVideoOverlay' || key.type==='picture' || key.type==='staticVideoOverlay'){
                              time+= (key.timing.slideTime + key.timing.transitionTime);
                            } else if (key.type==='bioPanels'){
                              time+= (key.timing.openFirstSection + (key.timing.openSection*6) + (key.timing.sectionTime*6) + key.timing.transitionTime);
                          } else if(key.type==='weather'){ //if type is weather then add time same as others and get weather info from api
                              time+= (key.timing.slideTime + key.timing.transitionTime);
                              $.ajax({
                                 url: 'http://api.openweathermap.org/data/2.5/weather?zip='+ key.content.zip + ',us&units=imperial&APPID=8cbe87b8668498c44b0ade0ce19afd6b',
                                 data: {
                                    format: 'json'
                                 },
                                 error: function() {
                                    console.error("something went wrong with ajax call")
                                 },
                                 dataType: 'jsonp',
                                 success: function(data) {
                                    $('.weather p').html("
" + data.name + "
" + data.main.temp + "º | " +toCamelCase(data.weather[0].description));
                                 },
                                 type: 'GET'
                             });

                          }

                        });
                      return time;
                    };

                    preloadMedia(snapshot.val());

                    // start interval
                    (function(){
                        setInterval(function(){
                            window[slideOrder[0]](snapshot.val(), slideOrder, 0);
                        }, totalTime());
                    })();

                    window[slideOrder[0]](snapshot.val(), slideOrder, 0); //pass slide1 the firebase data & array

                }, function (err) { // throw error if get request fails
                    console.error(err);
                }

                );

            });
}

//Caches photos and videos immediately so media is loaded in time
function preloadMedia(slides){
media["fullScreen"] = [];

  for(i in slides){
    if(slides[i] != undefined){
      if(slides[i].type == "picture"){
        var image = new Image();
        image.src = slides[i].content.imageUrl;
        media["fullScreen"].push(image);
      }
      else if(slides[i].type == "staticVideoOverlay"){
        var video = new Image();
        video.src = slides[i].content.videoUrl;
        media["staticVideoOverlay"] = video;
      }
      else if(slides[i].type == "bioPanels"){
        for(k in slides[i].content.content){
          var imageCover = new Image();
          imageCover.src = slides[i].content.content[k].imageUrlCover;
          media["bioCover"+k] = imageCover;

          var imageContent = new Image();
          imageContent.src = slides[i].content.content[k].imageUrlContent;
          media["bioContent"+k] = imageContent;
        }
      }
    }
  }
}<|endoftext|>


<commit_before>/* global TrelloPowerUp */

var t = TrelloPowerUp.iframe();

// you can access arguments passed to your iframe like so

var resizeOverlayMap = function() {
    //var mapFrameElement = document.getElementById('map-frame');
    //var overlayContentElement = document.getElementById('no-settings-content');
    //var overlayContentHeight = overlayContentElement.offsetHeight;
    //var mapOffsetTop = mapFrameElement.offsetTop;
    //var mapHeight = overlayContentHeight - mapOffsetTop;
    //mapFrameElement.height = mapHeight;
};

var handleWindowResize = function(event) {
    resizeOverlayMap();
};

t.render(function () {
    // make sure your rendering logic lives here, since we will
    // recall this method as the user adds and removes attachments
    // from your section
    var noSettingsSectionElement = document.getElementById('no-settings-section');
    noSettingsSectionElement.style.display='block';
    resizeOverlayMap();

    optimizedResize.addWindowResizeListener(handleWindowResize);

    // close overlay if user clicks outside our content
    document.addEventListener('click', function(event) {
        var eventtarget = event.target;
        if (eventtarget.tagName == 'BODY' || eventtarget.id == 'close-no-settings' || eventtarget.id == 'close-no-settings-button') {
            t.closeOverlay().done();
        }
    });

    // close overlay if user presses escape key
    document.addEventListener('keyup', function(event) {
        if (event.keyCode == 27) {
            t.closeOverlay().done();
        }
    });
});
<commit_msg>update<commit_after>/* global TrelloPowerUp */

var t = TrelloPowerUp.iframe();

// you can access arguments passed to your iframe like so

var resizeOverlayMap = function() {
    //var mapFrameElement = document.getElementById('map-frame');
    //var overlayContentElement = document.getElementById('no-settings-content');
    //var overlayContentHeight = overlayContentElement.offsetHeight;
    //var mapOffsetTop = mapFrameElement.offsetTop;
    //var mapHeight = overlayContentHeight - mapOffsetTop;
    //mapFrameElement.height = mapHeight;
};

var handleWindowResize = function(event) {
    resizeOverlayMap();
};

t.render(function () {
    // make sure your rendering logic lives here, since we will
    // recall this method as the user adds and removes attachments
    // from your section
    var noSettingsSectionElement = document.getElementById('no-settings-section');
    noSettingsSectionElement.style.display='block';
    resizeOverlayMap();

    optimizedResize.addWindowResizeListener(handleWindowResize);

    // close overlay if user clicks outside our content
    document.addEventListener('click', function(event) {
        var eventtarget = event.target;
        if (eventtarget.tagName == 'BODY' || eventtarget.id == 'close-no-settings' || eventtarget.id == 'close-no-settings-button') {
            t.closeOverlay().closePopup().done();
        }
    });

    // close overlay if user presses escape key
    document.addEventListener('keyup', function(event) {
        if (event.keyCode == 27) {
            t.closeOverlay().closePopup().done();
        }
    });
});
<|endoftext|>