<commit_before>// The SocialSemanticService wraps the SSS REST API v3.4.0

define(['logger', 'vie', 'underscore', 'voc', 'service/SocialSemanticServiceModel', 'jquery'],
function(Logger, VIE, _, Voc, SSSModel, $) {

// ## VIE.SocialSemanticService(options)
// This is the constructor to instantiate a new service.
// **Parameters**:
// *{object}* **options** Optional set of fields.
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.SocialSemanticService}* : A **new** VIE.SocialSemanticService instance.
// **Example usage**:
//
//     var ssService = new vie.SocialSemanticService({<some-configuration>});
    VIE.prototype.SocialSemanticService = function(options) {
        var defaults = {
            'namespaces' : {
                'sss' : "http://20130930devDays.ll/",
                'evernote' : 'https://www.evernote.com/'
            }
        };
        /* the options are merged with the default options */
        this.options = jQuery.extend(true, defaults, options ? options : {});

        this.vie = null; /* will be set via VIE.use(); */
        /* overwrite options.name if you want to set another name */
        this.name = this.options.name;

        this.user = this.options.user;
        this.userKey = this.options.userKey;

        if ( !this.user || !this.userKey )
            throw Error("No user/userKey given for SocialSemanicService");
    };

    VIE.prototype.SocialSemanticService.prototype = {

        LOG : Logger.get('SocialSemanticService'),
// ### init()
// This method initializes certain properties of the service and is called
// via ```VIE.use()```.
// **Parameters**:
// *nothing*
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.SocialSemanticService}* : The VIE.SocialSemanticService instance itself.
// **Example usage**:
//
//     var ssService = new vie.SocialSemanticService({<some-configuration>});
//     ssService.init();
//
        pendingCalls: {},
        pendingCallsCount : 0,
        init: function() {
            for (var key in this.options.namespaces) {
                var val = this.options.namespaces[key];
                this.vie.namespaces.add(key, val);
            }
            this.hostREST = this.options.hostREST;
            this.hostRESTV2 = this.options.hostRESTV2;
            if( !(this.hostREST && this.hostRESTV2) ) {
                throw new Error("no REST endpoint for SocialSemanticService defined");
            }
        },
        resolve: function(serviceCall, service, resultHandler, errorHandler, params) {
            this.LOG.debug('resolve', this);
            var i = 0;
            var that = this;
            var found;
            this.LOG.debug('resolve', serviceCall, params);
            if( this.pendingCalls[serviceCall] ) {
                if( found = this.findPendingCall(serviceCall, params)) {
                    this.LOG.debug('resolve params found');
                    found.resultHandlers.push(resultHandler);
                    found.errorHandlers.push(errorHandler);
                    return;
                }
            } else {
                this.pendingCalls[serviceCall] = {};
            }
            var p = {
                'params' : _.clone(params),
                'resultHandlers' : [resultHandler],
                'errorHandlers' : [errorHandler]
            };
            var pos = this.pendingCallsCount++;
            this.pendingCalls[serviceCall][pos] = p;
            this.LOG.debug('resolve pos', pos);
            this.send(serviceCall, service, params || {},
                    function(result) {
                        delete that.pendingCalls[serviceCall][pos];
                        that.LOG.debug("resolve resultHandlers", p);
                        _.each(p.resultHandlers, function(f) {
                            f(result);
                        });
                    },
                    function(result) {
                        delete that.pendingCalls[serviceCall][pos];
                        _.each(p.errorHandlers, function(f) {
                            f(result);
                        });
                    });

        },
        findPendingCall: function(serviceCall, params) {
            for( var fp in this.pendingCalls[serviceCall] ) {
                if( _.isEqual(this.pendingCalls[serviceCall][fp].params, params) ) {
                    return this.pendingCalls[serviceCall][fp];
                }
            }
        },
        /* AJAX request wrapper */
        send : function(op, service, par, success, error ){
            this.LOG.debug('par', par);
            var sss = this;
            this.vie.onUrisReady(
                this.user,
                function(userUri) {
                    var data = JSON.stringify(_.extend(par, {
                        'user' : userUri || "mailto:dummyUser",
                        'key' : sss.userKey || "someKey"
                    }));
                    var serviceUrl = sss.hostREST;
                    var serviceHeaders = {};
                    if ( service.reqPath ) {
                        data = '';
                        serviceUrl = sss.hostRESTV2;
                        serviceHeaders = { 'Authorization' : "Bearer " + sss.userKey };
                    }
                    $.ajax({
                        'url' : serviceUrl + ( (service.reqPath) ? service.reqPath : op ) + "/",
                        'type': (service.reqType) ? service.reqType : 'POST',
                        'data' : data,
                        'contentType' : "application/json",
                        'async' : true,
                        'dataType': "application/json",
                        'headers': serviceHeaders,
                        'complete' : function(jqXHR, textStatus) {

                            if( jqXHR.readyState !== 4 || jqXHR.status !== 200){
                                sss.LOG.error("sss json request failed");
                                // XXX This might not be enough for the new API
                                if ( sss.reqPath ) {
                                    if ( error ) error(result);
                                }
                                return;
                            }

                            var result = $.parseJSON(jqXHR.responseText);

                            // XXX This will not work for the new API
                            if( result.error ) {
                                if( error ) error(result);

                                // This could trigger a logout
                                sss.checkErrorAndAct(result);

                                return;
                            }

                            if ( service.reqPath ) {
                              success(result);
                            } else {
                              success(result[op]);
                            }
                        }
                    });
                }
            );
        },

        getService: function(serviceName) {
            if( !SSSModel[serviceName] ) {
                throw new Error(serviceName + ' not found');
            }
            return SSSModel[serviceName];
        },

        decorateResult: function(able, result, service) {
            var sss = this,
                resultSet;
            this.LOG.debug('decorateResult', result, service);
            if( !_.isArray(result[service['resultKey']] )) {
                resultSet = [result[service['resultKey']]];
            } else {
                resultSet = result[service['resultKey']];
            }

            this.LOG.debug('resultSet', resultSet);

            _.each(resultSet, function(item) {
                sss.LOG.debug('item', item);
                // recursion
                if( service['subResults'] ) {
                    _.each(service['subResults'], function(subService) {
                        sss.decorateResult(able, item, subService);
                    });
                }
                if( service['decoration']) {
                    var i = 0, decorator;
                    for ( ; i < service['decoration'].length; i++) {
                        decorator = service['decoration'][i];
                        // invoke decorator with loadable as context on result and result meta data
                        if( !decorator.call(able, item, service['@id'], service['@type'], service['@resourceKey']) ) {
                            return;
                        }
                    }
                }
            });
        },

        invoke: function(able) {
            var params = able.options.data || {};

            var serviceName = able.options.service;
            var sss = this;
            var service = this.getService(serviceName);
            this.LOG.debug("service", service);
            if( service['preparation'] ) {
                _.each(service['preparation'], function(preparator) {
                    preparator.call(sss, params, service);
                });
            }
            this.LOG.debug('params', params);
            this.resolve(serviceName, service,
                function(result) {
                    sss.LOG.debug('result', result);
                    // TODO change to call in context of service, not able
                    sss.decorateResult(able, result, service);
                    // Check if pass through keys are set and pass values
                    // as object keys of second argument
                    if ( _.isArray(service['passThroughKeys']) && service['passThroughKeys'].length > 0 ) {
                        var passThrough = {};
                        _.each(service['passThroughKeys'], function(key) {
                            passThrough[key] = result[key];
                        });

                        able.resolve(result[service['resultKey']], passThrough);
                    } else {
                        able.resolve(result[service['resultKey']]);
                    }
                },
                function(result) {
                    able.reject(able.options);
                    sss.LOG.error('error:', result);
                },
                params
            );
        },

        analyze: function(analyzable) {
            var correct = analyzable instanceof this.vie.Analyzable
            if (!correct) {
                throw new Error("Invalid Analyzable passed");
            }

            this.LOG.debug("SocialSemanticService analyze");
            this.LOG.debug("analyzable",analyzable.options);
            try{
                this.invoke(analyzable);
            }catch(e) {
                this.LOG.error(e);
            }
        },
        load: function(loadable) {
            var correct = loadable instanceof this.vie.Loadable || loadable instanceof this.vie.Analyzable;
            if (!correct) {
                throw new Error("Invalid Loadable passed");
            }

            this.LOG.debug("SocialSemanticService load");
            this.LOG.debug("loadable",loadable.options);
            try{
                this.invoke(loadable);
            } catch(e) {
                this.LOG.error(e);
            }
        },

        save: function(savable) {
            var correct = savable instanceof this.vie.Savable;
            if (!correct) {
                throw "Invalid Savable passed";
            }

            this.LOG.debug("SocialSemanticService save");
            this.LOG.debug("savable.options", savable.options);

            try{
                this.invoke(savable);
            }catch(e) {
                this.LOG.error(e);
            }
        },

        remove: function(removable) {
            var correct = removable instanceof this.vie.Removable;
            if (!correct) {
                throw "Invalid Removable passed";
            }

            this.LOG.debug("SocialSemanticService remove");
            this.LOG.debug("removable.options", removable.options);

            try{
                this.invoke(removable);
                return;
            }catch(e) {
                this.LOG.error(e);
            }
        },

        checkErrorAndAct: function(result) {
            if ( result.error && result.id === 'authOIDCUserInfoRequestFailed' ) {
                var ev = $.Event('bnp:oidcTokenExpired', {});
                $(document).trigger(ev);
            }
        }
    };

    return VIE.prototype.SocialSemanticService;

});

<commit_msg>A fix to allow passing params to API V2.<commit_after>// The SocialSemanticService wraps the SSS REST API v3.4.0

define(['logger', 'vie', 'underscore', 'voc', 'service/SocialSemanticServiceModel', 'jquery'],
function(Logger, VIE, _, Voc, SSSModel, $) {

// ## VIE.SocialSemanticService(options)
// This is the constructor to instantiate a new service.
// **Parameters**:
// *{object}* **options** Optional set of fields.
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.SocialSemanticService}* : A **new** VIE.SocialSemanticService instance.
// **Example usage**:
//
//     var ssService = new vie.SocialSemanticService({<some-configuration>});
    VIE.prototype.SocialSemanticService = function(options) {
        var defaults = {
            'namespaces' : {
                'sss' : "http://20130930devDays.ll/",
                'evernote' : 'https://www.evernote.com/'
            }
        };
        /* the options are merged with the default options */
        this.options = jQuery.extend(true, defaults, options ? options : {});

        this.vie = null; /* will be set via VIE.use(); */
        /* overwrite options.name if you want to set another name */
        this.name = this.options.name;

        this.user = this.options.user;
        this.userKey = this.options.userKey;

        if ( !this.user || !this.userKey )
            throw Error("No user/userKey given for SocialSemanicService");
    };

    VIE.prototype.SocialSemanticService.prototype = {

        LOG : Logger.get('SocialSemanticService'),
// ### init()
// This method initializes certain properties of the service and is called
// via ```VIE.use()```.
// **Parameters**:
// *nothing*
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.SocialSemanticService}* : The VIE.SocialSemanticService instance itself.
// **Example usage**:
//
//     var ssService = new vie.SocialSemanticService({<some-configuration>});
//     ssService.init();
//
        pendingCalls: {},
        pendingCallsCount : 0,
        init: function() {
            for (var key in this.options.namespaces) {
                var val = this.options.namespaces[key];
                this.vie.namespaces.add(key, val);
            }
            this.hostREST = this.options.hostREST;
            this.hostRESTV2 = this.options.hostRESTV2;
            if( !(this.hostREST && this.hostRESTV2) ) {
                throw new Error("no REST endpoint for SocialSemanticService defined");
            }
        },
        resolve: function(serviceCall, service, resultHandler, errorHandler, params) {
            this.LOG.debug('resolve', this);
            var i = 0;
            var that = this;
            var found;
            this.LOG.debug('resolve', serviceCall, params);
            if( this.pendingCalls[serviceCall] ) {
                if( found = this.findPendingCall(serviceCall, params)) {
                    this.LOG.debug('resolve params found');
                    found.resultHandlers.push(resultHandler);
                    found.errorHandlers.push(errorHandler);
                    return;
                }
            } else {
                this.pendingCalls[serviceCall] = {};
            }
            var p = {
                'params' : _.clone(params),
                'resultHandlers' : [resultHandler],
                'errorHandlers' : [errorHandler]
            };
            var pos = this.pendingCallsCount++;
            this.pendingCalls[serviceCall][pos] = p;
            this.LOG.debug('resolve pos', pos);
            this.send(serviceCall, service, params || {},
                    function(result) {
                        delete that.pendingCalls[serviceCall][pos];
                        that.LOG.debug("resolve resultHandlers", p);
                        _.each(p.resultHandlers, function(f) {
                            f(result);
                        });
                    },
                    function(result) {
                        delete that.pendingCalls[serviceCall][pos];
                        _.each(p.errorHandlers, function(f) {
                            f(result);
                        });
                    });

        },
        findPendingCall: function(serviceCall, params) {
            for( var fp in this.pendingCalls[serviceCall] ) {
                if( _.isEqual(this.pendingCalls[serviceCall][fp].params, params) ) {
                    return this.pendingCalls[serviceCall][fp];
                }
            }
        },
        /* AJAX request wrapper */
        send : function(op, service, par, success, error ){
            this.LOG.debug('par', par);
            var sss = this;
            this.vie.onUrisReady(
                this.user,
                function(userUri) {
                    var serviceUrl = sss.hostREST;
                    var serviceHeaders = {};
                    var dataAddition = {
                        'user' : userUri || "mailto:dummyUser",
                        'key' : sss.userKey || "someKey"
                    };
                    if ( service.reqPath ) {
                        serviceUrl = sss.hostRESTV2;
                        serviceHeaders = { 'Authorization' : "Bearer " + sss.userKey };
                        dataAddition = {};
                    }
                    var data = JSON.stringify(_.extend(par, dataAddition));
                    $.ajax({
                        'url' : serviceUrl + ( (service.reqPath) ? service.reqPath : op ) + "/",
                        'type': (service.reqType) ? service.reqType : 'POST',
                        'data' : data,
                        'contentType' : "application/json",
                        'async' : true,
                        'dataType': "application/json",
                        'headers': serviceHeaders,
                        'complete' : function(jqXHR, textStatus) {

                            if( jqXHR.readyState !== 4 || jqXHR.status !== 200){
                                sss.LOG.error("sss json request failed");
                                // XXX This might not be enough for the new API
                                if ( sss.reqPath ) {
                                    if ( error ) error(result);
                                }
                                return;
                            }

                            var result = $.parseJSON(jqXHR.responseText);

                            // XXX This will not work for the new API
                            if( result.error ) {
                                if( error ) error(result);

                                // This could trigger a logout
                                sss.checkErrorAndAct(result);

                                return;
                            }

                            if ( service.reqPath ) {
                              success(result);
                            } else {
                              success(result[op]);
                            }
                        }
                    });
                }
            );
        },

        getService: function(serviceName) {
            if( !SSSModel[serviceName] ) {
                throw new Error(serviceName + ' not found');
            }
            return SSSModel[serviceName];
        },

        decorateResult: function(able, result, service) {
            var sss = this,
                resultSet;
            this.LOG.debug('decorateResult', result, service);
            if( !_.isArray(result[service['resultKey']] )) {
                resultSet = [result[service['resultKey']]];
            } else {
                resultSet = result[service['resultKey']];
            }

            this.LOG.debug('resultSet', resultSet);

            _.each(resultSet, function(item) {
                sss.LOG.debug('item', item);
                // recursion
                if( service['subResults'] ) {
                    _.each(service['subResults'], function(subService) {
                        sss.decorateResult(able, item, subService);
                    });
                }
                if( service['decoration']) {
                    var i = 0, decorator;
                    for ( ; i < service['decoration'].length; i++) {
                        decorator = service['decoration'][i];
                        // invoke decorator with loadable as context on result and result meta data
                        if( !decorator.call(able, item, service['@id'], service['@type'], service['@resourceKey']) ) {
                            return;
                        }
                    }
                }
            });
        },

        invoke: function(able) {
            var params = able.options.data || {};

            var serviceName = able.options.service;
            var sss = this;
            var service = this.getService(serviceName);
            this.LOG.debug("service", service);
            if( service['preparation'] ) {
                _.each(service['preparation'], function(preparator) {
                    preparator.call(sss, params, service);
                });
            }
            this.LOG.debug('params', params);
            this.resolve(serviceName, service,
                function(result) {
                    sss.LOG.debug('result', result);
                    // TODO change to call in context of service, not able
                    sss.decorateResult(able, result, service);
                    // Check if pass through keys are set and pass values
                    // as object keys of second argument
                    if ( _.isArray(service['passThroughKeys']) && service['passThroughKeys'].length > 0 ) {
                        var passThrough = {};
                        _.each(service['passThroughKeys'], function(key) {
                            passThrough[key] = result[key];
                        });

                        able.resolve(result[service['resultKey']], passThrough);
                    } else {
                        able.resolve(result[service['resultKey']]);
                    }
                },
                function(result) {
                    able.reject(able.options);
                    sss.LOG.error('error:', result);
                },
                params
            );
        },

        analyze: function(analyzable) {
            var correct = analyzable instanceof this.vie.Analyzable
            if (!correct) {
                throw new Error("Invalid Analyzable passed");
            }

            this.LOG.debug("SocialSemanticService analyze");
            this.LOG.debug("analyzable",analyzable.options);
            try{
                this.invoke(analyzable);
            }catch(e) {
                this.LOG.error(e);
            }
        },
        load: function(loadable) {
            var correct = loadable instanceof this.vie.Loadable || loadable instanceof this.vie.Analyzable;
            if (!correct) {
                throw new Error("Invalid Loadable passed");
            }

            this.LOG.debug("SocialSemanticService load");
            this.LOG.debug("loadable",loadable.options);
            try{
                this.invoke(loadable);
            } catch(e) {
                this.LOG.error(e);
            }
        },

        save: function(savable) {
            var correct = savable instanceof this.vie.Savable;
            if (!correct) {
                throw "Invalid Savable passed";
            }

            this.LOG.debug("SocialSemanticService save");
            this.LOG.debug("savable.options", savable.options);

            try{
                this.invoke(savable);
            }catch(e) {
                this.LOG.error(e);
            }
        },

        remove: function(removable) {
            var correct = removable instanceof this.vie.Removable;
            if (!correct) {
                throw "Invalid Removable passed";
            }

            this.LOG.debug("SocialSemanticService remove");
            this.LOG.debug("removable.options", removable.options);

            try{
                this.invoke(removable);
                return;
            }catch(e) {
                this.LOG.error(e);
            }
        },

        checkErrorAndAct: function(result) {
            if ( result.error && result.id === 'authOIDCUserInfoRequestFailed' ) {
                var ev = $.Event('bnp:oidcTokenExpired', {});
                $(document).trigger(ev);
            }
        }
    };

    return VIE.prototype.SocialSemanticService;

});

<|endoftext|>


<commit_before>/******************************************
* Officer Modal View
*/
app.Views.ModalOfficerView = app.Views.GenericModalView.extend({

	templateHTML : 'modals/modalOfficer',

	// The DOM events //
	events: function(){
		return _.defaults({
			'submit #formSaveOfficer'     : 'saveOfficer'
		},
			app.Views.GenericModalView.prototype.events
		);
	},

	/** View Initialization
	*/
	initialize : function() {
		var self = this;

		this.modal = $(this.el);

		// Check if it's a create or an update //
		if(_.isUndefined(this.model)){

			this.model = new app.Models.Officer();
			this.render();
		}
		else{
			// Render with loader //
			this.render(true);
			this.model.fetch({silent: true, data : {fields : this.model.fields}}).done(function(){
				self.render();
			});
		}

	},

	/** Display the view
	*/
	render : function(loader) {
		var self = this;

		// Retrieve the template //
		$.get("templates/" + this.templateHTML + ".html", function(templateData){

			var template = _.template(templateData, {
				lang    : app.lang,
				officer : self.model,
				loader  : loader,
				service : (!_.isUndefined(self.options.officersListView) ? self.options.officersListView.options.model : '')
			});

			self.modal.html(template);

			if(!loader){
				// Advance Select List View //
				app.views.advancedSelectBoxOfficerGroupView = new app.Views.AdvancedSelectBoxView({el: $("#officerGroup"), collection: app.Collections.STCGroups.prototype })
				app.views.advancedSelectBoxOfficerGroupView.setSearchParam({ field : 'name', operator : 'ilike', value : 'openstc' }, true);
				app.views.advancedSelectBoxOfficerGroupView.render();

				app.views.advancedSelectBoxOfficerServiceView = new app.Views.AdvancedSelectBoxView({el: $("#officerService"), collection: app.Collections.ClaimersServices.prototype })
				app.views.advancedSelectBoxOfficerServiceView.render();

				app.views.advancedSelectBoxOfficerServicesView = new app.Views.AdvancedSelectBoxView({el: $("#officerOtherServices"), collection: app.Collections.ClaimersServices.prototype })
				app.views.advancedSelectBoxOfficerServicesView.render();
			}

			self.modal.modal('show');
		});

		return this;
	},

	/** Save the model pass in the view
	*/
	saveOfficer: function(e){
		e.preventDefault();

		var self = this;

		// Set the button in loading State //
		$(this.el).find("button[type=submit]").button('loading');

		var params = {
			firstname   : $('#officerFirstname').val(),
			name        : $('#officerName').val(),
			user_email  : $('#officerEmail').val(),
			groups_id   : [[6, 0, [app.views.advancedSelectBoxOfficerGroupView.getSelectedItem()]]],
			service_id  : app.views.advancedSelectBoxOfficerServiceView.getSelectedItem(),

		};

		if(!_.isEmpty(app.views.advancedSelectBoxOfficerServicesView.getSelectedItems())){
			params.service_ids = [[6, 0, app.views.advancedSelectBoxOfficerServicesView.getSelectedItems()]];
		}
		// Set login and password if the user is new //
		if(this.model.isNew()){
			params.login     = $('#officerLogin').val();
			params.password  = $('#officerPassword').val();
		}

		this.model.save(params, {silent: true})
			.done(function(data) {
				self.modal.modal('hide');

				// Create mode //
				if(self.model.isNew()) {
					self.model.setId(data);
					self.model.fetch({silent: true, data : {fields : app.Collections.Officers.prototype.fields} }).done(function(){
						self.options.officersListView.collection.add(self.model);
					})
				// Update mode //
				} else {
					self.model.fetch({ data : {fields : self.model.fields} });
				}
			})
			.fail(function (e) {
				console.log(e);
				alert('impossible de créer l\'utilisateur');
			})
			.always(function () {
				$(self.el).find("button[type=submit]").button('reset');
			});
	}

});<commit_msg>bugfix: added option 'patch=true' when updating a user<commit_after>/******************************************
* Officer Modal View
*/
app.Views.ModalOfficerView = app.Views.GenericModalView.extend({

	templateHTML : 'modals/modalOfficer',

	// The DOM events //
	events: function(){
		return _.defaults({
			'submit #formSaveOfficer'     : 'saveOfficer'
		},
			app.Views.GenericModalView.prototype.events
		);
	},

	/** View Initialization
	*/
	initialize : function() {
		var self = this;

		this.modal = $(this.el);

		// Check if it's a create or an update //
		if(_.isUndefined(this.model)){

			this.model = new app.Models.Officer();
			this.render();
		}
		else{
			// Render with loader //
			this.render(true);
			this.model.fetch({silent: true, data : {fields : this.model.fields}}).done(function(){
				self.render();
			});
		}

	},

	/** Display the view
	*/
	render : function(loader) {
		var self = this;

		// Retrieve the template //
		$.get("templates/" + this.templateHTML + ".html", function(templateData){

			var template = _.template(templateData, {
				lang    : app.lang,
				officer : self.model,
				loader  : loader,
				service : (!_.isUndefined(self.options.officersListView) ? self.options.officersListView.options.model : '')
			});

			self.modal.html(template);

			if(!loader){
				// Advance Select List View //
				app.views.advancedSelectBoxOfficerGroupView = new app.Views.AdvancedSelectBoxView({el: $("#officerGroup"), collection: app.Collections.STCGroups.prototype })
				app.views.advancedSelectBoxOfficerGroupView.setSearchParam({ field : 'name', operator : 'ilike', value : 'openstc' }, true);
				app.views.advancedSelectBoxOfficerGroupView.render();

				app.views.advancedSelectBoxOfficerServiceView = new app.Views.AdvancedSelectBoxView({el: $("#officerService"), collection: app.Collections.ClaimersServices.prototype })
				app.views.advancedSelectBoxOfficerServiceView.render();

				app.views.advancedSelectBoxOfficerServicesView = new app.Views.AdvancedSelectBoxView({el: $("#officerOtherServices"), collection: app.Collections.ClaimersServices.prototype })
				app.views.advancedSelectBoxOfficerServicesView.render();
			}

			self.modal.modal('show');
		});

		return this;
	},

	/** Save the model pass in the view
	*/
	saveOfficer: function(e){
		e.preventDefault();

		var self = this;

		// Set the button in loading State //
		$(this.el).find("button[type=submit]").button('loading');

		var params = {
			firstname   : $('#officerFirstname').val(),
			name        : $('#officerName').val(),
			user_email  : $('#officerEmail').val(),
			groups_id   : [[6, 0, [app.views.advancedSelectBoxOfficerGroupView.getSelectedItem()]]],
			service_id  : app.views.advancedSelectBoxOfficerServiceView.getSelectedItem(),

		};

		if(!_.isEmpty(app.views.advancedSelectBoxOfficerServicesView.getSelectedItems())){
			params.service_ids = [[6, 0, app.views.advancedSelectBoxOfficerServicesView.getSelectedItems()]];
		}
		// Set login and password if the user is new //
		if(this.model.isNew()){
			params.login     = $('#officerLogin').val();
			params.password  = $('#officerPassword').val();
		}

		this.model.save(params, {silent: true, patch: !self.model.isNew()})
			.done(function(data) {
				self.modal.modal('hide');

				// Create mode //
				if(self.model.isNew()) {
					self.model.setId(data);
					self.model.fetch({silent: true, data : {fields : app.Collections.Officers.prototype.fields} }).done(function(){
						self.options.officersListView.collection.add(self.model);
					})
				// Update mode //
				} else {
					self.model.fetch({ data : {fields : self.model.fields} });
				}
			})
			.fail(function (e) {
				console.log(e);
				alert('impossible de créer l\'utilisateur');
			})
			.always(function () {
				$(self.el).find("button[type=submit]").button('reset');
			});
	}

});<|endoftext|>


<commit_before>import App from 'app';

/**
 * Main menu.
 */
export default class MainMenu {
  /**
   * Create menu.
   *
   * @param {Main} context Application instance.
   *
   * @return {Array.<Object>} Menu.
   */
  static menu( context ) {
    const templates = [
      { label: 'App', submenu: [
        { label: 'About Electron Audio Player', command: 'application:about' },
        { label: 'Quit', command: 'application:quit' }
      ] }
    ];

    if( DEBUG ) {
      templates.push( {
        label: 'Debug', submenu: [
          { label: 'Reload', command: 'debug:reload' },
          { label: 'Developer Tools', command: 'debug:dev-tools' }
        ]
      } );
    }

    const keymaps  = MainMenu._keymaps();
    const handlers = MainMenu._handlers( context );

    return templates.map( ( template ) => {
      return {
        label:   template.label,
        submenu: template.submenu.map( ( item ) => {
          return {
            label: item.label,
            accelerator: keymaps[ item.command ],
            click: handlers[ item.command ]
          }
        } )
      }
    } );
  }

  /**
   * Get the keyboard shortcuts maps for OS X.
   *
   * @return {Object} Success is key maps ( Key/Value pare ).
   */
  static _keymaps() {
    switch( process.platform ) {
      case 'darwin':
        return {
          'application:quit': 'command+q',

          'debug:reload':    'command+r',
          'debug:dev-tools': 'command+alt+i'
        };

      case 'win32':
        return {
          'application:quit': 'alt+f4',

          'debug:reload':    'ctrl+r',
          'debug:dev-tools': 'ctrl+alt+i'
        };

      // Otherwise Linux
      default:
        return {
          'application:quit': 'ctrl+q',

          'debug:reload':    'ctrl+r',
          'debug:dev-tools': 'ctrl+alt+i'
        };
    }
  }

  /**
   * Get the handler functions when the menu item is clicked.
   *
   * @param {Main} context Application instance.
   *
   * @return {Object} Menu handler functions ( Key/Value pare ).
   */
  static _handlers( context ) {
    return {
      'application:about': () => { context.windowManager.createAboutWindow(); },
      'application:quit': () => { App.quit(); },

      'debug:reload':    () => { context.windowManager.reload(); },
      'debug:dev-tools': () => { context.windowManager.toggleDevTools(); }
    }
  }
}
<commit_msg>#61 Fix a menu text<commit_after>import App from 'app';

/**
 * Main menu.
 */
export default class MainMenu {
  /**
   * Create menu.
   *
   * @param {Main} context Application instance.
   *
   * @return {Array.<Object>} Menu.
   */
  static menu( context ) {
    const templates = [
      { label: 'App', submenu: [
        { label: 'About Multiple Windows', command: 'application:about' },
        { label: 'Quit', command: 'application:quit' }
      ] }
    ];

    if( DEBUG ) {
      templates.push( {
        label: 'Debug', submenu: [
          { label: 'Reload', command: 'debug:reload' },
          { label: 'Developer Tools', command: 'debug:dev-tools' }
        ]
      } );
    }

    const keymaps  = MainMenu._keymaps();
    const handlers = MainMenu._handlers( context );

    return templates.map( ( template ) => {
      return {
        label:   template.label,
        submenu: template.submenu.map( ( item ) => {
          return {
            label: item.label,
            accelerator: keymaps[ item.command ],
            click: handlers[ item.command ]
          }
        } )
      }
    } );
  }

  /**
   * Get the keyboard shortcuts maps for OS X.
   *
   * @return {Object} Success is key maps ( Key/Value pare ).
   */
  static _keymaps() {
    switch( process.platform ) {
      case 'darwin':
        return {
          'application:quit': 'command+q',

          'debug:reload':    'command+r',
          'debug:dev-tools': 'command+alt+i'
        };

      case 'win32':
        return {
          'application:quit': 'alt+f4',

          'debug:reload':    'ctrl+r',
          'debug:dev-tools': 'ctrl+alt+i'
        };

      // Otherwise Linux
      default:
        return {
          'application:quit': 'ctrl+q',

          'debug:reload':    'ctrl+r',
          'debug:dev-tools': 'ctrl+alt+i'
        };
    }
  }

  /**
   * Get the handler functions when the menu item is clicked.
   *
   * @param {Main} context Application instance.
   *
   * @return {Object} Menu handler functions ( Key/Value pare ).
   */
  static _handlers( context ) {
    return {
      'application:about': () => { context.windowManager.createAboutWindow(); },
      'application:quit': () => { App.quit(); },

      'debug:reload':    () => { context.windowManager.reload(); },
      'debug:dev-tools': () => { context.windowManager.toggleDevTools(); }
    }
  }
}
<|endoftext|>


<commit_before>var fs     = require('fs'),
    nodecr = require('nodecr'),
    Q      = require('q'),
    _      = require('lodash'),
    spawn  = require('child_process').spawn;

nodecr.log = function () {};

Q.nfcall(fs.readFile, 'cache/posts-raw.json').then(function (json) {
    const MINIMUM_WIDTH = 300;

    var posts = JSON.parse(json);
    var postAndPhotos = _(posts).map(function (post) {
        return _.map(post.photos || [], function (photo) {
            return [ post.post_url, photo.original_size, photo.alt_sizes ]
        });
    }).flatten(true).map(function (tuple) {
        var suitablePhoto = _(tuple[2]).sortBy('width').find(function (p) {
            return p.width >= MINIMUM_WIDTH;
        });
        return [ tuple[0], tuple[1], suitablePhoto && suitablePhoto.url ];
    }).filter(function (tuple) {
        return tuple[2];
    }).value();

    function downloadImage (url) {
        var filePath = url.replace(/^http:\/\//, 'cache/');

        if (fs.existsSync(filePath)) {
            process.stderr.write('  exists ' + filePath + '\n');
            return Q(filePath);
        }

        process.stderr.write('download ' + url + ' -> ' + filePath + '\n');

        var q = Q.defer();
        spawn('wget', [ '-nv', '--mirror', '-P', 'cache', url ], { stdio: 'inherit' })
            .on('close', function () { q.resolve(filePath) });
        return q;
    }

    function extractText (filePath) {
        process.stderr.write(' extract ' + filePath + '\n');

        return Q.ninvoke(nodecr, 'process', filePath).then(function (text) {
            return text.replace(/^\s+|\s+$/g, '');
        }).then(function (text) {
            process.stderr.write('    text ' + JSON.stringify(text) + '\n');
            return text;
        }, function (e) {
            process.stderr.write(e + '\n');
        });
    }

    var result = [];

    new function loop () {
        var postAndPhoto = postAndPhotos.shift();
        if (!postAndPhoto) {
            console.log(JSON.stringify(result, null, 4));
            return;
        }

        var postUrl      = postAndPhoto[0],
            originalSize = postAndPhoto[1],
            photoUrl     = postAndPhoto[2];
        Q(photoUrl)
            .then(downloadImage)
            .then(extractText)
            .then(function (text) {
                result.push({
                    text: text,
                    postUrl: postUrl,
                    photo: originalSize,
                });
            })
            .then(loop);
    }
})
<commit_msg>should return promise<commit_after>var fs     = require('fs'),
    nodecr = require('nodecr'),
    Q      = require('q'),
    _      = require('lodash'),
    spawn  = require('child_process').spawn;

nodecr.log = function () {};

Q.nfcall(fs.readFile, 'cache/posts-raw.json').then(function (json) {
    const MINIMUM_WIDTH = 300;

    var posts = JSON.parse(json);
    var postAndPhotos = _(posts).map(function (post) {
        return _.map(post.photos || [], function (photo) {
            return [ post.post_url, photo.original_size, photo.alt_sizes ]
        });
    }).flatten(true).map(function (tuple) {
        var suitablePhoto = _(tuple[2]).sortBy('width').find(function (p) {
            return p.width >= MINIMUM_WIDTH;
        });
        return [ tuple[0], tuple[1], suitablePhoto && suitablePhoto.url ];
    }).filter(function (tuple) {
        return tuple[2];
    }).value();

    function downloadImage (url) {
        var filePath = url.replace(/^http:\/\//, 'cache/');

        if (fs.existsSync(filePath)) {
            process.stderr.write('  exists ' + filePath + '\n');
            return Q(filePath);
        }

        process.stderr.write('download ' + url + ' -> ' + filePath + '\n');

        var q = Q.defer();
        spawn('wget', [ '-nv', '--mirror', '-P', 'cache', url ], { stdio: 'inherit' })
            .on('close', function () { q.resolve(filePath) });
        return q.promise;
    }

    function extractText (filePath) {
        process.stderr.write(' extract ' + filePath + '\n');

        return Q.ninvoke(nodecr, 'process', filePath).then(function (text) {
            return text.replace(/^\s+|\s+$/g, '');
        }).then(function (text) {
            process.stderr.write('    text ' + JSON.stringify(text) + '\n');
            return text;
        }, function (e) {
            process.stderr.write(e + '\n');
        });
    }

    var result = [];

    new function loop () {
        var postAndPhoto = postAndPhotos.shift();
        if (!postAndPhoto) {
            console.log(JSON.stringify(result, null, 4));
            return;
        }

        var postUrl      = postAndPhoto[0],
            originalSize = postAndPhoto[1],
            photoUrl     = postAndPhoto[2];
        Q(photoUrl)
            .then(downloadImage)
            .then(extractText)
            .then(function (text) {
                result.push({
                    text: text,
                    postUrl: postUrl,
                    photo: originalSize,
                });
            })
            .then(loop);
    }
})
<|endoftext|>


<commit_before><commit_msg>csharp: reload files list after closing upload dialog by Close button<commit_after><|endoftext|>


<commit_before>
/* global jQuery, Zepto, Pin */

(function ($) {
    'use strict';

    var defaults = {
        slide:           0,
        delay:           5000,
        preload:         true,
        timer:           true,
        overlay:         false,
        autoplay:        true,
        shuffle:         false,
        fill:            true,
        color:           null,
        align:           'center',
        valign:          'center',
        transition:      'fade',
        transitionDelay: 1000,
        init:  function () {},
        play:  function () {},
        pause: function () {},
        walk:  function () {},
        slides: [
            // {
            //  src:             null,
            //  color:           null,
            //  delay:           null,
            //  align:           null,
            //  valign:          null,
            //  transition:      null,
            //  transitiondelay: null,
            //  fill:            true,
            //  videos:          []
            // }
            // ...
        ]
    };

    var Vegas = function (elmt, options) {
        this.elmt         = elmt;
        this.settings     = $.extend({}, defaults, $.vegas.defaults, options);
        this.slide        = this.settings.slide;
        this.total        = this.settings.slides.length;
        this.noshow       = this.total < 2;
        this.paused       = !this.settings.autoplay || this.noshow;
        this.$elmt        = $(elmt);
        this.$timer       = null;
        this.$overlay     = null;
        this.$slide       = null;
        this.timeout      = null;
        this.transitions  = [];

        this.support = {
            objectFit:  'objectFit'  in document.body.style,
            transition: 'transition' in document.body.style || 'WebkitTransition' in document.body.style,
            video:      $.vegas.isVideoCompatible()
        };

        for (var i = 0; i < document.styleSheets.length; i++) {
            var sheet = document.styleSheets[i],
                rules = sheet.rules ? sheet.rules : sheet.cssRules;

            if (/vegas(\..*?)?(\.min)?\.css$/.test(sheet.href)) {
                for (var j = 0; j < rules.length; j++) {
                    var rule  = rules[j],
                        match = /vegas\-transition\-([a-z0-9]*)/gi.exec(rule.selectorText);

                    if (match && match[1]) {
                        if (this.transitions.indexOf(match[1]) === -1) {
                            this.transitions.push(match[1]);
                        }
                    }
                }
            }
        }

        if (this.settings.shuffle === true) {
            this.shuffle();
        }

        this._init();
    };

    Vegas.prototype = {
        _init: function () {
            var $wrapper,
                $overlay,
                $timer,
                isBody    = this.elmt.tagName === 'BODY',
                timer     = this.settings.timer,
                overlay   = this.settings.overlay;

            // Preloading
            this._preload();

            // Wrapper with content
            if (!isBody) {
                $wrapper = $('
')
                    .css('overflow', this.$elmt.css('overflow'))
                    .css('padding',  this.$elmt.css('padding'));

                // Some browsers don't compute padding shorthand
                if (!this.$elmt.css('padding')) {
                    $wrapper
                        .css('padding-top',    this.$elmt.css('padding-top'))
                        .css('padding-bottom', this.$elmt.css('padding-bottom'))
                        .css('padding-left',   this.$elmt.css('padding-left'))
                        .css('padding-right',  this.$elmt.css('padding-right'));
                }

                $wrapper[0].innerHTML = this.elmt.innerHTML;
                this.elmt.innerHTML = '';
            }

            // Timer
            if (timer && this.support.transition) {
                $timer = $('

');
                this.$timer = $timer;
                this.$elmt.prepend($timer);
            }

            // Overlay
            if (overlay) {
                $overlay = $('
');
                if (typeof overlay === 'string') {
                    $overlay.css('background-image', 'url(' + overlay + ')');
                }
                this.$overlay = $overlay;
                this.$elmt.prepend($overlay);
            }

            // Container
            this.$elmt.addClass('vegas-container');
            if (!isBody) {
                this.$elmt.append($wrapper);
            }

            this.trigger('init');
            this._goto(this.slide);
        },

        _preload: function () {
            var preload = this.settings.preload,
                img,
                i;

            if (preload) {
                for (i = 0; i < this.settings.slides.length; i++) {
                    if (this.settings.slides[i].src) {
                        img = new Image();
                        img.src = this.settings.slides[i].src;
                    }
                }

                // TODO:
                // Preload videos
            }
        },

        _slideShow: function () {
            var self = this;

            if (this.total > 1 && !this.paused && !this.noshow) {
                this.timeout = setTimeout(function () {
                    self.next();
                }, this._options('delay'));
            }
        },

        _timer: function (state) {
            var self = this;

            clearTimeout(this.timeout);

            if (!this.$timer) {
                return;
            }

            this.$timer
                .removeClass('vegas-timer-running')
                    .find('div')
                        .css('transition-duration', '0ms');

            if (this.paused || this.noshow) {
                return;
            }

            if (state) {
                setTimeout(function () {
                   self.$timer
                    .addClass('vegas-timer-running')
                        .find('div')
                            .css('transition-duration', self._options('delay') - 100 + 'ms');
                }, 100);
            }
        },

        _options: function (key, i) {
            if (i === undefined) {
                i = this.slide;
            }

            if (this.settings.slides[i][key] !== undefined) {
                return this.settings.slides[i][key];
            }

            return this.settings[key];
        },

        _goto: function (nb) {
            if (typeof this.settings.slides[nb] === 'undefined') {
                nb = 0;
            }

            this.slide = nb;

            var $slide,
                $slides    = this.$elmt.children('.vegas-slide'),
                total      = $slides.length,
                self       = this,
                src        = this.settings.slides[nb].src,
                videos     = this.settings.slides[nb].video,
                delay      = this._options('delay'),
                duration   = this._options('transitionDelay'),
                align      = this._options('align'),
                valign     = this._options('valign'),
                color      = this._options('color') || this.$elmt.css('background-color'),
                fill       = this._options('fill') ? 'cover' : 'contain',
                transition = this._options('transition'),
                isRandom   = transition === 'random',
                video,
                source,
                img;

            if (isRandom) {
                transition = this.transitions[Math.floor(Math.random() * (this.transitions.length - 1))];
            }

            if (transition !== 'none' && this.transitions.indexOf(transition) < 0) {
                console.error("Vegas: Transition " + transition + " doesn't exist.");
            }

            if (duration > delay) {
                duration = delay;
            }

            if (this.support.video && videos) {
                if (videos instanceof Array === false) {
                    videos = [ videos ];
                }

                video = document.createElement('video');
                video.muted = true;
                video.loop = true;
                video.autoplay = true;

                videos.forEach(function (src) {
                    source = document.createElement('source');
                    source.src = src;
                    video.appendChild(source);
                });

                $slide = $(video)
                    .addClass('vegas-video')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-color', color);

                if (this.support.objectFit) {
                    $slide
                        .css('object-position', align + ' ' + valign)
                        .css('object-fit', fill)
                        .css('width',  '100%')
                        .css('height', '100%');
                } else if (fill === 'contain') {
                    $slide
                        .css('width',  '100%')
                        .css('height', '100%');
                }
            } else {
                img = new Image();
                img.src = src;

                $slide = $('

')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-image',    'url(' + src + ')')
                    .css('background-color',    color)
                    .css('background-position', align + ' ' + valign)
                    .css('background-size',     fill);
            }

            if (!self.support.transition) {
                $slide.css('display', 'none');
            }

            if (total) {
                $slides.eq(total - 1).after($slide);
            } else {
                this.$elmt.prepend($slide);
            }

            $slides
                .css('transition', 'all 0ms')
                .each(function () {
                    this.className  = ' vegas-slide';
                    this.className += ' vegas-transition-' +  transition;
                    this.className += ' vegas-transition-' +  transition + '-in';

                    if (this.tagName === 'VIDEO') {
                        this.className += ' vegas-video';
                    }
                }
            );

            self._timer(false);

            function go () {
                self._timer(true);

                setTimeout(function () {
                    if (self.support.transition) {
                        $slides
                            .css('transition', 'all ' + duration + 'ms')
                            .addClass('vegas-transition-' + transition + '-out');
                    }

                    $slide
                        .css('transition', 'all ' + duration + 'ms')
                        .addClass('vegas-transition-' + transition + '-in');

                    if (!self.support.transition) {
                        $slide.fadeIn(duration);
                    }

                    for (var i = 0; i < $slides.length - 2; i++) {
                         $slides.eq(i).remove();
                    }

                    self.trigger('walk');
                    self._slideShow();
                }, 100);
            }

            if (video) {
                // oncanplay is triggered every time when loop=true
                // so let's start the slide only once
                var played = false;

                video.play();
                video.oncanplay = function () {
                    if (!played) {
                        played = true;
                        go();
                    }
                };
            } else {
                img.onload = go;
            }
        },

        shuffle: function () {
            var temp,
                rand;

            for (var i = this.total - 1; i > 0; i--) {
                rand = Math.floor(Math.random() * (i + 1));
                temp = this.settings.slides[i];
                this.settings.slides[i] = this.settings.slides[rand];
                this.settings.slides[rand] = temp;
            }
        },

        play: function () {
            if (this.paused) {
                this.paused = false;
                this.next();
                this.trigger('play');
            }
        },

        pause: function () {
            this._timer(false);
            this.paused = true;
            this.trigger('pause');
        },

        toggle: function () {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        },

        playing: function () {
            return !this.paused && !this.noshow;
        },

        current: function (advanced) {
            if (advanced) {
                return {
                    slide: this.slide,
                    data:  this.settings.slides[this.slide]
                };
            }
            return this.slide;
        },

        jump: function (nb) {
            if (nb < 0 || nb > this.total - 1 || nb === this.slide) {
                return;
            }

            this.slide = nb;
            this._goto(this.slide);
        },

        next: function () {
            this.slide++;

            if (this.slide >= this.total) {
                this.slide = 0;
            }

            this._goto(this.slide);
        },

        previous: function () {
            this.slide--;

            if (this.slide < 0) {
                this.slide = this.total - 1;
            }

            this._goto(this.slide);
        },

        trigger: function (fn) {
            var params = [];

            if (fn !== 'init') {
                params = [
                    this.slide,
                    this.settings.slides[this.slide]
                ];
            }

            this.$elmt.trigger('vegas' + fn, params);

            if (typeof this.settings[fn] === 'function') {
                this.settings[fn].apply(this.$elmt, params);
            }
        },

        options: function (key, value) {
            var oldSlides = this.settings.slides;

            if (typeof key === 'object') {
                this.settings = $.extend({}, defaults, $.vegas.defaults, key);
            } else if (typeof key === 'string') {
                if (value === undefined) {
                    return this.settings[key];
                }
                this.settings[key] = value;
            } else {
                return this.settings;
            }

            // In case slides have changed
            if (this.settings.slides !== oldSlides) {
                this.total  = this.settings.slides.length;
                this.noshow = this.total < 2;
                this._preload();
            }
        }
    };

    $.fn.vegas = function(options) {
        var args = arguments,
            error = false,
            returns;

        if (options === undefined || typeof options === 'object') {
            return this.each(function () {
                if (!this._vegas) {
                    this._vegas = new Vegas(this, options);
                }
            });
        } else if (typeof options === 'string') {
            this.each(function () {
                var instance = this._vegas;

                if (!instance) {
                    throw new Error('No Vegas applied to this element.');
                }

                if (typeof instance[options] === 'function' && options[0] !== '_') {
                    returns = instance[options].apply(instance, [].slice.call(args, 1));
                } else {
                    error = true;
                }
            });

            if (error) {
                throw new Error('No method "' + options + '" in Vegas.');
            }

            return returns !== undefined ? returns : this;
        }
    };

    $.vegas = {};
    $.vegas.defaults = defaults;

    $.vegas.isVideoCompatible = function () {
        return !('ontouchstart' in window || 'onmsgesturechange' in window);
    };

})(typeof jQuery !== 'undefined' ? jQuery :
   typeof Zepto  !== 'undefined' ? Zepto  :
   typeof Pin    !== 'undefined' ? Pin    : null
);
<commit_msg>Add Video preloading<commit_after>
/* global jQuery, Zepto, Pin */

(function ($) {
    'use strict';

    var defaults = {
        slide:           0,
        delay:           5000,
        preload:         false,
        preloadImage:    false,
        preloadVideo:    false,
        timer:           true,
        overlay:         false,
        autoplay:        true,
        shuffle:         false,
        fill:            true,
        color:           null,
        align:           'center',
        valign:          'center',
        transition:      'fade',
        transitionDelay: 1000,
        init:  function () {},
        play:  function () {},
        pause: function () {},
        walk:  function () {},
        slides: [
            // {
            //  src:             null,
            //  color:           null,
            //  delay:           null,
            //  align:           null,
            //  valign:          null,
            //  transition:      null,
            //  transitiondelay: null,
            //  fill:            true,
            //  videos:          []
            // }
            // ...
        ]
    };

    var videoCache = {};

    var Vegas = function (elmt, options) {
        this.elmt         = elmt;
        this.settings     = $.extend({}, defaults, $.vegas.defaults, options);
        this.slide        = this.settings.slide;
        this.total        = this.settings.slides.length;
        this.noshow       = this.total < 2;
        this.paused       = !this.settings.autoplay || this.noshow;
        this.$elmt        = $(elmt);
        this.$timer       = null;
        this.$overlay     = null;
        this.$slide       = null;
        this.timeout      = null;
        this.transitions  = [];

        this.support = {
            objectFit:  'objectFit'  in document.body.style,
            transition: 'transition' in document.body.style || 'WebkitTransition' in document.body.style,
            video:      $.vegas.isVideoCompatible()
        };

        for (var i = 0; i < document.styleSheets.length; i++) {
            var sheet = document.styleSheets[i],
                rules = sheet.rules ? sheet.rules : sheet.cssRules;

            if (/vegas(\..*?)?(\.min)?\.css$/.test(sheet.href)) {
                for (var j = 0; j < rules.length; j++) {
                    var rule  = rules[j],
                        match = /vegas\-transition\-([a-z0-9]*)/gi.exec(rule.selectorText);

                    if (match && match[1]) {
                        if (this.transitions.indexOf(match[1]) === -1) {
                            this.transitions.push(match[1]);
                        }
                    }
                }
            }
        }

        if (this.settings.shuffle === true) {
            this.shuffle();
        }

        this._init();
    };

    Vegas.prototype = {
        _init: function () {
            var $wrapper,
                $overlay,
                $timer,
                isBody    = this.elmt.tagName === 'BODY',
                timer     = this.settings.timer,
                overlay   = this.settings.overlay;

            // Preloading
            this._preload();

            // Wrapper with content
            if (!isBody) {
                $wrapper = $('
')
                    .css('overflow', this.$elmt.css('overflow'))
                    .css('padding',  this.$elmt.css('padding'));

                // Some browsers don't compute padding shorthand
                if (!this.$elmt.css('padding')) {
                    $wrapper
                        .css('padding-top',    this.$elmt.css('padding-top'))
                        .css('padding-bottom', this.$elmt.css('padding-bottom'))
                        .css('padding-left',   this.$elmt.css('padding-left'))
                        .css('padding-right',  this.$elmt.css('padding-right'));
                }

                $wrapper[0].innerHTML = this.elmt.innerHTML;
                this.elmt.innerHTML = '';
            }

            // Timer
            if (timer && this.support.transition) {
                $timer = $('

');
                this.$timer = $timer;
                this.$elmt.prepend($timer);
            }

            // Overlay
            if (overlay) {
                $overlay = $('
');
                if (typeof overlay === 'string') {
                    $overlay.css('background-image', 'url(' + overlay + ')');
                }
                this.$overlay = $overlay;
                this.$elmt.prepend($overlay);
            }

            // Container
            this.$elmt.addClass('vegas-container');
            if (!isBody) {
                this.$elmt.append($wrapper);
            }

            this.trigger('init');
            this._goto(this.slide);
        },

        _preload: function () {
            var video, img, i;

            for (i = 0; i < this.settings.slides.length; i++) {
                if (this.settings.preload || this.settings.preloadImages) {
                    if (this.settings.slides[i].src) {
                        img = new Image();
                        img.src = this.settings.slides[i].src;
                    }
                }

                if (this.settings.preload || this.settings.preloadVideos) {
                    if (this.support.video && this.settings.slides[i].video) {
                        video = this._video(this.settings.slides[i].video);
                        video.preload = true;

                        videoCache[this.settings.slides[i].video.toString()] = video;
                    }
                }
            }
        },

        _slideShow: function () {
            var self = this;

            if (this.total > 1 && !this.paused && !this.noshow) {
                this.timeout = setTimeout(function () {
                    self.next();
                }, this._options('delay'));
            }
        },

        _timer: function (state) {
            var self = this;

            clearTimeout(this.timeout);

            if (!this.$timer) {
                return;
            }

            this.$timer
                .removeClass('vegas-timer-running')
                    .find('div')
                        .css('transition-duration', '0ms');

            if (this.paused || this.noshow) {
                return;
            }

            if (state) {
                setTimeout(function () {
                   self.$timer
                    .addClass('vegas-timer-running')
                        .find('div')
                            .css('transition-duration', self._options('delay') - 100 + 'ms');
                }, 100);
            }
        },

        _video: function (srcs) {
            var video,
                source;

            if (videoCache[srcs.toString()]) {
                return videoCache[srcs.toString()];
            }

            if (srcs instanceof Array === false) {
                srcs = [ srcs ];
            }

            video = document.createElement('video');

            srcs.forEach(function (src) {
                source = document.createElement('source');
                source.src = src;
                video.appendChild(source);
            });

            return video;
        },

        _options: function (key, i) {
            if (i === undefined) {
                i = this.slide;
            }

            if (this.settings.slides[i][key] !== undefined) {
                return this.settings.slides[i][key];
            }

            return this.settings[key];
        },

        _goto: function (nb) {
            if (typeof this.settings.slides[nb] === 'undefined') {
                nb = 0;
            }

            this.slide = nb;

            var $slide,
                $slides    = this.$elmt.children('.vegas-slide'),
                total      = $slides.length,
                self       = this,
                src        = this.settings.slides[nb].src,
                videos     = this.settings.slides[nb].video,
                delay      = this._options('delay'),
                duration   = this._options('transitionDelay'),
                align      = this._options('align'),
                valign     = this._options('valign'),
                color      = this._options('color') || this.$elmt.css('background-color'),
                fill       = this._options('fill') ? 'cover' : 'contain',
                transition = this._options('transition'),
                isRandom   = transition === 'random',
                video,
                img;

            if (isRandom) {
                transition = this.transitions[Math.floor(Math.random() * (this.transitions.length - 1))];
            }

            if (transition !== 'none' && this.transitions.indexOf(transition) < 0) {
                console.error("Vegas: Transition " + transition + " doesn't exist.");
            }

            if (duration > delay) {
                duration = delay;
            }

            if (this.support.video && videos) {
                video = this._video(videos);
                video.muted = true;
                video.loop = true;
                video.autoplay = true;

                $slide = $(video)
                    .addClass('vegas-video')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-color', color);

                if (this.support.objectFit) {
                    $slide
                        .css('object-position', align + ' ' + valign)
                        .css('object-fit', fill)
                        .css('width',  '100%')
                        .css('height', '100%');
                } else if (fill === 'contain') {
                    $slide
                        .css('width',  '100%')
                        .css('height', '100%');
                }
            } else {
                img = new Image();
                img.src = src;

                $slide = $('

')
                    .addClass('vegas-slide')
                    .addClass('vegas-transition-' + transition)
                    .css('background-image',    'url(' + src + ')')
                    .css('background-color',    color)
                    .css('background-position', align + ' ' + valign)
                    .css('background-size',     fill);
            }

            if (!self.support.transition) {
                $slide.css('display', 'none');
            }

            if (total) {
                $slides.eq(total - 1).after($slide);
            } else {
                this.$elmt.prepend($slide);
            }

            $slides
                .css('transition', 'all 0ms')
                .each(function () {
                    this.className  = ' vegas-slide';
                    this.className += ' vegas-transition-' +  transition;
                    this.className += ' vegas-transition-' +  transition + '-in';

                    if (this.tagName === 'VIDEO') {
                        this.className += ' vegas-video';
                    }
                }
            );

            self._timer(false);

            function go () {
                self._timer(true);

                setTimeout(function () {
                    if (self.support.transition) {
                        $slides
                            .css('transition', 'all ' + duration + 'ms')
                            .addClass('vegas-transition-' + transition + '-out');
                    }

                    $slide
                        .css('transition', 'all ' + duration + 'ms')
                        .addClass('vegas-transition-' + transition + '-in');

                    if (!self.support.transition) {
                        $slide.fadeIn(duration);
                    }

                    for (var i = 0; i < $slides.length - 2; i++) {
                         $slides.eq(i).remove();
                    }

                    self.trigger('walk');
                    self._slideShow();
                }, 100);
            }

            if (video) {
                // oncanplay is triggered every time when loop=true
                // so let's start the slide only once
                var played = false;

                video.play();
                video.oncanplay = function () {
                    if (!played) {
                        played = true;
                        go();
                    }
                };
            } else {
                img.onload = go;
            }
        },

        shuffle: function () {
            var temp,
                rand;

            for (var i = this.total - 1; i > 0; i--) {
                rand = Math.floor(Math.random() * (i + 1));
                temp = this.settings.slides[i];
                this.settings.slides[i] = this.settings.slides[rand];
                this.settings.slides[rand] = temp;
            }
        },

        play: function () {
            if (this.paused) {
                this.paused = false;
                this.next();
                this.trigger('play');
            }
        },

        pause: function () {
            this._timer(false);
            this.paused = true;
            this.trigger('pause');
        },

        toggle: function () {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        },

        playing: function () {
            return !this.paused && !this.noshow;
        },

        current: function (advanced) {
            if (advanced) {
                return {
                    slide: this.slide,
                    data:  this.settings.slides[this.slide]
                };
            }
            return this.slide;
        },

        jump: function (nb) {
            if (nb < 0 || nb > this.total - 1 || nb === this.slide) {
                return;
            }

            this.slide = nb;
            this._goto(this.slide);
        },

        next: function () {
            this.slide++;

            if (this.slide >= this.total) {
                this.slide = 0;
            }

            this._goto(this.slide);
        },

        previous: function () {
            this.slide--;

            if (this.slide < 0) {
                this.slide = this.total - 1;
            }

            this._goto(this.slide);
        },

        trigger: function (fn) {
            var params = [];

            if (fn !== 'init') {
                params = [
                    this.slide,
                    this.settings.slides[this.slide]
                ];
            }

            this.$elmt.trigger('vegas' + fn, params);

            if (typeof this.settings[fn] === 'function') {
                this.settings[fn].apply(this.$elmt, params);
            }
        },

        options: function (key, value) {
            var oldSlides = this.settings.slides;

            if (typeof key === 'object') {
                this.settings = $.extend({}, defaults, $.vegas.defaults, key);
            } else if (typeof key === 'string') {
                if (value === undefined) {
                    return this.settings[key];
                }
                this.settings[key] = value;
            } else {
                return this.settings;
            }

            // In case slides have changed
            if (this.settings.slides !== oldSlides) {
                this.total  = this.settings.slides.length;
                this.noshow = this.total < 2;
                this._preload();
            }
        }
    };

    $.fn.vegas = function(options) {
        var args = arguments,
            error = false,
            returns;

        if (options === undefined || typeof options === 'object') {
            return this.each(function () {
                if (!this._vegas) {
                    this._vegas = new Vegas(this, options);
                }
            });
        } else if (typeof options === 'string') {
            this.each(function () {
                var instance = this._vegas;

                if (!instance) {
                    throw new Error('No Vegas applied to this element.');
                }

                if (typeof instance[options] === 'function' && options[0] !== '_') {
                    returns = instance[options].apply(instance, [].slice.call(args, 1));
                } else {
                    error = true;
                }
            });

            if (error) {
                throw new Error('No method "' + options + '" in Vegas.');
            }

            return returns !== undefined ? returns : this;
        }
    };

    $.vegas = {};
    $.vegas.defaults = defaults;

    $.vegas.isVideoCompatible = function () {
        return !('ontouchstart' in window || 'onmsgesturechange' in window);
    };

})(typeof jQuery !== 'undefined' ? jQuery :
   typeof Zepto  !== 'undefined' ? Zepto  :
   typeof Pin    !== 'undefined' ? Pin    : null
);
<|endoftext|>


<commit_before>/*JavaScript for the pop out window.*/
steal('../api/waveUI.js', '../api/uri.js').then(function() {
uri = parseUri(location.hash);

//manage options

//setup interface

//display specified wave

});<commit_msg>Edited pyofwave_client/pyofwave_client/wave.js via GitHub<commit_after>/*JavaScript for the pop out window.*/
steal('../api/waveUI.js', '../api/uri.js').then(function() {
uri = parseUri(location.hash);

//manage options
if (uri.querykey.css) steal().css(uri.querykey.css);
if (uri.querykey.alias) loginAlias(uri.querykey.alias);

if (uri.host == "__new__") {
   // Send operations to create a new wave with URI options.
}
else {
   // Send operations to retrieve uri.host
}
});

function loginAlias(alias) {

}<|endoftext|>


<commit_before>/**
	_enyo.Anchor_ implements an HTML anchor (<a>) tag. Published properties
	allow you to bind the anchor's _href_ and _title_ attributes to appropriate
	fields on data objects.
*/
enyo.kind({
	name: "enyo.Anchor",
	kind: "enyo.Control",
	tag: "a",
	//* @public
	published: {
		//* Maps to the _href_ attribute of the <a> tag
		href: "",
		//* Maps to the title attribute of the <a> tag
		title: ""
	},
	//* @protected
	create: enyo.super(function (sup) {
		return function() {
			sup.apply(this, arguments);
			this.hrefChanged();
			this.titleChanged();
		};
	}),
	//* @protected
	hrefChanged: function() {
		this.setAttribute("href", this.href);
	},
	//* @protected
	titleChanged: function() {
		this.setAttribute("title", this.title);
	}
});
<commit_msg>Missed a spot. Enyo-DCO-1.1-Signed-Off-By: Jim Tang (jim.tang@lge.com)<commit_after>/**
	_enyo.Anchor_ implements an HTML anchor (<a>) tag. Published properties
	allow you to bind the anchor's _href_ and _title_ attributes to appropriate
	fields on data objects.
*/
enyo.kind({
	name: "enyo.Anchor",
	kind: "enyo.Control",
	tag: "a",
	//* @public
	published: {
		//* Maps to the _href_ attribute of the <a> tag
		href: "",
		//* Maps to the _title_ attribute of the <a> tag
		title: ""
	},
	//* @protected
	create: enyo.super(function (sup) {
		return function() {
			sup.apply(this, arguments);
			this.hrefChanged();
			this.titleChanged();
		};
	}),
	//* @protected
	hrefChanged: function() {
		this.setAttribute("href", this.href);
	},
	//* @protected
	titleChanged: function() {
		this.setAttribute("title", this.title);
	}
});
<|endoftext|>


<commit_before>(function(module) {
  var projectsView = {};

  //when < 640px: selected nav item will display it's data content
  //when > 640px: hover will display hovered link's data content
  projectsView.handleMainNav = function() {
    $('.hamburger-li').hover(function() {
      var $hoverData = $(this).attr('data-content');
      $('.display-link').toggleClass('show-link');
      $('.display-link').text($hoverData);
    });

    //changes content displayed on the page based on the selected list item's data content
    $('.main-nav').on('click', '.hamburger-li', function(e) {
      e.preventDefault();
      $('.page-content').hide();
      var $clickEvent = $(this);
      console.log($clickEvent);
      $('[id="' + $clickEvent.attr('data-content') + '"]').show();
      $('.hamburger-menu').removeClass('expand');
      projectsView.handleTeasers();
    });
    $('.main-nav .hamburger-li:first').click();
  };

  projectsView.handleCourseFilter = function() {
    $('#course-filter').on('change', function() {
      if($(this).val()) {
        $('.project-container').hide();
        $('.project-container[data-category="' + $(this).val() + '"]').fadeIn('fast');
      } else {
        $('.project-container').fadeIn('fast');
      }
      projectsView.handleTeasers();
    });
  };

  projectsView.handleTeasers = function() {
    $('.read-more').show();
    console.log($('.article-body'));
    $('.article-body *:nth-of-type(n+2)').hide();
    $('article').on('click', 'a:eq(1)', function(e){
      e.preventDefault();
      console.log('project container click event ran');
      $($(this).parent().children('.article-body')).children().fadeIn('fast');
      $(this).hide();
    });
  };

  //appends project data to the DOM
  projectsView.initProjectContent = function() {
    Project.all.forEach(function (data) {
      $('#projects').append(data.toHtml($('#article-template')));
      if($('#course-filter option:contains("' + data.course + '")').length === 0) {
        $('#course-filter').append(data.toHtml($('#filter-template')));
      };
    });
    projectsView.handleTeasers();
  };

  //when < 640px: menu shows up when hamburger menu is clicked
  $(document).ready(function() {
    projectsView.handleMainNav();
    projectsView.handleCourseFilter();
    $('.hamburger-icon').click(function() {
      $('.hamburger-menu').toggleClass('expand');
    });
  });

  module.projectsView = projectsView;
})(window);
<commit_msg>merging<commit_after>(function(module) {
  var projectsView = {};

  //when < 640px: selected nav item will display it's data content
  //when > 640px: hover will display hovered link's data content
  projectsView.handleMainNav = function() {
    $('.hamburger-li').hover(function() {
      var $hoverData = $(this).attr('data-content');
      $('.display-link').toggleClass('show-link');
      $('.display-link').text($hoverData);
    });

    //changes content displayed on the page based on the selected list item's data content
    $('.main-nav').on('click', '.hamburger-li', function(e) {
      e.preventDefault();
      $('.page-content').hide();
      var $clickEvent = $(this);
      console.log($clickEvent);
      $('[id="' + $clickEvent.attr('data-content') + '"]').show();
      $('.hamburger-menu').removeClass('expand');
      projectsView.handleTeasers();
    });
    $('.main-nav .hamburger-li:first').click();
  };

  //handles course filter
  projectsView.handleCourseFilter = function() {
    $('#course-filter').on('change', function() {
      if($(this).val()) {
        $('.project-container').hide();
        $('.project-container[data-category="' + $(this).val() + '"]').fadeIn('fast');
      } else {
        $('.project-container').fadeIn('fast');
      }
      projectsView.handleTeasers();
    });
  };

  projectsView.handleTeasers = function() {
    $('.read-more').show();
    console.log($('.article-body'));
    $('.article-body *:nth-of-type(n+2)').hide();
    $('article').on('click', 'a:eq(1)', function(e){
      e.preventDefault();
      console.log('project container click event ran');
      $($(this).parent().children('.article-body')).children().fadeIn('fast');
      $(this).hide();
    });
  };

  //appends project data to the DOM
  projectsView.initProjectContent = function() {
    Project.all.forEach(function (data) {
      $('#projects').append(data.toHtml($('#article-template')));
      if($('#course-filter option:contains("' + data.course + '")').length === 0) {
        $('#course-filter').append(data.toHtml($('#filter-template')));
      };
    });
    projectsView.handleTeasers();
  };

  //when < 640px: menu shows up when hamburger menu is clicked
  $(document).ready(function() {
    projectsView.handleMainNav();
    projectsView.handleCourseFilter();
    $('.hamburger-icon').click(function() {
      $('.hamburger-menu').toggleClass('expand');
    });
  });

  module.projectsView = projectsView;
})(window);
<|endoftext|>


<commit_before>var number = 1;

//Buttons
$(document).ready(function () {
	$("#openbook").click( function() {
		number++;
		getData();
	});
	$('#back').click(function() {
		number--;
		getData();
	});
	$('#next').click(function() {
		number++;
		getData();
	});
});

function animalNoise(text) {
	var hasGorilla = text.includes("Gorilla");
	var hasTiger = text.includes("Tiger");
	var hasPeacock = text.includes("Peacock");
	var hasFlamingo	= text.includes("Flamingo");

	if(hasGorilla == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='audio/Gorilla.mp3' type='audio/mpeg'></audio>";
	} else if(hasTiger == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='audio/Tiger.mp3' type='audio/mpeg'></audio>";
	} else if(hasPeacock == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='audio/Peacock.mp3' type='audio/mpeg'></audio>";
	} else if(hasFlamingo == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='http://www.wildlifelands.com/wxs/flamingo.mp3' type='audio/mpeg'></audio>";
	}
}

function getData() {
	$.ajax({
		dataType: "html",
		url: "http://tarheelreader.org/2015/03/30/at-the-zoo-10/" + number,
		crossDomain: true,
		error: function(xhr, textStatus, error){
      		console.log(xhr.statusText);
      		console.log(textStatus);
      		console.log(error);
  		},
  		success: function(data) {
  			if(number <= 12) {
	  			console.log("SUCCESS");

	  			if(number == 2 || number == 11) {
	  				initial();
	  				document.getElementById('enddiv').innerHTML= "";
	  			} else if(number < 3) {
	  				clearPage();
	  			}

	  			//Reset audio
	  			document.getElementById('audio').innerHTML = "";

	  			//Get and set tarheel reader content
	  			var text = getTRContent(data);

	  			//Add animal noises
	  			animalNoise(text);
	  		}
	  		else {
	  			//If last page then get rid of content and replace with the end
	  			clearPage();
	  			$("#openbook").addClass("hidden");
	  			document.getElementById('enddiv').innerHTML= "The End";
	  			number--;
	  		}
		}
	})
}

function initial() {
	//Get rid of open book button and add back and next
	$("#back").removeClass("hidden");
	$("#next").removeClass("hidden");
	$("#openbook").addClass("hidden");
	$("#image").removeClass("hidden");
}

function getTRContent(data) {
	var imgurl = $(data).find('img.thr-pic').attr("src");
	imgurl = "http://tarheelreader.org/" + imgurl;
	document.getElementById('img').src=imgurl;
	var text = $(data).find('p.thr-caption').text();
	document.getElementById('imgcaption').innerHTML=text;
	return(text);
}

function clearPage() {
	//Add open button and hide next and back
	$("#back").addClass("hidden");
	$("#next").addClass("hidden");
	$("#openbook").removeClass("hidden");
	$("#image").addClass("hidden");
}
document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
        // up arrow
        document.getElementById('audiotag').currentTime=0;
        document.getElementById('audiotag').play();

    }
    else if (e.keyCode == '40') {
        // down arrow
    }
    else if (e.keyCode == '37') {
       // left arrow
    	number--;
		getData();

    }
    else if (e.keyCode == '39') {
       // right arrow
        number++;
		getData();
    }

}
<commit_msg>use down arrow to pause and play<commit_after>var number = 1;

//Buttons
$(document).ready(function () {
	$("#openbook").click( function() {
		number++;
		getData();
	});
	$('#back').click(function() {
		number--;
		getData();
	});
	$('#next').click(function() {
		number++;
		getData();
	});
});

function animalNoise(text) {
	var hasGorilla = text.includes("Gorilla");
	var hasTiger = text.includes("Tiger");
	var hasPeacock = text.includes("Peacock");
	var hasFlamingo	= text.includes("Flamingo");

	if(hasGorilla == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='audio/Gorilla.mp3' type='audio/mpeg'></audio>";
	} else if(hasTiger == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='audio/Tiger.mp3' type='audio/mpeg'></audio>";
	} else if(hasPeacock == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='audio/Peacock.mp3' type='audio/mpeg'></audio>";
	} else if(hasFlamingo == true) {
		document.getElementById('audio').innerHTML = "<audio id='audiotag' controls autoplay><source src='http://www.wildlifelands.com/wxs/flamingo.mp3' type='audio/mpeg'></audio>";
	}
}

function getData() {
	$.ajax({
		dataType: "html",
		url: "http://tarheelreader.org/2015/03/30/at-the-zoo-10/" + number,
		crossDomain: true,
		error: function(xhr, textStatus, error){
      		console.log(xhr.statusText);
      		console.log(textStatus);
      		console.log(error);
  		},
  		success: function(data) {
  			if(number <= 12) {
	  			console.log("SUCCESS");

	  			if(number == 2 || number == 11) {
	  				initial();
	  				document.getElementById('enddiv').innerHTML= "";
	  			} else if(number < 3) {
	  				clearPage();
	  			}

	  			//Reset audio
	  			document.getElementById('audio').innerHTML = "";

	  			//Get and set tarheel reader content
	  			var text = getTRContent(data);

	  			//Add animal noises
	  			animalNoise(text);
	  		}
	  		else {
	  			//If last page then get rid of content and replace with the end
	  			clearPage();
	  			$("#openbook").addClass("hidden");
	  			document.getElementById('enddiv').innerHTML= "The End";
	  			number--;
	  		}
		}
	})
}

function initial() {
	//Get rid of open book button and add back and next
	$("#back").removeClass("hidden");
	$("#next").removeClass("hidden");
	$("#openbook").addClass("hidden");
	$("#image").removeClass("hidden");
}

function getTRContent(data) {
	var imgurl = $(data).find('img.thr-pic').attr("src");
	imgurl = "http://tarheelreader.org/" + imgurl;
	document.getElementById('img').src=imgurl;
	var text = $(data).find('p.thr-caption').text();
	document.getElementById('imgcaption').innerHTML=text;
	return(text);
}

function clearPage() {
	//Add open button and hide next and back
	$("#back").addClass("hidden");
	$("#next").addClass("hidden");
	$("#openbook").removeClass("hidden");
	$("#image").addClass("hidden");
}
document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
        // up arrow
        document.getElementById('audiotag').currentTime=0;
        document.getElementById('audiotag').play();

    }
    else if (e.keyCode == '40') {
        // down arrow
        var audio = document.getElementById('audiotag')
        if(audio.paused) {
        	audio.play();
        } else {
        	audio.pause();
        }

    }
    else if (e.keyCode == '37') {
       // left arrow
    	number--;
		getData();

    }
    else if (e.keyCode == '39') {
       // right arrow
        number++;
		getData();
    }

}
<|endoftext|>