<commit_before>Vps.Connection = Ext.extend(Ext.data.Connection, {
    _progressData    : { },

    /**
     * Options:
     * - mask (true für body, sonst element)
     * - maskText (default Loading...)
     */
    request: function(options)
    {

        Vps.requestSentSinceLastKeepAlive = true;
        Vps.Connection.runningRequests++;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.mask(options.maskText || trlVps('Loading...'));
            } else {
                if (Vps.Connection.masks == 0) {
                    if (Ext.get('loading')) {
                        Ext.getBody().mask();
                    } else {
                        Ext.getBody().mask(options.maskText || trlVps('Loading...'));
                    }
                }
                Vps.Connection.masks++;
            }
        }

        if (options.url.match(/[\/a-zA-Z0-9]*\/json[a-zA-Z0-9\-]+(\/|\?|)/)) {
            options.vpsCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.vpsJsonSuccess;
            options.failure = this.vpsJsonFailure;
            options.callback = this.vpsCallback;
            options.scope = this;
        } else {
            options.vpsCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.vpsNoJsonSuccess;
            options.failure = this.vpsNoJsonFailure;
            options.callback = this.vpsCallback;
            options.scope = this;
        }
        if (!options.params) options.params = {};
        options.params.application_version = Vps.application.version;
        if (!options.url.match(':\/\/')) {
            //absolute url incl. http:// erstellen
            //wird benötigt wenn fkt über mozrepl aufgerufen wird
            var u = location.protocol + '/'+'/' + location.host;
            if (options.url.substr(0, 1) == '/') {
                options.url = u + options.url;
            } else {
                options.url = u + '/' + options.url;
            }
        }

        if (options.progress) {
            var progressNum = Math.floor(Math.random() * 1000000000) + 1;
            options.params.progressNum = progressNum;
        }

        Vps.Connection.superclass.request.call(this, options);

        if (options.progress) {
            this._showProgress(options);
        }
    },

    _showProgress: function(options)
    {
        var progressNum = options.params.progressNum;

        this._progressData[progressNum] = {
            progressBar: this._createProgressDialog({
                title: options.progressTitle || trlVps('Progress'),
                transId: this.transId,
                requestOptions: options
            }),
            breakStatusRequests: false
        }
        this._progressData[progressNum].progressBar.updateProgress(0, '0%', '');

        this._doProgressStatusRequest.defer(1500, this, [ progressNum ]);
    },

    _doProgressStatusRequest: function(progressNum)
    {
        this.request({
            url: '/vps/json-progress-status',
            params: { progressNum: progressNum },
            success: function(response, options, r) {
                var progressNum = options.params.progressNum;
                if (!this._progressData[progressNum]) return;

                if (typeof r.finished != 'undefined') {
                    if (r.finished) {
                        this._progressData[progressNum].progressBar.updateProgress(
                            1, '100%', trlVps('Finished')
                        );
                        return;
                    }

                    this._progressData[progressNum].progressBar.updateProgress(
                        r.percent / 100,
                        Math.floor(r.percent)+'%',
                        r.text ? r.text : ''
                    );
                }

                if (!this._progressData[progressNum].breakStatusRequests) {
                    // recursing
                    this._doProgressStatusRequest.defer(500, this, [ progressNum ]);
                }
            },
            scope: this
        });
    },

    _createProgressDialog: function(cfg)
    {
        var progressBar = new Ext.ProgressBar({
            text:'0%',
            animate: true
        });
        cfg = Ext.applyIf(cfg, {
            title: trlVps('Progress'),
            autoCreate : true,
            resizable:false,
            constrain:true,
            constrainHeader:true,
            minimizable : false,
            maximizable : false,
            stateful: false,
            modal: true,
            shim:true,
            buttonAlign:"center",
            width:400,
            plain:true,
            footer:true,
            closable:false
        });;
        var dlg = new Ext.Window(cfg);

        if (typeof cfg.showCancel == 'undefined' || cfg.showCancel) {
            dlg.addButton(
                { text: trlVps('Cancel') },
                (function(dialog) {
                    Ext.Ajax.abort(dialog.transId);

                    var responseObject = Ext.lib.Ajax.createExceptionObject(
                        dialog.transId, null, true
                    );
                    Ext.callback(
                        dialog.requestOptions.vpsCallback.failure,
                        dialog.requestOptions.vpsCallback.scope,
                        [responseObject, dialog.requestOptions]
                    );
                    dialog.requestOptions.callback.call(
                        this,
                        dialog.requestOptions,
                        false,
                        responseObject
                    );
                }).createDelegate(this, [ dlg ])
            );
        }

        dlg.render(document.body);
        dlg.myEls = { };
        dlg.myEls.bodyEl = dlg.body.createChild({
            html:'

'
        });
        dlg.myEls.bodyEl.addClass('vps-progress-window');
        dlg.myEls.msgEl = Ext.get(dlg.myEls.bodyEl.dom.childNodes[0].firstChild);

        dlg.progressBar = new Ext.ProgressBar({
            renderTo:dlg.myEls.bodyEl,
            text: '0%',
            animate: true
        });
        dlg.myEls.bodyEl.createChild({cls:'x-clear'});

        dlg.updateProgress = function(num, progressBarText, text)
        {
            this.progressBar.updateProgress(num, progressBarText, true);
            this.myEls.msgEl.update(text || ' ');
        }

        dlg.show();
        return dlg;
    },

    repeatRequest: function(options) {
        Vps.Connection.runningRequests++;
        delete options.vpsIsSuccess;
        Vps.Connection.superclass.request.call(this, options);
        if (options.progress) {
            this._showProgress(options);
        }
    },
    vpsJsonSuccess: function(response, options)
    {
        if (!options.ignoreErrors) {
            options.vpsIsSuccess = false;
            options.vpsLogin = false;

            var errorMsg = false;

            var encParams;
            if (typeof options.params == "string") {
                encParams = options.params;
            } else {
                encParams = Ext.urlEncode(options.params);
            }
            try {
                if (!response.responseText) {
                    errorMsg = 'response is empty';
                } else {
                    var r = Ext.decode(response.responseText);
                }
            } catch(e) {
                errorMsg = e.toString()+':
'+response.responseText;
                var errorMsgTitle = 'Javascript Parse Exception';
            }
            if (Vps.Debug.querylog && r && r.requestNum) {
                var rm = location.protocol + '/'+'/' + location.host;
                var url = options.url;
                if (url.substr(0, rm.length) == rm) {
                    url = url.substr(rm.length);
                }
                var data = [[new Date(), url, encParams, r.requestNum]];
                Vps.Debug.requestsStore.loadData(data, true);
            }
            if (!errorMsg && r.exception) {
                var p;
                if (typeof options.params == "string") {
                    p = options.params;
                } else {
                    p = Ext.urlEncode(options.params);
                }
                errorMsg = '
'+r.exception+'
';
                var errorMsgTitle = 'PHP Exception';
            }
            if (errorMsg && !options.ignoreErrors) {
                errorMsg = 'request-url
' + errorMsg;
                var sendMail = !r || !r.exception;
                if (options.errorText) {
                    errorText = options.errorText;
                } else {
                    errorText = null;
                }
                Vps.handleError({
                    url: options.url,
                    message: errorMsg,
                    title: errorMsgTitle,
                    mail: sendMail,
                    errorText: errorText,
                    checkRetry: false,
                    retry: function() {
                        this.connection.repeatRequest(this.options);
                    },
                    abort: function() {
                        Ext.callback(this.options.vpsCallback.failure, this.options.vpsCallback.scope, [this.response, this.options]);
                    },
                    scope: { connection: this, options: options, response: response }
                });
                return;
            }

            if (!r.success && !options.ignoreErrors) {
                if (r.wrongversion) {
                    Ext.Msg.alert(trlVps('Error - wrong version'),
                    trlVps('Because of an application update the application has to be reloaded.'),
                    function(){
                        location.reload();
                    });
                    Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
                    return;
                }
                if (r.login) {
                    options.vpsLogin = true;
                    var dlg = new Vps.User.Login.Dialog({
                        message: r.message,
                        success: function() {
                            //redo action...
                            this.repeatRequest(options);
                        },
                        scope: this
                    });
                    Ext.getBody().unmask();
                    dlg.showLogin();
                    return;
                }
                if (r.error) {
                    Ext.Msg.alert(trlVps('Error'), r.error);
                } else {
                    Ext.Msg.alert(trlVps('Error'), trlVps("A Server failure occured."));
                }
                Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
                return;
            }
            options.vpsIsSuccess = true;
            options.vpsCallback.success.call(options.vpsCallback.scope, response, options, r);
        };
    },
    vpsNoJsonSuccess: function(response, options)
    {
        options.vpsIsSuccess = true;
        options.vpsCallback.success.call(options.vpsCallback.scope, response, options);
    },
    vpsNoJsonFailure: function(response, options)
    {
        options.vpsIsSuccess = false;
        options.vpsCallback.failure.call(options.vpsCallback.scope, response, options);
    },
    vpsJsonFailure: function(response, options)
    {
        if (!options.ignoreErrors) {
            options.vpsIsSuccess = false;

            errorMsgTitle = trlVps('Error');
            if (options.errorText) {
                errorText = options.errorText;
                errorMsg = options.errorText;
            } else {
               errorMsg = trlVps("A connection problem occured.");
               errorText = null;
            }
            if (!options.ignoreErrors) {
                Vps.handleError({
                    url: options.url,
                    message: errorMsg,
                    title: errorMsgTitle,
                    errorText: errorText,
                    mail: false,
                    checkRetry: true,
                    retry: function() {
                        this.repeatRequest(options);
                    },
                    abort: function() {
                        Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
                    },
                    scope: this
                });
                Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
            }
            return;
        }
    },

    vpsCallback: function(options, success, response)
    {
        //wenn login-fenster angezeigt wird keinen callback aufrufen - weil der request
        //wird ja erneut gesendet und da dann der callback aufgerufen.
        if (options.vpsLogin) return;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.unmask();
            } else {
                Vps.Connection.masks--;
                if (Vps.Connection.masks == 0) {
                    Ext.getBody().unmask();
                    if (Ext.get('loading')) {
                        Ext.get('loading').fadeOut({remove: true});
                    }
                }
            }
        }

        if (options.progress) {
            this._progressData[options.params.progressNum].progressBar.hide();
            delete this._progressData[options.params.progressNum];
        }

        if(success && !options.vpsIsSuccess) {
            success = false;
        }
        Ext.callback(options.vpsCallback.callback, options.vpsCallback.scope, [options, success, response]);
        Vps.Connection.runningRequests--;
    }
});
Vps.Connection.masks = 0; //static var that hols number of masked requests
Vps.Connection.runningRequests = 0;

Ext.Ajax = new Vps.Connection({
    /**
     * The timeout in milliseconds to be used for requests. (defaults
     * to 30000)
     * @type Number
     * @property  timeout
     */
    autoAbort : false,

    /**
     * Serialize the passed form into a url encoded string
     * @return {String}
     */
    serializeForm : function(form){
        return Ext.lib.Ajax.serializeForm(form);
    }
});

<commit_msg>fix wenn kein callback<commit_after>Vps.Connection = Ext.extend(Ext.data.Connection, {
    _progressData    : { },

    /**
     * Options:
     * - mask (true für body, sonst element)
     * - maskText (default Loading...)
     */
    request: function(options)
    {

        Vps.requestSentSinceLastKeepAlive = true;
        Vps.Connection.runningRequests++;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.mask(options.maskText || trlVps('Loading...'));
            } else {
                if (Vps.Connection.masks == 0) {
                    if (Ext.get('loading')) {
                        Ext.getBody().mask();
                    } else {
                        Ext.getBody().mask(options.maskText || trlVps('Loading...'));
                    }
                }
                Vps.Connection.masks++;
            }
        }

        if (options.url.match(/[\/a-zA-Z0-9]*\/json[a-zA-Z0-9\-]+(\/|\?|)/)) {
            options.vpsCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.vpsJsonSuccess;
            options.failure = this.vpsJsonFailure;
            options.callback = this.vpsCallback;
            options.scope = this;
        } else {
            options.vpsCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.vpsNoJsonSuccess;
            options.failure = this.vpsNoJsonFailure;
            options.callback = this.vpsCallback;
            options.scope = this;
        }
        if (!options.params) options.params = {};
        options.params.application_version = Vps.application.version;
        if (!options.url.match(':\/\/')) {
            //absolute url incl. http:// erstellen
            //wird benötigt wenn fkt über mozrepl aufgerufen wird
            var u = location.protocol + '/'+'/' + location.host;
            if (options.url.substr(0, 1) == '/') {
                options.url = u + options.url;
            } else {
                options.url = u + '/' + options.url;
            }
        }

        if (options.progress) {
            var progressNum = Math.floor(Math.random() * 1000000000) + 1;
            options.params.progressNum = progressNum;
        }

        Vps.Connection.superclass.request.call(this, options);

        if (options.progress) {
            this._showProgress(options);
        }
    },

    _showProgress: function(options)
    {
        var progressNum = options.params.progressNum;

        this._progressData[progressNum] = {
            progressBar: this._createProgressDialog({
                title: options.progressTitle || trlVps('Progress'),
                transId: this.transId,
                requestOptions: options
            }),
            breakStatusRequests: false
        }
        this._progressData[progressNum].progressBar.updateProgress(0, '0%', '');

        this._doProgressStatusRequest.defer(1500, this, [ progressNum ]);
    },

    _doProgressStatusRequest: function(progressNum)
    {
        this.request({
            url: '/vps/json-progress-status',
            params: { progressNum: progressNum },
            success: function(response, options, r) {
                var progressNum = options.params.progressNum;
                if (!this._progressData[progressNum]) return;

                if (typeof r.finished != 'undefined') {
                    if (r.finished) {
                        this._progressData[progressNum].progressBar.updateProgress(
                            1, '100%', trlVps('Finished')
                        );
                        return;
                    }

                    this._progressData[progressNum].progressBar.updateProgress(
                        r.percent / 100,
                        Math.floor(r.percent)+'%',
                        r.text ? r.text : ''
                    );
                }

                if (!this._progressData[progressNum].breakStatusRequests) {
                    // recursing
                    this._doProgressStatusRequest.defer(500, this, [ progressNum ]);
                }
            },
            scope: this
        });
    },

    _createProgressDialog: function(cfg)
    {
        var progressBar = new Ext.ProgressBar({
            text:'0%',
            animate: true
        });
        cfg = Ext.applyIf(cfg, {
            title: trlVps('Progress'),
            autoCreate : true,
            resizable:false,
            constrain:true,
            constrainHeader:true,
            minimizable : false,
            maximizable : false,
            stateful: false,
            modal: true,
            shim:true,
            buttonAlign:"center",
            width:400,
            plain:true,
            footer:true,
            closable:false
        });;
        var dlg = new Ext.Window(cfg);

        if (typeof cfg.showCancel == 'undefined' || cfg.showCancel) {
            dlg.addButton(
                { text: trlVps('Cancel') },
                (function(dialog) {
                    Ext.Ajax.abort(dialog.transId);

                    var responseObject = Ext.lib.Ajax.createExceptionObject(
                        dialog.transId, null, true
                    );
                    Ext.callback(
                        dialog.requestOptions.vpsCallback.failure,
                        dialog.requestOptions.vpsCallback.scope,
                        [responseObject, dialog.requestOptions]
                    );
                    dialog.requestOptions.callback.call(
                        this,
                        dialog.requestOptions,
                        false,
                        responseObject
                    );
                }).createDelegate(this, [ dlg ])
            );
        }

        dlg.render(document.body);
        dlg.myEls = { };
        dlg.myEls.bodyEl = dlg.body.createChild({
            html:'

'
        });
        dlg.myEls.bodyEl.addClass('vps-progress-window');
        dlg.myEls.msgEl = Ext.get(dlg.myEls.bodyEl.dom.childNodes[0].firstChild);

        dlg.progressBar = new Ext.ProgressBar({
            renderTo:dlg.myEls.bodyEl,
            text: '0%',
            animate: true
        });
        dlg.myEls.bodyEl.createChild({cls:'x-clear'});

        dlg.updateProgress = function(num, progressBarText, text)
        {
            this.progressBar.updateProgress(num, progressBarText, true);
            this.myEls.msgEl.update(text || ' ');
        }

        dlg.show();
        return dlg;
    },

    repeatRequest: function(options) {
        Vps.Connection.runningRequests++;
        delete options.vpsIsSuccess;
        Vps.Connection.superclass.request.call(this, options);
        if (options.progress) {
            this._showProgress(options);
        }
    },
    vpsJsonSuccess: function(response, options)
    {
        if (!options.ignoreErrors) {
            options.vpsIsSuccess = false;
            options.vpsLogin = false;

            var errorMsg = false;

            var encParams;
            if (typeof options.params == "string") {
                encParams = options.params;
            } else {
                encParams = Ext.urlEncode(options.params);
            }
            try {
                if (!response.responseText) {
                    errorMsg = 'response is empty';
                } else {
                    var r = Ext.decode(response.responseText);
                }
            } catch(e) {
                errorMsg = e.toString()+':
'+response.responseText;
                var errorMsgTitle = 'Javascript Parse Exception';
            }
            if (Vps.Debug.querylog && r && r.requestNum) {
                var rm = location.protocol + '/'+'/' + location.host;
                var url = options.url;
                if (url.substr(0, rm.length) == rm) {
                    url = url.substr(rm.length);
                }
                var data = [[new Date(), url, encParams, r.requestNum]];
                Vps.Debug.requestsStore.loadData(data, true);
            }
            if (!errorMsg && r.exception) {
                var p;
                if (typeof options.params == "string") {
                    p = options.params;
                } else {
                    p = Ext.urlEncode(options.params);
                }
                errorMsg = '
'+r.exception+'
';
                var errorMsgTitle = 'PHP Exception';
            }
            if (errorMsg && !options.ignoreErrors) {
                errorMsg = 'request-url
' + errorMsg;
                var sendMail = !r || !r.exception;
                if (options.errorText) {
                    errorText = options.errorText;
                } else {
                    errorText = null;
                }
                Vps.handleError({
                    url: options.url,
                    message: errorMsg,
                    title: errorMsgTitle,
                    mail: sendMail,
                    errorText: errorText,
                    checkRetry: false,
                    retry: function() {
                        this.connection.repeatRequest(this.options);
                    },
                    abort: function() {
                        Ext.callback(this.options.vpsCallback.failure, this.options.vpsCallback.scope, [this.response, this.options]);
                    },
                    scope: { connection: this, options: options, response: response }
                });
                return;
            }

            if (!r.success && !options.ignoreErrors) {
                if (r.wrongversion) {
                    Ext.Msg.alert(trlVps('Error - wrong version'),
                    trlVps('Because of an application update the application has to be reloaded.'),
                    function(){
                        location.reload();
                    });
                    Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
                    return;
                }
                if (r.login) {
                    options.vpsLogin = true;
                    var dlg = new Vps.User.Login.Dialog({
                        message: r.message,
                        success: function() {
                            //redo action...
                            this.repeatRequest(options);
                        },
                        scope: this
                    });
                    Ext.getBody().unmask();
                    dlg.showLogin();
                    return;
                }
                if (r.error) {
                    Ext.Msg.alert(trlVps('Error'), r.error);
                } else {
                    Ext.Msg.alert(trlVps('Error'), trlVps("A Server failure occured."));
                }
                Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
                return;
            }
            options.vpsIsSuccess = true;
            if (options.vpsCallback.success) {
                options.vpsCallback.success.call(options.vpsCallback.scope, response, options, r);
            }
        };
    },
    vpsNoJsonSuccess: function(response, options)
    {
        options.vpsIsSuccess = true;
        if (options.vpsCallback.success) {
            options.vpsCallback.success.call(options.vpsCallback.scope, response, options);
        }
    },
    vpsNoJsonFailure: function(response, options)
    {
        options.vpsIsSuccess = false;
        if (options.vpsCallback.failure) {
            options.vpsCallback.failure.call(options.vpsCallback.scope, response, options);
        }
    },
    vpsJsonFailure: function(response, options)
    {
        if (!options.ignoreErrors) {
            options.vpsIsSuccess = false;

            errorMsgTitle = trlVps('Error');
            if (options.errorText) {
                errorText = options.errorText;
                errorMsg = options.errorText;
            } else {
               errorMsg = trlVps("A connection problem occured.");
               errorText = null;
            }
            if (!options.ignoreErrors) {
                Vps.handleError({
                    url: options.url,
                    message: errorMsg,
                    title: errorMsgTitle,
                    errorText: errorText,
                    mail: false,
                    checkRetry: true,
                    retry: function() {
                        this.repeatRequest(options);
                    },
                    abort: function() {
                        Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
                    },
                    scope: this
                });
                Ext.callback(options.vpsCallback.failure, options.vpsCallback.scope, [response, options]);
            }
            return;
        }
    },

    vpsCallback: function(options, success, response)
    {
        //wenn login-fenster angezeigt wird keinen callback aufrufen - weil der request
        //wird ja erneut gesendet und da dann der callback aufgerufen.
        if (options.vpsLogin) return;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.unmask();
            } else {
                Vps.Connection.masks--;
                if (Vps.Connection.masks == 0) {
                    Ext.getBody().unmask();
                    if (Ext.get('loading')) {
                        Ext.get('loading').fadeOut({remove: true});
                    }
                }
            }
        }

        if (options.progress) {
            this._progressData[options.params.progressNum].progressBar.hide();
            delete this._progressData[options.params.progressNum];
        }

        if(success && !options.vpsIsSuccess) {
            success = false;
        }
        Ext.callback(options.vpsCallback.callback, options.vpsCallback.scope, [options, success, response]);
        Vps.Connection.runningRequests--;
    }
});
Vps.Connection.masks = 0; //static var that hols number of masked requests
Vps.Connection.runningRequests = 0;

Ext.Ajax = new Vps.Connection({
    /**
     * The timeout in milliseconds to be used for requests. (defaults
     * to 30000)
     * @type Number
     * @property  timeout
     */
    autoAbort : false,

    /**
     * Serialize the passed form into a url encoded string
     * @return {String}
     */
    serializeForm : function(form){
        return Ext.lib.Ajax.serializeForm(form);
    }
});

<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * Mode of operation
 * - check result accuracy
 *   - get a url, and a local path for the same content
 *   - do request on the url and on the local file, and check the result are the same
 * - load test
 *   - get an url on a static content
 *   - just hammer the server with random request
*/

// system dependancies
var sys		= require('sys');
var fs		= require('fs');
// local dependancies
var cmp_digest	= require('./test_accuracy').cmp_digest;
var http_get	= require('../vendor/node-helpers/ez_http').http_get;
var ezhttp	= require('../vendor/node-helpers/ez_http');
var ttyc	= require('../vendor/node-helpers/ez_tty_color');
var strutils	= require('../vendor/node-helpers/strutils');

// default parameters for cmdline options
var range_len_base	= null;
var range_len_rand	= null;
var nb_concurent	= 1;

//////////////////////////////////////////////////////////////////////////////////
//	parse cmdline								//
//////////////////////////////////////////////////////////////////////////////////
var optind	= 2;
for(;optind < process.argv.length; optind++){
	var key	= process.argv[optind];
	var val	= process.argv[optind+1];
	//sys.puts("key="+key+" val="+val);
	if( key == "-c" || key == "--concurent" ){
		nb_concurent	= parseInt(val);
		optind		+= 1;
	}else if( key == "-l" || key == "--req_length_base" ){
		range_len_base	= strutils.string_to_size(val);
		optind		+= 1;
		//sys.puts("range_len_base="+range_len_base);
	}else if( key == "-r" || key == "--req_length_rand" ){
		range_len_rand	= strutils.string_to_size(val);
		optind		+= 1;
	}else if( key == "-h" || key == "--help" ){
		sys.puts("usage: oload_stress_test [-c ncnx] [-l nbytes] [-r nbytes] URL [filename]");
		sys.puts(" - If <filename> is present, an accuracy test is performed. AKA data are loaded from");
		sys.puts("   the reference file and from the <URL> and both are checked to be equal.");
		sys.puts(" - If <filename> is not present, a stress test is performed. AKA data are loaded from");
		sys.puts("   the url as fast as possible.");
		sys.puts("");
		sys.puts("-c|--concurent ncnx\t\tDetermine the number of concurent connections during the tests.");
		sys.puts("-l|--req_length_base nbytes\tThe base length of the request to make");
		sys.puts("-r|--req_length_rand nbytes\tThe randomized length of the request to make");
		process.exit(0);
	}else{
		// if the option doesnt exist, consider it is the first non-option parameters
		break;
	}
}

// get url/ref_fname from cmdline
var url		= process.argv[optind++];
var ref_fname	= process.argv[optind++];

//////////////////////////////////////////////////////////////////////////////////
//	accuracy test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_accuracy()
{
	var filesize	= fs.statSync(ref_fname).size
	// set default range_len_base/range_len_rand
	range_len_base	= range_len_base || (filesize / 20.0);
	range_len_rand	= range_len_rand || (range_len_base / 2.0);
	// clamp range_len_base/range_len_rand
	range_len_base	= Math.min(range_len_base, filesize);
	range_len_rand	= Math.min(range_len_rand, range_len_base);

	var cmp_digest_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		cmp_digest(url, ref_fname, range_beg, range_len, function(err, succeed){
			if( succeed )	sys.print(".");
			else		sys.puts("accuracy: beg="+range_beg+" len="+range_len+" succeed="+succeed);
			cmp_digest_multiple();
		})
	}

	// display informations headers
	sys.log("Check accuracy between url "+url);
	sys.log("and file "+ ref_fname);
	sys.log("Total content length "+filesize+"-bytes");
	sys.log("using "+nb_concurent+" concurent requests");
	sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

	for(var i = 0; i < nb_concurent; i++ ){
		cmp_digest_multiple();
	}
}

//////////////////////////////////////////////////////////////////////////////////
//	stress	test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_stress()
{
	var http_request_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		http_get(url, range_beg, range_len, function(error, data){
			//sys.puts("stress: beg="+range_beg+" len="+range_len+" error="+error);
			if( error === null )	sys.print(".");
			else			sys.log("beg="+range_beg+" len="+range_len+" error="+error);
			http_request_multiple();
		})
	}

	var callback	= function(error, headers){
		//sys.puts('HEADERS: ' + sys.inspect(headers));
		filesize	= parseInt(headers['content-length'], 10);
		// set default range_len_base/range_len_rand
		range_len_base	= range_len_base || Math.floor(filesize / 20);
		range_len_rand	= range_len_rand || Math.floor(range_len_base / 2);
		// clamp range_len_base/range_len_rand
		range_len_base	= Math.min(range_len_base, filesize);
		range_len_rand	= Math.min(range_len_rand, range_len_base);

		// display informations headers
		sys.log("Stress server at url "+url);
		sys.log("Total content length "+filesize+"-bytes");
		sys.log("using "+nb_concurent+" concurent requests");
		sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

		for(var i = 0; i < nb_concurent; i++ ){
			http_request_multiple();
		}
	}

	ezhttp.http_resp_headers(url, callback);
}

//////////////////////////////////////////////////////////////////////////////////
//	main program								//
//////////////////////////////////////////////////////////////////////////////////
if( ref_fname !== undefined )	do_test_accuracy();
else				do_test_stress();

<commit_msg>oload_stress_test.js: better comment 	modified:   contrib/oload_stress_test/oload_stress_test.js<commit_after>#!/usr/bin/env node
/**
 * Mode of operation
 * - check result accuracy
 *   - get a url, and a local path for the same content
 *   - do request on the url and on the local file, and check the result are the same
 * - load test
 *   - get an url on a static content
 *   - just hammer the server with random request
 * Usage Example:
 * ./oload_stress_test.js -l 30k -r 5k `neoip-url http://lo^Clhost/~jerome/Videos/Fearless.mp4` ~/Videos/Fearless.mp4
*/

// system dependancies
var sys		= require('sys');
var fs		= require('fs');
// local dependancies
var cmp_digest	= require('./test_accuracy').cmp_digest;
var http_get	= require('../vendor/node-helpers/ez_http').http_get;
var ezhttp	= require('../vendor/node-helpers/ez_http');
var ttyc	= require('../vendor/node-helpers/ez_tty_color');
var strutils	= require('../vendor/node-helpers/strutils');

// default parameters for cmdline options
var range_len_base	= null;
var range_len_rand	= null;
var nb_concurent	= 1;

//////////////////////////////////////////////////////////////////////////////////
//	parse cmdline								//
//////////////////////////////////////////////////////////////////////////////////
var optind	= 2;
for(;optind < process.argv.length; optind++){
	var key	= process.argv[optind];
	var val	= process.argv[optind+1];
	//sys.puts("key="+key+" val="+val);
	if( key == "-c" || key == "--concurent" ){
		nb_concurent	= parseInt(val);
		optind		+= 1;
	}else if( key == "-l" || key == "--req_length_base" ){
		range_len_base	= strutils.string_to_size(val);
		optind		+= 1;
		//sys.puts("range_len_base="+range_len_base);
	}else if( key == "-r" || key == "--req_length_rand" ){
		range_len_rand	= strutils.string_to_size(val);
		optind		+= 1;
	}else if( key == "-h" || key == "--help" ){
		sys.puts("usage: oload_stress_test [-c ncnx] [-l nbytes] [-r nbytes] URL [filename]");
		sys.puts(" - If <filename> is present, an accuracy test is performed. AKA data are loaded from");
		sys.puts("   the reference file and from the <URL> and both are checked to be equal.");
		sys.puts(" - If <filename> is not present, a stress test is performed. AKA data are loaded from");
		sys.puts("   the url as fast as possible.");
		sys.puts("");
		sys.puts("-c|--concurent ncnx\t\tDetermine the number of concurent connections during the tests.");
		sys.puts("-l|--req_length_base nbytes\tThe base length of the request to make");
		sys.puts("-r|--req_length_rand nbytes\tThe randomized length of the request to make");
		process.exit(0);
	}else{
		// if the option doesnt exist, consider it is the first non-option parameters
		break;
	}
}

// get url/ref_fname from cmdline
var url		= process.argv[optind++];
var ref_fname	= process.argv[optind++];

//////////////////////////////////////////////////////////////////////////////////
//	accuracy test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_accuracy()
{
	var filesize	= fs.statSync(ref_fname).size
	// set default range_len_base/range_len_rand
	range_len_base	= range_len_base || (filesize / 20.0);
	range_len_rand	= range_len_rand || (range_len_base / 2.0);
	// clamp range_len_base/range_len_rand
	range_len_base	= Math.min(range_len_base, filesize);
	range_len_rand	= Math.min(range_len_rand, range_len_base);

	var cmp_digest_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		cmp_digest(url, ref_fname, range_beg, range_len, function(err, succeed){
			if( succeed )	sys.print(".");
			else		sys.puts("accuracy: beg="+range_beg+" len="+range_len+" succeed="+succeed);
			cmp_digest_multiple();
		})
	}

	// display informations headers
	sys.log("Check accuracy between url "+url);
	sys.log("and file "+ ref_fname);
	sys.log("Total content length "+filesize+"-bytes");
	sys.log("using "+nb_concurent+" concurent requests");
	sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

	for(var i = 0; i < nb_concurent; i++ ){
		cmp_digest_multiple();
	}
}

//////////////////////////////////////////////////////////////////////////////////
//	stress	test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_stress()
{
	var http_request_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		http_get(url, range_beg, range_len, function(error, data){
			//sys.puts("stress: beg="+range_beg+" len="+range_len+" error="+error);
			if( error === null )	sys.print(".");
			else			sys.log("beg="+range_beg+" len="+range_len+" error="+error);
			http_request_multiple();
		})
	}

	var callback	= function(error, headers){
		//sys.puts('HEADERS: ' + sys.inspect(headers));
		filesize	= parseInt(headers['content-length'], 10);
		// set default range_len_base/range_len_rand
		range_len_base	= range_len_base || Math.floor(filesize / 20);
		range_len_rand	= range_len_rand || Math.floor(range_len_base / 2);
		// clamp range_len_base/range_len_rand
		range_len_base	= Math.min(range_len_base, filesize);
		range_len_rand	= Math.min(range_len_rand, range_len_base);

		// display informations headers
		sys.log("Stress server at url "+url);
		sys.log("Total content length "+filesize+"-bytes");
		sys.log("using "+nb_concurent+" concurent requests");
		sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

		for(var i = 0; i < nb_concurent; i++ ){
			http_request_multiple();
		}
	}

	ezhttp.http_resp_headers(url, callback);
}

//////////////////////////////////////////////////////////////////////////////////
//	main program								//
//////////////////////////////////////////////////////////////////////////////////
if( ref_fname !== undefined )	do_test_accuracy();
else				do_test_stress();

<|endoftext|>


<commit_before>'use strict';
class QuantityUpdate {
  constructor(htmlDivElement) {
    this.elem        = htmlDivElement;
    this.plus        = this.elem.querySelector('.quantity-update__button--plus');
    this.minus       = this.elem.querySelector('.quantity-update__button--minus');
    this.input       = this.elem.querySelector('.quantity-update__input');
    this.activeClass = 'quantity-update--active';
    this.events();
    this.evaluateConditions();
  }
  events() {
    this.plus.addEventListener('click', () => {
      this.increment();
      this.evaluateConditions();
    });
    this.minus.addEventListener('click', () => {
      this.decrement();
      this.evaluateConditions();
    });
    this.input.addEventListener('focusin', () => {
      this.elem.classList.add(this.activeClass);
    });
    this.input.addEventListener('focusout', () => {
      this.elem.classList.remove(this.activeClass);
    });
  }
  evaluateConditions() {
    this.input.value > 0 ? this.disableMinus() : this.enableMinus();
  }
  increment() {
    this.input.value = Number(this.input.value) + 1;
  }
  decrement() {
    if (this.input.value >= 1) {
      this.input.value = Number(this.input.value) - 1;
    }
  }
  disableMinus() {
    this.minus.classList.remove('quantity-update__button--disabled')
  }
  enableMinus() {
    this.minus.classList.add('quantity-update__button--disabled')
  }
}

(function quantityUpdateObjectsInit() {
  [...document.querySelectorAll('.quantity-update')].forEach((htmlDivElement) => {
    new QuantityUpdate(htmlDivElement);
  });
})();
<commit_msg>65250 add event trigger for increment & decrement value in qty input<commit_after>'use strict';
class QuantityUpdate {
  constructor(htmlDivElement) {
    this.elem        = htmlDivElement;
    this.plus        = this.elem.querySelector('.quantity-update__button--plus');
    this.minus       = this.elem.querySelector('.quantity-update__button--minus');
    this.input       = this.elem.querySelector('.quantity-update__input');
    this.activeClass = 'quantity-update--active';
    this.events();
    this.evaluateConditions();
  }
  events() {
    this.plus.addEventListener('click', (ev) => {
      this.increment();
      this.evaluateConditions();
      this.triggerInput(ev);
    });
    this.minus.addEventListener('click', (ev) => {
      this.decrement();
      this.evaluateConditions();
      this.triggerInput(ev);
    });
    this.input.addEventListener('focusin', () => {
      this.elem.classList.add(this.activeClass);
    });
    this.input.addEventListener('focusout', () => {
      this.elem.classList.remove(this.activeClass);
    });
  }
  triggerInput() {
    const event = new Event('change', {
      'bubbles': true,
      'cancelable': true
    });

    this.input.dispatchEvent(event);
  }
  evaluateConditions() {
    this.input.value > 0 ? this.disableMinus() : this.enableMinus();
  }
  increment() {
    this.input.value = Number(this.input.value) + 1;
  }
  decrement() {
    if (this.input.value >= 1) {
      this.input.value = Number(this.input.value) - 1;
    }
  }
  disableMinus() {
    this.minus.classList.remove('quantity-update__button--disabled')
  }
  enableMinus() {
    this.minus.classList.add('quantity-update__button--disabled')
  }
}

(function quantityUpdateObjectsInit() {
  [...document.querySelectorAll('.quantity-update')].forEach((htmlDivElement) => {
    new QuantityUpdate(htmlDivElement);
  });
})();
<|endoftext|>


<commit_before>/* Web Utilities */
/*! CopyRight: juuen, Licensed under: MIT */
; (function ($, window, document, undefined) {
    //Web常用方法扩展库
    var webutils = function () { };

    //url utils for web
    webutils.url = {
        _url: function (u) { return u || window.location.href; },
        get: function (name, uri) {
            var value = new RegExp('[\?&]' + name + '=([^&#]*)', 'i').exec(this._url(uri));
            return value == null ? null : value[1];
        },
        set: function (name, value, uri) {
            var _u = this._url(uri);
            if (_u.indexOf(name + '=') > 0) {
                return _u.replace(new RegExp('([\?&])' + name + '=[^&#]*', 'i'), '$1' + name + '=' + value);
            } else {
                return _u + (_u.indexOf('?') > 0 ? '&' : '?') + name + '=' + value;
                //考虑锚点待定
            }
        }
    };

    //xml utils for web
    webutils.xml = {
        callXslt: function (options) {
            var settings = {
                type: 'GET',
                dataType: 'text'//输出text类型可避免DOM/MSDOM差异带来的兼容性问题。
            };
            $.extend(settings, options);
            $.ajax({
                type: settings.type,
                url: settings.url,
                data: settings.data,
                dataType: settings.dataType,
                success: function (result) {
                    if (typeof (XSLTProcessor) == "undefined") {
                        var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.6.0");
                        xslDoc.loadXML(result);
                        var xslt = new ActiveXObject("Msxml2.XSLTemplate.6.0");
                        xslt.stylesheet = xslDoc;
                        var xslProc = xslt.createProcessor();
                        xslProc.input = settings.xml;
                        xslProc.transform();
                        settings.success(xslProc.output);
                    } else {
                        var xsltProcessor = new XSLTProcessor();
                        xsltProcessor.importStylesheet((new DOMParser()).parseFromString(result, "text/xml"));
                        var resultDocument = xsltProcessor.transformToFragment(settings.xml, document);
                        settings.success(resultDocument);
                    }
                },
                error: settings.error
            });
        }
    };

    //Web常用对象扩展库
    //....

    //扩展DOM方法

    //扩展Date方法format()
    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

    //访问接口
    //if (typeof $ != undefined) {
    //    $.wu = webutils;
    //} else {
    window.webutils = webutils;
    //}

})(jQuery, window, document);
<commit_msg>url方法及Date扩展更新<commit_after>/* Web Utilities */
/*! CopyRight: juuen, Licensed under: MIT */
; (function ($, window, document, undefined) {
    //Web常用方法扩展库
    var webutils = function () { };

    //url utils for web
    webutils.url = {
        _url: function (u) { return u || window.location.href; },
        get: function (name, uri) {
            var value = new RegExp('[\?&]' + name + '=([^&#]*)', 'i').exec(this._url(uri));
            return value == null ? null : decodeURIComponent(value[1]);
        },
        set: function (name, value, uri) {
            var _u = this._url(uri);
            if (_u.indexOf(name + '=') > 0) {
                return _u.replace(new RegExp('([\?&])' + name + '=[^&#]*', 'i'), '$1' + name + '=' + encodeURIComponent(value));
            } else {
                return _u + (_u.indexOf('?') > 0 ? '&' : '?') + name + '=' + encodeURIComponent(value);
                //考虑锚点待定
            }
        }
    };

    //
    webutils.xml = {
        callXslt: function (options) {
            var settings = {
                type: 'GET',
                dataType: 'text'//输出text类型可避免DOM/MSDOM差异带来的兼容性问题。
            };
            $.extend(settings, options);
            $.ajax({
                type: settings.type,
                url: settings.url,
                data: settings.data,
                dataType: settings.dataType,
                success: function (result) {
                    if (typeof (XSLTProcessor) == "undefined") {
                        var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.6.0");
                        xslDoc.loadXML(result);
                        var xslt = new ActiveXObject("Msxml2.XSLTemplate.6.0");
                        xslt.stylesheet = xslDoc;
                        var xslProc = xslt.createProcessor();
                        xslProc.input = settings.xml;
                        xslProc.transform();
                        settings.success(xslProc.output);
                    } else {
                        var xsltProcessor = new XSLTProcessor();
                        xsltProcessor.importStylesheet((new DOMParser()).parseFromString(result, "text/xml"));
                        var resultDocument = xsltProcessor.transformToFragment(settings.xml, document);
                        settings.success(resultDocument);
                    }
                },
                error: settings.error
            });
        }
    };
    //Web常用对象扩展库
    //....

    //扩展DOM方法

    //扩展Date方法format()
    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

    Date.prototype.firstdate = function () {
        return new Date(this.getFullYear(), this.getMonth(), 1);
    }

    Date.prototype.lastdate = function () {
        return new Date(this.getFullYear(), this.getMonth() + 1, 0);
    }
    //访问接口
    //if (typeof $ != undefined) {
    //    $.wu = webutils;
    //} else {
    window.webutils = webutils;
    //}

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


<commit_before>'use strict';

const rp = require('request-promise-native');
const he = require('he');

const Microservices = require('../configs/microservices');

const self = module.exports = {

    // creates a thumbnail for a given slide
    createThumbnail: function(slideContent, slideId, theme='default') {
        let encodedContent = he.encode(slideContent, { allowUnsafeSymbols: true });

        return rp.post({
            uri: `${Microservices.file.uri}/slideThumbnail/${slideId}/${theme}`,
            body: encodedContent,
            headers: {
                'Content-Type': 'text/plain'
            },
        });
    },

};
<commit_msg>Use new thumbnail submission route in file service<commit_after>'use strict';

const rp = require('request-promise-native');
const he = require('he');

const Microservices = require('../configs/microservices');

const self = module.exports = {

    // creates a thumbnail for a given slide
    createThumbnail: function(slideContent, slideId, theme='default') {
        let encodedContent = he.encode(slideContent, { allowUnsafeSymbols: true });

        return rp.post({
            uri: `${Microservices.file.uri}/thumbnail/slide/${slideId}/${theme}`,
            body: encodedContent,
            headers: {
                'Content-Type': 'text/plain'
            },
        });
    },

};
<|endoftext|>


<commit_before>var ajaxLoadImg = "";

var AliasList = function(){}
AliasList.prototype = {
    aliases : [],
    numAddedLast: 0,
    add: function(aliases) {
        var oldLen = this.aliases.length
        this.aliases = _.union(aliases, this.aliases)
        this.numAddedLast = this.aliases.length - oldLen
        return this.numAddedLast
    },
    count: function() {
        return this.aliases.length
    }
}

var AliasListInputs = function() {}
AliasListInputs.prototype = {
    aliases: new AliasList(),
    init: function() {
        var that = this

        this.textareaPlaceholders()
        this.initHelpModals()

        // import orcid, github, and slideshare from usernames
        $(".control-group.username input")
            .each(function(){
                $(this).blur(function(){
                    if (!$(this).val()) return false
                    var importer = new UsernameImporter(that.aliases, this)
                    importer.import()
            })
        })

    },
    textareaPlaceholders: function() {
        // placeholder replacement
        $("textarea").each(function(){
            var this$ = $(this)
            var placeholderText = this$.attr("data-placeholder")
            this$.val(placeholderText).addClass("default")
            this$.blur(function(){
                if (!this$.val()) {
                    this$.val(placeholderText).addClass("default")
                    return false
                }
            })
            this$.focus(function(){
                if (this$.val() == placeholderText){
                    this$.val("").removeClass("default")
                }
            })
        })
    },
    initHelpModals: function(){

        $("#google-scholar-help-link").click(function(){
            $("#google-scholar-help").modal("show")
            return false
        })
        $("#orcid-help-link").click(function(){
            $("#orcid-help").modal("show")
            return false
        })
        $("#bibtex-fail-help a").click(function(){
            $(".modal").modal("hide")
            if ($(this).hasClass("uservoice")) {
                UserVoice.showPopupWidget()
            }
        })
    }
}

// Import aliases that have been directly entered in textareas:
var TextAreaImporter = function(aliases, elem) {
    this.aliases = aliases
    this.elem = elem
}
TextAreaImporter.prototype = {

    import: function() {
        this.start()
        var inputStr = $(this.elem).val()
        newAliasesCount = this.aliases.add(inputStr.split("\n"))
        this.update()
        this.done()
    },
    start:function() {
        console.log("start ", this.elem)
        $(this.elem)
            .parents("div.control-group")
            .find("label.control-label span.items-added").
            remove()
    },
    update: function(){},
    done: function(aliases){
        $("p#artcounter span").html(this.aliases.count())
        $(this.elem)
            .parents("div.control-group")
            .find("label.control-label span.main")
            .after("Added "+this.aliases.numAddedLast+" items")
    }
}

// Import aliases from external services that want a username
var UsernameImporter = function(aliases, elem) {
    this.aliases = aliases
    this.elem$ = $(elem)
    this.inputClasses = ["ready", "working", "success", "failure"]
}
UsernameImporter.prototype = {

    import: function() {
        var that = this
        this.start()
        var providerName = this.elem$.attr("id").replace("input_", "")
        var queryStr = this.elem$.val()

        $.ajax({
            url: "http://"+api_root+"/provider/"+providerName+"/memberitems/"+queryStr+"?method=sync",
            type: "GET",
            dataType: "json",
            success: function(data){that.done.call(that, data)},
            error: function(request){that.failure.call(that, request)}
        });

    },
    changeControlGroupState: function(newClassName){
        var classesToRemove = _.without(this.inputClasses, "ready").join(" ")
        this.elem$
            .parents(".control-group")
            .removeClass(this.inputClasses.join(" "))
            .addClass(newClassName)
    },
    start:function() {
        this.changeControlGroupState("working")
    },
    update: function(){},
    done: function(data){
        this.changeControlGroupState("success")
        this.aliases.add(data.memberitems)
        this.elem$
            .parents(".control-group")
            .find("span.success span.value")
            .html(this.aliases.numAddedLast)
        $("p#artcounter span").html(this.aliases.count())
    },
    failure: function(request) {
        this.changeControlGroupState("failure")
    }
}

<commit_msg>bibtex uploads form, gets query hash back from server.<commit_after>
var AliasList = function(){}
AliasList.prototype = {
    aliases : [],
    numAddedLast: 0,
    add: function(aliases) {
        var oldLen = this.aliases.length
        this.aliases = _.union(aliases, this.aliases)
        this.numAddedLast = this.aliases.length - oldLen
        return this.numAddedLast
    },
    count: function() {
        return this.aliases.length
    }
}

var AliasListInputs = function() {}
AliasListInputs.prototype = {
    aliases: new AliasList(),
    init: function() {
        var that = this

        this.textareaPlaceholders()
        this.initHelpModals()

        // import orcid, github, and slideshare from usernames
        $(".control-group.username input")
            .each(function(){
                $(this).blur(function(){
                    if (!$(this).val()) return false
                    var importer = new UsernameImporter(that.aliases, this)
                    importer.import()
            })
        })

        // import from bibtex
        $("input#input_bibtex").change(function(){
            var importer = new BibtexImporter(that.aliases, this)
            importer.import()
        })

    },
    textareaPlaceholders: function() {
        // placeholder replacement
        $("textarea").each(function(){
            var this$ = $(this)
            var placeholderText = this$.attr("data-placeholder")
            this$.val(placeholderText).addClass("default")
            this$.blur(function(){
                if (!this$.val()) {
                    this$.val(placeholderText).addClass("default")
                    return false
                }
            })
            this$.focus(function(){
                if (this$.val() == placeholderText){
                    this$.val("").removeClass("default")
                }
            })
        })
    },
    initHelpModals: function(){

        $("#google-scholar-help-link").click(function(){
            $("#google-scholar-help").modal("show")
            return false
        })
        $("#orcid-help-link").click(function(){
            $("#orcid-help").modal("show")
            return false
        })
        $("#bibtex-fail-help a").click(function(){
            $(".modal").modal("hide")
            if ($(this).hasClass("uservoice")) {
                UserVoice.showPopupWidget()
            }
        })
    }
}

// Import aliases from external services that want a username
var UsernameImporter = function(aliases, elem) {
    this.aliases = aliases
    this.elem$ = $(elem)
    this.inputClasses = ["ready", "working", "success", "failure"]
}
UsernameImporter.prototype = {

    import: function() {
        var that = this
        this.start()
        var providerName = this.elem$.attr("id").replace("input_", "")
        var queryStr = this.elem$.val()

        $.ajax({
            url: "http://"+api_root+"/provider/"+providerName+"/memberitems/"+queryStr+"?method=sync",
            type: "GET",
            dataType: "json",
            success: function(data){that.done.call(that, data)},
            error: function(request){that.failure.call(that, request)}
        });

    },
    changeControlGroupState: function(newClassName){
        var classesToRemove = _.without(this.inputClasses, "ready").join(" ")
        this.elem$
            .parents(".control-group")
            .removeClass(this.inputClasses.join(" "))
            .addClass(newClassName)
    },
    start:function() {
        this.changeControlGroupState("working")
    },
    update: function(){},
    done: function(data){
        this.changeControlGroupState("success")
        this.aliases.add(data.memberitems)
        this.elem$
            .parents(".control-group")
            .find("span.success span.value")
            .html(this.aliases.numAddedLast)
        $("p#artcounter span").html(this.aliases.count())
    },
    failure: function(request) {
        this.changeControlGroupState("failure")
    }
}

// upload bibtex from google scholar
var BibtexImporter = function(aliases, elem) {
    this.aliases = aliases
    this.elem$ = $(elem)
    this.inputClasses = ["ready", "working", "success", "failure"]
}
BibtexImporter.prototype = {

    import: function() {
        var that = this
        this.start()
        var providerName = this.elem$.attr("id").replace("input_", "")

        var formData = new FormData();
        formData.append('file', this.elem$[0].files[0]);

        $.ajax({
                   url: "http://"+api_root+'/provider/bibtex/memberitems',
                   type: "POST",
                   processData: false,
                   contentType: false,
                   timeout: 120*1000,  // 120 seconds, because bibtex is very slow
                   data: formData,
                   dataType: "json",
                   success:  function(response,status,xhr){
                       query_hash = response.query_hash
                       console.log("started update request; got this query_hash back: " + query_hash)
//                       update_bibtex_progress(query_hash)
                   },
                   error: function(XMLHttpRequest, textStatus, errorThrown) {
                       console.log("error")
                       return true
                       $("span.loading").remove()
                       $("div.fileupload span.added").remove()
                       $("div.fileupload").append("sorry, there was an error.")
                   }
               });

    },
    changeControlGroupState: function(newClassName){
        var classesToRemove = _.without(this.inputClasses, "ready").join(" ")
        this.elem$
            .parents(".control-group")
            .removeClass(this.inputClasses.join(" "))
            .addClass(newClassName)
    },
    start:function() {
        this.changeControlGroupState("working")
    },
    update: function(){},
    done: function(data){
        this.changeControlGroupState("success")
        this.aliases.add(data.memberitems)
        this.elem$
            .parents(".control-group")
            .find("span.success span.value")
            .html(this.aliases.numAddedLast)
        $("p#artcounter span").html(this.aliases.count())
    },
    failure: function(request) {
        this.changeControlGroupState("failure")
    }
}
<|endoftext|>


<commit_before>---
---
/*In order to access variables from _config.yml we are allowing this here,
* this so we only specigy the categories in one location.
*/

(function(window) {

  /* Google Analytics Categories */
  var companyCategory = '{{site.analytics.categories.company}}';
  var newcomerCategory = '{{site.analytics.categories.newcomer}}';
  var ctaCategory = '{{site.analytics.categories.cta}}';

  /**
  * Convenience function for tracking using Google Analytics
  * Since we only post events this function can be used for all tracking at this point.
  *
  @ param category    The category to post the event under
  @ param action      Action (type of click) that was performed
  @ param label       The label you want to use to describe the event
  */
  function gaTracking(category, action, label) {
    ga('send', {
      hitType: 'event',
      eventCategory: category,
      eventAction: action,
      eventLabel: label
    });
  }

  function findValueWithName(array, name) {
    var value;

    array.forEach(function(object) {
      if (object.name === name) {
        value = object.value;
      }
    });

    return value;
  }

  function trackNewcomerSignupDone() {
    if ($('.js-newcomer-register-submit-thanks').length > 0) {
      gaTracking(newcomerCategory,
                'click',
                'Wintrgarden - Finished signup');
    }
  }

  function trackNewcomerSignupStart() {
    var trackNewcomer = function(selector, eventLabel) {
      $(document).on('click', selector, function() {
        gaTracking(newcomerCategory,
                   'started',
                   eventLabel);
      });
    }

    var newcomerStart = 'Wintrgarden - Started signup';
    trackNewcomer('.js-wintrgarden-signup-no-reg', newcomerStart + ' (No reg.)');
    trackNewcomer('.js-wintrgarden-signup-reg', newcomerStart + ' (Reg.)');
  }

  function trackCompanySignup() {
    $('.js-company-signup-form').submit(function() {
      gaTracking(companyCategory, 'submit', 'Company has submitted interest for JA');
    });
  }

  function trackNewcomerRegPopupOpen() {
    $('.cd-popup-trigger-newcomer-signup').on('click', function() {
      gaTracking(
        newcomerCategory,
        'click',
        'Registration popup open');
    });
  }

  function trackCompanyRegPopupOpen() {
    $('.cd-popup-trigger-signin').on('click', function() {
      gaTracking(
        companyCategory,
        'click',
        'Registration popup open');
    });
  }

  function initTrackOfDOMElements() {
    $('[data-action]').each(function() {
      var $element = $(this);
      var category =  $element.attr('category');
      var action = $element.attr('data-action') || 'click';
      var label = $element.attr('data-action-label');

      if (!category) {
        console.error('[just-track] category can *not* be blank!');
      } else if (label) {
        // Add event listener to element
        $element.on(action, function() {
          gaTracking(
            category,
            action,
            label
          );
        });
      } else {
        console.error('[just-track] data-action-label can *not* be blank!')
      }
    });
  }

  function trackJobCardClick() {
    $(document).on('click', '.job-card', function() {
      gaTracking(ctaCategory, 'click', 'Job card on startpage clicked');
    });
  }

  var JustTrack = {
    init: function() {
      trackCompanySignup();
      trackNewcomerSignupStart();
      trackNewcomerSignupDone();
      trackNewcomerRegPopupOpen();
      trackCompanyRegPopupOpen();
      initTrackOfDOMElements();
      trackJobCardClick();
    }
  };

  window.JustTrack = JustTrack;
})(window);
<commit_msg>Semantics fix (whatever makes Per happy :) )<commit_after>---
---
/*In order to access variables from _config.yml we are allowing this here,
* this so we only specigy the categories in one location.
*/

(function(window) {

  /* Google Analytics Categories */
  var companyCategory = '{{site.analytics.categories.company}}';
  var newcomerCategory = '{{site.analytics.categories.newcomer}}';
  var ctaCategory = '{{site.analytics.categories.cta}}';

  /**
  * Convenience function for tracking using Google Analytics
  * Since we only post events this function can be used for all tracking at this point.
  *
  @ param category    The category to post the event under
  @ param action      Action (type of click) that was performed
  @ param label       The label you want to use to describe the event
  */
  function gaTracking(category, action, label) {
    ga('send', {
      hitType: 'event',
      eventCategory: category,
      eventAction: action,
      eventLabel: label
    });
  }

  function findValueWithName(array, name) {
    var value;

    array.forEach(function(object) {
      if (object.name === name) {
        value = object.value;
      }
    });

    return value;
  }

  function trackNewcomerSignupDone() {
    if ($('.js-newcomer-register-submit-thanks').length > 0) {
      gaTracking(newcomerCategory,
                'click',
                'Wintrgarden - Finished signup');
    }
  }

  function trackNewcomerSignupStart() {
    var trackNewcomer = function(selector, eventLabel) {
      $(document).on('click', selector, function() {
        gaTracking(newcomerCategory,
                   'started',
                   eventLabel);
      });
    }

    var newcomerStart = 'Wintrgarden - Started signup';
    trackNewcomer('.js-wintrgarden-signup-no-reg', newcomerStart + ' (No reg.)');
    trackNewcomer('.js-wintrgarden-signup-reg', newcomerStart + ' (Reg.)');
  }

  function trackCompanySignup() {
    $('.js-company-signup-form').submit(function() {
      gaTracking(companyCategory, 'submit', 'Company has submitted interest for JA');
    });
  }

  function trackNewcomerRegPopupOpen() {
    $('.cd-popup-trigger-newcomer-signup').on('click', function() {
      gaTracking(
        newcomerCategory,
        'click',
        'Registration popup open');
    });
  }

  function trackCompanyRegPopupOpen() {
    $('.cd-popup-trigger-signin').on('click', function() {
      gaTracking(
        companyCategory,
        'click',
        'Indicate interest popup open');
    });
  }

  function initTrackOfDOMElements() {
    $('[data-action]').each(function() {
      var $element = $(this);
      var category =  $element.attr('category');
      var action = $element.attr('data-action') || 'click';
      var label = $element.attr('data-action-label');

      if (!category) {
        console.error('[just-track] category can *not* be blank!');
      } else if (label) {
        // Add event listener to element
        $element.on(action, function() {
          gaTracking(
            category,
            action,
            label
          );
        });
      } else {
        console.error('[just-track] data-action-label can *not* be blank!')
      }
    });
  }

  function trackJobCardClick() {
    $(document).on('click', '.job-card', function() {
      gaTracking(ctaCategory, 'click', 'Job card on startpage clicked');
    });
  }

  var JustTrack = {
    init: function() {
      trackCompanySignup();
      trackNewcomerSignupStart();
      trackNewcomerSignupDone();
      trackNewcomerRegPopupOpen();
      trackCompanyRegPopupOpen();
      initTrackOfDOMElements();
      trackJobCardClick();
    }
  };

  window.JustTrack = JustTrack;
})(window);
<|endoftext|>


<commit_before>function filePickerController($scope, dialogService) {

    $scope.openPicker = function () {
        dialogService.open({
            template: "/App_Plugins/FilePicker/filepickerdialog.html",
            callback: populate,
            dialogData: {
                filter: $scope.model.config.filter,
                folder: $scope.model.config.folder
            }
        });
    };

    $scope.remove = function () {
        $scope.model.value = "";
    };

    function populate(data) {
        $scope.model.value = $scope.model.config.folder + data;
    };
};
angular.module("umbraco").controller("Our.Umbraco.FilePickerController", filePickerController);

function folderPickerController($scope, dialogService) {
    $scope.openPicker = function () {
        dialogService.open({
            template: "/App_Plugins/FilePicker/folderpickerdialog.html",
            callback: populate
        });
    };
    function populate(data) {
        $scope.model.value = "/" + data;
    };

};
angular.module("umbraco").controller("Our.Umbraco.FolderPickerController", folderPickerController);

function filePickerDialogController($scope, dialogService) {

    $scope.dialogEventHandler = $({});
    $scope.dialogEventHandler.bind("treeNodeSelect", nodeSelectHandler);

    function nodeSelectHandler(ev, args) {
        args.event.preventDefault();
        args.event.stopPropagation();
        if (args.node.icon !== "icon-folder")
            $scope.submit(args.node.id);
    };
};
angular.module("umbraco").controller("Our.Umbraco.FilePickerDialogController", filePickerDialogController);

function folderPickerDialogController($scope, dialogService) {

    $scope.dialogEventHandler = $({});
    $scope.dialogEventHandler.bind("treeNodeSelect", nodeSelectHandler);

    function nodeSelectHandler(ev, args) {
        args.event.preventDefault();
        args.event.stopPropagation();
        $scope.submit(args.node.id);
    };
};
angular.module("umbraco").controller("Our.Umbraco.FolderPickerDialogController", folderPickerDialogController);<commit_msg>Updated model value to be an array<commit_after>function filePickerController($scope, dialogService) {
    $scope.model.value = $scope.model.value || [];

    $scope.openPicker = function () {
        dialogService.open({
            template: "/App_Plugins/FilePicker/filepickerdialog.html",
            callback: populate,
            dialogData: {
                filter: $scope.model.config.filter,
                folder: $scope.model.config.folder
            }
        });
    };

    $scope.remove = function (item) {
        $scope.model.value.filter(function (obj) {
            return obj !== item;
        });
    };

    function populate(data) {
        var file = $scope.model.config.folder + data;
        if ($scope.model.value.indexOf(file) === -1) {
            $scope.model.value.push(file);
        }
    };
};
angular.module("umbraco").controller("Our.Umbraco.FilePickerController", filePickerController);

function folderPickerController($scope, dialogService) {
    $scope.openPicker = function () {
        dialogService.open({
            template: "/App_Plugins/FilePicker/folderpickerdialog.html",
            callback: populate
        });
    };
    function populate(data) {
        $scope.model.value = "/" + data;
    };

};
angular.module("umbraco").controller("Our.Umbraco.FolderPickerController", folderPickerController);

function filePickerDialogController($scope, dialogService) {
    $scope.dialogEventHandler = $({});
    $scope.dialogEventHandler.bind("treeNodeSelect", nodeSelectHandler);

    function nodeSelectHandler(ev, args) {
        args.event.preventDefault();
        args.event.stopPropagation();
        if (args.node.icon !== "icon-folder")
            $scope.submit(args.node.id);
    };
};
angular.module("umbraco").controller("Our.Umbraco.FilePickerDialogController", filePickerDialogController);

function folderPickerDialogController($scope, dialogService) {
    $scope.dialogEventHandler = $({});
    $scope.dialogEventHandler.bind("treeNodeSelect", nodeSelectHandler);

    function nodeSelectHandler(ev, args) {
        args.event.preventDefault();
        args.event.stopPropagation();
        $scope.submit(args.node.id);
    };
};
angular.module("umbraco").controller("Our.Umbraco.FolderPickerDialogController", folderPickerDialogController);
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// init ui
		this.initDonate();

	} // init()

, initDonate: function() {

		$('body').on('submit', '#donate-form', function() {
			var defaultAmount = 20;

			var $specify = $('#donate-specify');
			var $amount = $('#donate-amount');

			$amount.val('').prop('checked',false);
			var specify = parseInt($specify.val());
			if ( typeof(specify) != 'NaN' && specify > 0 ) {
				$amount.val(specify).prop('checked',true);
			} else {
				$amount.val('');
			}

			var amount = parseInt($('input[name="amount"]:checked').val());
			if ( (typeof(specify) == 'NaN') || !(specify > 0) ) {
				$amount.val(defaultAmount).prop('checked',true);
			}

			console.log( $('input[name="amount"]:checked').val() );

			//$('input', this).prop('disabled', true);
			//$('button', this).prop('disabled', true);

			return false;

		});

  } // initDonate()

, toggleCheckboxGroup: function(all, item, scope) {
		var $selectAll;
		var $selectItem;
		if ( scope ) {
			$selectAll = $(all, scope);
			$selectItem = $(item, scope);
		} else {
			$selectAll = $(all);
			$selectItem = $(item);
		}

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<commit_msg>donate<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// init ui
		this.initDonate();

	} // init()

, initDonate: function() {

		$('body').on('submit', '#donate-form', function() {
			var defaultAmount = 20;

			var $specify = $('#donate-specify');
			var $amount = $('#donate-amount');

			//$amount.val('').prop('checked',false);
			var specify = parseInt($specify.val());
			if ( typeof(specify) != 'NaN' && specify > 0 ) {
				$amount.val(specify).prop('checked',true);
			} else {
				$amount.val('');
			}

			/*
			var amount = parseInt($('input[name="amount"]:checked').val());
			if ( (typeof(specify) == 'NaN') || !(specify > 0) ) {
				$amount.val(defaultAmount).prop('checked',true);
			}
			*/

			console.log( $('input[name="amount"]:checked').val() );

			//$('input', this).prop('disabled', true);
			//$('button', this).prop('disabled', true);

			return false;

		});

  } // initDonate()

, toggleCheckboxGroup: function(all, item, scope) {
		var $selectAll;
		var $selectItem;
		if ( scope ) {
			$selectAll = $(all, scope);
			$selectItem = $(item, scope);
		} else {
			$selectAll = $(all);
			$selectItem = $(item);
		}

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<|endoftext|>


<commit_before>// Filename: views/form.js
define([
  'jquery',
  'underscore',
  'backbone',
  'bootstrap',
  'js/views/equation.js',
  '/js/views/html5.js',
  'js/views/sign_up.js',
  'js/models/equation.js',
  'js/models/html5.js',
  'text!/templates/form.html'
], function($, _, Backbone, Bootstrap, EquationView, Html5View, SignUpView, Equation, Html5, formTemplate) {
  var FormView = Backbone.View.extend({

    tagName:  "div",

    events: {
      "submit .mml-editor": "submitConversionForm",
      "click input[name=conversionType]": "toggleFormSection",
      "click .register": "showRegisterModal"
    },

    render: function() {
      var formView = this;
      var compiledTemplate = _.template(formTemplate)({user: App.user});
      formView.$el.html(compiledTemplate);
      return this;
    },

    submitConversionForm: function(e) {
      e.preventDefault();
      var formView = this;
      formView.$("#go").val("Processing...");
      var conversionType = formView.$("input[name=conversionType]:checked");
      if (conversionType.attr("id") == "singleEquation") {
        formView.convertEquation(e);
      } else {
        formView.uploadHtml5(e);
      }
    },

    uploadHtml5: function(e) {
      var formView = this;
      if ($("#html5").val() == "") {
        alert ("Please select a HTML5 file to upload.");
        formView.$("#go").val("Process");
        return false;
      }
      formView.$(".errorMessage").html("");
      $("#results").html("");
      var data = new FormData();
      data.append("outputFormat", $("input[name='outputFormat']:checked").val());
      if (typeof(App.user) != "undefined") {
        data.append("access_token", App.user.get("access_token"));
      }
      data.append("html5", formView.$("#html5")[0].files[0], formView.$("#html5")[0].files[0].name);
      $.ajax({
        url: '/html5',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST'
      }).fail(function(jqXHR, textStatus, errorThrown) {
        var errResponse = $.parseJSON(jqXHR.responseText);
        var errMsg = errResponse.message ? errResponse.message : jqXHR.responseText;
        formView.$(".errorMessage").text("There was an error converting your math: " + errMsg);
        formView.$("#go").val("Process");
        setTimeout(function() {
          formView.$(".errorMessage").attr('tabindex', '-1').focus();
        }, 500);
      }).success(function(data) {
        App.router.navigate('#/html5/' + data.id, {trigger: true});
      });
    },

    convertEquation: function(e) {
      var formView = this;
      formView.$(".errorMessage").html("");
      $("#results").html("");
      if (formView.$("#mml-input").val() != "") {
        formView.convert();
      } else {
        alert("Please enter an equation.");
      }
    },

    convert: function() {
      var formView = this;
      var equation = new Equation();
      equation.set({
        math: formView.$("textarea[name=math]").val(),
        mathType: formView.$("input[name=mathType]:checked").val(),
        svg: true,
        mml: true,
        png: true,
        description: true
      });
      if (typeof(App.user) != "undefined") {
        equation.set({access_token: App.user.get("access_token")});
      }
      equation.save(null, {
        success: function(model, response, options) {
          App.router.navigate('#/equation/' + response.id, {trigger: true});
        },
        error: function(model, response, options) {
          formView.$(".errorMessage").text("There was an error converting your math: " + response);
          setTimeout(function() {
            formView.$(".errorMessage").attr('tabindex', '-1').focus();
          }, 500);
          formView.$("#go").val("Process");
        }
      });
    },

    hideOutputOptions: function() {
      $("#outputOptions").hide();
    },

    toggleFormSection: function(e) {
      var radio = $(e.currentTarget);
      var enable = radio.prop("id");
      var disable = enable == "singleEquation" ? "multipleEquations" : "singleEquation";
      $("." + enable).prop("disabled", false);
      $("." + disable).prop("disabled", true);

    },

    showRegisterModal: function(e) {
      e.preventDefault();
      var signUpView = new SignUpView();
      signUpView.render();
      $("#mmlcModal").modal('show');
      $("#mmlcModal").on('hidden.bs.modal', function (e) {
        App.navBar.render();
      });
    }
  });
  // Our module now returns our view
  return FormView;
});<commit_msg>MMLC-91: Display conversion error message.<commit_after>// Filename: views/form.js
define([
  'jquery',
  'underscore',
  'backbone',
  'bootstrap',
  'js/views/equation.js',
  '/js/views/html5.js',
  'js/views/sign_up.js',
  'js/models/equation.js',
  'js/models/html5.js',
  'text!/templates/form.html'
], function($, _, Backbone, Bootstrap, EquationView, Html5View, SignUpView, Equation, Html5, formTemplate) {
  var FormView = Backbone.View.extend({

    tagName:  "div",

    events: {
      "submit .mml-editor": "submitConversionForm",
      "click input[name=conversionType]": "toggleFormSection",
      "click .register": "showRegisterModal"
    },

    render: function() {
      var formView = this;
      var compiledTemplate = _.template(formTemplate)({user: App.user});
      formView.$el.html(compiledTemplate);
      return this;
    },

    submitConversionForm: function(e) {
      e.preventDefault();
      var formView = this;
      formView.$("#go").val("Processing...");
      var conversionType = formView.$("input[name=conversionType]:checked");
      if (conversionType.attr("id") == "singleEquation") {
        formView.convertEquation(e);
      } else {
        formView.uploadHtml5(e);
      }
    },

    uploadHtml5: function(e) {
      var formView = this;
      if ($("#html5").val() == "") {
        alert ("Please select a HTML5 file to upload.");
        formView.$("#go").val("Process");
        return false;
      }
      formView.$(".errorMessage").html("");
      $("#results").html("");
      var data = new FormData();
      data.append("outputFormat", $("input[name='outputFormat']:checked").val());
      if (typeof(App.user) != "undefined") {
        data.append("access_token", App.user.get("access_token"));
      }
      data.append("html5", formView.$("#html5")[0].files[0], formView.$("#html5")[0].files[0].name);
      $.ajax({
        url: '/html5',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST'
      }).fail(function(jqXHR, textStatus, errorThrown) {
        var errResponse = $.parseJSON(jqXHR.responseText);
        var errMsg = errResponse.message ? errResponse.message : jqXHR.responseText;
        formView.$(".errorMessage").text("There was an error converting your math: " + errMsg);
        formView.$("#go").val("Process");
        setTimeout(function() {
          formView.$(".errorMessage").attr('tabindex', '-1').focus();
        }, 500);
      }).success(function(data) {
        App.router.navigate('#/html5/' + data.id, {trigger: true});
      });
    },

    convertEquation: function(e) {
      var formView = this;
      formView.$(".errorMessage").html("");
      $("#results").html("");
      if (formView.$("#mml-input").val() != "") {
        formView.convert();
      } else {
        alert("Please enter an equation.");
      }
    },

    convert: function() {
      var formView = this;
      var equation = new Equation();
      equation.set({
        math: formView.$("textarea[name=math]").val(),
        mathType: formView.$("input[name=mathType]:checked").val(),
        svg: true,
        mml: true,
        png: true,
        description: true
      });
      if (typeof(App.user) != "undefined") {
        equation.set({access_token: App.user.get("access_token")});
      }
      equation.save(null, {
        success: function(model, response, options) {
          App.router.navigate('#/equation/' + response.id, {trigger: true});
        },
        error: function(model, response, options) {
			var message = response.responseJSON.message || "Unknown";
			formView.$(".errorMessage").text("There was an error converting your math: " + message);
          setTimeout(function() {
            formView.$(".errorMessage").attr('tabindex', '-1').focus();
          }, 500);
          formView.$("#go").val("Process");
        }
      });
    },

    hideOutputOptions: function() {
      $("#outputOptions").hide();
    },

    toggleFormSection: function(e) {
      var radio = $(e.currentTarget);
      var enable = radio.prop("id");
      var disable = enable == "singleEquation" ? "multipleEquations" : "singleEquation";
      $("." + enable).prop("disabled", false);
      $("." + disable).prop("disabled", true);

    },

    showRegisterModal: function(e) {
      e.preventDefault();
      var signUpView = new SignUpView();
      signUpView.render();
      $("#mmlcModal").modal('show');
      $("#mmlcModal").on('hidden.bs.modal', function (e) {
        App.navBar.render();
      });
    }
  });
  // Our module now returns our view
  return FormView;
});<|endoftext|>


<commit_before>// bbcode editor button definitions for AIM Enhanced.

window._hansen = {};

window._hansen.buttons = [
{
  id: 'text_editor_cmd_bold',
  accesskey: 'b',
  src: 'https://illiweb.com/fa/wysiwyg/text_bold.png',
  tag: 'b'
},
{
  id: 'text_editor_cmd_italic',
  accesskey: 'i',
  src: 'https://illiweb.com/fa/wysiwyg/text_italic.png',
  tag: 'i'
},
{
  id: 'text_editor_cmd_underline',
  accesskey: 'u',
  src: 'https://illiweb.com/fa/wysiwyg/text_underline.png',
  tag: 'u'
},
{
  id: 'text_editor_cmd_strikethrough',
  accesskey: 'x',
  src: 'https://illiweb.com/fa/wysiwyg/text_strikethrough.png',
  tag: 'strike'
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'text_editor_cmd_justifyleft',
  accesskey: 'm',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_left.png',
  tag: 'left'
},
{
  id: 'text_editor_cmd_justifycenter',
  accesskey: 't',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_center.png',
  tag: 'center'
},
{
  id: 'text_editor_cmd_justifyright',
  accesskey: 'g',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_right.png',
  tag: 'right'
},
{
  id: 'text_editor_cmd_justifyfull',
  accesskey: 'jt',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_justify.png',
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'text_editor_cmd_insertunorderedlist',
  accesskey: 'l',
  src: 'https://illiweb.com/fa/wysiwyg/text_list_bullets.png',
  tag: 'list'
},
{
  id: 'text_editor_cmd_insertorderedlist',
  accesskey: 'o',
  src: 'https://illiweb.com/fa/wysiwyg/text_list_numbers.png',
  tag: 'list'
},
{
  id: 'text_editor_cmd_inserthorizontalrule',
  accesskey: '',
  src: 'https://illiweb.com/fa/wysiwyg/text_horizontalrule.png',
  tag: 'hr'
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'text_editor_cmd_wrap0_quote',
  accesskey: 'q',
  src: 'https://illiweb.com/fa/wysiwyg/comments.png',
  tag: 'quote'
},
{
  id: 'text_editor_cmd_wrap0_code',
  accesskey: 'c',
  src: 'https://illiweb.com/fa/wysiwyg/page_white_code.png',
  tag: 'code'
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'bbcodewimg',
  accesskey: 'p',
  src: 'https://illiweb.com/fa/wysiwyg/picture.png',
  tag: 'img'
},
{
  id: 'addbbcode16',
  accesskey: 'w',
  src: 'https://illiweb.com/fa/wysiwyg/link.png',
  tag: 'url'
},

];
<commit_msg>this is some weeeird behavior<commit_after>// bbcode editor button definitions for AIM Enhanced.

if (!window._hansen)
  window._hansen = {};

const buttons = window._hansen.buttons = [
{
  id: 'text_editor_cmd_bold',
  accesskey: 'b',
  src: 'https://illiweb.com/fa/wysiwyg/text_bold.png',
  tag: 'b'
},
{
  id: 'text_editor_cmd_italic',
  accesskey: 'i',
  src: 'https://illiweb.com/fa/wysiwyg/text_italic.png',
  tag: 'i'
},
{
  id: 'text_editor_cmd_underline',
  accesskey: 'u',
  src: 'https://illiweb.com/fa/wysiwyg/text_underline.png',
  tag: 'u'
},
{
  id: 'text_editor_cmd_strikethrough',
  accesskey: 'x',
  src: 'https://illiweb.com/fa/wysiwyg/text_strikethrough.png',
  tag: 'strike'
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'text_editor_cmd_justifyleft',
  accesskey: 'm',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_left.png',
  tag: 'left'
},
{
  id: 'text_editor_cmd_justifycenter',
  accesskey: 't',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_center.png',
  tag: 'center'
},
{
  id: 'text_editor_cmd_justifyright',
  accesskey: 'g',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_right.png',
  tag: 'right'
},
{
  id: 'text_editor_cmd_justifyfull',
  accesskey: 'jt',
  src: 'https://illiweb.com/fa/wysiwyg/text_align_justify.png',
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'text_editor_cmd_insertunorderedlist',
  accesskey: 'l',
  src: 'https://illiweb.com/fa/wysiwyg/text_list_bullets.png',
  tag: 'list'
},
{
  id: 'text_editor_cmd_insertorderedlist',
  accesskey: 'o',
  src: 'https://illiweb.com/fa/wysiwyg/text_list_numbers.png',
  tag: 'list'
},
{
  id: 'text_editor_cmd_inserthorizontalrule',
  accesskey: '',
  src: 'https://illiweb.com/fa/wysiwyg/text_horizontalrule.png',
  tag: 'hr'
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'text_editor_cmd_wrap0_quote',
  accesskey: 'q',
  src: 'https://illiweb.com/fa/wysiwyg/comments.png',
  tag: 'quote'
},
{
  id: 'text_editor_cmd_wrap0_code',
  accesskey: 'c',
  src: 'https://illiweb.com/fa/wysiwyg/page_white_code.png',
  tag: 'code'
},

'https://illiweb.com/fa/wysiwyg/separator.png',

{
  id: 'bbcodewimg',
  accesskey: 'p',
  src: 'https://illiweb.com/fa/wysiwyg/picture.png',
  tag: 'img'
},
{
  id: 'addbbcode16',
  accesskey: 'w',
  src: 'https://illiweb.com/fa/wysiwyg/link.png',
  tag: 'url'
},

];
<|endoftext|>