<commit_before>if(typeof module !== 'undefined' && module.exports) var PIXI = require('pixi.js');

PIXI.GraphicsRenderer.prototype.buildPolygonLine = PIXI.GraphicsRenderer.prototype.buildLine;

PIXI.GraphicsRenderer.prototype.buildLine = function(graphicsData, webGLData) {
	if (graphicsData.lineWidth === 1) {
		webGLData.drawNativeLine = true;
		this.buildNativeLine(graphicsData, webGLData);
	} else {
		webGLData.drawNativeLine = false;
		this.buildPolygonLine(graphicsData, webGLData);
	}
};

PIXI.GraphicsRenderer.prototype.buildNativeLine = function(graphicsData, webGLData) {

	var i = 0;
	var points = graphicsData.points;

	if (points.length === 0) return;

	var verts = webGLData.points;
	//var indices = webGLData.indices;
	var length = points.length / 2;
	var indexCount = points.length;
	var indexStart = verts.length / 6;

	// sort color
	var color = PIXI.hex2rgb(graphicsData.lineColor);
	var alpha = graphicsData.lineAlpha;
	var r = color[0] * alpha;
	var g = color[1] * alpha;
	var b = color[2] * alpha;

	var p1x, p1y, p2x, p2y;

	for (i = 1; i < length; i++) {
		p1x = points[(i - 1) * 2];
		p1y = points[(i - 1) * 2 + 1];

		p2x = points[i * 2];
		p2y = points[i * 2 + 1];

		verts.push(p1x, p1y);
		verts.push(r, g, b, alpha);

		verts.push(p2x, p2y);
		verts.push(r, g, b, alpha);
	}

	/*for (i = 0; i < indexCount; i++) {
		indices.push(indexStart++);
	}*/

};

PIXI.GraphicsRenderer._oldRender = PIXI.GraphicsRenderer.prototype.render;

PIXI.GraphicsRenderer.prototype.render = function(graphics) {
	var renderer = this.renderer;
	var gl = renderer.gl;
	var shader = renderer.shaderManager.plugins.primitiveShader,
		webGLData;
	if (graphics.dirty) {
		this.updateGraphics(graphics, gl);
	}
	var webGL = graphics._webGL[gl.id];
	// This could be speeded up for sure!
	renderer.blendModeManager.setBlendMode(graphics.blendMode);
	// var matrix = graphics.worldTransform.clone();
	// var matrix = renderer.currentRenderTarget.projectionMatrix.clone();
	// matrix.append(graphics.worldTransform);
	for (var i = 0; i < webGL.data.length; i++) {
		if (webGL.data[i].mode === 1) {
			webGLData = webGL.data[i];
			renderer.stencilManager.pushStencil(graphics, webGLData, renderer);
			// render quad..
			gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, (webGLData.indices.length - 4) * 2);
			renderer.stencilManager.popStencil(graphics, webGLData, renderer);
		} else {
			webGLData = webGL.data[i];
			shader = renderer.shaderManager.primitiveShader;
			renderer.shaderManager.setShader(shader); //activatePrimitiveShader();
			gl.uniformMatrix3fv(shader.uniforms.translationMatrix._location, false, graphics.worldTransform.toArray(true));
			gl.uniformMatrix3fv(shader.uniforms.projectionMatrix._location, false, renderer.currentRenderTarget.projectionMatrix.toArray(true));
			gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint));
			gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha);
			gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
			gl.vertexAttribPointer(shader.attributes.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
			gl.vertexAttribPointer(shader.attributes.aColor, 4, gl.FLOAT, false, 4 * 6, 2 * 4);

			if (webGLData.drawNativeLine)
				gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6);
			else {
				// set the index buffer!
				gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
				gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0);
			}
		}
	}
};
<commit_msg>added utils for new pixi functions. Now only works with browserify<commit_after>var PIXI = require('pixi.js');

var utils = PIXI.utils;

PIXI.GraphicsRenderer.prototype.buildPolygonLine = PIXI.GraphicsRenderer.prototype.buildLine;

PIXI.GraphicsRenderer.prototype.buildLine = function(graphicsData, webGLData) {
	if (graphicsData.lineWidth === 1) {
		webGLData.drawNativeLine = true;
		this.buildNativeLine(graphicsData, webGLData);
	} else {
		webGLData.drawNativeLine = false;
		this.buildPolygonLine(graphicsData, webGLData);
	}
};

PIXI.GraphicsRenderer.prototype.buildNativeLine = function(graphicsData, webGLData) {

	var i = 0;
	var points = graphicsData.points;

	if (points.length === 0) return;

	var verts = webGLData.points;
	//var indices = webGLData.indices;
	var length = points.length / 2;
	var indexCount = points.length;
	var indexStart = verts.length / 6;

	// sort color
	var color = utils.hex2rgb(graphicsData.lineColor);
	var alpha = graphicsData.lineAlpha;
	var r = color[0] * alpha;
	var g = color[1] * alpha;
	var b = color[2] * alpha;

	var p1x, p1y, p2x, p2y;

	for (i = 1; i < length; i++) {
		p1x = points[(i - 1) * 2];
		p1y = points[(i - 1) * 2 + 1];

		p2x = points[i * 2];
		p2y = points[i * 2 + 1];

		verts.push(p1x, p1y);
		verts.push(r, g, b, alpha);

		verts.push(p2x, p2y);
		verts.push(r, g, b, alpha);
	}

	/*for (i = 0; i < indexCount; i++) {
		indices.push(indexStart++);
	}*/

};

PIXI.GraphicsRenderer._oldRender = PIXI.GraphicsRenderer.prototype.render;

PIXI.GraphicsRenderer.prototype.render = function(graphics) {
	var renderer = this.renderer;
	var gl = renderer.gl;
	var shader = renderer.shaderManager.plugins.primitiveShader,
		webGLData;
	if (graphics.dirty) {
		this.updateGraphics(graphics, gl);
	}
	var webGL = graphics._webGL[gl.id];
	// This could be speeded up for sure!
	renderer.blendModeManager.setBlendMode(graphics.blendMode);
	// var matrix = graphics.worldTransform.clone();
	// var matrix = renderer.currentRenderTarget.projectionMatrix.clone();
	// matrix.append(graphics.worldTransform);
	for (var i = 0; i < webGL.data.length; i++) {
		if (webGL.data[i].mode === 1) {
			webGLData = webGL.data[i];
			renderer.stencilManager.pushStencil(graphics, webGLData, renderer);
			// render quad..
			gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, (webGLData.indices.length - 4) * 2);
			renderer.stencilManager.popStencil(graphics, webGLData, renderer);
		} else {
			webGLData = webGL.data[i];
			shader = renderer.shaderManager.primitiveShader;
			renderer.shaderManager.setShader(shader); //activatePrimitiveShader();
			gl.uniformMatrix3fv(shader.uniforms.translationMatrix._location, false, graphics.worldTransform.toArray(true));
			gl.uniformMatrix3fv(shader.uniforms.projectionMatrix._location, false, renderer.currentRenderTarget.projectionMatrix.toArray(true));
			gl.uniform3fv(shader.uniforms.tint._location, utils.hex2rgb(graphics.tint));
			gl.uniform1f(shader.uniforms.alpha._location, graphics.worldAlpha);
			gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
			gl.vertexAttribPointer(shader.attributes.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
			gl.vertexAttribPointer(shader.attributes.aColor, 4, gl.FLOAT, false, 4 * 6, 2 * 4);

			if (webGLData.drawNativeLine)
				gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6);
			else {
				// set the index buffer!
				gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
				gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0);
			}
		}
	}
};
<|endoftext|>


<commit_before>/**
 * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
/*browser:true*/
/*global define*/
define(
    [
        'jquery',
        'uiComponent',
        'mage/translate',
        'jquery/ui',
        'jquery/validate'
    ],
    function ($, Class, $t) {
        'use strict';
        var pollTimer, windowOpen = false;

        return Class.extend({

                defaults: {
                    $amazonFields: null,
                    $amazonCredentialJson: null,
                    $amazonSpBack: null,
                    $amazonMerchantId: null,
                    selector: 'amazon_payment',
                    $container: null,
                    pollInterval: 1500,
                    $form: null,
                },

                /**
                 * Set list of observable attributes
                 * @returns {exports.initObservable}
                 */
                initObservable: function () {
                    var self = this;

                    self.$amazonSimplepath = $('#amazon_simplepath');
                    self.$amazonFields = $('#payment_' + self.getCountry() + '_' + self.selector + ' .form-list');
                    self.$amazonCredentialsHeader = $('#payment_' + self.getCountry() + '_' + self.selector
                        + '_credentials-head');
                    self.$amazonCredentialJson = $('#payment_' + self.getCountry() + '_' + self.selector
                        + '_credentials_credentials_json');
                    self.$amazonMerchantId = $('#payment_' + self.getCountry() + '_' + self.selector
                        + '_credentials_merchant_id').val();
                    self.$amazonSpBack = $('#amazon_simplepath_back');
                    self.$container = $('#amazon_simplepath');

                    if (self.$amazonMerchantId) {
                        self.hideAmazonConfig();
                    }
                    else {
                        self.showAmazonConfig();
                    }

                    if (!self.$form) {
                        self.generateSimplePathForm();
                    }

                    self._super();

                    self.initEventHandlers();

                    return self;
                },

                /**
                 * Init event handlers
                 */
                initEventHandlers: function () {
                    var self = this;

                    self.$amazonSpBack.click(function () {
                        self.showAmazonConfig();
                        return false;
                    });

                    $('#simplepath-skip').click(function () {
                        self.hideAmazonConfig();
                        return false;
                    });

                    $('#simplepath_form').on('submit', function () {
                        self.setupWindowLaunch();
                    });

                    self.$amazonCredentialJson.on('input', function () {
                        self.updateCredentials(self);
                    });
                },

                /**
                 * Detects when a properly formatted JSON block is pasted into the Credentials JSON field
                 * and auto populates specified fields.
                 *
                 * @param self
                 */
                updateCredentials: function (self) {
                    var elJson = self.$amazonCredentialJson.val(), obj = null, success = true, item = null;

                    try {
                        obj = $.parseJSON($.trim(elJson));
                    }
                    catch (err) {
                        obj = null;
                        self.$amazonCredentialJson.val('').attr(
                            'placeholder',
                            $t('Invalid JSON credentials entered, please try again.')
                        ).focus();
                    }

                    if (obj && typeof obj === 'object') {

                        for (var prop in obj) {
                            if (obj.hasOwnProperty(prop)) {
                                item = $('#payment_' + self.getCountry() + '_amazon_payment_credentials_'
                                    + $.trim(prop));

                                if (item && item.length) {
                                    $('#payment_' + self.getCountry() + '_amazon_payment_credentials_'
                                        + $.trim(prop)).val($.trim(obj[prop]));
                                }
                                else {
                                    success = false;
                                }
                            }
                        }

                        if (success) {
                            self.$amazonCredentialJson.val('').attr(
                                'placeholder',
                                $t('Credential fields successfully updated and being saved.')
                            ).focus();
                            $('#save').click();
                        }
                        else {
                            self.$amazonCredentialJson.val('').attr(
                                'placeholder',
                                $t('One or more of your credential fields did not parse correctly. ' +
                                    'Please review your entry and try again.')
                            ).focus();
                        }
                    }
                },

                /**
                 * Sets up Amazon merchant key popup and polls for data update upon user completion.
                 */
                setupWindowLaunch: function () {
                    var self = this,
                        heights = [660, 720, 810, 900],
                        popupWidth = this.getCountry() !== 'us' ? 768 : 1050, popupHeight = heights[0],
                        region = self.region,
                        elCheckDefault = $('#payment_' + self.getCountry()
                            + '_amazon_payment_credentials_payment_region_inherit:checked'),
                        elRegion = $('payment_' + self.getCountry() + '_amazon_payment_credentials_payment_region'),
                        elJson = self.$amazonCredentialJson.val();

                    for (var i in heights) {
                        if (heights.hasOwnProperty(i)) {
                            popupHeight = window.innerHeight >= heights[i] ? heights[i] : popupHeight;
                        }
                    }

                    self.launchPopup(self.amazonUrl, popupWidth, popupHeight);

                    // flags that popup is open and poll timer can proceed
                    windowOpen = true;

                    // begin polling for feedback
                    pollTimer = setTimeout(self.pollForKeys(self), self.pollInterval);

                    // Save JSON
                    $('#save-json').click(function (e) {
                        e.stop();
                        var json = $('#json-import').value;

                        if (!json || !json.isJSON()) {
                            return;
                        }
                        elJson.value = json;
                        $('#save').click();
                    });

                    // Autoset payment region (for EU/UK)
                    if (self.region.indexOf('eu') !== -1) {
                        region = 'de';
                    }

                    if (elCheckDefault && elCheckDefault.length) {
                        elCheckDefault[0].click();
                    }

                    if (elRegion) {
                        elRegion.value = region;
                    }
                },

                /**
                 * Perform Ajax request looking for new keys.
                 */
                pollForKeys: function (self) {
                    clearTimeout(pollTimer);
                    if (windowOpen) {
                        $.ajax({
                            url: self.pollUrl,
                            data: {},
                            type: 'GET',
                            cache: true,
                            dataType: 'json',
                            context: this,

                            /**
                             * Response handler
                             * @param {Object} response
                             */
                            success: function (response) {
                                // poll controller returns a 0 if invalid and a 1 if valid
                                if (response) {
                                    $('#amazon_reload').show();
                                    document.location.replace(document.location + '#payment_amazon_payments-head');
                                    location.reload();
                                }
                                else {
                                    pollTimer = setTimeout(self.pollForKeys(self), self.pollInterval);
                                }
                            }
                        });
                    }
                },

                /**
                 * Sets up dynamic form for capturing popup/form input for simple path setup.
                 */
                generateSimplePathForm: function () {
                    var spElement = null;

                    this.$form = new Element('form', {
                        method: 'post',
                        action: this.amazonUrl,
                        id: 'simplepath_form',
                        target: 'simplepath',
                        novalidate: 'novalidate',
                    });

                    this.$container.wrap(this.$form);

                    // Convert formParams JSON to hidden inputs
                    for (var key in this.formParams) {
                        if (typeof this.formParams[key] == 'object' || typeof this.formParams[key] === 'array') {
                            for (var i in this.formParams[key]) {
                                if (typeof this.formParams[key][i] !== 'function') {
                                    spElement = new Element('input', {
                                        type: 'hidden',
                                        name: key,
                                        value: this.formParams[key][i],
                                        novalidate: 'novalidate'
                                    });

                                    $(spElement).appendTo($("#simplepath_form"));
                                }
                            }
                        } else {
                            spElement = new Element('input', {
                                type: 'hidden',
                                name: key,
                                novalidate: 'novalidate',
                                value: this.formParams[key]
                            });

                            $(spElement).appendTo($("#simplepath_form"));
                        }
                    }

                    // unable to use this.form, had to resort to direct call
                    $('#simplepath_form').validate({});
                },

                /**
                 * display amazon simple path config section
                 */
                showAmazonConfig: function () {
                    this.$amazonSimplepath.show();
                    this.$amazonSpBack.hide();
                    if (this.$amazonCredentialsHeader.hasClass('open')) {
                        this.$amazonCredentialsHeader.click();
                    }
                },

                /**
                 * hide amazon simple path config.
                 */
                hideAmazonConfig: function () {
                    this.$amazonSimplepath.hide();
                    this.$amazonSpBack.show();
                    if (!this.$amazonCredentialsHeader.hasClass('open')) {
                        this.$amazonCredentialsHeader.click();
                    }
                },

                /**
                 * Get payment code
                 * @returns {String}
                 */
                getCountry: function () {
                    return this.co.toLowerCase();
                },

                /**
                 * Generate popup window for simple path process
                 * @param url
                 * @param requestedWidth
                 * @param requestedHeight
                 */
                launchPopup: function (url, requestedWidth, requestedHeight) {
                    var leftOffset = this.getLeftOffset(requestedWidth),
                        topOffset = this.getTopOffset(requestedHeight),
                        newWindow = window.open(url, 'simplepath', 'scrollbars=yes, width=' + requestedWidth
                            + ', height=' + requestedHeight + ', top=' + topOffset + ', left=' + leftOffset);

                    if (window.focus) {
                        newWindow.focus();
                    }

                    // Set interval to check when this popup window is closed so timeout can be suspended.
                    var winTimer = window.setInterval(function () {
                        if (newWindow.closed !== false) {
                            window.clearInterval(winTimer);
                            windowOpen = false;
                        }
                    });
                },

                /**
                 * Determine left offset for popup window
                 * @param requestedWidth
                 * @returns {number}
                 */
                getLeftOffset: function (requestedWidth) {
                    var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;

                    return (this.windowWidth() / 2) - (requestedWidth / 2) + dualScreenLeft;
                },

                /**
                 * Determine top offset for popup window
                 * @param requestedHeight
                 * @returns {number}
                 */
                getTopOffset: function (requestedHeight) {
                    var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

                    return (this.windowHeight() / 2) - (requestedHeight / 2) + dualScreenTop;
                },

                /**
                 * Determine width of popup window
                 * @returns {number}
                 */
                windowWidth: function () {
                    if (window.innerWidth) {
                        return window.innerWidth;
                    } else if (document.documentElement.clientWidth) {
                        return document.documentElement.clientWidth;
                    }

                    return screen.width;
                },

                /**
                 * Determine window height of popup
                 * @returns {number}
                 */
                windowHeight: function () {
                    if (window.innerHeight) {
                        return window.innerHeight;
                    } else if (document.documentElement.clientHeight) {
                        return document.documentElement.clientHeight;
                    }

                    return screen.height;
                }
            }
        );
    }
);
<commit_msg>Update - fixes issues in last Magento PR (#396)<commit_after>/**
 * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
/*browser:true*/
/*global define*/
define(
    [
        'jquery',
        'uiComponent',
        'mage/translate',
        'jquery/ui',
        'jquery/validate'
    ],
    function ($, Class, $t) {
        'use strict';
        var pollTimer, windowOpen = false;

        return Class.extend({

                defaults: {
                    $amazonFields: null,
                    $amazonCredentialJson: null,
                    $amazonSpBack: null,
                    $amazonMerchantId: null,
                    selector: 'amazon_payment',
                    $container: null,
                    pollInterval: 1500,
                    $form: null,
                },

                /**
                 * Set list of observable attributes
                 * @returns {exports.initObservable}
                 */
                initObservable: function () {
                    var self = this;

                    self.$amazonSimplepath = $('#amazon_simplepath');
                    self.$amazonFields = $('#payment_' + self.getCountry() + '_' + self.selector + ' .form-list');
                    self.$amazonCredentialsHeader = $('#payment_' + self.getCountry() + '_' + self.selector
                        + '_credentials-head');
                    self.$amazonCredentialJson = $('#payment_' + self.getCountry() + '_' + self.selector
                        + '_credentials_credentials_json');
                    self.$amazonMerchantId = $('#payment_' + self.getCountry() + '_' + self.selector
                        + '_credentials_merchant_id').val();
                    self.$amazonSpBack = $('#amazon_simplepath_back');
                    self.$container = $('#amazon_simplepath');

                    if (self.$amazonMerchantId) {
                        self.hideAmazonConfig();
                    }
                    else {
                        self.showAmazonConfig();
                    }

                    if (!self.$form) {
                        self.generateSimplePathForm();
                    }

                    self._super();

                    self.initEventHandlers();

                    return self;
                },

                /**
                 * Init event handlers
                 */
                initEventHandlers: function () {
                    var self = this;

                    self.$amazonSpBack.click(function () {
                        self.showAmazonConfig();
                        return false;
                    });

                    $('#simplepath-skip').click(function () {
                        self.hideAmazonConfig();
                        return false;
                    });

                    $('#simplepath_form').on('submit', function () {
                        self.setupWindowLaunch();
                    });

                    self.$amazonCredentialJson.on('input', function () {
                        self.updateCredentials(self);
                    });
                },

                /**
                 * Detects when a properly formatted JSON block is pasted into the Credentials JSON field
                 * and auto populates specified fields.
                 *
                 * @param self
                 */
                updateCredentials: function (self) {
                    var elJson = self.$amazonCredentialJson.val(), obj = null, success = true, item = null;

                    try {
                        obj = $.parseJSON($.trim(elJson));
                    }
                    catch (err) {
                        obj = null;
                        self.$amazonCredentialJson.val('').attr(
                            'placeholder',
                            $t('Invalid JSON credentials entered, please try again.')
                        ).focus();
                    }

                    if (obj && typeof obj === 'object') {

                        for (var prop in obj) {
                            if (obj.hasOwnProperty(prop)) {
                                item = $('#payment_' + self.getCountry() + '_amazon_payment_credentials_'
                                    + $.trim(prop));

                                if (item && item.length) {
                                    $('#payment_' + self.getCountry() + '_amazon_payment_credentials_'
                                        + $.trim(prop)).val($.trim(obj[prop]));
                                }
                                else {
                                    success = false;
                                }
                            }
                        }

                        if (success) {
                            self.$amazonCredentialJson.val('').attr(
                                'placeholder',
                                $t('Credential fields successfully updated and being saved.')
                            ).focus();
                            $('#save').click();
                        }
                        else {
                            self.$amazonCredentialJson.val('').attr(
                                'placeholder',
                                $t('One or more of your credential fields did not parse correctly. ' +
                                    'Please review your entry and try again.')
                            ).focus();
                        }
                    }
                },

                /**
                 * Sets up Amazon merchant key popup and polls for data update upon user completion.
                 */
                setupWindowLaunch: function () {
                    var self = this,
                        heights = [660, 720, 810, 900],
                        popupWidth = this.getCountry() !== 'us' ? 768 : 1050, popupHeight = heights[0],
                        region = self.region,
                        elCheckDefault = $('#payment_' + self.getCountry()
                            + '_amazon_payment_credentials_payment_region_inherit:checked'),
                        elRegion = $('payment_' + self.getCountry() + '_amazon_payment_credentials_payment_region'),
                        elJson = self.$amazonCredentialJson.val();

                    for (var i in heights) {
                        if (heights.hasOwnProperty(i)) {
                            popupHeight = window.innerHeight >= heights[i] ? heights[i] : popupHeight;
                        }
                    }

                    self.launchPopup(self.amazonUrl, popupWidth, popupHeight);

                    // flags that popup is open and poll timer can proceed
                    windowOpen = true;

                    // begin polling for feedback
                    pollTimer = setTimeout(self.pollForKeys(self), self.pollInterval);

                    // Save JSON
                    $('#save-json').click(function (e) {
                        e.stop();
                        var json = $('#json-import').value;

                        if (!json || !json.isJSON()) {
                            return;
                        }
                        elJson.value = json;
                        $('#save').click();
                    });

                    // Autoset payment region (for EU/UK)
                    if (self.region.indexOf('eu') !== -1) {
                        region = 'de';
                    }

                    if (elCheckDefault && elCheckDefault.length) {
                        elCheckDefault[0].click();
                    }

                    if (elRegion) {
                        elRegion.value = region;
                    }
                },

                /**
                 * Perform Ajax request looking for new keys.
                 */
                pollForKeys: function (self) {
                    clearTimeout(pollTimer);
                    if (windowOpen) {
                        $.ajax({
                            url: self.pollUrl,
                            data: {},
                            type: 'GET',
                            cache: true,
                            dataType: 'json',
                            context: this,

                            /**
                             * Response handler
                             * @param {Object} response
                             */
                            success: function (response) {
                                // poll controller returns a 0 if invalid and a 1 if valid
                                if (response) {
                                    $('#amazon_reload').show();
                                    document.location.replace(document.location + '#payment_amazon_payments-head');
                                    location.reload();
                                }
                                else {
                                    pollTimer = setTimeout(self.pollForKeys(self), self.pollInterval);
                                }
                            }
                        });
                    }
                },

                /**
                 * Sets up dynamic form for capturing popup/form input for simple path setup.
                 */
                generateSimplePathForm: function () {

                    this.$form = new Element('form', {
                        method: 'post',
                        action: this.amazonUrl,
                        id: 'simplepath_form',
                        target: 'simplepath',
                        novalidate: 'novalidate',
                    });

                    this.$container.wrap(this.$form);

                    // Convert formParams JSON to hidden inputs
                    for (var key in this.formParams) {
                        if ( $.isPlainObject(this.formParams[key]) || $.isArray(this.formParams[key])) {
                            for (var i in this.formParams[key]) {
                                if (typeof this.formParams[key][i] !== 'function') {
                                    $(new Element('input', {
                                        type: 'hidden',
                                        name: key,
                                        value: this.formParams[key][i],
                                        novalidate: 'novalidate'
                                    })).appendTo($("#simplepath_form"));
                                }
                            }
                        } else {
                            $(new Element('input', {
                                type: 'hidden',
                                name: key,
                                novalidate: 'novalidate',
                                value: this.formParams[key]
                            })).appendTo($("#simplepath_form"));
                        }
                    }

                    // unable to use this.form, had to resort to direct call
                    $('#simplepath_form').validate({});
                },

                /**
                 * display amazon simple path config section
                 */
                showAmazonConfig: function () {
                    this.$amazonSimplepath.show();
                    this.$amazonSpBack.hide();
                    if (this.$amazonCredentialsHeader.hasClass('open')) {
                        this.$amazonCredentialsHeader.click();
                    }
                },

                /**
                 * hide amazon simple path config.
                 */
                hideAmazonConfig: function () {
                    this.$amazonSimplepath.hide();
                    this.$amazonSpBack.show();
                    if (!this.$amazonCredentialsHeader.hasClass('open')) {
                        this.$amazonCredentialsHeader.click();
                    }
                },

                /**
                 * Get payment code
                 * @returns {String}
                 */
                getCountry: function () {
                    return this.co.toLowerCase();
                },

                /**
                 * Generate popup window for simple path process
                 * @param url
                 * @param requestedWidth
                 * @param requestedHeight
                 */
                launchPopup: function (url, requestedWidth, requestedHeight) {
                    var leftOffset = this.getLeftOffset(requestedWidth),
                        topOffset = this.getTopOffset(requestedHeight),
                        newWindow = window.open(url, 'simplepath', 'scrollbars=yes, width=' + requestedWidth
                            + ', height=' + requestedHeight + ', top=' + topOffset + ', left=' + leftOffset);

                    if (window.focus) {
                        newWindow.focus();
                    }

                    // Set interval to check when this popup window is closed so timeout can be suspended.
                    var winTimer = window.setInterval(function () {
                        if (newWindow.closed !== false) {
                            window.clearInterval(winTimer);
                            windowOpen = false;
                        }
                    });
                },

                /**
                 * Determine left offset for popup window
                 * @param requestedWidth
                 * @returns {number}
                 */
                getLeftOffset: function (requestedWidth) {
                    var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;

                    return (this.windowWidth() / 2) - (requestedWidth / 2) + dualScreenLeft;
                },

                /**
                 * Determine top offset for popup window
                 * @param requestedHeight
                 * @returns {number}
                 */
                getTopOffset: function (requestedHeight) {
                    var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

                    return (this.windowHeight() / 2) - (requestedHeight / 2) + dualScreenTop;
                },

                /**
                 * Determine width of popup window
                 * @returns {number}
                 */
                windowWidth: function () {
                    return window.innerWidth
                        || document.documentElement.clientWidth
                        || screen.width;
                },

                /**
                 * Determine window height of popup
                 * @returns {number}
                 */
                windowHeight: function () {
                    return window.innerHeight
                        || document.documentElement.clientHeight
                        || screen.height;
                }
            }
        );
    }
);
<|endoftext|>


<commit_before>$(document).ready(function() {
  tileListener();

})

function tileListener() {
  $(".arrow").on("click",clickedArrorw());
}

function clickedArrow() {
  var divId = addPiece($(this),color);
  if (divId) {
    // ajax call here
    if (checkForWin()){
      //ajax call to announce winner
    }
    changeColor();
  }

}

// BEGIN BOARD GAME LOGIC//

var color = "black"
var board = [["","","","","","",""],["","","","","","",""],["","","","","","",""],["","","","","","",""],["","","","","","",""],["","","","","","",""]];
var height = 6;
var width = 7;

function changeColor() {
  if (color === "black"){
    color = "red";
  } else if (color === "red"){
    color = "black";
  }
}

function addPiece(column, piece){
  if (board[0][column]){
    console.log("Cannot add a piece there");
    return false;
  }
  if (!board[5][column]){
    console.log(piece + " piece added to column " + column);
    board[5][column] = piece;
    return (50+column);
  }
  for (var row = 1; row < height; row ++){
    if (board[row][column]){
      console.log(piece + " piece added to column " + column);
      board[row-1][column] = piece;
      return ((row * 10)+column);
    }
  }
}

function checkForWin(){
  for (var row = 0; row < height; row ++){
    for (var column = 0; column < width; column ++){
      var space = board[row][column];
      if (space){
        var checkRows = rowCheckMethod(space, row, column);
        var checkColumns = columnCheckMethod(space, row, column);
        var checkDiags = diagCheckMethod(space, row, column)
        if (checkRows || checkColumns || checkDiags){
          return winner(space);
        }else{
          return false;
        }

      }
    }
  }
}

function rowCheckMethod(space, row, column){
  if (row > 2){
    return false;
  }
  var checker = (board[row + 1][column] === space) && (board[row + 2][column] === space) && (board[row + 3][column] === space);
  return checker;
}

function columnCheckMethod(space, row, column){
  var checker = (board[row][column + 1] === space) && (board[row][column + 2] === space) && (board[row][column + 3] === space);
  return checker;
}

function diagCheckMethod(space, row, column){
  return (bckDiagCheckMethod(space, row, column) || fwdDiagCheckMethod(space, row, column));
}

function bckDiagCheckMethod(space, row, column){
  if (row > 2){
    return false
  }
  var backSlash = (board[row + 1][column + 1] === space) && (board[row + 2][column + 2] === space) && (board[row + 3][column + 3] === space);
  return backSlash;
}

function fwdDiagCheckMethod(space, row, column){
  if (row < 3){
    return false
  }
  var forwardSlash = (board[row - 1][column + 1] === space) && (board[row - 2][column + 2] === space) && (board[row - 3][column + 3] === space);
  return forwardSlash;

}

function winner(space){
  return true;
}
<commit_msg>Small change to listeners<commit_after>$(document).ready(function() {
  tileListener();

})

function tileListener() {
  $(".arrow").on("click", function(){
    var arrow = this.attr("id");
    clickedArrow(arrow);
  });
}

function clickedArrow(arrow) {
  var divId = addPiece(arrow,color);
  if (divId) {
    console.log(arrow);
    // ajax call here
    if (checkForWin()){
      //ajax call to announce winner
    }
    changeColor();
  }

}

// BEGIN BOARD GAME LOGIC//

var color = "black"
var board = [["","","","","","",""],["","","","","","",""],["","","","","","",""],["","","","","","",""],["","","","","","",""],["","","","","","",""]];
var height = 6;
var width = 7;

function changeColor() {
  if (color === "black"){
    color = "red";
  } else if (color === "red"){
    color = "black";
  }
}

function addPiece(column, piece){
  if (board[0][column]){
    console.log("Cannot add a piece there");
    return false;
  }
  if (!board[5][column]){
    console.log(piece + " piece added to column " + column);
    board[5][column] = piece;
    var spaceToStr = ("5" + column.toString());
    return spaceToStr;
  }
  for (var row = 1; row < height; row ++){
    if (board[row][column]){
      console.log(piece + " piece added to column " + column);
      board[row-1][column] = piece;
      var spaceToStr = ((row * 10) + column).toString();
      if (spaceToStr.length < 2){
        spaceToStr = "0" + spaceToStr;
      }
      return spaceToStr;
    }
  }
}

function checkForWin(){
  for (var row = 0; row < height; row ++){
    for (var column = 0; column < width; column ++){
      var space = board[row][column];
      if (space){
        var checkRows = rowCheckMethod(space, row, column);
        var checkColumns = columnCheckMethod(space, row, column);
        var checkDiags = diagCheckMethod(space, row, column)
        if (checkRows || checkColumns || checkDiags){
          return winner(space);
        }else{
          return false;
        }

      }
    }
  }
}

function rowCheckMethod(space, row, column){
  if (row > 2){
    return false;
  }
  var checker = (board[row + 1][column] === space) && (board[row + 2][column] === space) && (board[row + 3][column] === space);
  return checker;
}

function columnCheckMethod(space, row, column){
  var checker = (board[row][column + 1] === space) && (board[row][column + 2] === space) && (board[row][column + 3] === space);
  return checker;
}

function diagCheckMethod(space, row, column){
  return (bckDiagCheckMethod(space, row, column) || fwdDiagCheckMethod(space, row, column));
}

function bckDiagCheckMethod(space, row, column){
  if (row > 2){
    return false
  }
  var backSlash = (board[row + 1][column + 1] === space) && (board[row + 2][column + 2] === space) && (board[row + 3][column + 3] === space);
  return backSlash;
}

function fwdDiagCheckMethod(space, row, column){
  if (row < 3){
    return false
  }
  var forwardSlash = (board[row - 1][column + 1] === space) && (board[row - 2][column + 2] === space) && (board[row - 3][column + 3] === space);
  return forwardSlash;

}

function winner(space){
  return true;
}
<|endoftext|>


<commit_before>var app = angular.module("app");

app.controller('TrackCtrl', function($scope, TrackingService) {
    $scope.showCargo = function(trackingId) {
        TrackingService.getCargo(trackingId).$promise.then(function(result) {
            $scope.cargo = result.cargo;
        });
    }
});

app.controller('ListCtrl', function($scope, $modal, $location, BookingService) {
    BookingService.getCargos().$promise.then(function(result) {
        $scope.cargos = result.cargos;
    });

    // Method to open dialog for booking a cargo.
    $scope.open = function() {
        var modalInstance = $modal.open({
            templateUrl: 'views/bookCargo.html',
            controller: 'BookCargoCtrl'
        });

        // Redirect to details page if cargo was booked.
        modalInstance.result.then(function(bookedCargo) {
            $location.path('/details').search('trackingId', bookedCargo.tracking_id);
        });
    };
});

app.controller('BookCargoCtrl', function($scope, $location, BookingService, $modalInstance) {
    // Populate location dropdowns
    BookingService.getLocations().$promise.then(function(result) {
        $scope.locations = result.locations;
        $scope.selectedOrigin = $scope.locations[0].locode
        $scope.selectedDestination = $scope.locations[0].locode
    });
    $scope.selectOrigin = function(locode) {
        $scope.selectedOrigin = locode;
    }
    $scope.selectDestination = function(locode) {
        $scope.selectedDestination = locode;
    }

    // Books a cargo with selected origin, destinal and arrival deadline and closes the modal.
    $scope.bookCargo = function() {
        BookingService.bookCargo($scope.selectedOrigin, $scope.selectedDestination, $scope.deadline.toISOString()).$promise.then(function(result) {
            $modalInstance.close(result);
        });
    }

    // Dismiss the modal.
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

app.controller('DetailsCtrl', function($scope, $modal, $location, BookingService) {
    var trackingId = $location.search().trackingId;
    BookingService.loadCargo(trackingId).$promise.then(function(result) {
        $scope.cargo = result.cargo;
    });

    $scope.open = function() {
        var modalInstance = $modal.open({
            templateUrl: 'views/changeDestination.html',
            controller: 'ChangeDestinationCtrl',
            resolve: {
                cargo: function(BookingService) {
                    return BookingService.loadCargo(trackingId).$promise;
                }
            }
        });

        modalInstance.result.then(function(data) {
            $scope.cargo = data.cargo;
        });
    };
});

app.controller('ChangeDestinationCtrl', function($scope, $modalInstance, cargo, BookingService) {
    cargo = cargo.cargo;

    // Populate location dropdown
    BookingService.getLocations().$promise.then(function(result) {
        $scope.locations = result.locations;
        $scope.selectedDestination = cargo.destination;
    });
    $scope.selectDestination = function(locode) {
        $scope.selectedDestination = locode;
    }

    // Change destination and close the modal.
    $scope.changeDestination = function() {
        BookingService.changeDestination(cargo.tracking_id, $scope.selectedDestination).$promise.then(function() {
            BookingService.loadCargo(cargo.tracking_id).$promise.then(function(result) {
                $modalInstance.close(result);
            });
        });
    }

    // Dismiss the modal.
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

app.controller('SelectItineraryCtrl', function($scope, $location, BookingService) {
    var trackingId = $location.search().tracking_id;

    $scope.cargo = BookingService.loadCargo(trackingId);

    BookingService.requestPossibleRoutes(trackingId).$promise.then(function(result) {
        $scope.routeCandidates = result.routes;
    });

    $scope.assignToRoute = function(itinerary) {
        BookingService.assignToRoute(trackingId, itinerary).$promise.then(function() {
            $location.path('/details').search('trackingId', trackingId);
        });
    }
});

app.controller('SelectBackendCtrl', function($scope, $window, BackendService) {
    $scope.backends = BackendService.getAll();
    $scope.currentBackend = BackendService.getCurrent();

    $scope.selectBackend = function(b) {
        $scope.currentBackend = b;
        BackendService.select(b);
        $window.location.reload();
    }
});

app.controller('IncidentLoggingCtrl', function($scope, IncidentService) {
    $scope.eventTypes = ['Receive', 'Load', 'Unload', 'Customs', 'Claim'];
    $scope.selectedEventType = $scope.eventTypes[0];

    $scope.selectEventType = function(type) {
        $scope.selectedEventType = type;
    }

    $scope.registerIncident = function() {
        var promise = IncidentService.registerIncident($scope.completionTime.getTime(), $scope.trackingId, $scope.voyage, $scope.location, $scope.selectedEventType).$promise.then(function(data) {
            $scope.showMessage = true;
            $scope.showError = false;
        }, function(error) {
            $scope.showError = true;
            $scope.showMessage = false;
        })    }
});
<commit_msg>Fix missing cargo in select itinerary<commit_after>var app = angular.module("app");

app.controller('TrackCtrl', function($scope, TrackingService) {
    $scope.showCargo = function(trackingId) {
        TrackingService.getCargo(trackingId).$promise.then(function(result) {
            $scope.cargo = result.cargo;
        });
    }
});

app.controller('ListCtrl', function($scope, $modal, $location, BookingService) {
    BookingService.getCargos().$promise.then(function(result) {
        $scope.cargos = result.cargos;
    });

    // Method to open dialog for booking a cargo.
    $scope.open = function() {
        var modalInstance = $modal.open({
            templateUrl: 'views/bookCargo.html',
            controller: 'BookCargoCtrl'
        });

        // Redirect to details page if cargo was booked.
        modalInstance.result.then(function(bookedCargo) {
            $location.path('/details').search('trackingId', bookedCargo.tracking_id);
        });
    };
});

app.controller('BookCargoCtrl', function($scope, $location, BookingService, $modalInstance) {
    // Populate location dropdowns
    BookingService.getLocations().$promise.then(function(result) {
        $scope.locations = result.locations;
        $scope.selectedOrigin = $scope.locations[0].locode
        $scope.selectedDestination = $scope.locations[0].locode
    });
    $scope.selectOrigin = function(locode) {
        $scope.selectedOrigin = locode;
    }
    $scope.selectDestination = function(locode) {
        $scope.selectedDestination = locode;
    }

    // Books a cargo with selected origin, destinal and arrival deadline and closes the modal.
    $scope.bookCargo = function() {
        BookingService.bookCargo($scope.selectedOrigin, $scope.selectedDestination, $scope.deadline.toISOString()).$promise.then(function(result) {
            $modalInstance.close(result);
        });
    }

    // Dismiss the modal.
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

app.controller('DetailsCtrl', function($scope, $modal, $location, BookingService) {
    var trackingId = $location.search().trackingId;
    BookingService.loadCargo(trackingId).$promise.then(function(result) {
        $scope.cargo = result.cargo;
    });

    $scope.open = function() {
        var modalInstance = $modal.open({
            templateUrl: 'views/changeDestination.html',
            controller: 'ChangeDestinationCtrl',
            resolve: {
                cargo: function(BookingService) {
                    return BookingService.loadCargo(trackingId).$promise;
                }
            }
        });

        modalInstance.result.then(function(data) {
            $scope.cargo = data.cargo;
        });
    };
});

app.controller('ChangeDestinationCtrl', function($scope, $modalInstance, cargo, BookingService) {
    cargo = cargo.cargo;

    // Populate location dropdown
    BookingService.getLocations().$promise.then(function(result) {
        $scope.locations = result.locations;
        $scope.selectedDestination = cargo.destination;
    });
    $scope.selectDestination = function(locode) {
        $scope.selectedDestination = locode;
    }

    // Change destination and close the modal.
    $scope.changeDestination = function() {
        BookingService.changeDestination(cargo.tracking_id, $scope.selectedDestination).$promise.then(function() {
            BookingService.loadCargo(cargo.tracking_id).$promise.then(function(result) {
                $modalInstance.close(result);
            });
        });
    }

    // Dismiss the modal.
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

app.controller('SelectItineraryCtrl', function($scope, $location, BookingService) {
    var trackingId = $location.search().tracking_id;

	BookingService.loadCargo(trackingId).$promise.then(function(result){
	    $scope.cargo = result.cargo;
	});

    BookingService.requestPossibleRoutes(trackingId).$promise.then(function(result) {
        $scope.routeCandidates = result.routes;
    });

    $scope.assignToRoute = function(itinerary) {
        BookingService.assignToRoute(trackingId, itinerary).$promise.then(function() {
            $location.path('/details').search('trackingId', trackingId);
        });
    }
});

app.controller('SelectBackendCtrl', function($scope, $window, BackendService) {
    $scope.backends = BackendService.getAll();
    $scope.currentBackend = BackendService.getCurrent();

    $scope.selectBackend = function(b) {
        $scope.currentBackend = b;
        BackendService.select(b);
        $window.location.reload();
    }
});

app.controller('IncidentLoggingCtrl', function($scope, IncidentService) {
    $scope.eventTypes = ['Receive', 'Load', 'Unload', 'Customs', 'Claim'];
    $scope.selectedEventType = $scope.eventTypes[0];

    $scope.selectEventType = function(type) {
        $scope.selectedEventType = type;
    }

    $scope.registerIncident = function() {
        var promise = IncidentService.registerIncident($scope.completionTime.getTime(), $scope.trackingId, $scope.voyage, $scope.location, $scope.selectedEventType).$promise.then(function(data) {
            $scope.showMessage = true;
            $scope.showError = false;
        }, function(error) {
            $scope.showError = true;
            $scope.showMessage = false;
        })    }
});
<|endoftext|>


<commit_before><script id="mathjaxscript_pelican_#%@#$@#" type="text/javascript">
//see https://docs.mathjax.org/en/v2.5-latest/configuration.html#using-plain-javascript
    var align = "{{align}}",
        indent = "{{indent}}",
        linebreak = "{{linebreak_automatic}}";

    if ({{responsive}}) {
        align = (screen.width < {{responsive_break}}) ? "left" : align;
        indent = (screen.width < {{responsive_break}}) ? "0em" : indent;
        linebreak = (screen.width < {{responsive_break}}) ? 'true' : linebreak;
    }
    window.MathJax = {
        config: ['MMLorHTML.js'],
        TeX: {
            extensions: {{tex_extensions|join(',')}}],
            equationNumbers: { autoNumber: 'AMS' } },
        jax: ['input/TeX','input/MathML','output/HTML-CSS'],
        extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],
        displayAlign: align,
        displayIndent: indent,
        showMathMenu: '{{show_menu}}',
        messageStyle: '{{mesage_style}}',
        tex2jax: {
            inlineMath: [ ['\\(','\\)'] ],
            displayMath: [ ['$$','$$'] ],
            processEscapes: {{process_escapes}},
            preview: '{{latex_preview}}',
        },
        "HTML-CSS": {
            styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: '{{color}} !important'} },
            linebreaks: { automatic: linebreak, width: '90% container' },
        },
    };
    if ('{{mathjax_font}}' !== 'default') {
        window.MathJax.AuthorInit = function() {
            MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {
                var VARIANT = MathJax.OutputJax['HTML-C}'].FONTDATA.VARIANT;
                VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
                VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
                VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
                VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            });
            MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {
                var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;
                VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
                VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
                VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
                VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            });
        }
    }
</script>
<script id="mathjaxscript_pelican_#%@#$@#"
        type="text/javascript"
        src="{{source}}" >
</script><commit_msg>correctly quote text extensions list<commit_after><script id="mathjaxscript_pelican_#%@#$@#" type="text/javascript">
//see https://docs.mathjax.org/en/v2.5-latest/configuration.html#using-plain-javascript
    var align = "{{align}}",
        indent = "{{indent}}",
        linebreak = "{{linebreak_automatic}}";

    if ({{responsive}}) {
        align = (screen.width < {{responsive_break}}) ? "left" : align;
        indent = (screen.width < {{responsive_break}}) ? "0em" : indent;
        linebreak = (screen.width < {{responsive_break}}) ? 'true' : linebreak;
    }
    window.MathJax = {
        config: ['MMLorHTML.js'],
        TeX: {
            extensions: [
                {% for ext in tex_extensions %}
                    {% if not loop.last %}
                        "{{ext}}",
                    {% else %}
                        "{{ext}}"
                    {% endif %}
                {% endfor %}
            ],
            equationNumbers: { autoNumber: 'AMS' } },
        jax: ['input/TeX','input/MathML','output/HTML-CSS'],
        extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],
        displayAlign: align,
        displayIndent: indent,
        showMathMenu: '{{show_menu}}',
        messageStyle: '{{mesage_style}}',
        tex2jax: {
            inlineMath: [ ['\\(','\\)'] ],
            displayMath: [ ['$$','$$'] ],
            processEscapes: {{process_escapes}},
            preview: '{{latex_preview}}',
        },
        "HTML-CSS": {
            styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: '{{color}} !important'} },
            linebreaks: { automatic: linebreak, width: '90% container' },
        },
    };
    if ('{{mathjax_font}}' !== 'default') {
        window.MathJax.AuthorInit = function() {
            MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {
                var VARIANT = MathJax.OutputJax['HTML-C}'].FONTDATA.VARIANT;
                VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
                VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
                VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
                VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            });
            MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {
                var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;
                VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
                VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
                VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
                VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            });
        }
    }
</script>
<script id="mathjaxscript_pelican_#%@#$@#"
        type="text/javascript"
        src="{{source}}" >
</script><|endoftext|>


<commit_before>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var data = require('./data');
var game = require('game').game;
var status = require('game').status;
var ground = require('./ground');
var socket = require('./socket');
var title = require('./title');
var promotion = require('./promotion');
var hold = require('./hold');
var blur = require('./blur');
var init = require('./init');
var blind = require('./blind');
var clockCtrl = require('./clock/ctrl');
var correspondenceClockCtrl = require('./correspondenceClock/ctrl');
var moveOn = require('./moveOn');
var atomic = require('./atomic');
var sound = require('./sound');
var util = require('./util');

module.exports = function(opts) {

  this.data = data({}, opts.data);

  this.userId = opts.userId;

  this.firstPly = function() {
    return this.data.steps[0].ply;
  }.bind(this);

  this.lastPly = function() {
    return this.data.steps[this.data.steps.length - 1].ply;
  }.bind(this);

  this.plyStep = function(ply) {
    return this.data.steps[ply - this.firstPly()];
  }.bind(this);

  this.vm = {
    ply: this.lastPly(),
    flip: false,
    redirecting: false,
    replayHash: '',
    moveToSubmit: null,
    buttonFeedback: null,
    goneBerserk: {},
    resignConfirm: false
  };
  this.vm.goneBerserk[this.data.player.color] = opts.data.player.berserk;
  this.vm.goneBerserk[this.data.opponent.color] = opts.data.opponent.berserk;

  this.socket = new socket(opts.socketSend, this);

  var onUserMove = function(orig, dest, meta) {
    if (this.data.game.variant.key === 'standard')
      hold.register(this.socket, meta.holdTime);
    if (!promotion.start(this, orig, dest, meta.premove))
      this.sendMove(orig, dest, false, meta.premove);
  }.bind(this);

  var onMove = function(orig, dest, captured) {
    if (captured) {
      if (this.data.game.variant.key === 'atomic') {
        sound.explode();
        atomic.capture(this, dest, captured);
      } else sound.capture();
    } else sound.move();
  }.bind(this);

  this.chessground = ground.make(this.data, opts.data.game.fen, onUserMove, onMove);

  this.replaying = function() {
    return this.vm.ply !== this.lastPly();
  }.bind(this);

  this.stepsHash = function(steps) {
    var h = '';
    for (i in steps) {
      h += steps[i].san;
    }
    return h;
  };

  this.jump = function(ply) {
    if (ply < this.firstPly() || ply > this.lastPly()) return;
    this.vm.ply = ply;
    var s = this.plyStep(ply);
    var config = {
      fen: s.fen,
      lastMove: s.uci ? [s.uci.substr(0, 2), s.uci.substr(2, 2)] : null,
      check: s.check,
      turnColor: this.vm.ply % 2 === 0 ? 'white' : 'black'
    };
    if (this.replaying()) this.chessground.stop();
    else config.movable = {
      color: game.isPlayerPlaying(this.data) ? this.data.player.color : null,
      dests: util.parsePossibleMoves(this.data.possibleMoves)
    }
    this.chessground.set(config);
    if (s.san) {
      if (s.san.indexOf('x') !== -1) sound.capture();
      else sound.move();
      if (/\+|\#/.test(s.san)) sound.check();
    }
  }.bind(this);

  this.replayEnabledByPref = function() {
    var d = this.data;
    return d.pref.replay === 2 || (
      d.pref.replay === 1 && (d.game.speed === 'classical' || d.game.speed === 'unlimited' || d.game.speed === 'correspondence')
    );
  }.bind(this);

  this.isLate = function() {
    return this.replaying() && status.playing(this.data);
  }.bind(this);

  this.flip = function() {
    this.vm.flip = !this.vm.flip;
    this.chessground.set({
      orientation: this.vm.flip ? this.data.opponent.color : this.data.player.color
    });
  }.bind(this);

  this.setTitle = partial(title.set, this);

  this.sendMove = function(orig, dest, prom, isPremove) {
    var move = {
      from: orig,
      to: dest
    };
    if (prom) move.promotion = prom;
    if (blur.get()) move.b = 1;
    if (this.clock) move.lag = Math.round(lichess.socket.averageLag);
    this.resign(false);
    if (this.userId && this.data.pref.submitMove && !isPremove) {
      this.vm.moveToSubmit = move;
      m.redraw();
    } else this.socket.send('move', move, {
      ackable: true
    });
  }.bind(this);

  var showYourMoveNotification = function() {
    if (game.isPlayerTurn(this.data)) lichess.desktopNotification("It's your move!");
  }.bind(this);

  this.apiMove = function(o) {
    m.startComputation();
    var d = this.data;
    d.game.turns = o.ply;
    d.game.player = o.ply % 2 === 0 ? 'white' : 'black';
    var playedColor = o.ply % 2 === 0 ? 'black' : 'white';
    if (o.status) d.game.status = o.status;
    if (o.winner) d.game.winner = o.winner;
    d[d.player.color === 'white' ? 'player' : 'opponent'].offeringDraw = o.wDraw;
    d[d.player.color === 'black' ? 'player' : 'opponent'].offeringDraw = o.bDraw;
    d.possibleMoves = d.player.color === d.game.player ? o.dests : null;
    this.setTitle();
    showYourMoveNotification();
    if (!this.replaying()) {
      this.vm.ply++;
      this.chessground.apiMove(o.uci.substr(0, 2), o.uci.substr(2, 2));
      if (o.enpassant) {
        var p = o.enpassant,
          pieces = {};
        pieces[p.key] = null;
        this.chessground.setPieces(pieces);
        if (d.game.variant.key === 'atomic') {
          atomic.enpassant(this, p.key, p.color);
          sound.explode();
        } else sound.capture();
      }
      if (o.promotion) ground.promote(this.chessground, o.promotion.key, o.promotion.pieceClass);
      if (o.castle && !this.chessground.data.autoCastle) {
        var c = o.castle,
          pieces = {};
        pieces[c.king[0]] = null;
        pieces[c.rook[0]] = null;
        pieces[c.king[1]] = {
          role: 'king',
          color: c.color
        };
        pieces[c.rook[1]] = {
          role: 'rook',
          color: c.color
        };
        this.chessground.setPieces(pieces);
      }
      this.chessground.set({
        turnColor: d.game.player,
        movable: {
          dests: game.isPlayerPlaying(d) ? util.parsePossibleMoves(d.possibleMoves) : {}
        },
        check: o.check
      });
      if (o.check) $.sound.check();
    }
    if (o.clock) {
      var c = o.clock
      if (this.clock) this.clock.update(c.white, c.black);
      else if (this.correspondenceClock) this.correspondenceClock.update(c.white, c.black);
    }
    d.game.threefold = !!o.threefold;
    d.steps.push({
      ply: this.lastPly() + 1,
      fen: o.fen,
      san: o.san,
      uci: o.uci,
      check: o.check
    });
    game.setOnGame(d, playedColor, true);
    m.endComputation();
    if (d.blind) blind.reload(this);
    if (game.isPlayerPlaying(d) && playedColor === d.player.color) this.moveOn.next();

    if (!this.replaying() && playedColor !== d.player.color) {
      // atrocious hack to prevent race condition
      // with explosions and premoves
      // https://github.com/ornicar/lila/issues/343
      setTimeout(this.chessground.playPremove, d.game.variant.key === 'atomic' ? 100 : 10);
    }
  }.bind(this);

  this.reload = function(cfg) {
    m.startComputation();
    if (this.stepsHash(cfg.steps) !== this.stepsHash(this.data.steps))
      this.vm.ply = cfg.steps[cfg.steps.length - 1].ply;
    this.data = data(this.data, cfg);
    makeCorrespondenceClock();
    if (this.clock) this.clock.update(this.data.clock.white, this.data.clock.black);
    if (!this.replaying()) ground.reload(this.chessground, this.data, cfg.game.fen, this.vm.flip);
    this.setTitle();
    if (this.data.blind) blind.reload(this);
    this.moveOn.next();
    setQuietMode();
    m.endComputation();
  }.bind(this);

  this.clock = this.data.clock ? new clockCtrl(
    this.data.clock,
    this.socket.outoftime, (this.data.simul || this.data.player.spectator || !this.data.pref.clockSound) ? null : this.data.player.color
  ) : false;

  this.isClockRunning = function() {
    return this.data.clock && game.playable(this.data) &&
      ((this.data.game.turns - this.data.game.startedAtTurn) > 1 || this.data.clock.running);
  }.bind(this);

  var clockTick = function() {
    if (this.isClockRunning()) this.clock.tick(this.data.game.player);
  }.bind(this);

  var makeCorrespondenceClock = function() {
    if (this.data.correspondence && !this.correspondenceClock)
      this.correspondenceClock = new correspondenceClockCtrl(
        this.data.correspondence,
        partial(this.socket.send, 'outoftime')
      );
  }.bind(this);
  makeCorrespondenceClock();

  var correspondenceClockTick = function() {
    if (this.correspondenceClock && game.playable(this.data))
      this.correspondenceClock.tick(this.data.game.player);
  }.bind(this);

  if (this.clock) setInterval(clockTick, 100);
  else setInterval(correspondenceClockTick, 1000);

  var setQuietMode = function() {
    lichess.quietMode = game.isPlayerPlaying(this.data);
    document.body.classList.toggle('no-select',
      lichess.quietMode && this.clock && this.clock.secondsOf(this.data.player.color) <= 300);
  }.bind(this);
  setQuietMode();

  this.takebackYes = function() {
    this.socket.send('takeback-yes');
    this.chessground.cancelPremove();
  }.bind(this);

  this.resign = function(v) {
    if (this.vm.resignConfirm) {
      if (v) this.socket.send('resign');
      else this.vm.resignConfirm = false;
    } else if (v !== false) {
      if (this.data.pref.confirmResign) this.vm.resignConfirm = true;
      else this.socket.send('resign');
    }
  }.bind(this);

  this.goBerserk = function() {
    this.socket.berserk();
    $.sound.berserk();
  }.bind(this);

  this.setBerserk = function(color) {
    if (this.vm.goneBerserk[color]) return;
    this.vm.goneBerserk[color] = true;
    m.redraw();
  }.bind(this);

  this.moveOn = new moveOn(this, 'lichess.move_on');

  this.setRedirecting = function() {
    this.vm.redirecting = true;
    setTimeout(function() {
      this.vm.redirecting = false;
      m.redraw();
    }.bind(this), 2000);
  }.bind(this);

  this.submitMove = function(v) {
    if (v && this.vm.moveToSubmit) this.socket.send('move', this.vm.moveToSubmit, {
      ackable: true
    });
    else this.jump(this.vm.ply);

    this.vm.moveToSubmit = null;
    this.vm.buttonFeedback = setTimeout(function() {
      this.vm.buttonFeedback = null;
      m.redraw();
    }.bind(this), 500);
  }.bind(this);

  this.router = opts.routes;

  this.trans = function(key) {
    var str = opts.i18n[key] || key;
    Array.prototype.slice.call(arguments, 1).forEach(function(arg) {
      str = str.replace('%s', arg);
    });
    return str;
  };

  init(this);
};
<commit_msg>translate turn notification<commit_after>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var data = require('./data');
var game = require('game').game;
var status = require('game').status;
var ground = require('./ground');
var socket = require('./socket');
var title = require('./title');
var promotion = require('./promotion');
var hold = require('./hold');
var blur = require('./blur');
var init = require('./init');
var blind = require('./blind');
var clockCtrl = require('./clock/ctrl');
var correspondenceClockCtrl = require('./correspondenceClock/ctrl');
var moveOn = require('./moveOn');
var atomic = require('./atomic');
var sound = require('./sound');
var util = require('./util');

module.exports = function(opts) {

  this.data = data({}, opts.data);

  this.userId = opts.userId;

  this.firstPly = function() {
    return this.data.steps[0].ply;
  }.bind(this);

  this.lastPly = function() {
    return this.data.steps[this.data.steps.length - 1].ply;
  }.bind(this);

  this.plyStep = function(ply) {
    return this.data.steps[ply - this.firstPly()];
  }.bind(this);

  this.vm = {
    ply: this.lastPly(),
    flip: false,
    redirecting: false,
    replayHash: '',
    moveToSubmit: null,
    buttonFeedback: null,
    goneBerserk: {},
    resignConfirm: false
  };
  this.vm.goneBerserk[this.data.player.color] = opts.data.player.berserk;
  this.vm.goneBerserk[this.data.opponent.color] = opts.data.opponent.berserk;

  this.socket = new socket(opts.socketSend, this);

  var onUserMove = function(orig, dest, meta) {
    if (this.data.game.variant.key === 'standard')
      hold.register(this.socket, meta.holdTime);
    if (!promotion.start(this, orig, dest, meta.premove))
      this.sendMove(orig, dest, false, meta.premove);
  }.bind(this);

  var onMove = function(orig, dest, captured) {
    if (captured) {
      if (this.data.game.variant.key === 'atomic') {
        sound.explode();
        atomic.capture(this, dest, captured);
      } else sound.capture();
    } else sound.move();
  }.bind(this);

  this.chessground = ground.make(this.data, opts.data.game.fen, onUserMove, onMove);

  this.replaying = function() {
    return this.vm.ply !== this.lastPly();
  }.bind(this);

  this.stepsHash = function(steps) {
    var h = '';
    for (i in steps) {
      h += steps[i].san;
    }
    return h;
  };

  this.jump = function(ply) {
    if (ply < this.firstPly() || ply > this.lastPly()) return;
    this.vm.ply = ply;
    var s = this.plyStep(ply);
    var config = {
      fen: s.fen,
      lastMove: s.uci ? [s.uci.substr(0, 2), s.uci.substr(2, 2)] : null,
      check: s.check,
      turnColor: this.vm.ply % 2 === 0 ? 'white' : 'black'
    };
    if (this.replaying()) this.chessground.stop();
    else config.movable = {
      color: game.isPlayerPlaying(this.data) ? this.data.player.color : null,
      dests: util.parsePossibleMoves(this.data.possibleMoves)
    }
    this.chessground.set(config);
    if (s.san) {
      if (s.san.indexOf('x') !== -1) sound.capture();
      else sound.move();
      if (/\+|\#/.test(s.san)) sound.check();
    }
  }.bind(this);

  this.replayEnabledByPref = function() {
    var d = this.data;
    return d.pref.replay === 2 || (
      d.pref.replay === 1 && (d.game.speed === 'classical' || d.game.speed === 'unlimited' || d.game.speed === 'correspondence')
    );
  }.bind(this);

  this.isLate = function() {
    return this.replaying() && status.playing(this.data);
  }.bind(this);

  this.flip = function() {
    this.vm.flip = !this.vm.flip;
    this.chessground.set({
      orientation: this.vm.flip ? this.data.opponent.color : this.data.player.color
    });
  }.bind(this);

  this.setTitle = partial(title.set, this);

  this.sendMove = function(orig, dest, prom, isPremove) {
    var move = {
      from: orig,
      to: dest
    };
    if (prom) move.promotion = prom;
    if (blur.get()) move.b = 1;
    if (this.clock) move.lag = Math.round(lichess.socket.averageLag);
    this.resign(false);
    if (this.userId && this.data.pref.submitMove && !isPremove) {
      this.vm.moveToSubmit = move;
      m.redraw();
    } else this.socket.send('move', move, {
      ackable: true
    });
  }.bind(this);

  var showYourMoveNotification = function() {
    if (game.isPlayerTurn(this.data)) lichess.desktopNotification(this.trans('yourTurn'));
  }.bind(this);

  this.apiMove = function(o) {
    m.startComputation();
    var d = this.data;
    d.game.turns = o.ply;
    d.game.player = o.ply % 2 === 0 ? 'white' : 'black';
    var playedColor = o.ply % 2 === 0 ? 'black' : 'white';
    if (o.status) d.game.status = o.status;
    if (o.winner) d.game.winner = o.winner;
    d[d.player.color === 'white' ? 'player' : 'opponent'].offeringDraw = o.wDraw;
    d[d.player.color === 'black' ? 'player' : 'opponent'].offeringDraw = o.bDraw;
    d.possibleMoves = d.player.color === d.game.player ? o.dests : null;
    this.setTitle();
    showYourMoveNotification();
    if (!this.replaying()) {
      this.vm.ply++;
      this.chessground.apiMove(o.uci.substr(0, 2), o.uci.substr(2, 2));
      if (o.enpassant) {
        var p = o.enpassant,
          pieces = {};
        pieces[p.key] = null;
        this.chessground.setPieces(pieces);
        if (d.game.variant.key === 'atomic') {
          atomic.enpassant(this, p.key, p.color);
          sound.explode();
        } else sound.capture();
      }
      if (o.promotion) ground.promote(this.chessground, o.promotion.key, o.promotion.pieceClass);
      if (o.castle && !this.chessground.data.autoCastle) {
        var c = o.castle,
          pieces = {};
        pieces[c.king[0]] = null;
        pieces[c.rook[0]] = null;
        pieces[c.king[1]] = {
          role: 'king',
          color: c.color
        };
        pieces[c.rook[1]] = {
          role: 'rook',
          color: c.color
        };
        this.chessground.setPieces(pieces);
      }
      this.chessground.set({
        turnColor: d.game.player,
        movable: {
          dests: game.isPlayerPlaying(d) ? util.parsePossibleMoves(d.possibleMoves) : {}
        },
        check: o.check
      });
      if (o.check) $.sound.check();
    }
    if (o.clock) {
      var c = o.clock
      if (this.clock) this.clock.update(c.white, c.black);
      else if (this.correspondenceClock) this.correspondenceClock.update(c.white, c.black);
    }
    d.game.threefold = !!o.threefold;
    d.steps.push({
      ply: this.lastPly() + 1,
      fen: o.fen,
      san: o.san,
      uci: o.uci,
      check: o.check
    });
    game.setOnGame(d, playedColor, true);
    m.endComputation();
    if (d.blind) blind.reload(this);
    if (game.isPlayerPlaying(d) && playedColor === d.player.color) this.moveOn.next();

    if (!this.replaying() && playedColor !== d.player.color) {
      // atrocious hack to prevent race condition
      // with explosions and premoves
      // https://github.com/ornicar/lila/issues/343
      setTimeout(this.chessground.playPremove, d.game.variant.key === 'atomic' ? 100 : 10);
    }
  }.bind(this);

  this.reload = function(cfg) {
    m.startComputation();
    if (this.stepsHash(cfg.steps) !== this.stepsHash(this.data.steps))
      this.vm.ply = cfg.steps[cfg.steps.length - 1].ply;
    this.data = data(this.data, cfg);
    makeCorrespondenceClock();
    if (this.clock) this.clock.update(this.data.clock.white, this.data.clock.black);
    if (!this.replaying()) ground.reload(this.chessground, this.data, cfg.game.fen, this.vm.flip);
    this.setTitle();
    if (this.data.blind) blind.reload(this);
    this.moveOn.next();
    setQuietMode();
    m.endComputation();
  }.bind(this);

  this.clock = this.data.clock ? new clockCtrl(
    this.data.clock,
    this.socket.outoftime, (this.data.simul || this.data.player.spectator || !this.data.pref.clockSound) ? null : this.data.player.color
  ) : false;

  this.isClockRunning = function() {
    return this.data.clock && game.playable(this.data) &&
      ((this.data.game.turns - this.data.game.startedAtTurn) > 1 || this.data.clock.running);
  }.bind(this);

  var clockTick = function() {
    if (this.isClockRunning()) this.clock.tick(this.data.game.player);
  }.bind(this);

  var makeCorrespondenceClock = function() {
    if (this.data.correspondence && !this.correspondenceClock)
      this.correspondenceClock = new correspondenceClockCtrl(
        this.data.correspondence,
        partial(this.socket.send, 'outoftime')
      );
  }.bind(this);
  makeCorrespondenceClock();

  var correspondenceClockTick = function() {
    if (this.correspondenceClock && game.playable(this.data))
      this.correspondenceClock.tick(this.data.game.player);
  }.bind(this);

  if (this.clock) setInterval(clockTick, 100);
  else setInterval(correspondenceClockTick, 1000);

  var setQuietMode = function() {
    lichess.quietMode = game.isPlayerPlaying(this.data);
    document.body.classList.toggle('no-select',
      lichess.quietMode && this.clock && this.clock.secondsOf(this.data.player.color) <= 300);
  }.bind(this);
  setQuietMode();

  this.takebackYes = function() {
    this.socket.send('takeback-yes');
    this.chessground.cancelPremove();
  }.bind(this);

  this.resign = function(v) {
    if (this.vm.resignConfirm) {
      if (v) this.socket.send('resign');
      else this.vm.resignConfirm = false;
    } else if (v !== false) {
      if (this.data.pref.confirmResign) this.vm.resignConfirm = true;
      else this.socket.send('resign');
    }
  }.bind(this);

  this.goBerserk = function() {
    this.socket.berserk();
    $.sound.berserk();
  }.bind(this);

  this.setBerserk = function(color) {
    if (this.vm.goneBerserk[color]) return;
    this.vm.goneBerserk[color] = true;
    m.redraw();
  }.bind(this);

  this.moveOn = new moveOn(this, 'lichess.move_on');

  this.setRedirecting = function() {
    this.vm.redirecting = true;
    setTimeout(function() {
      this.vm.redirecting = false;
      m.redraw();
    }.bind(this), 2000);
  }.bind(this);

  this.submitMove = function(v) {
    if (v && this.vm.moveToSubmit) this.socket.send('move', this.vm.moveToSubmit, {
      ackable: true
    });
    else this.jump(this.vm.ply);

    this.vm.moveToSubmit = null;
    this.vm.buttonFeedback = setTimeout(function() {
      this.vm.buttonFeedback = null;
      m.redraw();
    }.bind(this), 500);
  }.bind(this);

  this.router = opts.routes;

  this.trans = function(key) {
    var str = opts.i18n[key] || key;
    Array.prototype.slice.call(arguments, 1).forEach(function(arg) {
      str = str.replace('%s', arg);
    });
    return str;
  };

  init(this);
};
<|endoftext|>


<commit_before>//here we tell node that we are going to need express for this script
var express = require('express');
//here we declare our server as an instance of express
var app = express();
//and here we decide which port we run on
var port = 3000;

//here we actually run our server, by giving it (1) a port number and (2) a callback function to be executed if the server runs correctly
app.listen(port, function(){
	console.log('server started successfully on port', port);
});

//this is where we listen for incoming requests from our users and we respond to those
//in this particular case, we listen for all requests ('/')
app.get('/', function(request, response){
	//and our callback function sends back some text, saying "hey there!"
	response.send('hey there!');
});
<commit_msg>request code<commit_after>//here we tell node that we are going to need express for this script
var express = require('express');
//here we declare our server as an instance of express
var app = express();
//and here we decide which port we run on
var port = 2046;

//here we actually run our server, by giving it (1) a port number and (2) a callback function to be executed if the server runs correctly
app.listen(port, function(){
	console.log('server started successfully on port', port, 'please visit localhost:',port,'to get content served');
});

//this is where we listen for incoming requests from our users and we respond to those
//in this particular case, we listen for all requests ('/')
app.get('/', function(request, response){
	//and our callback function sends back some text, saying "hey there!"
	response.send('hey there!');
});

app.get('/content', function(request, response){
	//if the user goes to localhost:2046/content, then we display a regular html file
	response.sendFile(__dirname + '/index.html');
});
<|endoftext|>


<commit_before>'use strict';
/*jshint browser: true*/

/*global require: false*/
var utils = require('./utils');

var months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

var attr = utils.attr;
var query = utils.query;
var mkEl = utils.mkEl;
var keys = utils.keys;
var tmpl = utils.tmpl;

function mkListItems(target, texts, clickCb, that) {
  var items = [];
  that = that || {};

  texts.forEach(function (text, i) {
    var el = mkEl('li');
    el.innerHTML = '' + text + '';

    el.addEventListener('click', function (evt) {
      evt.preventDefault();
      items.forEach(function (e) {
        var cl = e.classList;
        if (e === el) {
          if (!cl.contains('active')) {
            cl.add('active');
          }
        }
        else {
          cl.remove('active');
        }
      });

      clickCb.call(that, i, el);
    });

    target.appendChild(el);

    items.push(el);
  });

  return items;
}

function camDownloadsWidget(info, holder) {
  var majorList = query('ul.major', holder);
  var patchList = query('ul.patch', holder);
  var serverList = query('ul.server', holder);
  var infoDiv = query('.selected-server', holder);
  var standaloneDiv = query('.standalone', infoDiv);

  var releaseTitle = query('.info h3', holder);
  var notesA = query('a.notes', holder);
  var dateSpan = query('span.date', holder);
  var zipA = query('a.zip', holder);
  var targzA = query('a.tar-gz', holder);
  var warA = query('a.war', holder);

  var branches = keys(info.branches).sort(function (a, b) {
    var foo = parseInt(a.split(".")[1], 10);
    var bar = parseInt(b.split(".")[1], 10);
    return (foo > bar ? -1 : (foo < bar ? 1 : 0));
  });

  function getReleaseInfo(branch, version) {
    return info.branches[branch].find(function (release) {
      return release.number === version;
    });
  }

  function getBranchVersions(branch) {
    return info.branches[branch].map(function (release) {
      return release.number;
    }).filter(function (item) { return !!item; });
  }

  function getServers(release) {
    var servers = keys(info.servers);
    if (release.excludeServers) {
      servers = servers.filter(function (name) {
        return release.excludeServers.indexOf(name) < 0;
      });
    }
    return servers;
  }

  var dlBasePath = 'https://camunda.org/enterprise-release/camunda-bpm/';
  function mkServerClickHandler(servers, version, branch) {
    return function (s) {
      var selectedServer = servers[s];
      var release = getReleaseInfo(branch, version);
      infoDiv.classList.add('accessible');

      var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-ee-{server}-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   (selectedServer === 'wildfly8')? 'wildfly' : selectedServer
      });

      releaseTitle.innerHTML = version + '-ee for ' + info.servers[selectedServer];

      var parts = release.date.split('.').map(function (part) {
        return parseInt(part, 10);
      });
      dateSpan.innerHTML = parts[2] + ' ' + months[parts[1] - 1] + ' ' + parts[0];

      attr(notesA, 'href', release.note);

      attr(warA, 'href', dlBasePath + tmpl('{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer.match(/wildfly*/) ? 'jboss' : selectedServer
      }) + '.war');

      attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

      attr(zipA, 'href', dlBasePath + dl + '.zip');

      if (selectedServer.startsWith('ibm-was') || selectedServer === 'oracle-wls') {
        dl = tmpl('{vendor}-{server}/{branch}/{version}/camunda-ee-{vendor}-{server}-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        });

        attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

        attr(zipA, 'href', dlBasePath + dl + '.zip');

        attr(warA, 'href', dlBasePath + tmpl('{vendor}-{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        }) + '.war');
      }

      if (release.excludeFormats && release.excludeFormats.indexOf('war') > -1) {
        standaloneDiv.style.display = 'none';
      }
      else {
        standaloneDiv.style.display = 'block';
      }
    };
  }

  function mkVersionClickHandler(branchName) {
    var patchReleases = getBranchVersions(branchName);

    return function selectVersion(r) {
      serverList.innerHTML = '';

      infoDiv.classList.remove('accessible');

      var selectedVersion = patchReleases[r];

      var releaseInfo = getReleaseInfo(branchName, selectedVersion);

      var releaseServers = getServers(releaseInfo);

      return mkListItems(serverList, releaseServers.map(function (name) {
        return info.servers[name];
      }), mkServerClickHandler(releaseServers, selectedVersion, branchName));
    };
  }

  function selectBranch(b) {
    patchList.innerHTML = '';

    serverList.innerHTML = '';

    infoDiv.classList.remove('accessible');

    var branchName = branches[b];

    var patchReleases = getBranchVersions(branchName);

    return mkListItems(patchList, patchReleases, mkVersionClickHandler(branchName));
  }

  var branchEls = mkListItems(majorList, branches, selectBranch);

  if (info.selected) {
    var b = branches.indexOf(info.selected.branch);

    var versionEls = selectBranch(b);

    branchEls[b].classList.add('active');

    var patchReleases = getBranchVersions(branches[b]);

    var v = patchReleases.indexOf(info.selected.version);

    var serverEls = mkVersionClickHandler(branches[b])(v);

    versionEls[v].classList.add('active');

    var servers = getServers(patchReleases[v]);

    var s = servers.indexOf(info.selected.server);

    serverEls[s].classList.add('active');

    mkServerClickHandler(servers, info.selected.version, info.selected.branch)(s);
  }
}

var camDownloadsEl = query('.cam-downloads');
if (window.camDownloads && camDownloadsEl) {
  camDownloadsWidget(window.camDownloads, camDownloadsEl);
}
<commit_msg>revert(ee-downloads): fix wildfly ee downloads<commit_after>'use strict';
/*jshint browser: true*/

/*global require: false*/
var utils = require('./utils');

var months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

var attr = utils.attr;
var query = utils.query;
var mkEl = utils.mkEl;
var keys = utils.keys;
var tmpl = utils.tmpl;

function mkListItems(target, texts, clickCb, that) {
  var items = [];
  that = that || {};

  texts.forEach(function (text, i) {
    var el = mkEl('li');
    el.innerHTML = '' + text + '';

    el.addEventListener('click', function (evt) {
      evt.preventDefault();
      items.forEach(function (e) {
        var cl = e.classList;
        if (e === el) {
          if (!cl.contains('active')) {
            cl.add('active');
          }
        }
        else {
          cl.remove('active');
        }
      });

      clickCb.call(that, i, el);
    });

    target.appendChild(el);

    items.push(el);
  });

  return items;
}

function camDownloadsWidget(info, holder) {
  var majorList = query('ul.major', holder);
  var patchList = query('ul.patch', holder);
  var serverList = query('ul.server', holder);
  var infoDiv = query('.selected-server', holder);
  var standaloneDiv = query('.standalone', infoDiv);

  var releaseTitle = query('.info h3', holder);
  var notesA = query('a.notes', holder);
  var dateSpan = query('span.date', holder);
  var zipA = query('a.zip', holder);
  var targzA = query('a.tar-gz', holder);
  var warA = query('a.war', holder);

  var branches = keys(info.branches).sort(function (a, b) {
    var foo = parseInt(a.split(".")[1], 10);
    var bar = parseInt(b.split(".")[1], 10);
    return (foo > bar ? -1 : (foo < bar ? 1 : 0));
  });

  function getReleaseInfo(branch, version) {
    return info.branches[branch].find(function (release) {
      return release.number === version;
    });
  }

  function getBranchVersions(branch) {
    return info.branches[branch].map(function (release) {
      return release.number;
    }).filter(function (item) { return !!item; });
  }

  function getServers(release) {
    var servers = keys(info.servers);
    if (release.excludeServers) {
      servers = servers.filter(function (name) {
        return release.excludeServers.indexOf(name) < 0;
      });
    }
    return servers;
  }

  var dlBasePath = 'https://camunda.org/enterprise-release/camunda-bpm/';
  function mkServerClickHandler(servers, version, branch) {
    return function (s) {
      var selectedServer = servers[s];
      var release = getReleaseInfo(branch, version);
      infoDiv.classList.add('accessible');

      var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-ee-{server}-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      });

      releaseTitle.innerHTML = version + '-ee for ' + info.servers[selectedServer];

      var parts = release.date.split('.').map(function (part) {
        return parseInt(part, 10);
      });
      dateSpan.innerHTML = parts[2] + ' ' + months[parts[1] - 1] + ' ' + parts[0];

      attr(notesA, 'href', release.note);

      attr(warA, 'href', dlBasePath + tmpl('{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer.match(/wildfly*/) ? 'jboss' : selectedServer
      }) + '.war');

      attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

      attr(zipA, 'href', dlBasePath + dl + '.zip');

      if (selectedServer.startsWith('ibm-was') || selectedServer === 'oracle-wls') {
        dl = tmpl('{vendor}-{server}/{branch}/{version}/camunda-ee-{vendor}-{server}-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        });

        attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

        attr(zipA, 'href', dlBasePath + dl + '.zip');

        attr(warA, 'href', dlBasePath + tmpl('{vendor}-{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        }) + '.war');
      }

      if (release.excludeFormats && release.excludeFormats.indexOf('war') > -1) {
        standaloneDiv.style.display = 'none';
      }
      else {
        standaloneDiv.style.display = 'block';
      }
    };
  }

  function mkVersionClickHandler(branchName) {
    var patchReleases = getBranchVersions(branchName);

    return function selectVersion(r) {
      serverList.innerHTML = '';

      infoDiv.classList.remove('accessible');

      var selectedVersion = patchReleases[r];

      var releaseInfo = getReleaseInfo(branchName, selectedVersion);

      var releaseServers = getServers(releaseInfo);

      return mkListItems(serverList, releaseServers.map(function (name) {
        return info.servers[name];
      }), mkServerClickHandler(releaseServers, selectedVersion, branchName));
    };
  }

  function selectBranch(b) {
    patchList.innerHTML = '';

    serverList.innerHTML = '';

    infoDiv.classList.remove('accessible');

    var branchName = branches[b];

    var patchReleases = getBranchVersions(branchName);

    return mkListItems(patchList, patchReleases, mkVersionClickHandler(branchName));
  }

  var branchEls = mkListItems(majorList, branches, selectBranch);

  if (info.selected) {
    var b = branches.indexOf(info.selected.branch);

    var versionEls = selectBranch(b);

    branchEls[b].classList.add('active');

    var patchReleases = getBranchVersions(branches[b]);

    var v = patchReleases.indexOf(info.selected.version);

    var serverEls = mkVersionClickHandler(branches[b])(v);

    versionEls[v].classList.add('active');

    var servers = getServers(patchReleases[v]);

    var s = servers.indexOf(info.selected.server);

    serverEls[s].classList.add('active');

    mkServerClickHandler(servers, info.selected.version, info.selected.branch)(s);
  }
}

var camDownloadsEl = query('.cam-downloads');
if (window.camDownloads && camDownloadsEl) {
  camDownloadsWidget(window.camDownloads, camDownloadsEl);
}
<|endoftext|>