<commit_before>'use strict';

/* Controllers */

KMCModule.controller('PlayerListCtrl',
    ['playersData', '$location', '$rootScope', '$scope', '$filter', '$modal', '$timeout', '$log', "$compile","$window",
        function (playersData, $location, $rootScope, $scope, $filter, $modal, $timeout, $log, $compile,$window) {
            $rootScope.lang = 'en-US';
            $scope.search = '';
            $scope.data = playersData.data.objects;
            $scope.currentPage = 1;
            $scope.maxSize = 5;
            $scope.playerVersions = [
                {"label": "1.0", "url": "", "value": "1.0"},
                {"label": "2.0", "url": "", "value": "2.0"},
                {"label": "2.0.1rc2", "url": '', "value": "2.0.1"}
            ]
            $scope.requiredVersion = '201';
            $scope.filterd = $filter('filter')($scope.data, $scope.search);
            $scope.calculateTotalItems = function () {
                $scope.totalItems = $scope.filterd.length;
                return $scope.totalItems;
            };
            $scope.checkVersionNeedsUpgrade = function (itemVersion) {
                itemVersion = itemVersion.replace(/\./g, '');
                if (itemVersion >= $scope.requiredVersion)
                    return false
                else
                    return true
            }
            $scope.calculateTotalItems();
            $scope.title = $filter('i18n')('players list');
            $scope.showSubTitle = true;
            $scope.$watch('search', function (newValue, oldValue) {
                $scope.showSubTitle = newValue;
                if (newValue.length > 0) {
                    $scope.title = $filter('i18n')('search for') + ' "' + newValue + '"';
                }
                else {
                    if (oldValue)
                        $scope.title = $filter('i18n')('players list');
                }

                $timeout(function () {
                    $scope.calculateTotalItems();
                }, 100);
            });
            $scope.oldVersionEditText = $filter('i18n')('Warning this player is out of date. \n' +
                'Saving changes to this player upgrade, some features and \n' +
                'design may be lost. (read more about upgrading players)');
            $scope.goToEditPage = function (item) {
                if (!$scope.checkVersionNeedsUpgrade(item.version)) {
                    return  $window.location.href = '/edit/' + item.id;
                } else {
                    var modal = $modal.open({
                        templateUrl: 'template/dialog/message.html',
                        controller: 'ModalInstanceCtrl',
                        resolve: {
                            settings: function () {
                                return {
                                    'title': 'Edit confirmation',
                                    'message': $scope.oldVersionEditText
                                };
                            }
                        }
                    })
                    modal.result.then(function (result) {
                        if (result) {
                            return  $location.url('edit/' + item.id);
                        }

                    }, function () {
                        return $log.info('edit when outdated modal dismissed at: ' + new Date());
                    });
                }
            };
            $scope.newPlayer = function () {
                $location.path('#/player/new');
            };
            $scope.duplicate = function (item) {
                $scope.data.splice($scope.data.indexOf(item) + 1, 0, item);
            };
            $scope.delete = function (item) {
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function () {
                            return {
                                'title': 'Delete confirmation',
                                'message': 'Are you sure you want to delete the player?'
                            };
                        }
                    }
                });
                modal.result.then(function (result) {
                    if (result)
                        $scope.data.splice($scope.data.indexOf(item), 1);
                }, function () {
                    $log.info('Delete modal dismissed at: ' + new Date());
                });
            };
            $scope.update = function (item) {
                var selectBox = '<model-select label="version" options="playerVersions"/>';
                var text = 'Updating the player -- TEXT MISSING -- please choose a ';
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function () {
                            return {
                                'title': 'Update confirmation',
                                'message': $compile(text + selectBox)($scope)
                            };
                        }
                    }
                });
                modal.result.then(function (result) {
                    if (result) {
                        $log.info('update modal confirmed for item version ' + item.version + 'at: ' + new Date());
                    }

                }, function () {
                    $log.info('update modal dismissed at: ' + new Date());
                });
            };

        }]);<commit_msg>fix relative path for edit page<commit_after>'use strict';

/* Controllers */

KMCModule.controller('PlayerListCtrl',
    ['playersData', '$location', '$rootScope', '$scope', '$filter', '$modal', '$timeout', '$log', "$compile","$window",
        function (playersData, $location, $rootScope, $scope, $filter, $modal, $timeout, $log, $compile,$window) {
            $rootScope.lang = 'en-US';
            $scope.search = '';
            $scope.data = playersData.data.objects;
            $scope.currentPage = 1;
            $scope.maxSize = 5;
            $scope.playerVersions = [
                {"label": "1.0", "url": "", "value": "1.0"},
                {"label": "2.0", "url": "", "value": "2.0"},
                {"label": "2.0.1rc2", "url": '', "value": "2.0.1"}
            ]
            $scope.requiredVersion = '201';
            $scope.filterd = $filter('filter')($scope.data, $scope.search);
            $scope.calculateTotalItems = function () {
                $scope.totalItems = $scope.filterd.length;
                return $scope.totalItems;
            };
            $scope.checkVersionNeedsUpgrade = function (itemVersion) {
                itemVersion = itemVersion.replace(/\./g, '');
                if (itemVersion >= $scope.requiredVersion)
                    return false
                else
                    return true
            }
            $scope.calculateTotalItems();
            $scope.title = $filter('i18n')('players list');
            $scope.showSubTitle = true;
            $scope.$watch('search', function (newValue, oldValue) {
                $scope.showSubTitle = newValue;
                if (newValue.length > 0) {
                    $scope.title = $filter('i18n')('search for') + ' "' + newValue + '"';
                }
                else {
                    if (oldValue)
                        $scope.title = $filter('i18n')('players list');
                }

                $timeout(function () {
                    $scope.calculateTotalItems();
                }, 100);
            });
            $scope.oldVersionEditText = $filter('i18n')('Warning this player is out of date. \n' +
                'Saving changes to this player upgrade, some features and \n' +
                'design may be lost. (read more about upgrading players)');
            $scope.goToEditPage = function (item) {
                if (!$scope.checkVersionNeedsUpgrade(item.version)) {
                    return  $window.location.href = 'edit/' + item.id;
                } else {
                    var modal = $modal.open({
                        templateUrl: 'template/dialog/message.html',
                        controller: 'ModalInstanceCtrl',
                        resolve: {
                            settings: function () {
                                return {
                                    'title': 'Edit confirmation',
                                    'message': $scope.oldVersionEditText
                                };
                            }
                        }
                    })
                    modal.result.then(function (result) {
                        if (result) {
                            return  $location.url('edit/' + item.id);
                        }

                    }, function () {
                        return $log.info('edit when outdated modal dismissed at: ' + new Date());
                    });
                }
            };
            $scope.newPlayer = function () {
                $location.path('#/player/new');
            };
            $scope.duplicate = function (item) {
                $scope.data.splice($scope.data.indexOf(item) + 1, 0, item);
            };
            $scope.delete = function (item) {
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function () {
                            return {
                                'title': 'Delete confirmation',
                                'message': 'Are you sure you want to delete the player?'
                            };
                        }
                    }
                });
                modal.result.then(function (result) {
                    if (result)
                        $scope.data.splice($scope.data.indexOf(item), 1);
                }, function () {
                    $log.info('Delete modal dismissed at: ' + new Date());
                });
            };
            $scope.update = function (item) {
                var selectBox = '<model-select label="version" options="playerVersions"/>';
                var text = 'Updating the player -- TEXT MISSING -- please choose a ';
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function () {
                            return {
                                'title': 'Update confirmation',
                                'message': $compile(text + selectBox)($scope)
                            };
                        }
                    }
                });
                modal.result.then(function (result) {
                    if (result) {
                        $log.info('update modal confirmed for item version ' + item.version + 'at: ' + new Date());
                    }

                }, function () {
                    $log.info('update modal dismissed at: ' + new Date());
                });
            };

        }]);<|endoftext|>


<commit_before>module.exports = {

	process : function(ctx, step, next) {
		if(step.url) {
			ctx.showCategory(step.url);
		}
		else if(step.cat) {
			ctx.showCategoryItems(step.cat);
		}
		setTimeout(next, 1);
	}
}<commit_msg>showPage<commit_after>module.exports = {

	process : function(ctx, step, next) {
		ctx.showItemNSPage(step.page);
		setTimeout(next, 1);
	}
}<|endoftext|>


<commit_before>module.exports = {

	process : function(ctx, step, next) {
		//console.log('In showPage');
		var page = {};
		if(typeof step.page == 'string') {
			page = ctx.pages[step.page];
		}
		else {
			page = step.page;
		}
		ctx.showItemNSPage(page);
		setTimeout(next, 500); //#357
	}
}<commit_msg>#357 showPage set to 510ms<commit_after>module.exports = {

	process : function(ctx, step, next) {
		//console.log('In showPage');
		var page = {};
		if(typeof step.page == 'string') {
			page = ctx.pages[step.page];
		}
		else {
			page = step.page;
		}
		ctx.showItemNSPage(page);
		setTimeout(next, 510); //#357
	}
}<|endoftext|>


<commit_before>/**
 * Just a simple example widget - makes a div with "Hello world!"
 * in a user-defined color (must be a css color - 'red' or 'yellow' or '#FF0000')
 */
(function( $, undefined ) {
    $.KBWidget({
        name: "AssemblyWidget",
        parent: "kbaseWidget",
        version: "1.0.0",
        options: {
            color: "black",
        },

        init: function(options) {
            this._super(options);
            var kb_info = options.kbase_assembly_input;

	    console.log(kb_info)
	    //Get this from options
            var user = options.ar_user
            var token = options.ar_token
            var arURL = options.ar_url
            var arRequest = {
                "data_id": null,
		"kbase_assembly_input": options.kbase_assembly_input,
                "file_sizes": [],
                "filename": [],
                "ids": [],
                "message": null,
                "pipeline": [['spades']],
                "queue": null,
                "single": [[]],
                "pair": [],
                "reference": null,
                "version": "widget"};

            var self = this;
            var data_report = $('
')
		.append('
Assembly Service Data Set
');

	    // Parses the AssemblyInput object and displays it in the table
	    var make_data_table = function(info) {
		var tables = $('
')
		if (info.paired_end_libs != undefined) {
		    for (var i = 0; i < info.paired_end_libs.length; i++) {
			var tbl = $('
');
			tbl.append('

Paired-End Files

');
			for (var j = 0; j < 2; j++) {
			    var file_row = '';
			    handle = 'handle_' + String(j+1)
			    var fname = info.paired_end_libs[i][handle].file_name
                            file_row += '
' + fname + '	';
                            file_row += '
'
			    tbl.append(file_row)
			}
			tables.append(tbl)
		    }
		}
		if (info.single_end_libs != undefined) {
		    for (var i = 0; i < info.single_end_libs.length; i++) {
			var tbl = $('
');
			tbl.append('

Single-End File

');
			var file_row = '';
			var fname = info.single_end_libs[i]['handle'].file_name
                        file_row += '
' + fname + '	';
                        file_row += '
'
			tbl.append(file_row)
			tables.append(tbl)
		    }
		}
		if (info.single_end_libs != undefined) {
		    for (var i = 0; i < info.references.length; i++) {
			var tbl = $('
');
			tbl.append('

Reference File

');
			var file_row = '';
			var fname = info.references[i]['handle'].file_name
                        file_row += '
' + fname + '	';
                        file_row += '
'
			tbl.append(file_row)
			tables.append(tbl)
		    }
		}
		return tables;
	    }

	    var dt = make_data_table(kb_info);
	    data_report.append(dt)
            self.$elem.append(data_report);

            var asm_div = $('
');
            var asm_choose = $('Assembly pipeline <select class="form-control" name="assemblers"> \
                                      <option value="sga_preprocess,bhammer,tagdust,spades,sspace">AssemblyRAST Pipeline</option> \
                                      <option value="sga_preprocess,bhammer,tagdust,kiki spades idba">Trifecta Pipeline</option> \
                                      <option value="a6">A6 Pipeline</option> \
                                      <option value="pacbio">PacBio SMRT Pipeline</option> \
                                      <option value="spades">SPAdes Assembler</option> \
                                      <option value="idba">IDBA-UD Assembler</option> \
                                      <option value="kiki">Kiki Assembler</option> \
                                    </select>');
            var asm_desc = $('<input type="text" class="form-control" placeholder="Description">')
            var asm_btn = $('<button class="btn btn-large btn-primary pull-right">Assemble</button>');
            asm_div.append($('<fieldset>
').append(asm_choose, asm_desc, asm_btn));

	    asm_btn.one("click", function() {
                var assembler = asm_choose.find('select option:selected').val();
                var desc = asm_desc.find('input').val();

                arRequest.pipeline = [assembler.split(',')];
                arRequest.message = desc;
                asm_div.find('fieldset').attr('disabled', "true");

                $.ajax({
                    contentType: 'application/json',
                    url: arURL + 'user/' + user + '/job/new/',
                    type: 'post',
                    data: JSON.stringify(arRequest),
                    headers: {Authorization: token},
                    datatype: 'json',
                    success: function(data){
                        console.log(data);
                        job_id = data;
                            // var job_alert = $('
 \
                            //   <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> \
                            //   Success:  Assembly Job ' + data + ' submitted.
');
                            // self.$elem.append(job_alert);
                        var status = 'Submitted';
                        var status_box = make_status_table(job_id, desc, status);
			var kill_div = $('

')
			var kill_btn = $('Terminate')
			kill_btn.one("click", function(){
			    kill_job(job_id, token).done(function(res){
				console.log(res)
				kill_btn.text('Terminating...');
			    })
			})
                        self.$elem.append(status_box);
			kill_div.append(kill_btn);
                        self.$elem.append(kill_div);

                        var update_status = function() {
                            var prom = check_status(job_id);
                            $.when(prom).done(function(stat){
                                status_box.html(make_status_table(job_id, desc, stat));
				status_box.css("border", "none")
                                if (stat.search('Complete') != -1 || stat.search('FAIL') != -1) {
                                    clearInterval(status_updater);
				    kill_div.html("");
                                    if (stat.search('Complete') != -1) {
                                        var report_txt = null;
                                        request_job_report(job_id).done(function(){
                                            get_job_report_txt(job_id).done(function(quast_txt){
                                                var full_link = arURL + '/static/' + user + '/job/' + job_id + '/quast/contig/report.html';
						var full_link_log = arURL + '/static/' + user + '/job/' + job_id + '/' + job_id + '_report.txt';
                                                var formatted = quast_txt.replace(/\n/g, '
')
                                                var formatted2 = formatted.replace(/\s/g, '&nbsp')
                                                var report_div = '
'
                                                    + formatted2 +'
'
						    report_div += 'Full Analysis
'
						    report_div += 'Assembly Log
'
                                                self.$elem.append(report_div);
                                            })
                                        })
                                    }
                                }
                            })
                        };
                        var status_updater = null;
                        status_updater = setInterval(update_status, 5000);
                    },
                    error: function(data){
                        console.log(data);
                    }
                });

            });
            self.$elem.append(asm_div);

            var make_status_table = function(job_id, desc, status) {
		var status_box = $('
')
                    .append('

Job ID	Description	Status

')
                    .append('
' + job_id + '	'+ desc +'	'+ status +'
')
                return status_box;
            };

            var check_status = function(j_id) {
                var prom = $.get(arURL + '/user/' + user + '/job/' + j_id + '/status/')
                return prom;
            }

            var request_job_report = function(job_id) {
                var prom = $.get(arURL + '/static/serve/' + user + '/job/' + job_id + '/?quast')
                return prom;
            }

            var get_job_report_txt = function(job_id) {
                var prom = $.get(arURL + '/static/' + user + '/job/' + job_id + '/quast/contig/report.txt');
                return prom
            }

            var kill_job = function(job_id, token) {
                var prom = $.ajax({
                    contentType: 'application/json',
                    url: arURL + 'user/' + user + '/job/' + job_id + '/kill',
                    type: 'get',
                    headers: {Authorization: token}});
                return prom;
            }

            return this;
        }

    })})( jQuery )

<commit_msg>handle bad asm, log btn, fix desc input<commit_after>/**
 * Just a simple example widget - makes a div with "Hello world!"
 * in a user-defined color (must be a css color - 'red' or 'yellow' or '#FF0000')
 */
(function( $, undefined ) {
    $.KBWidget({
        name: "AssemblyWidget",
        parent: "kbaseWidget",
        version: "1.0.0",
        options: {
            color: "black",
        },

        init: function(options) {
            this._super(options);
            var kb_info = options.kbase_assembly_input;

	    console.log(kb_info)
	    //Get this from options
            var user = options.ar_user
            var token = options.ar_token
            var arURL = options.ar_url
            var arRequest = {
                "data_id": null,
		"kbase_assembly_input": options.kbase_assembly_input,
                "file_sizes": [],
                "filename": [],
                "ids": [],
                "message": null,
                "pipeline": [['spades']],
                "queue": null,
                "single": [[]],
                "pair": [],
                "reference": null,
                "version": "widget"};

            var self = this;
            var data_report = $('
')
		.append('
Assembly Service Data Set
');

	    // Parses the AssemblyInput object and displays it in the table
	    var make_data_table = function(info) {
		var tables = $('
')
		if (info.paired_end_libs != undefined) {
		    for (var i = 0; i < info.paired_end_libs.length; i++) {
			var tbl = $('
');
			tbl.append('

Paired-End Files

');
			for (var j = 0; j < 2; j++) {
			    var file_row = '';
			    handle = 'handle_' + String(j+1)
			    var fname = info.paired_end_libs[i][handle].file_name
                            file_row += '
' + fname + '	';
                            file_row += '
'
			    tbl.append(file_row)
			}
			tables.append(tbl)
		    }
		}
		if (info.single_end_libs != undefined) {
		    for (var i = 0; i < info.single_end_libs.length; i++) {
			var tbl = $('
');
			tbl.append('

Single-End File

');
			var file_row = '';
			var fname = info.single_end_libs[i]['handle'].file_name
                        file_row += '
' + fname + '	';
                        file_row += '
'
			tbl.append(file_row)
			tables.append(tbl)
		    }
		}
		if (info.single_end_libs != undefined) {
		    for (var i = 0; i < info.references.length; i++) {
			var tbl = $('
');
			tbl.append('

Reference File

');
			var file_row = '';
			var fname = info.references[i]['handle'].file_name
                        file_row += '
' + fname + '	';
                        file_row += '
'
			tbl.append(file_row)
			tables.append(tbl)
		    }
		}
		return tables;
	    }

	    var dt = make_data_table(kb_info);
	    data_report.append(dt)
            self.$elem.append(data_report);

            var asm_div = $('
');
            var asm_choose = $('Assembly pipeline <select class="form-control" name="assemblers"> \
                                      <option value="sga_preprocess,bhammer,tagdust,spades,sspace">AssemblyRAST Pipeline</option> \
                                      <option value="sga_preprocess,bhammer,tagdust,kiki spades idba">Trifecta Pipeline</option> \
                                      <option value="a6">A6 Pipeline</option> \
                                      <option value="pacbio">PacBio SMRT Pipeline</option> \
                                      <option value="spades">SPAdes Assembler</option> \
                                      <option value="idba">IDBA-UD Assembler</option> \
                                      <option value="kiki">Kiki Assembler</option> \
                                    </select>');
            var asm_desc = $('<input type="text" class="form-control" style="width:100%" placeholder="Description">')
            var asm_btn = $('<button class="btn btn-large btn-primary pull-right">Assemble</button>');
            asm_div.append($('<fieldset>
').append(asm_choose, asm_desc, asm_btn));

	    asm_btn.one("click", function() {
                var assembler = asm_choose.find('select option:selected').val();
                var desc = asm_desc.find('input').val();

                arRequest.pipeline = [assembler.split(',')];
                arRequest.message = desc;
                asm_div.find('fieldset').attr('disabled', "true");

                $.ajax({
                    contentType: 'application/json',
                    url: arURL + 'user/' + user + '/job/new/',
                    type: 'post',
                    data: JSON.stringify(arRequest),
                    headers: {Authorization: token},
                    datatype: 'json',
                    success: function(data){
                        console.log(data);
                        job_id = data;
                            // var job_alert = $('
 \
                            //   <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> \
                            //   Success:  Assembly Job ' + data + ' submitted.
');
                            // self.$elem.append(job_alert);
                        var status = 'Submitted';
                        var status_box = make_status_table(job_id, desc, status);
			var kill_div = $('

')
			var kill_btn = $('Terminate')
			kill_btn.one("click", function(){
			    kill_job(job_id, token).done(function(res){
				console.log(res)
				kill_btn.text('Terminating...');
			    })
			})
                        self.$elem.append(status_box);
			kill_div.append(kill_btn);
                        self.$elem.append(kill_div);

                        var update_status = function() {
                            var prom = check_status(job_id);
                            $.when(prom).done(function(stat){
                                status_box.html(make_status_table(job_id, desc, stat));
				status_box.css("border", "none")
                                if (stat.search('Complete') != -1 || stat.search('FAIL') != -1) {
                                    clearInterval(status_updater);
				    kill_div.html("");
                                    if (stat.search('Complete') != -1) {
                                        var report_txt = null;
                                        request_job_report(job_id).done(function(){
                                            var report_div = '
'
					    var result_btn_row = $('
')
                                            get_job_report_txt(job_id)
						.done(function(quast_txt){
                                                var full_link = arURL + '/static/' + user + '/job/' + job_id + '/quast/contig/report.html';
                                                var formatted = quast_txt.replace(/\n/g, '
')
                                                var formatted2 = formatted.replace(/\s/g, '&nbsp')
						    report_div += '' + formatted2 +'
'
						    result_btn_row.append('Full Analysis')
                                            }).always(function(){
						var full_link_log = arURL + '/static/' + user + '/job/' + job_id + '/' + job_id + '_report.txt';
						result_btn_row.append('Assembly Log
')
                                                self.$elem.append(report_div);
						self.$elem.append(result_btn_row);
					    })
                                        })
                                    }
                                }
                            })
                        };
                        var status_updater = null;
                        status_updater = setInterval(update_status, 5000);
                    },
                    error: function(data){
                        console.log(data);
                    }
                });

            });
            self.$elem.append(asm_div);

            var make_status_table = function(job_id, desc, status) {
		var status_box = $('
')
                    .append('

Job ID	Description	Status

')
                    .append('
' + job_id + '	'+ desc +'	'+ status +'
')
                return status_box;
            };

            var check_status = function(j_id) {
                var prom = $.get(arURL + '/user/' + user + '/job/' + j_id + '/status/')
                return prom;
            }

            var request_job_report = function(job_id) {
                var prom = $.get(arURL + '/static/serve/' + user + '/job/' + job_id + '/?quast')
                return prom;
            }

            var get_job_report_txt = function(job_id) {
                var prom = $.get(arURL + '/static/' + user + '/job/' + job_id + '/quast/contig/report.txt');
                return prom
            }

            var kill_job = function(job_id, token) {
                var prom = $.ajax({
                    contentType: 'application/json',
                    url: arURL + 'user/' + user + '/job/' + job_id + '/kill',
                    type: 'get',
                    headers: {Authorization: token}});
                return prom;
            }

            return this;
        }

    })})( jQuery )

<|endoftext|>


<commit_before>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var rankModel = process.require("ranks/rankModel.js");
var updateModel = process.require("updates/updateModel.js");

/**
 * BestGuildsCronProcess constructor
 * @constructor
 */
function BestGuildsCronProcess() {
}

BestGuildsCronProcess.prototype.runCron = function () {
    var logger = applicationStorage.logger;
    var config = applicationStorage.config;

    async.forEach(config.progress.raids,function(raid,callback){
        async.waterfall([
            function(callback){
                //Load all guild in progress
                rankModel.getRanking("tier_"+raid.tier+"#"+raid.name,0,500,function(error,ranking){
                    callback(error,ranking);
                });
            },
            function(ranking,callback) {
                async.forEachSeries(ranking,function(guildStr,callback){
                    var guildArray = guildStr.split('#');

                    updateModel.insert("wp_gu", guildArray[0], guildArray[1], guildArray[2], 5, function (error) {
                        logger.info("Insert guild progress %s-%s-%s to update with priority 5", guildArray[0], guildArray[1], guildArray[2]);
                        if(error){
                            logger.error(error.message);
                        }
                        callback(error);
                    });
                },function(error){
                    callback(error);
                });
            }
        ],function(error){
            if (error){
                logger.error(error.message);
            }
            callback();
        });
    },function(error){
        if (error){
            logger.error(error.message);
        }
        process.exit();
    });

};

/**
 * Start BestGuildsCronProcess
 * @param callback
 */
BestGuildsCronProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting BestGuildsCronProcess");
    this.runCron();
    callback();
};

module.exports = BestGuildsCronProcess;<commit_msg>Add 1500 guilds to update in best guild<commit_after>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var rankModel = process.require("ranks/rankModel.js");
var updateModel = process.require("updates/updateModel.js");

/**
 * BestGuildsCronProcess constructor
 * @constructor
 */
function BestGuildsCronProcess() {
}

BestGuildsCronProcess.prototype.runCron = function () {
    var logger = applicationStorage.logger;
    var config = applicationStorage.config;

    async.forEach(config.progress.raids,function(raid,callback){
        async.waterfall([
            function(callback){
                //Load all guild in progress
                rankModel.getRanking("tier_"+raid.tier+"#"+raid.name,0,1500,function(error,ranking){
                    callback(error,ranking);
                });
            },
            function(ranking,callback) {
                async.forEachSeries(ranking,function(guildStr,callback){
                    var guildArray = guildStr.split('#');

                    updateModel.insert("wp_gu", guildArray[0], guildArray[1], guildArray[2], 5, function (error) {
                        logger.info("Insert guild progress %s-%s-%s to update with priority 5", guildArray[0], guildArray[1], guildArray[2]);
                        if(error){
                            logger.error(error.message);
                        }
                        callback(error);
                    });
                },function(error){
                    callback(error);
                });
            }
        ],function(error){
            if (error){
                logger.error(error.message);
            }
            callback();
        });
    },function(error){
        if (error){
            logger.error(error.message);
        }
        process.exit();
    });

};

/**
 * Start BestGuildsCronProcess
 * @param callback
 */
BestGuildsCronProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting BestGuildsCronProcess");
    this.runCron();
    callback();
};

module.exports = BestGuildsCronProcess;<|endoftext|>


<commit_before>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var updateModel = process.require("updates/updateModel.js");
var updateService = process.require("updates/updateService.js");
var guildProgressModel = process.require("guildProgress/guildProgressModel.js");
var killModel = process.require("kills/killModel.js");
var rankModel = process.require("ranks/rankModel.js");
var realmModel = process.require("realms/realmModel.js");

/**
 * ProgressUpdateProcess constructor
 * @constructor
 */
function ProgressUpdateProcess() {

}

/**
 * Update Guild Progress
 */
ProgressUpdateProcess.prototype.updateGuildProgress = function () {

    var logger = applicationStorage.logger;
    var config = applicationStorage.config;
    var self = this;

    async.waterfall([
            function (callback) {
                //Get next guild to update
                updateService.getNextUpdate('wp_pu', function (error, guildProgress) {
                    if (guildProgress == null) {
                        //Guild update is empty
                        logger.info("No guild progress to update ... waiting 3 sec");
                        setTimeout(function () {
                            callback(true);
                        }, 3000);
                    } else {
                        logger.info("Update guild process %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                        callback(error, guildProgress);
                    }
                });
            },
            function (guildProgress, callback) {
                var bestKillTimestamps = {all: 0, normal: 0, heroic: 0, mythic: 0};

                async.eachSeries(config.progress.raids, function (raid, callback) {

                    var progress = {normalCount: 0, heroicCount: 0, mythicCount: 0};

                    async.eachSeries(["normal", "heroic", "mythic"], function (difficulty, callback) {
                        progress[difficulty] = {};
                        async.eachSeries(raid.bosses, function (boss, callback) {
                            progress[difficulty][boss] = {timestamps: [], irrelevantTimestamps: []};
                            killModel.aggregateKills(raid.name, difficulty, boss, guildProgress.region, guildProgress.realm, guildProgress.name, function (error, kills) {
                                var mythicNewsProgressTimestamps = [];

                                for (var i = 0; i < kills.length; i++) {

                                    var currentKill = {
                                        timestamp: kills[i]._id.timestamp,
                                        count: kills[i].count,
                                        source: kills[i]._id.source
                                    };
                                    if (i + 1 < kills.length) {
                                        var nextKill = {
                                            timestamp: kills[i + 1]._id.timestamp,
                                            count: kills[i + 1].count,
                                            source: kills[i + 1]._id.source
                                        };
                                        if (currentKill.timestamp + 1000 == nextKill.timestamp && currentKill.source == nextKill.source) {
                                            if (difficulty == "mythic") {
                                                if (currentKill.count + nextKill.count >= 8) {
                                                    if (currentKill.source == "news") {
                                                        mythicNewsProgressTimestamps.push([currentKill.timestamp, nextKill.timestamp]);
                                                    } else {
                                                        progress[difficulty][boss]["timestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                    }
                                                } else {
                                                    if (currentKill.source != "news") {
                                                        progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                    }
                                                }
                                            } else {
                                                if (currentKill.count + nextKill.count >= 8) {
                                                    progress[difficulty][boss]["timestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                } else {
                                                    progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                }
                                            }
                                            //Skip the next
                                            i++;
                                            continue;
                                        }
                                    }

                                    //One timestamp kill
                                    if (difficulty == "mythic") {
                                        if (currentKill.count >= 8) {
                                            if (currentKill.source == "news") {
                                                mythicNewsProgressTimestamps.push([currentKill.timestamp]);
                                            } else {
                                                progress[difficulty][boss]["timestamps"].push([currentKill.timestamp]);
                                            }
                                        } else {
                                            if (currentKill.source != "news") {
                                                progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp]);
                                            }
                                        }
                                    } else {
                                        if (currentKill.count >= 8) {
                                            progress[difficulty][boss]["timestamps"].push([currentKill.timestamp]);
                                        } else {
                                            progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp]);

                                        }
                                    }
                                }

                                /**
                                 * Add news timestamps if not found in progress mythic
                                 */
                                if (difficulty == "mythic" && mythicNewsProgressTimestamps.length > 0) {
                                    var tmp = [];
                                    var k = 0;

                                    for (var j = 0; j < progress[difficulty][boss]["timestamps"].length; j++) {
                                        if (mythicNewsProgressTimestamps[k][0] < progress[difficulty][boss]["timestamps"][j][0]) {
                                            if (mythicNewsProgressTimestamps[k][0] + 60000 >= progress[difficulty][boss]["timestamps"][j][0]) {
                                                tmp.push(progress[difficulty][boss]["timestamps"][j])
                                            } else {
                                                tmp.push(mythicNewsProgressTimestamps[k]);
                                                tmp.push(progress[difficulty][boss]["timestamps"][j])
                                            }
                                            k++;
                                        } else {
                                            tmp.push(progress[difficulty][boss]["timestamps"][j])
                                        }
                                        j++
                                    }

                                    progress[difficulty][boss]["timestamps"] = tmp;
                                }

                                if (progress[difficulty][boss]["timestamps"].length > 0) {
                                    if (progress[difficulty][boss]["timestamps"][0][0] > bestKillTimestamps[difficulty]) {
                                        bestKillTimestamps[difficulty] = progress[difficulty][boss]["timestamps"][0][0];
                                    }
                                    progress[difficulty + "Count"]++;

                                }

                                callback(error);
                            });
                        }, function (error) {
                            callback(error);
                        });
                    }, function (error) {
                        if (error) {
                            return callback(error);
                        }

                        async.series([
                            function (callback) {
                                guildProgressModel.upsertProgress(guildProgress.region, guildProgress.realm, guildProgress.name, raid.tier, raid.name, progress, function (error) {
                                        logger.verbose("Update Progress for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                        callback(error);
                                    }
                                );
                            },
                            function (callback) {
                                if (bestKillTimestamps['mythic'] != 0) {
                                    bestKillTimestamps['all'] = bestKillTimestamps['mythic'];
                                } else if (bestKillTimestamps['heroic'] != 0) {
                                    bestKillTimestamps['all'] = bestKillTimestamps['heroic'];
                                } else if (bestKillTimestamps['normal'] != 0) {
                                    bestKillTimestamps['all'] = bestKillTimestamps['normal'];
                                }

                                if (bestKillTimestamps['all'] != 0) {
                                    var preScore = 0;
                                    if (progress.normalCount && progress.normalCount > 0) {
                                        preScore = progress.normalCount;
                                    }
                                    if (progress.heroicCount && progress.heroicCount > 0) {
                                        preScore = progress.heroicCount * 100;
                                    }
                                    if (progress.mythicCount && progress.mythicCount > 0) {
                                        preScore = progress.mythicCount * 10000;
                                    }

                                    //Calculate the score for redis bestTimestamp - 2Years * score
                                    var score = parseInt(bestKillTimestamps['all'] / 1000, 10) - (3600 * 24 * 365 * 2 * preScore);

                                    async.parallel([

                                        function (callback) {
                                            rankModel.upsert("tier_" + raid.tier + "#" + raid.name, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                logger.verbose("Update World Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                callback(error);
                                            });
                                        },
                                        function (callback) {
                                            rankModel.upsert("tier_" + raid.tier + "#" + raid.name + "#" + guildProgress.region, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                logger.verbose("Update Region Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                callback(error);
                                            });
                                        },
                                        function (callback) {
                                            realmModel.findOne({
                                                region: guildProgress.region,
                                                name: guildProgress.realm
                                            }, {
                                                connected_realms: 1,
                                                "bnet.locale": 1,
                                                "bnet.timezone": 1
                                            }, function (error, realm) {
                                                if (realm && realm.connected_realms && realm.bnet && realm.bnet.locale && realm.bnet.timezone) {
                                                    async.parallel([
                                                        function (callback) {
                                                            rankModel.upsert("tier_" + raid.tier + "#" + raid.name + "#" + guildProgress.region + "#" + realm.connected_realms.join('#'), guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                                logger.verbose("Update Realm Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                                callback(error);
                                                            });
                                                        },
                                                        function (callback) {
                                                            var zoneArray = realm.bnet.timezone.split('/');
                                                            if (zoneArray.length > 0) {
                                                                rankModel.upsert("tier_" + raid.tier + "#" + raid.name + "#" + realm.bnet.locale + "#" + zoneArray[0], guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                                    logger.verbose("Update Locale Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                                    callback(error);
                                                                });
                                                            } else {
                                                                callback(error)
                                                            }
                                                        }
                                                    ], function (error) {
                                                        callback(error)
                                                    });
                                                } else {
                                                    logger.warn("Realm %s-%s not found", guildProgress.region, guildProgress.realm);
                                                    callback(error);
                                                }
                                            });
                                        }
                                    ], function (error) {
                                        callback(error);
                                    });
                                } else {
                                    logger.verbose("No legit kill found for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                    callback();
                                }
                            }
                        ], function (error) {
                            callback(error);
                        });

                    });
                }, function (error) {
                    callback(error);
                });

            }
        ],
        function (error) {
            if (error && error !== true) {
                logger.error(error.message);
            }
            self.updateGuildProgress();
        }
    )

};

/**
 * Start ProgressUpdateProcess
 * @param callback
 */
ProgressUpdateProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting ProgressUpdateProcess");
    this.updateGuildProgress();
    callback();

};

module.exports = ProgressUpdateProcess;
<commit_msg>Fix bug with multiple raid<commit_after>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var updateModel = process.require("updates/updateModel.js");
var updateService = process.require("updates/updateService.js");
var guildProgressModel = process.require("guildProgress/guildProgressModel.js");
var killModel = process.require("kills/killModel.js");
var rankModel = process.require("ranks/rankModel.js");
var realmModel = process.require("realms/realmModel.js");

/**
 * ProgressUpdateProcess constructor
 * @constructor
 */
function ProgressUpdateProcess() {

}

/**
 * Update Guild Progress
 */
ProgressUpdateProcess.prototype.updateGuildProgress = function () {

    var logger = applicationStorage.logger;
    var config = applicationStorage.config;
    var self = this;

    async.waterfall([
            function (callback) {
                //Get next guild to update
                updateService.getNextUpdate('wp_pu', function (error, guildProgress) {
                    if (guildProgress == null) {
                        //Guild update is empty
                        logger.info("No guild progress to update ... waiting 3 sec");
                        setTimeout(function () {
                            callback(true);
                        }, 3000);
                    } else {
                        logger.info("Update guild process %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                        callback(error, guildProgress);
                    }
                });
            },
            function (guildProgress, callback) {

                async.eachSeries(config.progress.raids, function (raid, callback) {
                    var bestKillTimestamps = {all: 0, normal: 0, heroic: 0, mythic: 0};

                    var progress = {normalCount: 0, heroicCount: 0, mythicCount: 0};

                    async.eachSeries(["normal", "heroic", "mythic"], function (difficulty, callback) {
                        progress[difficulty] = {};
                        async.eachSeries(raid.bosses, function (boss, callback) {
                            progress[difficulty][boss] = {timestamps: [], irrelevantTimestamps: []};
                            killModel.aggregateKills(raid.name, difficulty, boss, guildProgress.region, guildProgress.realm, guildProgress.name, function (error, kills) {
                                var mythicNewsProgressTimestamps = [];

                                for (var i = 0; i < kills.length; i++) {

                                    var currentKill = {
                                        timestamp: kills[i]._id.timestamp,
                                        count: kills[i].count,
                                        source: kills[i]._id.source
                                    };
                                    if (i + 1 < kills.length) {
                                        var nextKill = {
                                            timestamp: kills[i + 1]._id.timestamp,
                                            count: kills[i + 1].count,
                                            source: kills[i + 1]._id.source
                                        };
                                        if (currentKill.timestamp + 1000 == nextKill.timestamp && currentKill.source == nextKill.source) {
                                            if (difficulty == "mythic") {
                                                if (currentKill.count + nextKill.count >= 8) {
                                                    if (currentKill.source == "news") {
                                                        mythicNewsProgressTimestamps.push([currentKill.timestamp, nextKill.timestamp]);
                                                    } else {
                                                        progress[difficulty][boss]["timestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                    }
                                                } else {
                                                    if (currentKill.source != "news") {
                                                        progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                    }
                                                }
                                            } else {
                                                if (currentKill.count + nextKill.count >= 8) {
                                                    progress[difficulty][boss]["timestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                } else {
                                                    progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp, nextKill.timestamp]);
                                                }
                                            }
                                            //Skip the next
                                            i++;
                                            continue;
                                        }
                                    }

                                    //One timestamp kill
                                    if (difficulty == "mythic") {
                                        if (currentKill.count >= 8) {
                                            if (currentKill.source == "news") {
                                                mythicNewsProgressTimestamps.push([currentKill.timestamp]);
                                            } else {
                                                progress[difficulty][boss]["timestamps"].push([currentKill.timestamp]);
                                            }
                                        } else {
                                            if (currentKill.source != "news") {
                                                progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp]);
                                            }
                                        }
                                    } else {
                                        if (currentKill.count >= 8) {
                                            progress[difficulty][boss]["timestamps"].push([currentKill.timestamp]);
                                        } else {
                                            progress[difficulty][boss]["irrelevantTimestamps"].push([currentKill.timestamp]);

                                        }
                                    }
                                }

                                /**
                                 * Add news timestamps if not found in progress mythic
                                 */
                                if (difficulty == "mythic" && mythicNewsProgressTimestamps.length > 0) {
                                    var tmp = [];
                                    var k = 0;

                                    for (var j = 0; j < progress[difficulty][boss]["timestamps"].length; j++) {
                                        if (mythicNewsProgressTimestamps[k][0] < progress[difficulty][boss]["timestamps"][j][0]) {
                                            if (mythicNewsProgressTimestamps[k][0] + 60000 >= progress[difficulty][boss]["timestamps"][j][0]) {
                                                tmp.push(progress[difficulty][boss]["timestamps"][j])
                                            } else {
                                                tmp.push(mythicNewsProgressTimestamps[k]);
                                                tmp.push(progress[difficulty][boss]["timestamps"][j])
                                            }
                                            k++;
                                        } else {
                                            tmp.push(progress[difficulty][boss]["timestamps"][j])
                                        }
                                        j++
                                    }

                                    progress[difficulty][boss]["timestamps"] = tmp;
                                }

                                if (progress[difficulty][boss]["timestamps"].length > 0) {
                                    if (progress[difficulty][boss]["timestamps"][0][0] > bestKillTimestamps[difficulty]) {
                                        bestKillTimestamps[difficulty] = progress[difficulty][boss]["timestamps"][0][0];
                                    }
                                    progress[difficulty + "Count"]++;

                                }

                                callback(error);
                            });
                        }, function (error) {
                            callback(error);
                        });
                    }, function (error) {
                        if (error) {
                            return callback(error);
                        }

                        async.series([
                            function (callback) {
                                guildProgressModel.upsertProgress(guildProgress.region, guildProgress.realm, guildProgress.name, raid.tier, raid.name, progress, function (error) {
                                        logger.verbose("Update Progress for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                        callback(error);
                                    }
                                );
                            },
                            function (callback) {
                                if (bestKillTimestamps['mythic'] != 0) {
                                    bestKillTimestamps['all'] = bestKillTimestamps['mythic'];
                                } else if (bestKillTimestamps['heroic'] != 0) {
                                    bestKillTimestamps['all'] = bestKillTimestamps['heroic'];
                                } else if (bestKillTimestamps['normal'] != 0) {
                                    bestKillTimestamps['all'] = bestKillTimestamps['normal'];
                                }

                                if (bestKillTimestamps['all'] != 0) {
                                    var preScore = 0;
                                    if (progress.normalCount && progress.normalCount > 0) {
                                        preScore = progress.normalCount;
                                    }
                                    if (progress.heroicCount && progress.heroicCount > 0) {
                                        preScore = progress.heroicCount * 100;
                                    }
                                    if (progress.mythicCount && progress.mythicCount > 0) {
                                        preScore = progress.mythicCount * 10000;
                                    }

                                    //Calculate the score for redis bestTimestamp - 2Years * score
                                    var score = parseInt(bestKillTimestamps['all'] / 1000, 10) - (3600 * 24 * 365 * 2 * preScore);

                                    async.parallel([

                                        function (callback) {
                                            rankModel.upsert("tier_" + raid.tier + "#" + raid.name, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                logger.verbose("Update World Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                callback(error);
                                            });
                                        },
                                        function (callback) {
                                            rankModel.upsert("tier_" + raid.tier + "#" + raid.name + "#" + guildProgress.region, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                logger.verbose("Update Region Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                callback(error);
                                            });
                                        },
                                        function (callback) {
                                            realmModel.findOne({
                                                region: guildProgress.region,
                                                name: guildProgress.realm
                                            }, {
                                                connected_realms: 1,
                                                "bnet.locale": 1,
                                                "bnet.timezone": 1
                                            }, function (error, realm) {
                                                if (realm && realm.connected_realms && realm.bnet && realm.bnet.locale && realm.bnet.timezone) {
                                                    async.parallel([
                                                        function (callback) {
                                                            rankModel.upsert("tier_" + raid.tier + "#" + raid.name + "#" + guildProgress.region + "#" + realm.connected_realms.join('#'), guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                                logger.verbose("Update Realm Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                                callback(error);
                                                            });
                                                        },
                                                        function (callback) {
                                                            var zoneArray = realm.bnet.timezone.split('/');
                                                            if (zoneArray.length > 0) {
                                                                rankModel.upsert("tier_" + raid.tier + "#" + raid.name + "#" + realm.bnet.locale + "#" + zoneArray[0], guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                                    logger.verbose("Update Locale Rank for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                                                    callback(error);
                                                                });
                                                            } else {
                                                                callback(error)
                                                            }
                                                        }
                                                    ], function (error) {
                                                        callback(error)
                                                    });
                                                } else {
                                                    logger.warn("Realm %s-%s not found", guildProgress.region, guildProgress.realm);
                                                    callback(error);
                                                }
                                            });
                                        }
                                    ], function (error) {
                                        callback(error);
                                    });
                                } else {
                                    logger.verbose("No legit kill found for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                    callback();
                                }
                            }
                        ], function (error) {
                            callback(error);
                        });

                    });
                }, function (error) {
                    callback(error);
                });

            }
        ],
        function (error) {
            if (error && error !== true) {
                logger.error(error.message);
            }
            self.updateGuildProgress();
        }
    )

};

/**
 * Start ProgressUpdateProcess
 * @param callback
 */
ProgressUpdateProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting ProgressUpdateProcess");
    this.updateGuildProgress();
    callback();

};

module.exports = ProgressUpdateProcess;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users'),
	requests = require('../../app/controllers/requests');

module.exports = function(app) {
	// Request Routes
	app.route('/requests')
		.get(requests.list)
		.post(users.requiresLogin, requests.create);

	app.route('/requests/:requestId')
		.get(requests.read)
		.put(users.requiresLogin, requests.hasAuthorization, requests.update)
		.delete(users.requiresLogin, requests.hasAuthorization, requests.delete);

	// Finish by binding the request middleware
	app.param('requestId', requests.requestByID);
};<commit_msg>Added requiresLogin middleware to all back-end routes.<commit_after>'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users'),
	requests = require('../../app/controllers/requests');

module.exports = function(app) {
	// Request Routes
	app.route('/requests')
		.get(users.requiresLogin, requests.list)
		.post(users.requiresLogin, requests.create);

	app.route('/requests/:requestId')
		.get(users.requiresLogin, requests.read)
		.put(users.requiresLogin, requests.update)
		.delete(users.requiresLogin, requests.delete);

	// Finish by binding the request middleware
	app.param('requestId', requests.requestByID);
};<|endoftext|>


<commit_before>/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

// This is mock data used while the front-end is not communicating with the macros
// The data structure is not definitive, and may change to match the final specs

define({

  query: {
    properties: ["doc_title", "age", "country", "job", "other"],

    source: {
      id: "...",
      url: "...",
    },

    hiddenFilters: {},

    filters: [
      {
        property: "country",
        matchAll: true,
        constrains: [
          {operator: "equals", value: "france"},
        ],
      },
    ],

    sort: [ {property: "age", descending: false} ],

    offset: 0,
    limit: 25,

  },

  meta: {

    layouts: ["table", "cards"],
    defaultLayout: "table",

    layoutDescriptors: [
      {
        id: "table",
        name: "Table",
        icon: {iconSetName: 'Font Awesome', cssClass: 'fa fa-table'}
        ,
      },
      {
        id: "cards",
        name: "Cards",
        icon: {iconSetName: 'Font Awesome', cssClass: 'fa fa-th'}
      },
    ],

    propertyDescriptors: [
      {
        id: "doc_title",
        name: "Name",
        type: "string",
        displayer: {
          id: 'link',
          propertyHref: "doc_url",
        },
      },
      {
        id: "age",
        name: "Age",
        type: "number",
        displayer: {
          id: 'number',
        },
      },
      {
        id: "job",
        name: "Job",
        type: "string",
      },
      {
        id: "country",
        name: "Country",
        type: "string",
      },
      {
        id: "other",
        name: "Autre truc",
        type: "string",
        displayer: {
          id: "html",
        },
        sortable: false,
        filterable: false,
      },
    ],

    propertyTypes: [
      {
        id: 'string',
        name: 'String',
        displayer: {
          id: 'text',
        },
        sortable: true,
        filterable: true,
        filter: {
          id: 'text'
        },
      },
      {
        id: 'number',
        name: 'Number',
        displayer: {
          id: 'text',
        },
        sortable: true,
        filterable: true,
        filter: {
          id: 'number'
        },
      },
    ],

    defaultFilter: 'text',

    filters: [
      {
        id: "text",
        operators: [
          { id: "contains", name: "Contains", },
          { id: "equals", name: "Equals", },
          { id: "nequals", name: "Not Equals", },
        ],
      },
      {
        id: "number",
        operators: [
          { id: "equals", name: "=", },
          { id: "nequals", name: "≠", },
          { id: "lower", name: "<", },
          { id: "greater", name: ">", },
        ],
      },
    ],

    defaultDisplayer: 'text',

    displayers: [
      {
        id: "text",
      },
      {
        id: "link",
      },
      {
        id: "html",
      },
    ],

    pagination: {
      maxShownPages: 10,
      pageSizes: [10, 25, 50, 100, 250],
      showNextPrevious: true,
      showFirstLast: false,
      showPageSizeDropdown: false,
    },

  },

  data: {

    count: 545,

    entries: [
      {
        "doc_url": "#link1",
        "doc_name": "Name1",
        "doc_date": "2020/03/27 13:23",
        "doc_title": "Title 1",
        "doc_author": "Author 1",
        "doc_creationDate": "2020/03/27 13:21",
        "doc_creator": "Creator 1",
        "age": 48,
        "job": "Job 1",
        "country": "France",
        "other": "lorem ipsum",
      },
      {
        "doc_url": "#link2",
        "doc_name": "Name2",
        "doc_date": "2020/04/22 14:07",
        "doc_title": "Title 2",
        "doc_author": "Author 2",
        "doc_creationDate": "2020/04/22 14:06",
        "doc_creator": "Creator 2",
        "age": 24,
        "job": "Job 2",
        "country": "France",
        "other": "dorol sit amet",
      },
      {
        "doc_url": "#link3",
        "doc_name": "Name3",
        "doc_date": "2020/03/27 14:34",
        "doc_title": "Title 3",
        "doc_author": "Author 3",
        "doc_creationDate": "2020/03/27 14:34",
        "doc_creator": "Creator 3",
        "age": 12,
        "job": "Job 3",
        "country": "Romania",
        "other": "consequtir",
      },
      {
        "doc_url": "#link4",
        "doc_name": "Name4",
        "doc_date": "2020/03/27 14:34",
        "doc_title": "Title 4",
        "doc_author": "Author 4",
        "doc_creationDate": "2020/03/27 14:34",
        "doc_creator": "Creator 4",
        "age": 52,
        "country": "Romania",
      },
    ],

  },

});<commit_msg>[Misc] Fix comma linting issue in LD mock data<commit_after>/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

// This is mock data used while the front-end is not communicating with the macros
// The data structure is not definitive, and may change to match the final specs

define({

  query: {
    properties: ["doc_title", "age", "country", "job", "other"],

    source: {
      id: "...",
      url: "...",
    },

    hiddenFilters: {},

    filters: [
      {
        property: "country",
        matchAll: true,
        constrains: [
          {operator: "equals", value: "france"},
        ],
      },
    ],

    sort: [ {property: "age", descending: false} ],

    offset: 0,
    limit: 25,

  },

  meta: {

    layouts: ["table", "cards"],
    defaultLayout: "table",

    layoutDescriptors: [
      {
        id: "table",
        name: "Table",
        icon: {iconSetName: 'Font Awesome', cssClass: 'fa fa-table'},
      },
      {
        id: "cards",
        name: "Cards",
        icon: {iconSetName: 'Font Awesome', cssClass: 'fa fa-th'},
      },
    ],

    propertyDescriptors: [
      {
        id: "doc_title",
        name: "Name",
        type: "string",
        displayer: {
          id: 'link',
          propertyHref: "doc_url",
        },
      },
      {
        id: "age",
        name: "Age",
        type: "number",
        displayer: {
          id: 'number',
        },
      },
      {
        id: "job",
        name: "Job",
        type: "string",
      },
      {
        id: "country",
        name: "Country",
        type: "string",
      },
      {
        id: "other",
        name: "Autre truc",
        type: "string",
        displayer: {
          id: "html",
        },
        sortable: false,
        filterable: false,
      },
    ],

    propertyTypes: [
      {
        id: 'string',
        name: 'String',
        displayer: {
          id: 'text',
        },
        sortable: true,
        filterable: true,
        filter: {
          id: 'text'
        },
      },
      {
        id: 'number',
        name: 'Number',
        displayer: {
          id: 'text',
        },
        sortable: true,
        filterable: true,
        filter: {
          id: 'number'
        },
      },
    ],

    defaultFilter: 'text',

    filters: [
      {
        id: "text",
        operators: [
          { id: "contains", name: "Contains", },
          { id: "equals", name: "Equals", },
          { id: "nequals", name: "Not Equals", },
        ],
      },
      {
        id: "number",
        operators: [
          { id: "equals", name: "=", },
          { id: "nequals", name: "≠", },
          { id: "lower", name: "<", },
          { id: "greater", name: ">", },
        ],
      },
    ],

    defaultDisplayer: 'text',

    displayers: [
      {
        id: "text",
      },
      {
        id: "link",
      },
      {
        id: "html",
      },
    ],

    pagination: {
      maxShownPages: 10,
      pageSizes: [10, 25, 50, 100, 250],
      showNextPrevious: true,
      showFirstLast: false,
      showPageSizeDropdown: false,
    },

  },

  data: {

    count: 545,

    entries: [
      {
        "doc_url": "#link1",
        "doc_name": "Name1",
        "doc_date": "2020/03/27 13:23",
        "doc_title": "Title 1",
        "doc_author": "Author 1",
        "doc_creationDate": "2020/03/27 13:21",
        "doc_creator": "Creator 1",
        "age": 48,
        "job": "Job 1",
        "country": "France",
        "other": "lorem ipsum",
      },
      {
        "doc_url": "#link2",
        "doc_name": "Name2",
        "doc_date": "2020/04/22 14:07",
        "doc_title": "Title 2",
        "doc_author": "Author 2",
        "doc_creationDate": "2020/04/22 14:06",
        "doc_creator": "Creator 2",
        "age": 24,
        "job": "Job 2",
        "country": "France",
        "other": "dorol sit amet",
      },
      {
        "doc_url": "#link3",
        "doc_name": "Name3",
        "doc_date": "2020/03/27 14:34",
        "doc_title": "Title 3",
        "doc_author": "Author 3",
        "doc_creationDate": "2020/03/27 14:34",
        "doc_creator": "Creator 3",
        "age": 12,
        "job": "Job 3",
        "country": "Romania",
        "other": "consequtir",
      },
      {
        "doc_url": "#link4",
        "doc_name": "Name4",
        "doc_date": "2020/03/27 14:34",
        "doc_title": "Title 4",
        "doc_author": "Author 4",
        "doc_creationDate": "2020/03/27 14:34",
        "doc_creator": "Creator 4",
        "age": 52,
        "country": "Romania",
      },
    ],

  },

});<|endoftext|>


<commit_before>'use strict';

var angular = require('angular')
  , app = angular.module('mjbondra.components.head.filters', []);

app.filter('formatDescription', [function () {
  return function (description) {
    return description ?
      description.trim().replace(/\r?\n|\r/g, '') :
      '';
  };
}]);

app.filter('formatTitle', [function () {
  return function (title) {
    return title ?
      title + ' | Michael J. Bondra' :
      'Michael J. Bondra';
  };
}]);
<commit_msg>update title filter<commit_after>'use strict';

var angular = require('angular')
  , app = angular.module('mjbondra.components.head.filters', []);

app.filter('formatDescription', [function () {
  return function (description) {
    return description ?
      description.trim().replace(/\r?\n|\r/g, '') :
      '';
  };
}]);

app.filter('formatTitle', ['$location', function ($location) {
  return function (title) {
    var base = 'Michael J. Bondra';
    return title ?
      $location.path() === '/' ?
        base + ' | ' + title :
        title + ' | ' + base:
      base;
  };
}]);
<|endoftext|>


<commit_before>/**
 * Animation Shim
 */
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

/**
 * SVG Animation library
 */
(function(){

	function precise_round(num,decimals){
		return Math.round(num*Math.pow(10,decimals))/Math.pow(10,decimals);
	}

	var backgroundComponent = function(){

		var componentElement = $('.canvas');
		var anims = [];
		var layerOne, layerTwo, snap;

		var detect = function(){
			return $('.homepage').length > 0 && Modernizr.svg;
		};

		var eneable = function(){
			attachEvents();
			console.log('enabled background!');
		};

		/**
		 * Get all paths from a context/layer
		 */
		var getPaths = function(context, layer){
			if(layer){
				return context.select(layer).selectAll('path');
			}

			return context.selectAll('path');
		};

		/**
		 * Event Dispatcher
		 */
		function animationQueue(animations){
			var current = 0;

			var animationCallback = function(){
				if(animations[current + 1]){
					current++;
					animations[current].progress = 0;
					animations[current].current_frame = 0;
					return animations[current].draw();
				}else{
					current = 0;
					animations[current].progress = 0;
					animations[current].current_frame = 0;
					return animations[current].draw();
				}
			};

			$.each(animations, function(index, animation){
				animation.current_frame = 0;
				animation.handler = 0;

				animation.draw = function(){
					animation.progress = animation.current_frame/animation.duration;

					if (animation.progress >= 1) {

						if(animation.endCallback){
							animation.endCallback(animationCallback);
						}else{
							animationCallback();
						}

						window.cancelAnimationFrame(animation.handler);
					}else{
						animation.current_frame++;

						animation.drawCallback && animation.drawCallback(animation.progress);
						animation.handler = window.requestAnimationFrame(animation.draw);
					}

					return true;
				};
			});

			return animations[current].draw();
		};

		/**
		 * Animation constructor
		 */
		function animation(name, duration, draw, end){
			return {
				'name': name,
				'elements': [],
				'current_frame': 0,
				'duration': duration,
				'handler': 0,
				'progress': 0,
				'drawCallback': draw,
				'endCallback': end
			};
		};

		/**
		 * Animation to draw the phone forward
		 */
		var phoneForwardAnimation = new animation('phoneForward', 240, function(progress){
				return $.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', (-1) * Math.floor( (2 * element.length) * (0.5 - progress) ) );
				});
			},function(callback){
				layerOne.attr('display', 'none');
				layerTwo.attr('display', 'block');

				$.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', element.length );
				});

				return callback();
			});

		/**
		 * Animation to draw the monitor dorward
		 */
		var monitorForwardAnimation = new animation('monitorForward', 240, function(progress){
				return $.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', Math.floor( (2 * element.length) * (0.5 - progress) ) );
				});

			}, function(callback){
				layerOne.attr('display', 'block');
				layerTwo.attr('display', 'none');

				$.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', element.length );
				});

				return callback();
			});

				var equation = function(pox){
					return (600 * ( Math.pow(pox, 2) ) - (600 * pox) + 150);
				};

				/**
				 * Forward animation
				 */
				var dn = new animation('2_button', 120, function(progress){
					var pixel_offset = 150;
					var offset;
					var offset2 = Math.floor(0 - (pixel_offset * progress));

					// var bbox = this.elements[0][0].select('path').getBBox();
					// var cx = bbox.x + (bbox.w / 2 );
					// var cy = bbox.y + (bbox.h / 2 );
					// this.elements[0][0] && this.elements[0][0].transform("s" + [(1.5- progress), cx, cy] );

					var els = this.elements[0];
					for( var i = 0; i < els.length; i++ ){
						// console.log(progress);
						offset = equation( (progress * (1/ (i+1)) ) );
						console.log(offset);
						// offset2 = Math.floor(0 - (pixel_offset * progress * (1/i) ));
						els[i].attr({
							transform: "t"+offset+",0"
						});

					}

				}, function(callback){
					return callback();
				});

				/**
				 * Backward animation
				 */
				var dnn = new animation('2_button', 120, function(progress){
					var pixel_offset = 150;
					// var offset = Math.floor( pixel_offset - (pixel_offset * progress) );
					// var offset2 = Math.floor((-pixel_offset) + (pixel_offset * progress));

					// var cx = this.elements[0][0].attr('cx');
					// var cy = this.elements[0][0].attr('cy');

					// this.elements[0][0] && this.elements[0][0].transform("s" + [(progress), cx, cy] );

					var els = this.elements[0];
					for( var i = 0; i < els.length; i++ ){

						// offset2 = Math.floor((-pixel_offset * (1/i)) + (pixel_offset * progress * (1/i)));
						els[i].attr({
							transform: "t"+equation( (progress * (1/(i+1))) )+",0"
						});

					}

					// this.elements[1].attr({
					// 	transform: "t"+offset2+",0"
					// });

				}, function(callback){
					return callback();
				});

		/**
		 * Initialise the component
		 */
		var init = function(){
			detect() && eneable();

			if(!detect())
				return;

			/**
			 * Load the SVG file in
			 */
			snap = Snap("#landing .container");
			Snap.load("/images/test-phone.svg", function (f) {
				layerOne = f.select('#Phone');
				layerTwo = f.select('#PC');

				/**
				 * Get elements and put them in specific animations
				 */
				$.each(getPaths(layerOne), function(index, element){
					var length = element.getTotalLength();

					element.attr('stroke-dasharray', length + ' ' + length);
					element.attr('stroke-dashoffset', length);

					phoneForwardAnimation.elements.push({ 'path': element, 'length': length });
				});

				$.each(getPaths(layerTwo), function(index, element){
					var length = element.getTotalLength();

					element.attr('stroke-dasharray', length + ' ' + length);
					element.attr('stroke-dashoffset', length);

					monitorForwardAnimation.elements.push({ 'path': element, 'length': length });
				});

				var ico = f.selectAll('#header_ico, #line_1_ico, #line_2_ico, #line_3_ico');
				var btn = f.selectAll('#header_btn1, #header_btn2, #line_1_btn, #line_2_btn, #line_3_btn');

				dn.elements.push(btn);
				dn.elements.push(ico);
				dnn.elements.push(btn);
				dnn.elements.push(ico);

				// console.log(ico[0].select('circle').getBBox().x);

				/**
				 * Prepare animations
				 */
				anims.push(phoneForwardAnimation);
				// anims.push(phoneBackwardAnimation);
				anims.push(monitorForwardAnimation);
				// anims.push(monitorBackwardAnimation);

				/**
				 * Start animations
				 */
				var mainAnimation = new animationQueue(anims);
				var contentsAnimation = new animationQueue([dn]);
				snap.append(f);
			});
		};

		var getElement = function(){
			return snap;
		};

		var attachEvents = function(){

		};

		var unbindEvents = function(){

		};

		init();

		return {
			'init': init,
			'detect': detect,
			'eneable': eneable,
			'getElement': getElement,
			'attachEvents': attachEvents,
			'unbindEvents': unbindEvents
		};
	};

	app.register('background', backgroundComponent);
})(jQuery, Modernizr, app);
<commit_msg>turn of Con/Sin based animation ,refactor animation queue to call endCallback after the handler has been removed<commit_after>/**
 * Animation Shim
 */
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

/**
 * SVG Animation library
 */
(function(){

	function precise_round(num,decimals){
		return Math.round(num*Math.pow(10,decimals))/Math.pow(10,decimals);
	}

	var backgroundComponent = function(){

		var componentElement = $('.canvas');
		var anims = [];
		var layerOne, layerTwo, snap;

		var detect = function(){
			return $('.homepage').length > 0 && Modernizr.svg;
		};

		var eneable = function(){
			attachEvents();
			console.log('enabled background!');
		};

		/**
		 * Get all paths from a context/layer
		 */
		var getPaths = function(context, layer){
			if(layer){
				return context.select(layer).selectAll('path');
			}

			return context.selectAll('path');
		};

		/**
		 * Event Dispatcher
		 */
		function animationQueue(animations){
			var current = 0;

			var animationCallback = function(){
				if( animations[current + 1] ){
					current++;
				}else{
					current = 0;
				}

				animations[current].progress = 0;
				animations[current].handler = 0;
				animations[current].current_frame = 0;
				return animations[current].draw();
			};

			$.each(animations, function(index, animation){
				animation.current_frame = 0;
				animation.handler = 0;

				animation.draw = function(){
					animation.progress = animation.current_frame/animation.duration;

					if (animation.progress >= 1) {
						window.cancelAnimationFrame(animation.handler);

						if(animation.endCallback){
							animation.endCallback(animationCallback);
						}else{
							animationCallback();
						}
					}else{
						animation.current_frame++;

						animation.drawCallback && animation.drawCallback(animation.progress);
						animation.handler = window.requestAnimationFrame(animation.draw);
					}

					return true;
				};
			});

			return animations[current].draw();
		};

		/**
		 * Animation constructor
		 */
		function animation(name, duration, draw, end){
			return {
				'name': name,
				'elements': [],
				'current_frame': 0,
				'duration': duration,
				'handler': 0,
				'progress': 0,
				'drawCallback': draw,
				'endCallback': end
			};
		};

		/**
		 * Animation to draw the phone forward
		 */
		var phoneForwardAnimation = new animation('phoneForward', 240, function(progress){
				return $.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', (-1) * Math.floor( (2 * element.length) * (0.5 - progress) ) );
				});
			},function(callback){
				layerOne.attr('display', 'none');
				layerTwo.attr('display', 'block');

				$.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', element.length );
				});

				return callback();
			});

		/**
		 * Animation to draw the monitor dorward
		 */
		var monitorForwardAnimation = new animation('monitorForward', 240, function(progress){
				return $.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', Math.floor( (2 * element.length) * (0.5 - progress) ) );
				});

			}, function(callback){
				layerOne.attr('display', 'block');
				layerTwo.attr('display', 'none');

				$.each(this.elements, function(index, element){
					element.path.attr('stroke-dashoffset', element.length );
				});

				return callback();
			});

		var equation = function(pox, pow){
			var x = (2 * Math.PI) * pox;
			var d = (1 + Math.cos( x ) );
			return d * 15 * pow;
			// return ((600 / pow) * ( Math.pow(pox, 2) ) - ((600 / pow) * pox) + 150);
		};

				/**
				 * Forward animation
				 */
				var dn = new animation('2_button', 240, function(progress){
					var pixel_offset = 0;
					var offset;
					var right_elements = this.elements[0];
					var left_elements = this.elements[1];

					for( var i = 0; i < right_elements.length; i++ ){

						var prog = progress;
						offset = (-1 * pixel_offset) + equation( prog, (i+1) );

						right_elements[i].attr({
							transform: "t"+offset+",0"
						});
					}

					for( var i = 0; i < left_elements.length; i++ ){

						var prog = progress;
						offset = (pixel_offset) + ((-1) * equation( prog, (i+1) ) );

						left_elements[i].attr({
							transform: "t"+offset+",0"
						});
					}

				}, function(callback){
					return callback();
				});

		/**
		 * Initialise the component
		 */
		var init = function(){
			detect() && eneable();

			if(!detect())
				return;

			/**
			 * Load the SVG file in
			 */
			snap = Snap("#landing .container");
			Snap.load("/images/test-phone.svg", function (f) {
				layerOne = f.select('#Phone');
				layerTwo = f.select('#PC');

				/**
				 * Get elements and put them in specific animations
				 */
				$.each(getPaths(layerOne), function(index, element){
					var length = element.getTotalLength();

					element.attr('stroke-dasharray', length + ' ' + length);
					element.attr('stroke-dashoffset', length);

					phoneForwardAnimation.elements.push({ 'path': element, 'length': length });
				});

				$.each(getPaths(layerTwo), function(index, element){
					var length = element.getTotalLength();

					element.attr('stroke-dasharray', length + ' ' + length);
					element.attr('stroke-dashoffset', length);

					monitorForwardAnimation.elements.push({ 'path': element, 'length': length });
				});

				var ico = f.selectAll('#header_ico, #line_1_ico, #line_2_ico, #line_3_ico');
				var btn = f.selectAll('#header_btn1, #header_btn2, #line_1_btn, #line_2_btn, #line_3_btn');

				dn.elements.push(btn);
				dn.elements.push(ico);

				/**
				 * Prepare animations
				 */
				anims.push(phoneForwardAnimation);
				anims.push(monitorForwardAnimation);

				/**
				 * Start animations
				 */
				var mainAnimation = new animationQueue(anims);
				// var contentsAnimation = new animationQueue([dn]);
				snap.append(f);
			});
		};

		var getElement = function(){
			return snap;
		};

		var attachEvents = function(){

		};

		var unbindEvents = function(){

		};

		init();

		return {
			'init': init,
			'detect': detect,
			'eneable': eneable,
			'getElement': getElement,
			'attachEvents': attachEvents,
			'unbindEvents': unbindEvents
		};
	};

	app.register('background', backgroundComponent);
})(jQuery, Modernizr, app);
<|endoftext|>