<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.extensionmanager.xmlEditor");
pimcore.extensionmanager.xmlEditor = Class.create(pimcore.settings.fileexplorer.file, {
    id: null,
    type: null,

    initialize: function (id, type, xmlFile) {
        this.id = id;
        this.type = type;
        this.loadFileContents(xmlFile);
    },

    loadFileContentsComplete: function (response) {
        response = Ext.decode(response.responseText);
        if(response.success) {
            var toolbarItems = [];
            if(response.writeable) {
                toolbarItems.push({
                    text: t("save"),
                    handler: this.saveFile.bind(this, response.path),
                    iconCls: "pimcore_icon_save"
                });
            }

            this.textarea = new Ext.form.TextArea({
                value: response.content,
                style: "font-family:courier"
            });

            this.editor = new Ext.Panel({
                title: response.path,
                closable: true,
                layout: "fit",
                tbar: toolbarItems,
                bodyStyle: "position:relative;",
                items: [this.textarea]
            });

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.editor);
            tabPanel.activate(this.editor);
            tabPanel.updateLayout();
        }
    },

    activate: function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.activate("pimcore_extension_" + this.id + "_" + type);
    }
});<commit_msg>extjs6 - tree -> extension manager - fixed reactivation of xml editor<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.extensionmanager.xmlEditor");
pimcore.extensionmanager.xmlEditor = Class.create(pimcore.settings.fileexplorer.file, {
    id: null,
    type: null,

    initialize: function (id, type, xmlFile) {
        this.id = id;
        this.type = type;
        this.loadFileContents(xmlFile);
    },

    loadFileContentsComplete: function (response) {
        response = Ext.decode(response.responseText);
        if(response.success) {
            var toolbarItems = [];
            if(response.writeable) {
                toolbarItems.push({
                    text: t("save"),
                    handler: this.saveFile.bind(this, response.path),
                    iconCls: "pimcore_icon_save"
                });
            }

            this.textarea = new Ext.form.TextArea({
                value: response.content,
                style: "font-family:courier"
            });

            this.editor = new Ext.Panel({
                title: response.path,
                closable: true,
                layout: "fit",
                tbar: toolbarItems,
                bodyStyle: "position:relative;",
                items: [this.textarea]
            });

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.editor);
            tabPanel.activate(this.editor);
            tabPanel.updateLayout();
        }
    },

    activate: function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.activate("pimcore_extension_" + this.id + "_" + this.type);
    }
});<|endoftext|>


<commit_before>define(["Ti/_/declare", "Ti/_/UI/TextBox", "Ti/_/css", "Ti/_/dom", "Ti/_/lang", "Ti/_/style", "Ti/UI", "Ti/UI/Tizen"],
	function(declare, TextBox, css, dom, lang, style, UI, Tizen) {

	var borderStyles = ["None", "Line", "Bezel", "Rounded"],
		keyboardPost = {
			post: "_setKeyboardType"
		},
		setStyle = style.set,
		on = require.on,

		_calculateWidth = function(showCancel, width) {
			var widthSign = "", widthLength = width.length, width_value = parseInt(width), cancelWidth = showCancel ? 43 : 0;

			if (width === UI.FILL || width === UI.SIZE || width == '100%') {
				return '97%';
			}
			widthSign = width.substring(widthLength - 1, widthLength) === "%" ? "%" : width.substring(widthLength - 2, widthLength);
			widthSign = ((widthSign !== "%") && (parseInt(widthSign) !== NaN)) ? 'px' : widthSign;
			if (widthSign !== "%") {
				return (width_value - cancelWidth) + widthSign;
			} else {
				return '97%';
			}
		};

	return declare("Ti.UI.SearchBar", TextBox, {

		constructor: function(args) {
			// note: do NOT add position:absolute to this style under ANY circumstances. It will break text field on WebKit
			if (!args.width) {
				args.width = '100%';
			}
			var self = this, f = this._field = dom.create("input", {
				autocomplete: "off",
				style: {
					left: 0,
					right: 0,
					top: 0,
					bottom: 0,
					float: 'left',
					display: 'inline-block',
					width: _calculateWidth(args.showCancel, args.width),
					height: '100%'
				}
			}, this._fieldWrapper = dom.create("span", {
				style: {
					position: "absolute",
					left: 0,
					right: 0,
					top: 0,
					bottom: 0,
					paddingRight: args.showCancel ? '43px' : 0,
					width: '100%',
					height: '100%',
					display: 'table'
				}
			}, this.domNode));

				this._cancelButton = dom.create("button", {
					style: {
						background: "url('themes/default/UI/SearchBar/close.png') no-repeat 50% 50%",
						position: "absolute",
						top: 0,
						bottom: 0,
						width: '43px',
						height: '43px',
						display: (args && args.showCancel) ? 'inline-block' : 'none'
					}
				}, this._fieldWrapper, this.domNode);
				this._cancelButton.addEventListener('click', function(e){
					f.value = "";
					f.blur();
					self.fireEvent("cancel");
				});

			this._initTextBox(f);
			this.keyboardType = void 0;
			this._setKeyboardType();
			this.borderStyle = UI.INPUT_BORDERSTYLE_BEZEL;

			this._disconnectFocusEvent = on(f, "focus", this, function() {
				this._focused = 1;
				this._setInternalText(this.clearOnEdit ? "" : this._getInternalText());
			});
			this._disconnectBlurEvent = on(f, "blur", this, function() {
				this._focused = 0;
				this._updateInternalText();
			});
			this.created = 1;

		},

		destroy: function() {
			this._disconnectFocusEvent();
			this._disconnectBlurEvent();
			TextBox.prototype.destroy.apply(this, arguments);
		},

		_showingHint: 1,

		_setInternalText: function(value) {
			var showingHint = !this._focused && !value;
			if (showingHint !== this._showingHint) {
				this._showingHint = showingHint;
				this._setKeyboardType();
			}
			TextBox.prototype._setInternalText.call(this, showingHint ? this.hintText : value);
		},

		_getInternalText: function() {
			return this._showingHint ? "" : TextBox.prototype._getInternalText.call(this);
		},

        _defaultWidth: UI.SIZE,

        _defaultHeight: UI.SIZE,

		_getContentSize: function(width, height) {
			return {
				width: this._measureText(this.value, this._field, width).width + 6,
				height: this._measureText(this.value, this._field, width).height + 6
			};
		},

		_setTouchEnabled: function(value) {
			this.slider && setStyle(this._field, "pointerEvents", value ? "auto" : "none");
		},

		_setKeyboardType: function() {
			var type = "text";
			if (this.passwordMask && !this._showingHint) {
				type = "password";
			} else {
				switch (this.keyboardType) {
					case UI.KEYBOARD_EMAIL:
						type = "email";
						break;
					case UI.KEYBOARD_NUMBER_PAD:
						type = "number";
						break;
					case UI.KEYBOARD_PHONE_PAD:
						type = "tel";
						break;
					case UI.KEYBOARD_URL:
						type = "url";
						break;
					case UI.KEYBOARD_NUMBERS_PUNCTUATION:
						type = "number";
						break;

				}
			}
			// Note: IE9 throws an exception if you don't set an input type it supports
			try {
				this._field.type = type;
			} catch(e) {
				this._field.type = "text";
			}
		},

		blur: function() {
			this._field.blur();
		},

		focus: function() {
			this._field.focus();
		},

		cancel: function() {
			this._field.value = "";
		},

		properties: {
			borderStyle: {
				set: function(value, oldValue) {
					var n = this.domNode,
						s = "TiUITextFieldBorderStyle";
					if (value !== oldValue) {
						// This code references constants Ti.UI.INPUT_BORDERSTYLE_NONE,
						// Ti.UI.INPUT_BORDERSTYLE_LINE, Ti.UI.INPUT_BORDERSTYLE_BEZEL, and Ti.UI.INPUT_BORDERSTYLE_ROUNDED
						css.remove(n, s + borderStyles[oldValue]);
						css.add(n, s + borderStyles[value]);
					}
					return value;
				}
			},

			clearOnEdit: false,

			showCancel: {
				set: function(value) {
					var width = this._field.style.width, offset = value ? -43 : 43,
						widthType = width.substring(width.length - 1, width.length);
					if ((widthType != '%') && (this.created == 1)) {
						width = parseInt(width, 10) + offset;
						this._field.style.width = width + "px";
					} else if (widthType == '%' && !value) {
						this._field.style.width = '97%';
					}

					this._fieldWrapper.style.paddingRight = value ? '43px' : '0';
					this._cancelButton.style.display = value ? "inline-block" : "none";
					return value;
				},
				value: false
			},

			hintText: {
				post: "_updateInternalText",
				value: ""
			},

			keyboardType: keyboardPost,

			passwordMask: keyboardPost,

			softKeyboardOnFocus: Tizen.SOFT_KEYBOARD_DEFAULT_ON_FOCUS
		}

	});

});
<commit_msg>rewrite Ti.UI.SearchBar<commit_after>define(["Ti/_/declare", "Ti/UI", "Ti/_/UI/Widget"],
	function(declare, UI, Widget) {

	var on = require.on;

	return declare("Ti.UI.SearchBar", Widget, {

		constructor: function(args) {
			var self = this,
				f = this._field = UI.createTextField({
					width: UI.FILL,
					height: args.height ? args.height : '43px'
				}),
				contentContainer = this._container = UI.createView(args),
				b = this._cancelButton = UI.createButton({
					width: '43px',
					height: args.height ? args.height : '43px',
					backgroundImage: 'themes/default/UI/SearchBar/close.png',
					visible: args.showCancel ? args.showCancel : false
				});

			contentContainer.layout = UI._LAYOUT_CONSTRAINING_HORIZONTAL;

			contentContainer.add(f);
			contentContainer.add(b);
			this._add(contentContainer);

			on(b, 'click', function(e) {
				f.value = "";
				self.fireEvent("cancel");
			});

			on(f, 'return', function(e){
				self.fireEvent('return');
			});

			on(f, 'change', function(e){
				self.fireEvent('change');
			});

			on(f, 'focus', function(e){
				self.fireEvent('focus');
			});

			on(f, 'blur', function(e){
				self.fireEvent('blur');
			});
		},

		destroy: function() {
			this._field.destroy();
			this._cancelButton.destroy();
		},

		blur: function() {
			this._field.blur();
		},

		focus: function() {
			this._field.focus();
		},

		cancel: function() {
			this._field.value = "";
		},

		properties: {
			hintText: {
				set: function(value) {
					this._field.hintText = value;
					return value;
				},
				get: function() {
					return this._field.hintText;
				},
				value: function() {
					return this._field.hintText;
				}
			},

			keyboardType: {
				set: function(value) {
					this._field.keyboardType = value;
					return value;
				},
				get: function() {
					return this._field.keyboardType;
				},
				value: function() {
					return this._field.keyboardType;
				}
			},

			showCancel: {
				set: function(value) {
					this._cancelButton.visible = value;
					return value;
				},
				value: false
			},

			value: {
				set: function(value) {
					this._field.value = value;
					return value;
				},
				get: function() {
					return this._field.value;
				},
				value: function() {
					return this._field.value;
				}
			}
		}

	});

});
<|endoftext|>


<commit_before>//////////////////////////////////////////
// User buys one ticket from an eee-top //
//////////////////////////////////////////

'use strict';

var Promise = require('bluebird');

module.exports = function (db, config) {
    var logger          = require('../../lib/log')(config);
    var rest            = require('../../lib/rest')(config, logger);
    var generateBarcode = require('../../lib/generateBarcode');

    return function (isExt) {
        return function (req, res) {
            var eventId = req.params.eventId;
            if (!req.form.isValid) {
                return Error.emit(res, 400, '400 - Bad Request', req.form.errors);
            }

            var priceWantedExt;

            var starterPromise;
            if (isExt) {
                starterPromise = db.Token.count({
                    mailCheck: req.form.code,
                    usermail: req.form.mail
                }).then(function (count) {
                    return new Promise(function (resolve, reject) {
                        if (count === 0) {
                            Error.emit(res, 401, '401 - Unauthorized', 'no token');
                            return reject();
                        }

                        resolve();
                    });
                });
            } else {
                starterPromise = new Promise(function (resolve) {
                    resolve();
                });

                req.form.displayName = req.user.firstname.nameCapitalize() + ' ' + req.user.lastname.nameCapitalize();
                req.form.mail = req.user.mail;
            }

            starterPromise
            .then(function () {
                return new Promise(function (resolve, reject) {
                    generateBarcode(resolve, db.Ticket);
                });
            })
            .then(function (barcode) {
                return new Promise(function (resolve, reject) {
                    db.SchoolDomain.findAll().complete(function (err, domains) {
                        if (err) {
                            return Error.emit(res, 500, '500 - SQL Server error', err);
                        }

                        var partnerPrice = false;
                        domains.forEach(function (domain) {
                            var reg = new RegExp('@' + domain.domain + '$', 'i');
                            if (reg.test(req.form.mail)) {
                                partnerPrice = true;
                            }
                        });

                        resolve([barcode, partnerPrice]);
                    });
                });
            })
            .then(function (data) {
                // data: [barcode, partnerMail]
                return new Promise(function (resolve, reject) {
                    if (req.user) {
                        if (req.user.inBDE) {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%cotisant en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 1, 1]);
                            });
                        } else {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%non-cotisant en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 1, 0]);
                            });
                        }
                    } else {
                        if (data[1]) {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%partenaire en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 0, 0]);
                            });
                        } else {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%extérieur en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 0, 0]);
                            });
                        }
                    }
                });
            })
            .then(function (data) {
                // data [price, barcode, student, contributor]
                return db.Ticket.create({
                    username: (req.user) ? req.user.id : 0,
                    displayName: req.form.displayName,
                    birthdate: req.form.birthdate,
                    mail: req.form.mail,
                    student: data[2],
                    contributor: data[3],
                    paid: 1,
                    paid_at: new Date(),
                    paid_with: 'card',
                    barcode: data[1],
                    price_id: data[0].id,
                    event_id: eventId
                });
            })
            .then(function () {
                if (req.form.additionalExtTickets) {
                    return new Promise(function (resolve, reject) {
                        db.Price.find({
                            where: {
                                event_id: eventId,
                                name: { like: '%extérieur en prévente' }
                            }
                        }).complete(function (err, price) {
                            if (err) {
                                return Error.emit(res, 500, '500 - SQL Server error', err);
                            }

                            if (!price) {
                                Error.emit(res, 404, '404 - Not found', err);
                                return reject();
                            }

                            resolve(price);
                        });
                    });
                }
            })
            .then(function (price) {
                if (req.form.additionalExtTickets && !req.form.isExt) {
                    priceWanted = price;
                    var additionalExtTickets = req.body.additionalExtTickets;
                    var promises = [];
                    additionalExtTickets.forEach(function (additionalExtTicket) {
                        promises.push(new Promise (function (resolve, reject) {
                            generateBarcode(resolve, db.Ticket);
                        }));
                    });

                    return Promise.all(promises);
                }
            })
            .then(function (barcodes) {
                if (req.form.additionalExtTickets && !req.form.isExt) {
                    var additionalExtTickets = req.body.additionalExtTickets;
                    return additionalExtTickets.map(function (additionalExtTicket, i) {
                        return db.Ticket.create({
                            username: (req.user) ? req.user.id : 0,
                            displayName: additionalExtTicket.displayName,
                            birthdate: additionalExtTicket.birthdate,
                            mail: req.form.mail,
                            student: 0,
                            contributor: 0,
                            paid: 1,
                            paid_at: new Date(),
                            paid_with: 'card',
                            barcode: barcodes[i],
                            price_id: priceWanted.id,
                            event_id: eventId
                        });
                    });
                }
            })
            .then(function () {
                if (isExt) {
                    return db.Token.destroy({
                        where: {
                            mailCheck: req.form.code,
                            usermail: req.form.mail
                        }
                    });
                }
            })
            .then(function () {
                res.status(200).end();
            })
            .catch(function (err) {
                console.dir(err);
                return Error.emit(res, 500, '500 - SQL Server error', err);
            });
        };
    };
};
<commit_msg>Fix card buy<commit_after>//////////////////////////////////////////
// User buys one ticket from an eee-top //
//////////////////////////////////////////

'use strict';

var Promise = require('bluebird');

module.exports = function (db, config) {
    var logger          = require('../../lib/log')(config);
    var rest            = require('../../lib/rest')(config, logger);
    var generateBarcode = require('../../lib/generateBarcode');

    return function (isExt) {
        return function (req, res) {
            var eventId = req.params.eventId;
            if (!req.form.isValid) {
                return Error.emit(res, 400, '400 - Bad Request', req.form.errors);
            }

            var priceWantedExt;
            var newTicketId;

            var starterPromise;
            if (isExt) {
                starterPromise = db.Token.count({
                    mailCheck: req.form.code,
                    usermail: req.form.mail
                }).then(function (count) {
                    return new Promise(function (resolve, reject) {
                        if (count === 0) {
                            Error.emit(res, 401, '401 - Unauthorized', 'no token');
                            return reject();
                        }

                        resolve();
                    });
                });
            } else {
                starterPromise = new Promise(function (resolve) {
                    resolve();
                });

                req.form.displayName = req.user.firstname.nameCapitalize() + ' ' + req.user.lastname.nameCapitalize();
                req.form.mail = req.user.mail;
            }

            starterPromise
            .then(function () {
                return new Promise(function (resolve, reject) {
                    generateBarcode(resolve, db.Ticket);
                });
            })
            .then(function (barcode) {
                return new Promise(function (resolve, reject) {
                    db.SchoolDomain.findAll().complete(function (err, domains) {
                        if (err) {
                            return Error.emit(res, 500, '500 - SQL Server error', err);
                        }

                        var partnerPrice = false;
                        domains.forEach(function (domain) {
                            var reg = new RegExp('@' + domain.domain + '$', 'i');
                            if (reg.test(req.form.mail)) {
                                partnerPrice = true;
                            }
                        });

                        resolve([barcode, partnerPrice]);
                    });
                });
            })
            .then(function (data) {
                // data: [barcode, partnerMail]
                return new Promise(function (resolve, reject) {
                    if (req.user) {
                        if (req.user.inBDE) {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%cotisant en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 1, 1]);
                            });
                        } else {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%non-cotisant en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 1, 0]);
                            });
                        }
                    } else {
                        if (data[1]) {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%partenaire en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 0, 0]);
                            });
                        } else {
                            db.Price.find({
                                where: {
                                    event_id: eventId,
                                    name: { like: '%extérieur en prévente' }
                                }
                            }).complete(function (err, price) {
                                if (err || !price) {
                                    return Error.emit(res, 500, '500 - SQL Server error', err);
                                }

                                resolve([price, data[0], 0, 0]);
                            });
                        }
                    }
                });
            })
            .then(function (data) {
                // data [price, barcode, student, contributor]
                return db.Ticket.create({
                    username: (req.user) ? req.user.id : 0,
                    displayName: req.form.displayName,
                    birthdate: req.form.birthdate,
                    mail: req.form.mail,
                    student: data[2],
                    contributor: data[3],
                    paid: 1,
                    paid_at: new Date(),
                    paid_with: 'card',
                    barcode: data[1],
                    price_id: data[0].id,
                    event_id: eventId
                });
            })
            .then(function (newTicket) {
                newTicketId = newTicket.id;
                if (req.form.additionalExtTickets) {
                    return new Promise(function (resolve, reject) {
                        db.Price.find({
                            where: {
                                event_id: eventId,
                                name: { like: '%extérieur en prévente' }
                            }
                        }).complete(function (err, price) {
                            if (err) {
                                return Error.emit(res, 500, '500 - SQL Server error', err);
                            }

                            if (!price) {
                                Error.emit(res, 404, '404 - Not found', err);
                                return reject();
                            }

                            resolve(price);
                        });
                    });
                }
            })
            .then(function (price) {
                if (req.form.additionalExtTickets && !req.form.isExt) {
                    priceWanted = price;
                    var additionalExtTickets = req.body.additionalExtTickets;
                    var promises = [];
                    additionalExtTickets.forEach(function (additionalExtTicket) {
                        promises.push(new Promise (function (resolve, reject) {
                            generateBarcode(resolve, db.Ticket);
                        }));
                    });

                    return Promise.all(promises);
                }
            })
            .then(function (barcodes) {
                if (req.form.additionalExtTickets && !req.form.isExt) {
                    var additionalExtTickets = req.body.additionalExtTickets;
                    return additionalExtTickets.map(function (additionalExtTicket, i) {
                        return db.Ticket.create({
                            username: (req.user) ? req.user.id : 0,
                            displayName: additionalExtTicket.displayName,
                            birthdate: additionalExtTicket.birthdate,
                            mail: req.form.mail,
                            student: 0,
                            contributor: 0,
                            paid: 1,
                            paid_at: new Date(),
                            paid_with: 'card',
                            barcode: barcodes[i],
                            price_id: priceWanted.id,
                            event_id: eventId,
                            mainTicket: newTicketId
                        });
                    });
                }
            })
            .then(function () {
                if (isExt) {
                    return db.Token.destroy({
                        where: {
                            mailCheck: req.form.code,
                            usermail: req.form.mail
                        }
                    });
                }
            })
            .then(function () {
                res.status(200).json({
                    id: newTicketId
                }).end();
            })
            .catch(function (err) {
                console.dir(err);
                return Error.emit(res, 500, '500 - SQL Server error', err);
            });
        };
    };
};
<|endoftext|>


<commit_before>define(function() {

});<commit_msg>Adds a helper to reset AMD modules<commit_after>/* global define: true */
define(function() {
  "use strict";
  return {
    reset: function (mod, cb) {
      return function (done) {
        require.undef(mod);
        require([mod], function (module) {
          cb(module);
          done();
        });
      };
    }
  };
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';
import { request } from 'ic-ajax';
import {
  convertResourceObject,
  normalizeResponseHelper,
  _normalizeSerializerPayload
} from 'ember-attachable/lib/serializer-response';

export default Ember.Mixin.create({
  attachmentAs: null,
  saveWithAttachment() {
    return this.createWithAttachment();
  },
  createWithAttachment() {
    let adapter, attachmentKey, data, formData, promise, root, serializer, url,
    _this = this;
    adapter = this.store.adapterFor(this.constructor.modelName);
    serializer = this.store.serializerFor(this._modelName());
    attachmentKey = this.get('attachmentAs');
    data = Ember.copy(this.serialize());

    // For each key set on `attachmentName` we add that key to `data` array
    // with its conrresponding BLOB file.
    Ember.makeArray(attachmentKey).forEach(function(key) {
      data[key] = this.get(key);
    }, this);

    formData = new FormData();
    root = this._rootKey();
    Object.keys(data).forEach(function(key) {
      if (!Ember.isNone(data[key])) {
        if (Ember.isArray(data[key])) {
          return _this._recursiveArrayAppend(formData,"" + root + "[" + key + "]",data,key);
        }else if(Object.prototype.toString.call(data[key]) === '[object Object]'){
          return _this._recursiveObjectAppend(formData,"" + root + "[" + key + "]",data,key);
        } else {
          return formData.append("" + root + "[" + key + "]", data[key]);
        }
      }
    });

    url = adapter.buildURL(this._modelName(), this.get('id'));
    if(this._oldEmberData()){
      this.adapterWillCommit();
    }else{
      this._internalModel.adapterWillCommit();
    }
    promise = request(url, {
      type: this._requestType(),
      data: formData,
      dataType: 'json',
      headers: adapter.get('headers'),
      processData: false,
      contentType: false,
      xhr() {
        var xhr;
        xhr = Ember.$.ajaxSettings.xhr();
        xhr.upload.onprogress = function(evt) {
          return _this.set('uploadProgress', evt.loaded / evt.total * 100);
        };
        return xhr;
      }
    });
    return this._commitWithAttachment(promise, adapter, serializer);
  },
  _recursiveArrayAppend(formData, appendRoot, data, key) {
    for (var qey = 0; qey < data[key].length; qey++) {
      if (!Ember.isNone(data[key][qey])) {
        if(Object.prototype.toString.call(data[key][qey]) === '[object Object]'){
          this._recursiveObjectAppend(formData,appendRoot + "[]", data[key], qey);
        } else if (Ember.isArray(data[key][qey])) {
          this._recursiveArrayAppend(formData,appendRoot + "[]", data[key], qey);
        }else{
          formData.append(appendRoot + "[]", data[key][qey]);
        }
      }
    }
  },
  _recursiveObjectAppend(formData, appendRoot, data, key) {
    for (var qey in data[key]){
      if (!Ember.isNone(data[key][qey])) {
        if(Object.prototype.toString.call(data[key][qey]) === '[object Object]'){
          this._recursiveObjectAppend(formData,appendRoot + "[" + qey + "]", data[key], qey);
        } else if (Ember.isArray(data[key][qey])) {
          this._recursiveArrayAppend(formData,appendRoot + "[" + qey + "]", data[key], qey);
        }else{
          formData.append(appendRoot + "[" + qey + "]", data[key][qey]);
        }
      }
    }
  },
  _rootKey() {
    return Ember.String.underscore(Ember.String.decamelize(this._modelName()));
  },
  _requestType() {
    if (this.get("isNew")) {
      return "POST";
    } else {
      return "PUT";
    }
  },
  _commitWithAttachment(promise, adapter, serializer) {
    var operation, record, store, type, oldEmberData;
    oldEmberData = this._oldEmberData();
    store = this.store;
    record = this;
    type = record.constructor;
    operation = '';
    if (Ember.get(record, "isNew")) {
      operation = "createRecord";
    } else if (Ember.get(record, "isDeleted")) {
      operation = "deleteRecord";
    } else {
      operation = "updateRecord";
    }
    return promise.then((function(adapterPayload) {
      if (oldEmberData) {
        var payload;
        payload = void 0;
        if (adapterPayload) {
          payload = serializer.extract(store, type, adapterPayload, Ember.get(record, "id"), operation);
        } else {
          payload = adapterPayload;
        }
        store.didSaveRecord(record, payload);
      } else{
        store._adapterRun(function() {
          var payload, data;
          var internalModel = record._internalModel;
          if (adapterPayload) {
            payload = normalizeResponseHelper(serializer, store, type, adapterPayload, Ember.get(record, "id"), operation);
            if (payload.included) {
              store.push({ data: payload.included });
            }
            data = convertResourceObject(payload.data);
          }else{
            data = adapterPayload;
          }
          store.didSaveRecord(internalModel, _normalizeSerializerPayload(internalModel.type, data));
        });
      }
      return record;
    }), (function(reason) {
      var error;
      if(adapter.ajaxError){
        error = adapter.ajaxError(reason.jqXHR);
        if (error instanceof DS.InvalidError) {
          store.recordWasInvalid(record, error.errors);
        } else if (error.status === 422){
          store.recordWasInvalid(record, error.responseJSON.errors);
        } else {
          store.recordWasError(record);
        }
      }else{
        error = adapter.handleResponse(reason.jqXHR.status, record._parseResponseHeaders(reason.jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(reason.jqXHR.responseText));
        if (error instanceof DS.InvalidError) {
          let stateToTransition = record.get('isNew') ? 'created.uncommitted' : 'updated.uncommitted';
          record.transitionTo(stateToTransition);
          let recordModel = record.adapterDidInvalidate ? record : record._internalModel;
          store.recordWasInvalid(recordModel, DS.errorsArrayToHash(error.errors));
        }
      }
      throw reason;
    }), "Uploading file with attachment");
  },
  _parseResponseHeaders(headerStr) {
    var headers = {};
    if (!headerStr) {
      return headers;
    }

    var headerPairs = headerStr.split('\u000d\u000a');
    for (var i = 0; i < headerPairs.length; i++) {
      var headerPair = headerPairs[i];
      // Can't use split() here because it does the wrong thing
      // if the header value has the string ": " in it.
      var index = headerPair.indexOf('\u003a\u0020');
      if (index > 0) {
        var key = headerPair.substring(0, index);
        var val = headerPair.substring(index + 2);
        headers[key] = val;
      }
    }

    return headers;
  },
  _oldEmberData() {
    return !Ember.isNone(this.adapterWillCommit);
  },
  // Provide backwards compatible modelName implementation
  _modelName() {
    if (Ember.isNone(this.constructor.typeKey)) {
      return this.constructor.modelName;
    } else {
      return this.constructor.typeKey;
    }
  }
});
<commit_msg>fixed bug on createWithAttachment. now including requestType on buildURL.<commit_after>import Ember from 'ember';
import DS from 'ember-data';
import { request } from 'ic-ajax';
import {
  convertResourceObject,
  normalizeResponseHelper,
  _normalizeSerializerPayload
} from 'ember-attachable/lib/serializer-response';

export default Ember.Mixin.create({
  attachmentAs: null,
  saveWithAttachment() {
    return this.createWithAttachment();
  },
  createWithAttachment() {
    let adapter, attachmentKey, data, formData, promise, root, serializer, url,
    _this = this;
    adapter = this.store.adapterFor(this.constructor.modelName);
    serializer = this.store.serializerFor(this._modelName());
    attachmentKey = this.get('attachmentAs');
    data = Ember.copy(this.serialize());

    // For each key set on `attachmentName` we add that key to `data` array
    // with its conrresponding BLOB file.
    Ember.makeArray(attachmentKey).forEach(function(key) {
      data[key] = this.get(key);
    }, this);

    formData = new FormData();
    root = this._rootKey();
    Object.keys(data).forEach(function(key) {
      if (!Ember.isNone(data[key])) {
        if (Ember.isArray(data[key])) {
          return _this._recursiveArrayAppend(formData,"" + root + "[" + key + "]",data,key);
        }else if(Object.prototype.toString.call(data[key]) === '[object Object]'){
          return _this._recursiveObjectAppend(formData,"" + root + "[" + key + "]",data,key);
        } else {
          return formData.append("" + root + "[" + key + "]", data[key]);
        }
      }
    });

    if(this.get('isNew')){
      url = adapter.buildURL(this._modelName(), this.get('id'), [], 'createRecord');
    }
    else{
      url = adapter.buildURL(this._modelName(), this.get('id'), [], 'updateRecord');
    }

    if(this._oldEmberData()){
      this.adapterWillCommit();
    }else{
      this._internalModel.adapterWillCommit();
    }
    promise = request(url, {
      type: this._requestType(),
      data: formData,
      dataType: 'json',
      headers: adapter.get('headers'),
      processData: false,
      contentType: false,
      xhr() {
        var xhr;
        xhr = Ember.$.ajaxSettings.xhr();
        xhr.upload.onprogress = function(evt) {
          return _this.set('uploadProgress', evt.loaded / evt.total * 100);
        };
        return xhr;
      }
    });
    return this._commitWithAttachment(promise, adapter, serializer);
  },
  _recursiveArrayAppend(formData, appendRoot, data, key) {
    for (var qey = 0; qey < data[key].length; qey++) {
      if (!Ember.isNone(data[key][qey])) {
        if(Object.prototype.toString.call(data[key][qey]) === '[object Object]'){
          this._recursiveObjectAppend(formData,appendRoot + "[]", data[key], qey);
        } else if (Ember.isArray(data[key][qey])) {
          this._recursiveArrayAppend(formData,appendRoot + "[]", data[key], qey);
        }else{
          formData.append(appendRoot + "[]", data[key][qey]);
        }
      }
    }
  },
  _recursiveObjectAppend(formData, appendRoot, data, key) {
    for (var qey in data[key]){
      if (!Ember.isNone(data[key][qey])) {
        if(Object.prototype.toString.call(data[key][qey]) === '[object Object]'){
          this._recursiveObjectAppend(formData,appendRoot + "[" + qey + "]", data[key], qey);
        } else if (Ember.isArray(data[key][qey])) {
          this._recursiveArrayAppend(formData,appendRoot + "[" + qey + "]", data[key], qey);
        }else{
          formData.append(appendRoot + "[" + qey + "]", data[key][qey]);
        }
      }
    }
  },
  _rootKey() {
    return Ember.String.underscore(Ember.String.decamelize(this._modelName()));
  },
  _requestType() {
    if (this.get("isNew")) {
      return "POST";
    } else {
      return "PUT";
    }
  },
  _commitWithAttachment(promise, adapter, serializer) {
    var operation, record, store, type, oldEmberData;
    oldEmberData = this._oldEmberData();
    store = this.store;
    record = this;
    type = record.constructor;
    operation = '';
    if (Ember.get(record, "isNew")) {
      operation = "createRecord";
    } else if (Ember.get(record, "isDeleted")) {
      operation = "deleteRecord";
    } else {
      operation = "updateRecord";
    }
    return promise.then((function(adapterPayload) {
      if (oldEmberData) {
        var payload;
        payload = void 0;
        if (adapterPayload) {
          payload = serializer.extract(store, type, adapterPayload, Ember.get(record, "id"), operation);
        } else {
          payload = adapterPayload;
        }
        store.didSaveRecord(record, payload);
      } else{
        store._adapterRun(function() {
          var payload, data;
          var internalModel = record._internalModel;
          if (adapterPayload) {
            payload = normalizeResponseHelper(serializer, store, type, adapterPayload, Ember.get(record, "id"), operation);
            if (payload.included) {
              store.push({ data: payload.included });
            }
            data = convertResourceObject(payload.data);
          }else{
            data = adapterPayload;
          }
          store.didSaveRecord(internalModel, _normalizeSerializerPayload(internalModel.type, data));
        });
      }
      return record;
    }), (function(reason) {
      var error;
      if(adapter.ajaxError){
        error = adapter.ajaxError(reason.jqXHR);
        if (error instanceof DS.InvalidError) {
          store.recordWasInvalid(record, error.errors);
        } else if (error.status === 422){
          store.recordWasInvalid(record, error.responseJSON.errors);
        } else {
          store.recordWasError(record);
        }
      }else{
        error = adapter.handleResponse(reason.jqXHR.status, record._parseResponseHeaders(reason.jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(reason.jqXHR.responseText));
        if (error instanceof DS.InvalidError) {
          let stateToTransition = record.get('isNew') ? 'created.uncommitted' : 'updated.uncommitted';
          record.transitionTo(stateToTransition);
          let recordModel = record.adapterDidInvalidate ? record : record._internalModel;
          store.recordWasInvalid(recordModel, DS.errorsArrayToHash(error.errors));
        }
      }
      throw reason;
    }), "Uploading file with attachment");
  },
  _parseResponseHeaders(headerStr) {
    var headers = {};
    if (!headerStr) {
      return headers;
    }

    var headerPairs = headerStr.split('\u000d\u000a');
    for (var i = 0; i < headerPairs.length; i++) {
      var headerPair = headerPairs[i];
      // Can't use split() here because it does the wrong thing
      // if the header value has the string ": " in it.
      var index = headerPair.indexOf('\u003a\u0020');
      if (index > 0) {
        var key = headerPair.substring(0, index);
        var val = headerPair.substring(index + 2);
        headers[key] = val;
      }
    }

    return headers;
  },
  _oldEmberData() {
    return !Ember.isNone(this.adapterWillCommit);
  },
  // Provide backwards compatible modelName implementation
  _modelName() {
    if (Ember.isNone(this.constructor.typeKey)) {
      return this.constructor.modelName;
    } else {
      return this.constructor.typeKey;
    }
  }
});
<|endoftext|>


<commit_before>define(['lodash', 'backbone'], function(_, Backbone) {
  var RandomThrowGenerator = function () {
    this.generate = function () {
      return Math.round(Math.random() * (6 - 1) + 1);
    }
  };

  var Pawn = function (homePosition, path) {
    this._homePosition = homePosition;
    this._position = homePosition;
    this._path = path;

    this.moveToHome = function () {
      this._position = this._homePosition;
    };

    this.isAtHome = function () {
      return this._homePosition === this._position;
    };

    this.isOnTheBoard = function () {
      for (var i = 0; i < this._path.length - 4; i++) {
        if (this._path[i] === this.getPosition()) return true;
      }
      return false;
    }

    this.isAtTheFinish = function () {
      return !this.isAtHome() && !this.isOnTheBoard();
    };

    this.setPosition = function (position) {
      this._position = position;
    };

    this.getPosition = function () {
      return this._position;
    };

    this._getFirstPositionOnPath = function () {
      return this._path[0];
    };

    this.getNextPosition = function (die) {
      if (this.isAtHome()) {
        if (die === 6) {
          return this._getFirstPositionOnPath();
        } else {
          return null;
        }
      }

      var newPosition = this.getNextPositionOnPath(this.getPosition(), die);

      if (typeof newPosition === 'number') return newPosition;
      return null;
    }

    this.moveBy = function (die) {
      this.setPosition(this.getNextPosition(die));
    }

    this.getNextPositionOnPath = function (startPosition, distance) {
      return this._path[this._findPositionIndex(startPosition) + distance];
    };

    this._findPositionIndex = function (position) {
      for (var i = 0; i < this._path.length; i++) {
        if (this._path[i] == position) return i;
      }
    };

  };

  var Player = function (pawns, path) {
    this._pawns = pawns;
    this._path = path;
    this.getPawn = function (pawnId) {
      return this._getPawn(pawnId);
    };

    this.isMovablePawnsExist = function (die) {
      return this.getMovablePawns(die) !== {};
    };

    this.isAnyPawnsOnTheBoard = function () {
      for (var i = 0; i < this._pawns.length; i++) {
        if (this._getPawn(i).isOnTheBoard()) {
          return true;
        }
      }
      return false;
    };

    this.isAllPawnsAreAtFinish = function() {
      for (var i = 0; i < this._pawns.length; i++) {
        var atTheFinish = this._getPawn(i).isAtTheFinish();
        if (!atTheFinish) {
          return false;
        }
      }
      return true;
    };

    this.isAllPawnsAreAtHome = function () {
      for (var i = 0; i < this._pawns.length; i++) {
        if (!this._getPawn(i).isAtHome()) {
          return false;
        }
      }
      return true;
    }

    this._getPawn = function (id) {
      return this._pawns[id];
    };

    this.getMovablePawns = function (die) {
      var pawnNextPositions = [];
      for (var i = 0; i < this._pawns.length; i++) {
        var pawn = this._getPawn(i);
        pawnNextPositions[i] = pawn.getNextPosition(die);
      }
      ;

      for (var i = 0; i < this._pawns.length; i++) {
        var pawn = this._getPawn(i);
        var pawnPosition = pawn.getPosition();
        for (var j = 0; j < this._pawns.length; j++) {
          if (pawnNextPositions[j] == pawnPosition) pawnNextPositions[j] = null;
        }
      }

      var result = {};
      for (var i = 0; i < this._pawns.length; i++) {
        if (typeof pawnNextPositions[i] === 'number') {
          result[i] = this._getPawn(i).getNextPosition(die);
        }
      }
      return result;
    };
  };

  var Game = function () {
    this.initialize.apply(this, arguments);
  };

  _.extend(Game.prototype, Backbone.Events, {
    initialize: function (options) {
      this._board = options.board;
      this._currentPlayerId = 0;

      this._dieThrowGenerator = options.dieThrowGenerator || new RandomThrowGenerator();
      this._generatePlayersFromBoard = function (board) {
        this._players = {};
        for (var playerId = 0; playerId < 4; playerId++) {
          var paths = board.paths[playerId];
          var homes = board.homes[playerId];
          var pawns = [];
          for (var pawnId = 0; pawnId < 4; pawnId++) {
            pawns.push(new Pawn(homes[pawnId], paths));
          }
          this._players[playerId] = new Player(pawns, paths);
        }
      };
      this._generatePlayersFromBoard(this._board);

      this.getCurrentPlayerId = function () {
        return this._currentPlayerId;
      };

      this.throwDie = function () {
        var value = this._dieThrowGenerator.generate();

        this._incrementDieThrowCount();
        this._setPlayedAfterDieThrow(false);
        this._currentDieValue = value;
        var movablePawnsExist = this._getCurrentPlayer().isMovablePawnsExist(value);
        var movablePawns = this._getCurrentPlayer().getMovablePawns(value);
        var result = { value: value, movablePawns: movablePawns};
        this.trigger('die:thrown', result);

        if (!movablePawnsExist) {
          this._changePlayerIfNeeded(value);
        }
        return result;
      };

      this._getPlayer = function (playerId) {
        return this._players[playerId];
      };

      this._getCurrentPlayer = function () {
        return this._getPlayer(this.getCurrentPlayerId());
      };

      this._getPlayersCount = function () {
        return 4;
      }

      this._getDieThrowCount = function () {
        return this._dieThrowCount || 0;
      };

      this._incrementDieThrowCount = function () {
        this._dieThrowCount = this._getDieThrowCount() + 1;
      };

      this._resetDieThrowCount = function () {
        this._dieThrowCount = 0;
      };

      this._isPlayedAfterDieThrow = function () {
        return !!this._playedAfterDieThrow || false;
      };

      this._setPlayedAfterDieThrow = function (value) {
        this._playedAfterDieThrow = value;
      };

      this._shouldChangePlayer = function (die) {
        var currentPlayer = this._getCurrentPlayer();
        if (die === 6) {
          return false;
        }
        ;
        if (currentPlayer.isAllPawnsAreAtHome()) {
          return this._getDieThrowCount() >= 3;
        } else {
          return  this._isPlayedAfterDieThrow() || !currentPlayer.isMovablePawnsExist(die);
        }
        return false;
      };

      this._changePlayerIfNeeded = function (die) {
        if (this._shouldChangePlayer(die)) {
          this._currentPlayerId = (this._currentPlayerId + 1) % this._getPlayersCount();
          this._resetDieThrowCount();
        }
      };

      this._getPlayerIdAndPawnIdAtSamePositionAs = function (pawn) {
        for (var playerId = 0; playerId < 4; playerId++) {
          for (var pawnId = 0; pawnId < 4; pawnId++) {
            var otherPawn = this._getPlayer(playerId).getPawn(pawnId);
            if (otherPawn !== pawn) {
              if (otherPawn.getPosition() === pawn.getPosition()) {
                return { playerId: playerId, pawnId: pawnId, pawn: otherPawn };
              }
            }
          }
        }
        return null;
      };

      this._checkForEatenPawns = function(pawn) {
        var eatenPawnInfo = this._getPlayerIdAndPawnIdAtSamePositionAs(pawn);
        if (eatenPawnInfo) {
          eatenPawnInfo.pawn.moveToHome();
          this.trigger('pawn:eaten', { playerId: eatenPawnInfo.playerId, pawnId: eatenPawnInfo.pawnId, pointId: eatenPawnInfo.pawn.getPosition()});
        }
      };

      this._checkIfFinished = function(playerId) {
        var player = this._getPlayer(playerId);
        var isFinished = player.isAllPawnsAreAtFinish();
        if (isFinished) {
          this.trigger('player:finished', { playerId: playerId});
        }
      };

      this.playMove = function (pawnId) {
        var die = this._currentDieValue;
        var playerId = this.getCurrentPlayerId();
        var player = this._getCurrentPlayer();
        var pawn = player.getPawn(pawnId);

        pawn.moveBy(die);
        var newPosition = pawn.getPosition();
        this._checkForEatenPawns(pawn);
        this._setPlayedAfterDieThrow(true);
        this._resetDieThrowCount();

        this._checkIfFinished(playerId);

        this._changePlayerIfNeeded(die);

        this.trigger('player:move', { playerId: playerId, pawnId: pawnId, pointId: newPosition});

      };
      this.getMovablePawns = function (die) {
        return this._getCurrentPlayer().getMovablePawns(die);
      };

      this._logState= function() {
        var state = {};
        for (var i = 0; i < 4; i++) {
          state[i] = [];
          var player = this._getPlayer(i);
          for (var j = 0; j < 4; j++) {
            var pawn = player.getPawn(j);
            state[i].push(pawn.getPosition());
          }
        }
        console.log(state);
      };
    }

  });

  Game.create = function (options) {
    return new Game(options);
  }

  return Game;
});
<commit_msg>Add playerId to throwDie<commit_after>define(['lodash', 'backbone'], function(_, Backbone) {
  var RandomThrowGenerator = function () {
    this.generate = function () {
      return Math.round(Math.random() * (6 - 1) + 1);
    }
  };

  var Pawn = function (homePosition, path) {
    this._homePosition = homePosition;
    this._position = homePosition;
    this._path = path;

    this.moveToHome = function () {
      this._position = this._homePosition;
    };

    this.isAtHome = function () {
      return this._homePosition === this._position;
    };

    this.isOnTheBoard = function () {
      for (var i = 0; i < this._path.length - 4; i++) {
        if (this._path[i] === this.getPosition()) return true;
      }
      return false;
    }

    this.isAtTheFinish = function () {
      return !this.isAtHome() && !this.isOnTheBoard();
    };

    this.setPosition = function (position) {
      this._position = position;
    };

    this.getPosition = function () {
      return this._position;
    };

    this._getFirstPositionOnPath = function () {
      return this._path[0];
    };

    this.getNextPosition = function (die) {
      if (this.isAtHome()) {
        if (die === 6) {
          return this._getFirstPositionOnPath();
        } else {
          return null;
        }
      }

      var newPosition = this.getNextPositionOnPath(this.getPosition(), die);

      if (typeof newPosition === 'number') return newPosition;
      return null;
    }

    this.moveBy = function (die) {
      this.setPosition(this.getNextPosition(die));
    }

    this.getNextPositionOnPath = function (startPosition, distance) {
      return this._path[this._findPositionIndex(startPosition) + distance];
    };

    this._findPositionIndex = function (position) {
      for (var i = 0; i < this._path.length; i++) {
        if (this._path[i] == position) return i;
      }
    };

  };

  var Player = function (pawns, path) {
    this._pawns = pawns;
    this._path = path;
    this.getPawn = function (pawnId) {
      return this._getPawn(pawnId);
    };

    this.isMovablePawnsExist = function (die) {
      return this.getMovablePawns(die) !== {};
    };

    this.isAnyPawnsOnTheBoard = function () {
      for (var i = 0; i < this._pawns.length; i++) {
        if (this._getPawn(i).isOnTheBoard()) {
          return true;
        }
      }
      return false;
    };

    this.isAllPawnsAreAtFinish = function() {
      for (var i = 0; i < this._pawns.length; i++) {
        var atTheFinish = this._getPawn(i).isAtTheFinish();
        if (!atTheFinish) {
          return false;
        }
      }
      return true;
    };

    this.isAllPawnsAreAtHome = function () {
      for (var i = 0; i < this._pawns.length; i++) {
        if (!this._getPawn(i).isAtHome()) {
          return false;
        }
      }
      return true;
    }

    this._getPawn = function (id) {
      return this._pawns[id];
    };

    this.getMovablePawns = function (die) {
      var pawnNextPositions = [];
      for (var i = 0; i < this._pawns.length; i++) {
        var pawn = this._getPawn(i);
        pawnNextPositions[i] = pawn.getNextPosition(die);
      }
      ;

      for (var i = 0; i < this._pawns.length; i++) {
        var pawn = this._getPawn(i);
        var pawnPosition = pawn.getPosition();
        for (var j = 0; j < this._pawns.length; j++) {
          if (pawnNextPositions[j] == pawnPosition) pawnNextPositions[j] = null;
        }
      }

      var result = {};
      for (var i = 0; i < this._pawns.length; i++) {
        if (typeof pawnNextPositions[i] === 'number') {
          result[i] = this._getPawn(i).getNextPosition(die);
        }
      }
      return result;
    };
  };

  var Game = function () {
    this.initialize.apply(this, arguments);
  };

  _.extend(Game.prototype, Backbone.Events, {
    initialize: function (options) {
      this._board = options.board;
      this._currentPlayerId = 0;

      this._dieThrowGenerator = options.dieThrowGenerator || new RandomThrowGenerator();
      this._generatePlayersFromBoard = function (board) {
        this._players = {};
        for (var playerId = 0; playerId < 4; playerId++) {
          var paths = board.paths[playerId];
          var homes = board.homes[playerId];
          var pawns = [];
          for (var pawnId = 0; pawnId < 4; pawnId++) {
            pawns.push(new Pawn(homes[pawnId], paths));
          }
          this._players[playerId] = new Player(pawns, paths);
        }
      };
      this._generatePlayersFromBoard(this._board);

      this.getCurrentPlayerId = function () {
        return this._currentPlayerId;
      };

      this.throwDie = function () {
        var value = this._dieThrowGenerator.generate();

        this._incrementDieThrowCount();
        this._setPlayedAfterDieThrow(false);
        this._currentDieValue = value;
        var movablePawnsExist = this._getCurrentPlayer().isMovablePawnsExist(value);
        var movablePawns = this._getCurrentPlayer().getMovablePawns(value);
        var result = { playerId: this.getCurrentPlayerId(), value: value, movablePawns: movablePawns};
        this.trigger('die:thrown', result);

        if (!movablePawnsExist) {
          this._changePlayerIfNeeded(value);
        }
        return result;
      };

      this._getPlayer = function (playerId) {
        return this._players[playerId];
      };

      this._getCurrentPlayer = function () {
        return this._getPlayer(this.getCurrentPlayerId());
      };

      this._getPlayersCount = function () {
        return 4;
      }

      this._getDieThrowCount = function () {
        return this._dieThrowCount || 0;
      };

      this._incrementDieThrowCount = function () {
        this._dieThrowCount = this._getDieThrowCount() + 1;
      };

      this._resetDieThrowCount = function () {
        this._dieThrowCount = 0;
      };

      this._isPlayedAfterDieThrow = function () {
        return !!this._playedAfterDieThrow || false;
      };

      this._setPlayedAfterDieThrow = function (value) {
        this._playedAfterDieThrow = value;
      };

      this._shouldChangePlayer = function (die) {
        var currentPlayer = this._getCurrentPlayer();
        if (die === 6) {
          return false;
        }
        ;
        if (currentPlayer.isAllPawnsAreAtHome()) {
          return this._getDieThrowCount() >= 3;
        } else {
          return  this._isPlayedAfterDieThrow() || !currentPlayer.isMovablePawnsExist(die);
        }
        return false;
      };

      this._changePlayerIfNeeded = function (die) {
        if (this._shouldChangePlayer(die)) {
          this._currentPlayerId = (this._currentPlayerId + 1) % this._getPlayersCount();
          this._resetDieThrowCount();
        }
      };

      this._getPlayerIdAndPawnIdAtSamePositionAs = function (pawn) {
        for (var playerId = 0; playerId < 4; playerId++) {
          for (var pawnId = 0; pawnId < 4; pawnId++) {
            var otherPawn = this._getPlayer(playerId).getPawn(pawnId);
            if (otherPawn !== pawn) {
              if (otherPawn.getPosition() === pawn.getPosition()) {
                return { playerId: playerId, pawnId: pawnId, pawn: otherPawn };
              }
            }
          }
        }
        return null;
      };

      this._checkForEatenPawns = function(pawn) {
        var eatenPawnInfo = this._getPlayerIdAndPawnIdAtSamePositionAs(pawn);
        if (eatenPawnInfo) {
          eatenPawnInfo.pawn.moveToHome();
          this.trigger('pawn:eaten', { playerId: eatenPawnInfo.playerId, pawnId: eatenPawnInfo.pawnId, pointId: eatenPawnInfo.pawn.getPosition()});
        }
      };

      this._checkIfFinished = function(playerId) {
        var player = this._getPlayer(playerId);
        var isFinished = player.isAllPawnsAreAtFinish();
        if (isFinished) {
          this.trigger('player:finished', { playerId: playerId});
        }
      };

      this.playMove = function (pawnId) {
        var die = this._currentDieValue;
        var playerId = this.getCurrentPlayerId();
        var player = this._getCurrentPlayer();
        var pawn = player.getPawn(pawnId);

        pawn.moveBy(die);
        var newPosition = pawn.getPosition();
        this._checkForEatenPawns(pawn);
        this._setPlayedAfterDieThrow(true);
        this._resetDieThrowCount();

        this._checkIfFinished(playerId);

        this._changePlayerIfNeeded(die);

        this.trigger('player:move', { playerId: playerId, pawnId: pawnId, pointId: newPosition});

      };
      this.getMovablePawns = function (die) {
        return this._getCurrentPlayer().getMovablePawns(die);
      };

      this._logState= function() {
        var state = {};
        for (var i = 0; i < 4; i++) {
          state[i] = [];
          var player = this._getPlayer(i);
          for (var j = 0; j < 4; j++) {
            var pawn = player.getPawn(j);
            state[i].push(pawn.getPosition());
          }
        }
        console.log(state);
      };
    }

  });

  Game.create = function (options) {
    return new Game(options);
  }

  return Game;
});
<|endoftext|>


<commit_before>class Fauxnix {
  constructor(events) {
    this.replies = [];
    this.onopen = function() {};
    events.apply(this);

    setTimeout(() => {
      this.readyState = 1;
      this.onopen();
    }, 500);
  }

  receive(topic, event, callback) {
    this.replies.push({ topic: topic, event: event, callback: callback });
  }

  send(rawMessage) {
    const message = JSON.parse(rawMessage);
    const reply = this._findReplyFor(message);

    if (reply) {
      const response = this._buildResponse(message, reply);
      const stringResponse = JSON.stringify(response);

      setTimeout(() => {
        this.onmessage({ data: stringResponse });
      }, 10);
    } else {
      console.warn(`Unhandled message: ${rawMessage}`);
    }
  }

  _findReplyFor(message) {
    return this.replies.find((reply) => {
      const eventMatches = message.event.match(reply.event);
      const topicMatches = message.topic.match(reply.topic);

      return eventMatches && topicMatches;
    });
  }

  _buildResponse(message, reply) {
    const payload = reply.callback(message.payload);
    return {
      topic: message.topic,
      event: "phx_reply",
      payload: {
        status: payload.status,
        response: payload.response || {},
      },
      ref: message.ref,
    };
  }
}

Fauxnix.doItLive = Fauxnix.inject = function(socket) {
  window.WebSocket = function() {
    return socket;
  };
};

export default Fauxnix;
<commit_msg>Add close method to fake socket<commit_after>class Fauxnix {
  constructor(events) {
    this.replies = [];
    this.onopen = function() {};
    this.onclose = function () {};
    events.apply(this);

    setTimeout(() => {
      this.readyState = 1;
      this.onopen();
    }, 500);
  }

  receive(topic, event, callback) {
    this.replies.push({ topic: topic, event: event, callback: callback });
  }

  send(rawMessage) {
    const message = JSON.parse(rawMessage);
    const reply = this._findReplyFor(message);

    if (reply) {
      const response = this._buildResponse(message, reply);
      const stringResponse = JSON.stringify(response);

      setTimeout(() => {
        this.onmessage({ data: stringResponse });
      }, 10);
    } else {
      console.warn(`Unhandled message: ${rawMessage}`);
    }
  }

  close() {
    this.readyState = 3;
    this.onclose();
  }

  _findReplyFor(message) {
    return this.replies.find((reply) => {
      const eventMatches = message.event.match(reply.event);
      const topicMatches = message.topic.match(reply.topic);

      return eventMatches && topicMatches;
    });
  }

  _buildResponse(message, reply) {
    const payload = reply.callback(message.payload);
    return {
      topic: message.topic,
      event: "phx_reply",
      payload: {
        status: payload.status,
        response: payload.response || {},
      },
      ref: message.ref,
    };
  }
}

Fauxnix.doItLive = Fauxnix.inject = function(socket) {
  window.WebSocket = function() {
    return socket;
  };
};

export default Fauxnix;
<|endoftext|>


<commit_before>/* jslint node: true */
'use strict';

var theme			= require('../core/theme.js');
//var Log				= require('../core/logger.js').log;
var ansi			= require('../core/ansi_term.js');
var userDb			= require('./database.js').dbs.user;

var async			= require('async');

exports.login		= login;
exports.logoff		= logoff;

function login(callingMenu, formData, extraArgs) {
	var client = callingMenu.client;

	client.user.authenticate(formData.value.username, formData.value.password, function authenticated(err) {
		if(err) {
			client.log.info( { username : formData.value.username }, 'Failed login attempt %s', err);

			client.gotoMenuModule( { name : callingMenu.menuConfig.fallback } );
		} else {
			var now		= new Date();
			var user	= callingMenu.client.user;

			//	use client.user so we can get correct case
			client.log.info( { username : user.username }, 'Successful login');

			async.parallel(
				[
					function loadThemeConfig(callback) {
						theme.loadTheme(user.properties.theme_id, function themeLoaded(err, theme) {
							client.currentTheme = theme;
							callback(null);	//	always non-fatal
						});
					},
					function recordLastLogin(callback) {
						user.persistProperty('last_login_timestamp', now.toISOString(), function persisted(err) {
							callback(err);
						});
					},
					function recordLoginHistory(callback) {

						userDb.serialize(function serialized() {
							userDb.run(
								'INSERT INTO user_login_history (user_id, user_name, timestamp) ' +
								'VALUES(?, ?, ?);', [ user.userId, user.username, now.toISOString() ]
							);

							//	keep 30 days of records
							userDb.run(
								'DELETE FROM user_login_history '	+
								'WHERE timestamp <= DATETIME("now", "-30 day");'
								);
						});

						callback(null);
					}
				],
				function complete(err, results) {
					if(err) {
						client.log.error(err);
						//	:TODO: drop the connection?
					}
					client.gotoMenuModule( { name : callingMenu.menuConfig.next } );
				}
			);
		}
	});
}

function logoff(callingMenu, formData, extraArgs) {
	var client = callingMenu.client;

	//	:TODO: record this.

	setTimeout(function timeout() {
		client.term.write(ansi.normal() + '\nATH0\n');
		client.end();
	}, 500);
}<commit_msg>* Login count property for users<commit_after>/* jslint node: true */
'use strict';

var theme			= require('../core/theme.js');
//var Log				= require('../core/logger.js').log;
var ansi			= require('../core/ansi_term.js');
var userDb			= require('./database.js').dbs.user;

var async			= require('async');

exports.login		= login;
exports.logoff		= logoff;

function login(callingMenu, formData, extraArgs) {
	var client = callingMenu.client;

	client.user.authenticate(formData.value.username, formData.value.password, function authenticated(err) {
		if(err) {
			client.log.info( { username : formData.value.username }, 'Failed login attempt %s', err);

			client.gotoMenuModule( { name : callingMenu.menuConfig.fallback } );
		} else {
			var now		= new Date();
			var user	= callingMenu.client.user;

			//	use client.user so we can get correct case
			client.log.info( { username : user.username }, 'Successful login');

			async.parallel(
				[
					function loadThemeConfig(callback) {
						theme.loadTheme(user.properties.theme_id, function themeLoaded(err, theme) {
							client.currentTheme = theme;
							callback(null);	//	always non-fatal
						});
					},
					function recordLastLogin(callback) {
						user.persistProperty('last_login_timestamp', now.toISOString(), function persisted(err) {
							callback(err);
						});
					},
					function updateUserLoginCount(callback) {
						if(!user.properties.login_count) {
							user.properties.login_count = 1;
						} else {
							user.properties.login_count++;
						}

						user.persistProperty('login_count', user.properties.login_count, function persisted(err) {
							callback(err);
						});
					},
					function recordLoginHistory(callback) {

						userDb.serialize(function serialized() {
							userDb.run(
								'INSERT INTO user_login_history (user_id, user_name, timestamp) ' +
								'VALUES(?, ?, ?);', [ user.userId, user.username, now.toISOString() ]
							);

							//	keep 30 days of records
							userDb.run(
								'DELETE FROM user_login_history '	+
								'WHERE timestamp <= DATETIME("now", "-30 day");'
								);
						});

						callback(null);
					}
				],
				function complete(err, results) {
					if(err) {
						client.log.error(err);
						//	:TODO: drop the connection?
					}
					client.gotoMenuModule( { name : callingMenu.menuConfig.next } );
				}
			);
		}
	});
}

function logoff(callingMenu, formData, extraArgs) {
	var client = callingMenu.client;

	//	:TODO: record this.

	setTimeout(function timeout() {
		client.term.write(ansi.normal() + '\nATH0\n');
		client.end();
	}, 500);
}<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// NAMESPACE //

/**
* Top-level namespace.
*
* @namespace regexp
*/
var regexp = {};

/**
* @name RE_DIRNAME
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/dirname}
*/
setReadOnly( regexp, 'RE_DIRNAME', require( '@stdlib/regexp/dirname' ) );

/**
* @name RE_DIRNAME_POSIX
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/dirname-posix}
*/
setReadOnly( regexp, 'RE_DIRNAME_POSIX', require( '@stdlib/regexp/dirname-posix' ) );

/**
* @name RE_DIRNAME_WINDOWS
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/dirname-windows}
*/
setReadOnly( regexp, 'RE_DIRNAME_WINDOWS', require( '@stdlib/regexp/dirname-windows' ) );

/**
* @name RE_EOL
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/eol}
*/
setReadOnly( regexp, 'RE_EOL', require( '@stdlib/regexp/eol' ) );

/**
* @name RE_EXTNAME
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/extname}
*/
setReadOnly( regexp, 'RE_EXTNAME', require( '@stdlib/regexp/extname' ) );

/**
* @name RE_EXTNAME_POSIX
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/extname-posix}
*/
setReadOnly( regexp, 'RE_EXTNAME_POSIX', require( '@stdlib/regexp/extname-posix' ) );

/**
* @name RE_EXTNAME_WINDOWS
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/extname-windows}
*/
setReadOnly( regexp, 'RE_EXTNAME_WINDOWS', require( '@stdlib/regexp/extname-windows' ) );

/**
* @name RE_FUNCTION_NAME
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/function-name}
*/
setReadOnly( regexp, 'RE_FUNCTION_NAME', require( '@stdlib/regexp/function-name' ) );

/**
* @name RE_REGEXP
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/regexp}
*/
setReadOnly( regexp, 'RE_REGEXP', require( '@stdlib/regexp/regexp' ) );

// EXPORTS //

module.exports = regexp;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// NAMESPACE //

/**
* Top-level namespace.
*
* @namespace regexp
*/
var regexp = {};

/**
* @name RE_DIRNAME
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/dirname}
*/
setReadOnly( regexp, 'RE_DIRNAME', require( '@stdlib/regexp/dirname' ) );

/**
* @name RE_DIRNAME_POSIX
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/dirname-posix}
*/
setReadOnly( regexp, 'RE_DIRNAME_POSIX', require( '@stdlib/regexp/dirname-posix' ) );

/**
* @name RE_DIRNAME_WINDOWS
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/dirname-windows}
*/
setReadOnly( regexp, 'RE_DIRNAME_WINDOWS', require( '@stdlib/regexp/dirname-windows' ) );

/**
* @name RE_EOL
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/eol}
*/
setReadOnly( regexp, 'RE_EOL', require( '@stdlib/regexp/eol' ) );

/**
* @name RE_EXTNAME
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/extname}
*/
setReadOnly( regexp, 'RE_EXTNAME', require( '@stdlib/regexp/extname' ) );

/**
* @name RE_EXTNAME_POSIX
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/extname-posix}
*/
setReadOnly( regexp, 'RE_EXTNAME_POSIX', require( '@stdlib/regexp/extname-posix' ) );

/**
* @name RE_EXTNAME_WINDOWS
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/extname-windows}
*/
setReadOnly( regexp, 'RE_EXTNAME_WINDOWS', require( '@stdlib/regexp/extname-windows' ) );

/**
* @name RE_FUNCTION_NAME
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/function-name}
*/
setReadOnly( regexp, 'RE_FUNCTION_NAME', require( '@stdlib/regexp/function-name' ) );

/**
* @name RE_REGEXP
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/regexp}
*/
setReadOnly( regexp, 'RE_REGEXP', require( '@stdlib/regexp/regexp' ) );

/**
* @name RE_UNC_PATH
* @memberof regexp
* @readonly
* @constant
* @type {RegExp}
* @see {@link module:@stdlib/regexp/unc-path}
*/
setReadOnly( regexp, 'RE_UNC_PATH', require( '@stdlib/regexp/unc-path' ) );

// EXPORTS //

module.exports = regexp;
<|endoftext|>


<commit_before>jQuery(document).ready(function() {
    var loginToken = window.localStorage.getItem("token");

    setTimeout(function() {
        keepAliveTwo(loginToken);
    }, 500);

    var listPlace = $("#jobList");

    displayAllUsersJobs();

    function displayAllUsersJobs() {
        // Get a list of users under the logged in job coach
        var jobList = JSON.parse(localStorage.getItem('jobList'));

        // Loop through list of users jobs and create buttons for each
        $.each(jobList, function (key, item) {
            console.log(item.routineTitle);
            $("
" + item.routineTitle +
                "
").appendTo(listPlace);

            listPlace.collapsibleset('refresh');
        });
        //TODO: Create more of a visual difference between list and add buttons
    $("
Add Job
").appendTo(listPlace);

        listPlace.collapsibleset('refresh');
    }
});

/*

Tools

 */<commit_msg>Fixed joblist not populating<commit_after>jQuery(document).ready(function() {
    var loginToken = window.localStorage.getItem("token");

    setTimeout(function() {
        keepAliveTwo(loginToken);
    }, 500);

    var listPlace = $("#jobList");

    displayAllUsersJobs();

    function displayAllUsersJobs() {
        // Get a list of users under the logged in job coach
        var jobList = JSON.parse(localStorage.getItem('jobList'));

        // Loop through list of users jobs and create buttons for each
        $.each(jobList, function (key, item) {
            console.log(item.routineTitle);
            $("
" + item.routineTitle +
                "
").appendTo(listPlace);

            listPlace.collapsibleset('refresh');
        });
        //TODO: Create more of a visual difference between list and add buttons
    $("
Add Job
").appendTo(listPlace);

        listPlace.collapsibleset('refresh');
    }
});

/*

Tools

 */<|endoftext|>