<commit_before>mf.include("navigator.js");
mf.include("player_tracker.js");
mf.include("chat_commands.js");

(function() {
    var current_following_interval_id;
    function follow(username, args, responder_func) {
        stop();
        var playerName = args[0];
        if (playerName !== undefined) {
            if (playerName === "me") {
                playerName = username;
            }
            args.shift();
        } else {
            playerName = username;
        }
        var distance = parseInt(args.shift());
        if (isNaN(distance)) {
            distance = 3;
        }
        var player = player_tracker.findUserEntityUnambiguously(playerName);
        if (player === undefined) {
            return;
        }
        responder_func("I'm now following " + player.username + ".");
        function go() {
            stop();
            var entity = mf.entity(player.entity_id);
            if (entity === undefined) {
                responder_func("can't see you anymore");
                return;
            }
            navigator.navigateTo(entity.position, {
                timeout_milliseconds: 3 * 1000,
                end_radius: distance,
                arrived_func: function() {
                    if (current_following_interval_id === undefined) {
                        // stopped
                        return;
                    }
                    stop();
                    go();
                },
            });
            // recalculate path every 5 seconds even if don't make it in that long
            current_following_interval_id = mf.setInterval(go, 5 * 1000);
        }
        go();
    };
    chat_commands.registerCommand("follow", follow, 0, 2);

    function stalk(username, args, responder_func) {
        // same as follow, but with a long distance
        args.push("12");
        follow(username, args, responder_func);
    }
    chat_commands.registerCommand("stalk", stalk, 1);

    function stop() {
        if (current_following_interval_id !== undefined) {
            mf.clearInterval(current_following_interval_id);
        }
    }
    chat_commands.registerCommand("stop", stop);
})();
<commit_msg>follower no longer crashes when the bot cannot see the speaker<commit_after>mf.include("navigator.js");
mf.include("player_tracker.js");
mf.include("chat_commands.js");

(function() {
    var current_following_interval_id;
    function follow(speaker, args, responder_func) {
        stop();
        var playerName = args[0];
        if (playerName !== undefined) {
            if (playerName === "me") {
                playerName = speaker;
            }
            args.shift();
        } else {
            playerName = speaker;
        }
        var distance = parseInt(args.shift());
        if (isNaN(distance)) {
            distance = 3;
        }
        var player = player_tracker.findUserEntityUnambiguously(playerName, speaker, responder_func);
        if (player === undefined) {
            return;
        }
        responder_func("I'm now following " + player.username + ".");
        function go() {
            stop();
            var entity = mf.entity(player.entity_id);
            if (entity === undefined) {
                responder_func("can't see you anymore");
                return;
            }
            navigator.navigateTo(entity.position, {
                timeout_milliseconds: 3 * 1000,
                end_radius: distance,
                arrived_func: function() {
                    if (current_following_interval_id === undefined) {
                        // stopped
                        return;
                    }
                    stop();
                    go();
                },
            });
            // recalculate path every 5 seconds even if don't make it in that long
            current_following_interval_id = mf.setInterval(go, 5 * 1000);
        }
        go();
    };
    chat_commands.registerCommand("follow", follow, 0, 2);

    function stalk(speaker, args, responder_func) {
        // same as follow, but with a long distance
        args.push("12");
        follow(speaker, args, responder_func);
    }
    chat_commands.registerCommand("stalk", stalk, 1);

    function stop() {
        if (current_following_interval_id !== undefined) {
            mf.clearInterval(current_following_interval_id);
        }
    }
    chat_commands.registerCommand("stop", stop);
})();
<|endoftext|>


<commit_before>javascript: (async () => {

    let api = new mw.Api();
    let titles = [];
    let result = '';

    await api.get({
        'action': 'query',
        'format': 'json',
        'prop': 'redirects',
        'titles': mw.config.get('wgPageName'),
        'rdlimit': 'max',
    }).then(async data => {
        let pageids = mw.config.get('wgArticleId') + '|' + $.map(data.query.pages[mw.config.get('wgArticleId')].redirects, redirect => redirect.pageid).join('|');
        pageids = pageids.replace(/\|$/, '');

        await api.get({
            'action': 'query',
            'format': 'json',
            'prop': 'info',
            'pageids': pageids,
            'inprop': 'varianttitles',
        }).then(data => {
            for (const pageid in data.query.pages) {
                const page = data.query.pages[pageid];
                for (const variant in page.varianttitles) {
                    const title = page.varianttitles[variant].replace(/^[^:]+?:/, '');
                    if (titles.indexOf(title) === -1) {
                        titles.push(title);
                        result += title + '
';
                    }
                }
            }
        });
    });

    let regex = '(' + $.map(titles, title => {
        if (title.match(/^[A-Z]/)) {
            title = '[' + title[0] + title[0].toLowerCase() + ']' + title.substr(1);
        }
        title = title.replace(/ /, '[ _]+');
        return title;
    }).join('|') + ')';

    let regexcilist = [];
    let checkdup = [];
    titles.forEach(title => {
        if (checkdup.indexOf(title.toLowerCase()) !== -1) {
            return;
        }
        checkdup.push(title.toLowerCase());
        regexcilist.push(title.replace(/ /, '[ _]+'));
    });

    let regexci = '(' + regexcilist.join('|') + ')';
    let templateprefix = '{{[\\s_]*(Template|T|样板|模板|樣板)?[\\s_]*:?[\\s_]*';

    result += '
Regex:
' + templateprefix + regex;
    result += '
Regex (case insensitive):
' + templateprefix + regexci;

    var win = window.open('');
    win.document.body.innerHTML = result;

}
)();
<commit_msg>Update Template-Alias.js<commit_after>javascript: (async () => {

    let api = new mw.Api();
    let titles = [];
    let result = '';

    await api.get({
        'action': 'query',
        'format': 'json',
        'prop': 'redirects',
        'titles': mw.config.get('wgPageName'),
        'rdlimit': 'max',
    }).then(async data => {
        let pageids = mw.config.get('wgArticleId') + '|' + $.map(data.query.pages[mw.config.get('wgArticleId')].redirects, redirect => redirect.pageid).join('|');
        pageids = pageids.replace(/\|$/, '');

        await api.get({
            'action': 'query',
            'format': 'json',
            'prop': 'info',
            'pageids': pageids,
            'inprop': 'varianttitles',
        }).then(data => {
            for (const pageid in data.query.pages) {
                const page = data.query.pages[pageid];
                for (const variant in page.varianttitles) {
                    const title = page.varianttitles[variant].replace(/^[^:]+?:/, '');
                    if (titles.indexOf(title) === -1) {
                        titles.push(title);
                        result += title + '
';
                    }
                }
            }
        });
    });

    let regex = '(' + $.map(titles, title => {
        if (title.match(/^[A-Z]/)) {
            title = '[' + title[0] + title[0].toLowerCase() + ']' + title.substr(1);
        }
        title = title.replace(/ /, '[ _]+');
        return title;
    }).join('|') + ')';

    let regexcilist = [];
    let checkdup = [];
    titles.forEach(title => {
        if (checkdup.indexOf(title.toLowerCase()) !== -1) {
            return;
        }
        checkdup.push(title.toLowerCase());
        regexcilist.push(title.replace(/ /, '[ _]+'));
    });

    let regexci = '(' + regexcilist.join('|') + ')';
    let compre = '{{[\\s_]*';
    let templateprefix = '(Template|T|样板|模板|樣板)?[\\s_]*:?[\\s_]*';

    result += '
Simple Regex:
' + regexci + '
';
    result += '
Simple Regex (case sensitive):
' + regex + '
';

    result += '
Regex:
' + compre + regexci + '
';
    result += '
Regex (case sensitive):
' + compre + regexci + '
';

    result += '
Regex with namespace:
' + compre + templateprefix + regexci + '
';
    result += '
Regex with namespace (case sensitive):
' + compre + templateprefix + regex + '
';

    var win = window.open('');
    win.document.body.innerHTML = result;

}
)();
<|endoftext|>


<commit_before>// #SPDX-License-Identifier: MIT
var configObject = require('../../frontend.config.json')
import Vue from 'vue';

// module for utility global state
export default {
  namespaced: true,
  state: {
    host: configObject["Frontend"].host,
    port: configObject["Frontend"].port,
    baseEndpointUrl: `http://${configObject["Frontend"].host}:${configObject["Frontend"].port}/api/unstable`,
    // baseEndpointUrl: 'http://localhost:5000/api/unstable',
    crudKey: sessionStorage.getItem("__augursessionstorage__crudkey") !== null ? sessionStorage.getItem("__augursessionstorage__crudkey") : '',
    availableEndpoints: [
      'http://localhost:5000/api/unstable',
      'http://augur.osshealth.io/api/unstable'
    ]
  },
  mutations: {
    setBaseEndpointUrl(state, newValue) {
      Vue.set(state, "baseEndpointUrl", newValue);
    },
    addAvailableEndpoint(state, newEndpoint) {
      Vue.set(state, "availableEndpoints", [...state.availableEndpoints, newEndpoint]);
    },
    setCrudKey(state, newKey) {
      Vue.set(state, "crudKey", newKey);
      sessionStorage.setItem("__augursessionstorage__crudkey", newKey);
    }
  },
  actions: {

  },
  getters: {
    getAvailableEndpoints(state) {
      return state.availableEndpoints;
    },
    getAvailableEndpointsForDropdown(state) {
      // maps available endpoints into array compatible with prop for AugDropdown.vue
      return state.availableEndpoints.map(endpoint => { return { text: endpoint, value: endpoint } });
    },
    getCurrentEndpointUrlForDropdown(state) {
      // maps current endpoint into object compatible with prop for AugDropDown.vue
      return { text: state.baseEndpointUrl, value: state.baseEndpointUrl };
    },
    getBaseEndpointUrl(state) {
      return state.baseEndpointUrl;
    },
    getCrudKey(state) {
      return state.crudKey;
    }
  }
}
<commit_msg>fixing so we use the same frontend.config.json for augurface<commit_after>// #SPDX-License-Identifier: MIT
var configObject = require('../../../frontend/frontend.config.json')
import Vue from 'vue';

// module for utility global state
export default {
  namespaced: true,
  state: {
    host: configObject["Frontend"].host,
    port: configObject["Frontend"].port,
    baseEndpointUrl: `http://${configObject["Frontend"].host}:${configObject["Frontend"].port}/api/unstable`,
    // baseEndpointUrl: 'http://localhost:5000/api/unstable',
    crudKey: sessionStorage.getItem("__augursessionstorage__crudkey") !== null ? sessionStorage.getItem("__augursessionstorage__crudkey") : '',
    availableEndpoints: [
      'http://localhost:5000/api/unstable',
      'http://augur.osshealth.io/api/unstable'
    ]
  },
  mutations: {
    setBaseEndpointUrl(state, newValue) {
      Vue.set(state, "baseEndpointUrl", newValue);
    },
    addAvailableEndpoint(state, newEndpoint) {
      Vue.set(state, "availableEndpoints", [...state.availableEndpoints, newEndpoint]);
    },
    setCrudKey(state, newKey) {
      Vue.set(state, "crudKey", newKey);
      sessionStorage.setItem("__augursessionstorage__crudkey", newKey);
    }
  },
  actions: {

  },
  getters: {
    getAvailableEndpoints(state) {
      return state.availableEndpoints;
    },
    getAvailableEndpointsForDropdown(state) {
      // maps available endpoints into array compatible with prop for AugDropdown.vue
      return state.availableEndpoints.map(endpoint => { return { text: endpoint, value: endpoint } });
    },
    getCurrentEndpointUrlForDropdown(state) {
      // maps current endpoint into object compatible with prop for AugDropDown.vue
      return { text: state.baseEndpointUrl, value: state.baseEndpointUrl };
    },
    getBaseEndpointUrl(state) {
      return state.baseEndpointUrl;
    },
    getCrudKey(state) {
      return state.crudKey;
    }
  }
}
<|endoftext|>


<commit_before>const { expect } = require('chai');
const GmailUser = require('../../../persistence').models.GmailUser;

describe('GmailUser models', () => {
  describe('displayName method', () => {

    it('returns correctly formatted name', () => {
      const testUser = new GmailUser({'id': 'id1', 'email': 'test@example.com', 'firstName': 'fn', 'lastName': 'ln'});

      expect(testUser.getDisplayName()).to.equal('fn ln');
    });
  });
});
<commit_msg>fixing lint error in test<commit_after>const { expect } = require('chai');
const GmailUser = require('../../../persistence').models.GmailUser;

describe('GmailUser models', () => {
  describe('displayName method', () => {
    it('returns correctly formatted name', () => {
      const testUser = new GmailUser({'id': 'id1', 'email': 'test@example.com', 'firstName': 'fn', 'lastName': 'ln'});

      expect(testUser.getDisplayName()).to.equal('fn ln');
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015
 *
 * @author John Molakvoæ <skjnldsv@protonmail.com>
 * @author Vincent Petry <vincent@nextcloud.com>
 *
 * @license AGPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/* eslint-disable */
(function(OC) {

	function filterFunction(model, term) {
		return model.get('name').substr(0, term.length).toLowerCase() === term.toLowerCase()
	}

	/**
	 * @class OCA.SystemTags.SystemTagsCollection
	 * @classdesc
	 *
	 * Collection of tags assigned to a file
	 *
	 */
	var SystemTagsCollection = OC.Backbone.Collection.extend(
		/** @lends OC.SystemTags.SystemTagsCollection.prototype */ {

			sync: OC.Backbone.davSync,

			model: OC.SystemTags.SystemTagModel,

			url: function() {
				return OC.linkToRemote('dav') + '/systemtags/'
			},

			filterByName: function(name) {
				return this.filter(function(model) {
					return filterFunction(model, name)
				})
			},

			reset: function() {
				this.fetched = false
				return OC.Backbone.Collection.prototype.reset.apply(this, arguments)
			},

			/**
		 * Lazy fetch.
		 * Only fetches once, subsequent calls will directly call the success handler.
		 *
		 * @param {any} options -
		 * @param [options.force] true to force fetch even if cached entries exist
		 *
		 * @see Backbone.Collection#fetch
		 */
			fetch: function(options) {
				var self = this
				options = options || {}
				if (this.fetched || options.force) {
				// directly call handler
					if (options.success) {
						options.success(this, null, options)
					}
					// trigger sync event
					this.trigger('sync', this, null, options)
					return Promise.resolve()
				}

				var success = options.success
				options = _.extend({}, options)
				options.success = function() {
					self.fetched = true
					if (success) {
						return success.apply(this, arguments)
					}
				}

				return OC.Backbone.Collection.prototype.fetch.call(this, options)
			}
		})

	OC.SystemTags = OC.SystemTags || {}
	OC.SystemTags.SystemTagsCollection = SystemTagsCollection

	/**
	 * @type OC.SystemTags.SystemTagsCollection
	 */
	OC.SystemTags.collection = new OC.SystemTags.SystemTagsCollection()
})(OC)
<commit_msg>Improve loading for tags<commit_after>/**
 * Copyright (c) 2015
 *
 * @author John Molakvoæ <skjnldsv@protonmail.com>
 * @author Vincent Petry <vincent@nextcloud.com>
 *
 * @license AGPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/* eslint-disable */
(function(OC) {

	function filterFunction(model, term) {
		return model.get('name').substr(0, term.length).toLowerCase() === term.toLowerCase()
	}

	/**
	 * @class OCA.SystemTags.SystemTagsCollection
	 * @classdesc
	 *
	 * Collection of tags assigned to a file
	 *
	 */
	var SystemTagsCollection = OC.Backbone.Collection.extend(
		/** @lends OC.SystemTags.SystemTagsCollection.prototype */ {

			sync: OC.Backbone.davSync,

			model: OC.SystemTags.SystemTagModel,

			url: function() {
				return OC.linkToRemote('dav') + '/systemtags/'
			},

			filterByName: function(name) {
				return this.filter(function(model) {
					return filterFunction(model, name)
				})
			},

			reset: function() {
				this.fetched = false
				return OC.Backbone.Collection.prototype.reset.apply(this, arguments)
			},

			/**
		 * Lazy fetch.
		 * Only fetches once, subsequent calls will directly call the success handler.
		 *
		 * @param {any} options -
		 * @param [options.force] true to force fetch even if cached entries exist
		 *
		 * @see Backbone.Collection#fetch
		 */
			fetch: function(options) {
				var self = this
				options = options || {}
				if (this.fetched || this.working || options.force) {
				// directly call handler
					if (options.success) {
						options.success(this, null, options)
					}
					// trigger sync event
					this.trigger('sync', this, null, options)
					return Promise.resolve()
				}

				this.working = true

				var success = options.success
				options = _.extend({}, options)
				options.success = function() {
					self.fetched = true
					self.working = false
					if (success) {
						return success.apply(this, arguments)
					}
				}

				return OC.Backbone.Collection.prototype.fetch.call(this, options)
			}
		})

	OC.SystemTags = OC.SystemTags || {}
	OC.SystemTags.SystemTagsCollection = SystemTagsCollection

	/**
	 * @type OC.SystemTags.SystemTagsCollection
	 */
	OC.SystemTags.collection = new OC.SystemTags.SystemTagsCollection()
})(OC)
<|endoftext|>


<commit_before>/**
 * Manage a display
 *
 * @param {Display} display
 * @param {Application} display
 */
function DisplayManager(display, application){
  this.display = display;
  this.application = application;
  this.services = new Services();
};

/**
 * Draw the display manager
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.init = function(canvas){
  var self = this;
  var name = $('
').css('text-align', 'left');
  name.append($('').attr('for', 'display-name').html('Display Name: '));
  name.append($('<input>').attr('id', 'display-name').val(this.display.getName()).bind('change', function(){
    self.display.setName($(this).val());
  }));
  canvas.append(name);
  var button = $('<button>').html('Select All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item', div).not('.selected').each(function(i){
      var element = $(this).data('element');
      element.weight = startWeight +i;
      self.display.addElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var button = $('<button>').html('Deselect All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item.selected', div).each(function(i){
      var element = $(this).data('element');
      self.display.removeElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var div = $('
').addClass('yui-g');
  var left = $('
').addClass('yui-u first').attr('id', 'chooser');
  var right = $('
').addClass('yui-u').attr('id', 'chosen');
  div.append(left);
  div.append(right);
  canvas.append(div);
  this.drawChooser();
  this.drawChosen();

  canvas.on('click', '.shrink_button', function() {
    $(this).next().toggle('slow');
    return false;
  });
};

/**
 * Draw the chooser
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.drawChooser = function(){
  var self = this;
  var div = $('
');
  div.append($('
').html('Available Elements'));
  var maximumDisplay = this.services.getMaximumDisplay();

  div.append(this.shrinkButton('Applicant', this.applicantBox(maximumDisplay)));
  div.append(self.shrinkButton("Tags", self.tagBox(maximumDisplay)));

  $.each(this.application.listApplicationPages(), function(){
     div.append(self.shrinkButton(this.title, self.pageBox(this, maximumDisplay)));
  });

  $('#chooser').empty().append(div);
};

/**
 * Draw the displayed
 *
 */
DisplayManager.prototype.drawChosen = function(){
  var self = this;
  var div = $('
');
  $.each(this.display.listElements(),function(){
    var displayElement = this;
    var ol = $('
');
    var sourceName = displayElement.type == 'applicant'?'Applicant':self.display.getElementPageTitle(displayElement) + ' Page';
    ol.append($('
').html('Source: ' + sourceName).addClass('item'));
    ol.append($('
').html('Original Name: ' + $('#'+ this.type + this.name).data('element').title).addClass('item'));
    var elementDiv = self.shrinkButton(displayElement.title, ol);
    elementDiv.addClass('element');
    elementDiv.data('element', displayElement);
    $('.shrink_button', elementDiv).prepend($('').addClass('left').addClass('handle ui-icon ui-icon-arrowthick-2-n-s'));

    $('.shrink_button p', elementDiv).append($('').addClass('right ui-icon ui-icon-pencil'));
     $('.shrink_button p', elementDiv).editable(function(value, settings) {
        displayElement.title = value;
     },
     {
       displayElement: displayElement,
       data: displayElement.title,
       callback: function(value, setting){
         self.drawChosen();
       }
<<<<<<< HEAD
    });
    var removeSpan = $('').addClass('right').addClass('ui-icon ui-icon-circle-minus');
    removeSpan.on('click', function(){
      self.display.removeElement($(this).closest('.shrinkable').data('element'));
      self.drawChosen();
      self.refreshDisplayedChooserElements();
    });
=======
    });
    var removeSpan = $('').addClass('right').addClass('ui-icon ui-icon-circle-minus');
    removeSpan.on('click', function(){
      self.display.removeElement($(this).closest('.shrinkable').data('element'));
      self.drawChosen();
      self.refreshDisplayedChooserElements();
    });
>>>>>>> 9d814696081f9326594ca5b2c1223a028934e541
    $('.shrink_button', elementDiv).append(removeSpan);
    div.append(elementDiv);
  });
  $('div.element',div).sort(function(a,b){
    return $(a).data('element').weight > $(b).data('element').weight ? 1 : -1;
  }).appendTo(div);
  div.sortable({
    handle: '.handle'
  });
  div.bind("sortupdate", function(e, ui) {
    $('div.element',$(ui.item).parent()).each(function(i){
      var element = $(this).data('element');
      element.weight = i;
    });
  });
  var chosen = $('
');
  chosen.append($('
').html('Selected Items for ' + this.display.getName() + ' Display'));
  chosen.append(div);
  $('#chosen').empty().append(chosen);
};

/**
 * Draw the applicant box
 *
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.applicantBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var arr = [
    {type:'applicant', title: 'First Name', name: 'firstName'},
    {type:'applicant', title: 'Last Name', name: 'lastName'},
    {type:'applicant', title: 'Email', name: 'email'},
    {type:'applicant', title: 'Last Update', name: 'updatedAt'},
    {type:'applicant', title: 'Progress', name: 'percentComplete'},
    {type:'applicant', title: 'Last Login', name: 'lastLogin'},
    {type:'applicant', title: 'Account Created', name: 'createdAt'},
    {type:'applicant', title: 'Locked', name: 'isLocked'},
    {type:'applicant', title: 'Paid', name: 'hasPaid'},
    {type:'applicant', title: 'Attachments', name: 'attachments'},

    // these should really be a separate type (eg. tag or decision).
    // the name part here corresponds to keys in the FullApplication.php display.
    {type:'applicant', title: 'Declined', name: 'status_declined'},
    {type:'applicant', title: 'Admitted', name: 'status_admitted'},
    {type:'applicant', title: 'Denied', name: 'status_denied'},
    {type:'applicant', title: 'Accepted', name: 'status_accepted'},
    {type:'applicant', title: 'Nominate Admit', name: 'status_nominate_admit'},
    {type:'applicant', title: 'Nominate Deny', name: 'status_nominate_deny'}
  ];
  var hasItems = false;
  $.each(arr,function(){
	  if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element',this);
      li.attr('id', this.type + this.name);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
            }
  });
  if(hasItems){
    return $('
').append(list);
  } else {
    return false;
  }
};

/**
 * Draw the shrink button
 *
 * @param String title
 * @param {jquery} content
 */
DisplayManager.prototype.shrinkButton = function(title, content){
  var div = $('
').addClass('shrinkable');
  if(content === false ){
    return div;
  }
  div.append($('
').addClass('shrink_button').addClass('item').append($('
').html(title)));
  div.append($('
').addClass('shrink_list').append(content));

  return div;
};

/**
 * Draw the page box
 *
 * @param {} applicationPage
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.pageBox = function(applicationPage, maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var pageClass = this.application.getPageClassById(applicationPage.page.id);
  var pageDisplayElements = pageClass.listDisplayElements();
  if(pageDisplayElements.length == 0){
    return false;
  }
  var hasItems = false;
  $.each(pageDisplayElements, function(){
    if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
      li.attr('id', this.type + this.name);
<<<<<<< HEAD
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
    }
  });
  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

DisplayManager.prototype.tagBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var hasItems = false;
  try{
      $.each(maximumDisplay.listTags(), function(){
	  this.type = 'applicant';
	  this.name = this.id;
	  this.weight = 1;
	  hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
=======
>>>>>>> 9d814696081f9326594ca5b2c1223a028934e541
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);

      });
  }catch(ex){
      console.log("unable to create tag list: "+ex);
  }

  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

/**
 * Save the display
 *
 * @param url string
 * @param display Display
 */
DisplayManager.save = function(url, display){
  $.ajax({
    url: url + '/saveDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * REmvoe the display
 *
 * @param {} applicationPage
 */
DisplayManager.remove = function(url, display){
  $.ajax({
    url: url + '/deleteDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * Get the weight for the next piece
 *
 * @return integer
 */
DisplayManager.prototype.nextWeight = function(){
  return $('#chosen li').length+1;
};

/**
 * Refresh the list of chooser elements to see which ones should be displayed
 *
 * @param {}
 * @return {jQuery}
 */
DisplayManager.prototype.refreshDisplayedChooserElements = function(){
  var self = this;
  $('ul.block_list li.item', '#chooser').each(function(i){
      var element = $(this).data('element');
      if(self.display.displayElement(element)){
        $(this).addClass('selected');
      } else {
        $(this).removeClass('selected');
      }
    });
<<<<<<>>>>>> 9d814696081f9326594ca5b2c1223a028934e541
<commit_msg>Fix bad merge on DisplayManager.class.js<commit_after>/**
 * Manage a display
 *
 * @param {Display} display
 * @param {Application} display
 */
function DisplayManager(display, application){
  this.display = display;
  this.application = application;
  this.services = new Services();
};

/**
 * Draw the display manager
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.init = function(canvas){
  var self = this;
  var name = $('
').css('text-align', 'left');
  name.append($('').attr('for', 'display-name').html('Display Name: '));
  name.append($('<input>').attr('id', 'display-name').val(this.display.getName()).bind('change', function(){
    self.display.setName($(this).val());
  }));
  canvas.append(name);
  var button = $('<button>').html('Select All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item', div).not('.selected').each(function(i){
      var element = $(this).data('element');
      element.weight = startWeight +i;
      self.display.addElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var button = $('<button>').html('Deselect All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item.selected', div).each(function(i){
      var element = $(this).data('element');
      self.display.removeElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var div = $('
').addClass('yui-g');
  var left = $('
').addClass('yui-u first').attr('id', 'chooser');
  var right = $('
').addClass('yui-u').attr('id', 'chosen');
  div.append(left);
  div.append(right);
  canvas.append(div);
  this.drawChooser();
  this.drawChosen();

  canvas.on('click', '.shrink_button', function() {
    $(this).next().toggle('slow');
    return false;
  });
};

/**
 * Draw the chooser
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.drawChooser = function(){
  var self = this;
  var div = $('
');
  div.append($('
').html('Available Elements'));
  var maximumDisplay = this.services.getMaximumDisplay();

  div.append(this.shrinkButton('Applicant', this.applicantBox(maximumDisplay)));
  div.append(self.shrinkButton("Tags", self.tagBox(maximumDisplay)));

  $.each(this.application.listApplicationPages(), function(){
     div.append(self.shrinkButton(this.title, self.pageBox(this, maximumDisplay)));
  });

  $('#chooser').empty().append(div);
};

/**
 * Draw the displayed
 *
 */
DisplayManager.prototype.drawChosen = function(){
  var self = this;
  var div = $('
');
  $.each(this.display.listElements(),function(){
    var displayElement = this;
    var ol = $('
');
    var sourceName = displayElement.type == 'applicant'?'Applicant':self.display.getElementPageTitle(displayElement) + ' Page';
    ol.append($('
').html('Source: ' + sourceName).addClass('item'));
    ol.append($('
').html('Original Name: ' + $('#'+ this.type + this.name).data('element').title).addClass('item'));
    var elementDiv = self.shrinkButton(displayElement.title, ol);
    elementDiv.addClass('element');
    elementDiv.data('element', displayElement);
    $('.shrink_button', elementDiv).prepend($('').addClass('left').addClass('handle ui-icon ui-icon-arrowthick-2-n-s'));

    $('.shrink_button p', elementDiv).append($('').addClass('right ui-icon ui-icon-pencil'));
     $('.shrink_button p', elementDiv).editable(function(value, settings) {
        displayElement.title = value;
     },
     {
       displayElement: displayElement,
       data: displayElement.title,
       callback: function(value, setting){
         self.drawChosen();
       }
    });
    var removeSpan = $('').addClass('right').addClass('ui-icon ui-icon-circle-minus');
    removeSpan.on('click', function(){
      self.display.removeElement($(this).closest('.shrinkable').data('element'));
      self.drawChosen();
      self.refreshDisplayedChooserElements();
    });
    $('.shrink_button', elementDiv).append(removeSpan);
    div.append(elementDiv);
  });
  $('div.element',div).sort(function(a,b){
    return $(a).data('element').weight > $(b).data('element').weight ? 1 : -1;
  }).appendTo(div);
  div.sortable({
    handle: '.handle'
  });
  div.bind("sortupdate", function(e, ui) {
    $('div.element',$(ui.item).parent()).each(function(i){
      var element = $(this).data('element');
      element.weight = i;
    });
  });
  var chosen = $('
');
  chosen.append($('
').html('Selected Items for ' + this.display.getName() + ' Display'));
  chosen.append(div);
  $('#chosen').empty().append(chosen);
};

/**
 * Draw the applicant box
 *
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.applicantBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var arr = [
    {type:'applicant', title: 'First Name', name: 'firstName'},
    {type:'applicant', title: 'Last Name', name: 'lastName'},
    {type:'applicant', title: 'Email', name: 'email'},
    {type:'applicant', title: 'Last Update', name: 'updatedAt'},
    {type:'applicant', title: 'Progress', name: 'percentComplete'},
    {type:'applicant', title: 'Last Login', name: 'lastLogin'},
    {type:'applicant', title: 'Account Created', name: 'createdAt'},
    {type:'applicant', title: 'Locked', name: 'isLocked'},
    {type:'applicant', title: 'Paid', name: 'hasPaid'},
    {type:'applicant', title: 'Attachments', name: 'attachments'},

    // these should really be a separate type (eg. tag or decision).
    // the name part here corresponds to keys in the FullApplication.php display.
    {type:'applicant', title: 'Declined', name: 'status_declined'},
    {type:'applicant', title: 'Admitted', name: 'status_admitted'},
    {type:'applicant', title: 'Denied', name: 'status_denied'},
    {type:'applicant', title: 'Accepted', name: 'status_accepted'},
    {type:'applicant', title: 'Nominate Admit', name: 'status_nominate_admit'},
    {type:'applicant', title: 'Nominate Deny', name: 'status_nominate_deny'}
  ];
  var hasItems = false;
  $.each(arr,function(){
	  if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element',this);
      li.attr('id', this.type + this.name);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
            }
  });
  if(hasItems){
    return $('
').append(list);
  } else {
    return false;
  }
};

/**
 * Draw the shrink button
 *
 * @param String title
 * @param {jquery} content
 */
DisplayManager.prototype.shrinkButton = function(title, content){
  var div = $('
').addClass('shrinkable');
  if(content === false ){
    return div;
  }
  div.append($('
').addClass('shrink_button').addClass('item').append($('
').html(title)));
  div.append($('
').addClass('shrink_list').append(content));

  return div;
};

/**
 * Draw the page box
 *
 * @param {} applicationPage
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.pageBox = function(applicationPage, maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var pageClass = this.application.getPageClassById(applicationPage.page.id);
  var pageDisplayElements = pageClass.listDisplayElements();
  if(pageDisplayElements.length == 0){
    return false;
  }
  var hasItems = false;
  $.each(pageDisplayElements, function(){
    if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
      li.attr('id', this.type + this.name);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
    }
  });
  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

DisplayManager.prototype.tagBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var hasItems = false;
  try{
      $.each(maximumDisplay.listTags(), function(){
	  this.type = 'applicant';
	  this.name = this.id;
	  this.weight = 1;
	  hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);

      });
  }catch(ex){
      console.log("unable to create tag list: "+ex);
  }

  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

/**
 * Save the display
 *
 * @param url string
 * @param display Display
 */
DisplayManager.save = function(url, display){
  $.ajax({
    url: url + '/saveDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * REmvoe the display
 *
 * @param {} applicationPage
 */
DisplayManager.remove = function(url, display){
  $.ajax({
    url: url + '/deleteDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * Get the weight for the next piece
 *
 * @return integer
 */
DisplayManager.prototype.nextWeight = function(){
  return $('#chosen li').length+1;
};

/**
 * Refresh the list of chooser elements to see which ones should be displayed
 *
 * @param {}
 * @return {jQuery}
 */
DisplayManager.prototype.refreshDisplayedChooserElements = function(){
  var self = this;
  $('ul.block_list li.item', '#chooser').each(function(i){
      var element = $(this).data('element');
      if(self.display.displayElement(element)){
        $(this).addClass('selected');
      } else {
        $(this).removeClass('selected');
      }
    });
};
<|endoftext|>


<commit_before>/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global require, exports, console, process, module, L, angular, _, jQuery */

angular.module('aditl')
	.directive('pages2page', function() {
		return {
			restrict:'E',
			scope:{ page:'=' },
			replace:true,
			templateUrl:'/apps/aditl/templates/pages2page.html',
			controller:function($scope, $element, utils) {
				var error_count = 0, u = utils;
				// literally nothing necessary here.
				// var original_thumb;
				var sa = function(fn) { return u.safeApply($scope, fn); };
				$scope.show = true;

				var getAppropriate = function(model) {
					var url = model.id;
					if ((/.jpeg$/gi).test(url) || (/.jpg$/gi).test(url) || (/.png$/gi).test(url) || (/.gif$/gi).test(url)) { return model.id; }
					if ((/youtube.com/gi).test(url)) {
						try {
							var vidid = (/v=([^&]*)/gi).exec(url)[1];
							return ['http://img.youtube.com/vi/',vidid,'/0.jpg'].join('');
						} catch(e) { }
					}
					return model.peek('thumbnail');
				};
				$scope.thumb = getAppropriate($scope.page);
				$element.find('img.thumbnail').on('error', function() {
					console.error('IMAGE ERROR  -- ', error_count, $scope.page.id);
					error_count++;
					if (error_count > 0) {  sa(function() { $scope.show = false; }); }
					sa(function() {
						$scope.thumb = getAppropriate($scope.page);
					});
				});
			}
		};
	}).controller('pages2', function($scope, $injector, client, utils, entities) {
		$scope.$watch('user + box', function() {
			var u = utils;
			var sa = function(fn) { return u.safeApply($scope, fn); };
			$scope.pages = [];
			var appenddebug = function(model) {
				var url = model.peek('thumbnail');
				var row = ['
','',model.id.slice(0,100),'	','',url && url.length,'	',url && url.slice(0,300),'
'].join('');
				console.log('appending row ', row);
				jQuery('#debugtable').append(row);
			};
			var prepend = function(model){
				// var parent = jQuery('.pages');
				// var datauri = model.peek('thumbnail');
				sa(function() {
					console.log('model >> ', model);
					if ($scope.pages.indexOf(model) < 0) {
						console.log('adding >> ');
						$scope.pages.splice(0, 0, model); // push(model); //  = [model].concat($scope.pages); // .push(model);
					} else {
						// console.log('moving it up! ');
						var oldindx = $scope.pages.indexOf(model);
						$scope.pages.splice(oldindx, 1);
						$scope.pages.splice(0, 0, model);
						console.log('pages 0 is now ', $scope.pages[0].id);
					}
				});
				// appenddebug(model);
			};
			client.store.getBox($scope.box).then(function(_box) {
				var update = function(id) {
					_box.getObj(id).then(function(model) {
						console.log(" model >> ", model.id);
						if (model && model.peek('type') == 'activity' && model.peek('activity') == 'browse') {
							console.log(" GOT A BROWSE >> ", model.peek('what').id);
							var page = model.peek('what');
							if (page) {
								console.log('New Page prepending >> ', page.id, page.peek('thumbnail'));
								prepend(page);
							} else {
								console.error("NO WHAT >> ", id);
							}
						} else if (model && model.peek('type') == 'web-page') {
							console.log('prepending because its a web page');
							prepend(model);
						} else {
							console.log('uncaching obj ', model.id);
							if (model.peek('type') !== 'web-page') {
								_box.uncacheObj(model);
							}
						}
					});
				};
				_box.on('obj-add', function(id) { update(id); });

				entities.activities.getAll(_box, { activity: 'browse' }).then(function(actions) {
					console.log('actions >> ', actions.length);
					actions.sort(function(x,y) { return y.peek('tstart') - x.peek('tstart'); });
					actions.map(function(action) {
						var page = action.peek('what');
						if (page) {  prepend(page);	}
					});
				});
			}).fail(function(bail) { console.error(bail); });
		});
		window.scope = $scope;
		// $scope.addImg = function(thumbobj) {
		// 	var data = $scope.decodeThumb(thumbobj);
		// 	jQuery(".pages").append("");
		// };
	});<commit_msg>pages<commit_after>/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global require, exports, console, process, module, L, angular, _, jQuery */

angular.module('aditl')
	.directive('pages2page', function() {
		return {
			restrict:'E',
			scope:{ page:'=' },
			replace:true,
			templateUrl:'/apps/aditl/templates/pages2page.html',
			controller:function($scope, $element, utils) {
				var error_count = 0, u = utils;
				// literally nothing necessary here.
				// var original_thumb;
				var sa = function(fn) { return u.safeApply($scope, fn); };
				$scope.show = true;

				var getAppropriate = function(model) {
					var url = model.id;
					if ((/.jpeg$/gi).test(url) || (/.jpg$/gi).test(url) || (/.png$/gi).test(url) || (/.gif$/gi).test(url)) { return model.id; }
					if ((/youtube.com/gi).test(url)) {
						try {
							var vidid = (/v=([^&]*)/gi).exec(url)[1];
							return ['http://img.youtube.com/vi/',vidid,'/0.jpg'].join('');
						} catch(e) { }
					}
					return model.peek('thumbnail');
				};
				$scope.thumb = getAppropriate($scope.page);
				$element.find('img.thumbnail').on('error', function() {
					console.error('IMAGE ERROR  -- ', error_count, $scope.page.id);
					error_count++;
					if (error_count > 0) {  sa(function() { $scope.show = false; }); }
					sa(function() {
						$scope.thumb = getAppropriate($scope.page);
					});
				});
			}
		};
	}).controller('pages2', function($scope, $injector, client, utils, entities) {
		$scope.$watch('user + box', function() {
			var u = utils;
			var sa = function(fn) { return u.safeApply($scope, fn); };
			$scope.pages = [];
			var appenddebug = function(model) {
				var url = model.peek('thumbnail');
				var row = ['
','',model.id.slice(0,100),'	','',url && url.length,'	',url && url.slice(0,300),'
'].join('');
				console.log('appending row ', row);
				jQuery('#debugtable').append(row);
			};
			var prepend = function(model){
				// var parent = jQuery('.pages');
				// var datauri = model.peek('thumbnail');
				sa(function() {
					console.log('model >> ', model);
					if ($scope.pages.indexOf(model) < 0) {
						console.log('adding >> ');
						$scope.pages.splice(0, 0, model); // push(model); //  = [model].concat($scope.pages); // .push(model);
					} else {
						// console.log('moving it up! ');
						var oldindx = $scope.pages.indexOf(model);
						$scope.pages.splice(oldindx, 1);
						$scope.pages.splice(0, 0, model);
						console.log('pages 0 is now ', $scope.pages[0].id);
					}
				});
				// appenddebug(model);
			};
			client.store.getBox($scope.box).then(function(_box) {
				var update = function(id) {
					_box.getObj(id).then(function(model) {
						console.log(" model >> ", model.id);
						if (model && model.peek('type') == 'activity' && model.peek('activity') == 'browse') {
							// console.log(" GOT A BROWSE >> ", model.peek('what').id);
							var page = model.peek('what');
							if (page) {
								// console.log('New Page prepending >> ', page.id, page.peek('thumbnail'));
								prepend(page);
							} else {
								// console.error("NO WHAT >> ", id);
							}
						} else if (model && model.peek('type') == 'web-page') {
							// console.log('prepending because its a web page');
							prepend(model);
						} else {
							console.log('uncaching obj ', model.id);
							if (model.peek('type') !== 'web-page') {
								_box.uncacheObj(model);
							}
						}
					});
				};
				_box.on('obj-add', function(id) { update(id); });

				entities.activities.getAll(_box, { activity: 'browse' }).then(function(actions) {
					console.log('actions >> ', actions.length);
					actions.sort(function(x,y) { return x.peek('tstart').valueOf() - y.peek('tstart').valueOf(); });
					actions.map(function(action) {
						var page = action.peek('what');
						if (page) {  prepend(page);	}
					});
				});
			}).fail(function(bail) { console.error(bail); });
		});
		window.scope = $scope;
		// $scope.addImg = function(thumbobj) {
		// 	var data = $scope.decodeThumb(thumbobj);
		// 	jQuery(".pages").append("");
		// };
	});<|endoftext|>


<commit_before>// balance.js
App.Views.Charts.Balance = Backbone.View.extend({

	events: {
	},
	chart: false,
	aTransactions: [],
	_data: {},
	dataReady: false,
	dataFetched: false,

	initialize: function() {
		if (!this.model || !this.id)
			console.error('views/charts/balance.js | model(wallet) and id of canvas should be provided for this view');
	},
	fetchTransactions: function() {
		if (this.aTransactions.length)
		{
			this.trigger('transactionsReady');
			return this.aTransactions;
		}

		var transactions = new App.Collections.Transactions();
		this.aTransactions = [];
        transactions.setWalletId(this.model.id);

        var that = this;
        transactions.once('sync',function(){
        	console.log('Synced current month');
        	transactions.forEach(function(t){
        		that.aTransactions.push(t);
        	});

        	transactions.once('sync',function(){
        	console.log('Synced prev month');
	        	transactions.forEach(function(t){
	        		that.aTransactions.push(t);
	        	});

	        	that.trigger('transactionsReady');
        	});
        	transactions.gotoPrev();
        });

        transactions.fetch();
	},
	fetchData: function() {
		if (this.dataFetched)
			return false;
		if (this.dataReady)
		{
        	that.trigger('dataReady');
			return this._data;
		}

		this.dataFetched = true;

		var that = this;
		this.once('transactionsReady',function(){
			_.each(this.aTransactions, function(item){
				console.log(item.get('amount'));
			});
			//// first step. Filter expenses
			var a = _.filter(this.aTransactions, function(t){ return t.get('amount') < 0; });

			//// second step. For each day
			var days = {};
			var curTime = new Date();
			var curDay = curTime.getDate();
			var curMonth = curTime.getMonth();
			curTime = curTime.getTime();
			for (var i = 0; i <= 60; i++)
			{
				var d = new Date(curTime - 24*60*60*1000*i);
				var day = d.getDate();
				var month = d.getMonth();
				var dayTotal = 0;
				_.each(a, function(t){
					var tDate = new Date(t.get('datetime')*1000);
					if (tDate.getDate() == day && tDate.getMonth() == month)
						dayTotal += Math.abs(t.get('amount'));
				});
				days[day+'-'+month] = {day: day, month: month, total: dayTotal};
			}
			/// third step. Find first day from a set at which transaction occurs.
			var firstDay = 0;
			var firstMonth = 0;
			_.each(days, function(day){
				if (day.total > 0)
				{
					if (firstDay == 0 && firstMonth == 0)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}

					if (day.month < firstMonth || day.day < firstDay)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}
				}
			});

			/// forth step. Fill days without transactions by values from next days started from firstDay
			if (firstDay)
			_.each(days, function(d){
				if (firstMonth < d.month || (firstDay < d.day && firstMonth == d.month))
				{
					if (d.total == 0 && typeof(d.filledMissed) === 'undefined')
					{
						var foundTotal = 0;
						var foundEmpty = [];
						var iDay = d.day + 1;
						var iMonth = d.month;
						foundEmpty.push(d.day+'-'+d.month);

						while ((foundTotal == 0) && ((curMonth == iMonth && curDay >= iDay) || (curMonth > iMonth)) )
						if (typeof(days[iDay+'-'+iMonth]) !== 'undefined')
						{

							if (days[iDay+'-'+iMonth].total == 0)
							{
								/// another empty day
								foundEmpty.push(iDay+'-'+iMonth);
							} else {
								/// day with total set
								foundEmpty.push(iDay+'-'+iMonth);
								foundTotal = days[iDay+'-'+iMonth].total;
							}

							iDay++;

						} else {
							/// next month
							iMonth++;
							iDay = 1;
						}

						//// fill missed sum
						foundEmpty = _.uniq(foundEmpty);
						if (foundTotal > 0 && foundEmpty.length > 0)
						{
							var total = foundTotal / foundEmpty.length;
							_.each(foundEmpty, function(found){
								days[found].total = total;
								days[found].filledMissed = true;
							});
						}
					}
				}
			});

			/// fifth step. Filter days with total set and truncate to 30 max
			//days = _.filter(days, function(d){ return d.total > 0; });
			//days = _.last(days, 30);

			/// generate labels
			//days.reverse();
			var values = [];
			_.each(days, function(day, key){
				values.push({label: day.day+'/'+(day.month+1), value: day.total});
			});
			values.reverse();
			values = _.last(values, 31);

			/// remove empty from the start
			var alreadyStarted = false;
			values = _.filter(values, function(item){ if (item.value > 0 || alreadyStarted) { alreadyStarted = true; return true; } else return false; });

			/// group by
			if (values.length > 10)
			{
				var rvalues = [];
				var i = 0;
				if (values.length > 20)
				{
					/// by 3
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;
						if (typeof(values[i+2]) !== 'undefined') rvalue+=values[i+2].value;

						if (typeof(values[i+1]) !== 'undefined' && typeof(values[i+2]) !== 'undefined')
							rvalue = rvalue / 3;
						else if (typeof(values[i+1]) !== 'undefined')
							rvalue = rvalue / 2;

						var rlabel = values[i].label;
						if (typeof(values[i+2]) !== 'undefined') rlabel+=' -
'+values[i+2].label;
						else
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 3;
					}
				} else {
					/// by 2
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;

						if (typeof(values[i+1]) !== 'undefined')
							rvalue = rvalue / 2;

						var rlabel = values[i].label;
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 2;
					}
				}

				values = rvalues;
			}

			var labels = _.map(values, function(item){ return item.label; });
			var series = [[]];
			series[0] = _.map(values, function(item){ return item.value; });

			that._data = {labels: labels, series: series};
			that.dataFetched = false;

			that.dataReady = true;
        	that.trigger('dataReady');
		});
		this.fetchTransactions();
	},
	wakeUp: function() {
		this.render();
	},
	render: function() {
		console.log('Rendering chart');

		if (!$('#'+this.id).length)
			return;

		this.once('dataReady', function(){
			if (typeof(this._data.labels) === 'undefined' || !this._data.labels || this._data.labels.length == 0)
				return; // @todo: show 'not enough data'

			this.chart = new Chartist.Line('#'+this.id, this._data, {
				low: 0,
				chartPadding: 0,
				fullWidth: false,
				showArea: true
			});
		});
		this.fetchData();
	}
});
<commit_msg>graph<commit_after>// balance.js
App.Views.Charts.Balance = Backbone.View.extend({

	events: {
	},
	chart: false,
	aTransactions: [],
	_data: {},
	dataReady: false,
	dataFetched: false,

	initialize: function() {
		if (!this.model || !this.id)
			console.error('views/charts/balance.js | model(wallet) and id of canvas should be provided for this view');
	},
	fetchTransactions: function() {
		if (this.aTransactions.length)
		{
			this.trigger('transactionsReady');
			return this.aTransactions;
		}

		var transactions = new App.Collections.Transactions();
		this.aTransactions = [];
        transactions.setWalletId(this.model.id);

        var that = this;
        transactions.once('sync',function(){
        	console.log('Synced current month');
        	transactions.forEach(function(t){
        		that.aTransactions.push(t);
        	});

        	transactions.once('sync',function(){
        	console.log('Synced prev month');
	        	transactions.forEach(function(t){
	        		that.aTransactions.push(t);
	        	});

	        	that.trigger('transactionsReady');
        	});
        	transactions.gotoPrev();
        });

        transactions.fetch();
	},
	fetchData: function() {
		if (this.dataFetched)
			return false;
		if (this.dataReady)
		{
        	this.trigger('dataReady');
			return this._data;
		}

		this.dataFetched = true;

		var that = this;
		this.once('transactionsReady',function(){
			_.each(this.aTransactions, function(item){
				console.log(item.get('amount'));
			});
			//// first step. Filter expenses
			var a = _.filter(this.aTransactions, function(t){ return t.get('amount') < 0; });

			//// second step. For each day
			var days = {};
			var curTime = new Date();
			var curDay = curTime.getDate();
			var curMonth = curTime.getMonth();
			curTime = curTime.getTime();
			for (var i = 0; i <= 60; i++)
			{
				var d = new Date(curTime - 24*60*60*1000*i);
				var day = d.getDate();
				var month = d.getMonth();
				var dayTotal = 0;
				_.each(a, function(t){
					var tDate = new Date(t.get('datetime')*1000);
					if (tDate.getDate() == day && tDate.getMonth() == month)
						dayTotal += Math.abs(t.get('amount'));
				});
				days[day+'-'+month] = {day: day, month: month, total: dayTotal};
			}
			/// third step. Find first day from a set at which transaction occurs.
			var firstDay = 0;
			var firstMonth = 0;
			_.each(days, function(day){
				if (day.total > 0)
				{
					if (firstDay == 0 && firstMonth == 0)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}

					if (day.month < firstMonth || day.day < firstDay)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}
				}
			});

			/// forth step. Fill days without transactions by values from next days started from firstDay
			if (firstDay)
			_.each(days, function(d){
				if (firstMonth < d.month || (firstDay < d.day && firstMonth == d.month))
				{
					if (d.total == 0 && typeof(d.filledMissed) === 'undefined')
					{
						var foundTotal = 0;
						var foundEmpty = [];
						var iDay = d.day + 1;
						var iMonth = d.month;
						foundEmpty.push(d.day+'-'+d.month);

						while ((foundTotal == 0) && ((curMonth == iMonth && curDay >= iDay) || (curMonth > iMonth)) )
						if (typeof(days[iDay+'-'+iMonth]) !== 'undefined')
						{

							if (days[iDay+'-'+iMonth].total == 0)
							{
								/// another empty day
								foundEmpty.push(iDay+'-'+iMonth);
							} else {
								/// day with total set
								foundEmpty.push(iDay+'-'+iMonth);
								foundTotal = days[iDay+'-'+iMonth].total;
							}

							iDay++;

						} else {
							/// next month
							iMonth++;
							iDay = 1;
						}

						//// fill missed sum
						foundEmpty = _.uniq(foundEmpty);
						if (foundTotal > 0 && foundEmpty.length > 0)
						{
							var total = foundTotal / foundEmpty.length;
							_.each(foundEmpty, function(found){
								days[found].total = total;
								days[found].filledMissed = true;
							});
						}
					}
				}
			});

			/// fifth step. Filter days with total set and truncate to 30 max
			//days = _.filter(days, function(d){ return d.total > 0; });
			//days = _.last(days, 30);

			/// generate labels
			//days.reverse();
			var values = [];
			_.each(days, function(day, key){
				values.push({label: day.day+'/'+(day.month+1), value: day.total});
			});
			values.reverse();
			values = _.last(values, 31);

			/// remove empty from the start
			var alreadyStarted = false;
			values = _.filter(values, function(item){ if (item.value > 0 || alreadyStarted) { alreadyStarted = true; return true; } else return false; });

			/// group by
			if (values.length > 10)
			{
				var rvalues = [];
				var i = 0;
				if (values.length > 20)
				{
					/// by 3
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;
						if (typeof(values[i+2]) !== 'undefined') rvalue+=values[i+2].value;

						if (typeof(values[i+1]) !== 'undefined' && typeof(values[i+2]) !== 'undefined')
							rvalue = rvalue / 3;
						else if (typeof(values[i+1]) !== 'undefined')
							rvalue = rvalue / 2;

						var rlabel = values[i].label;
						if (typeof(values[i+2]) !== 'undefined') rlabel+=' -
'+values[i+2].label;
						else
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 3;
					}
				} else {
					/// by 2
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;

						if (typeof(values[i+1]) !== 'undefined')
							rvalue = rvalue / 2;

						var rlabel = values[i].label;
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 2;
					}
				}

				values = rvalues;
			}

			var labels = _.map(values, function(item){ return item.label; });
			var series = [[]];
			series[0] = _.map(values, function(item){ return item.value; });

			that._data = {labels: labels, series: series};
			that.dataFetched = false;

			that.dataReady = true;
        	that.trigger('dataReady');
		});
		this.fetchTransactions();
	},
	wakeUp: function() {
		this.render();
	},
	render: function() {
		console.log('Rendering chart');

		if (!$('#'+this.id).length)
			return;

		this.once('dataReady', function(){
			if (typeof(this._data.labels) === 'undefined' || !this._data.labels || this._data.labels.length == 0)
				return; // @todo: show 'not enough data'

			this.chart = new Chartist.Line('#'+this.id, this._data, {
				low: 0,
				chartPadding: 0,
				fullWidth: false,
				showArea: true
			});
		});
		this.fetchData();
	}
});
<|endoftext|>


<commit_before>var pi_user_id = "";
var pi_user_code = "";
var accessToken = "";
var passkey = "";
const Pi = window.Pi;

function set_points(points) {
    if(pi_user_id != "" && pi_user_code != "")
    {
        var data = {
            'pi_user_id': pi_user_id,
            'pi_user_code': pi_user_code,
            'points': points,
            'app_client': 'auth_platform',
            'passkey': passkey,
            'accessToken': accessToken,
            'csrf_token': odoo.csrf_token,
        };
        $.ajaxSetup({async: false});
        return $.post( "/pi-points", data).done(function(data) {
            data = JSON.parse(data);
            if(data.result && points > 0)
                alert("You won " + points + " points");
        }).fail(function() {

        });
    }
}

function load_all_boards()
{
    if(all_was_loaded_lib == "mobile")
    {
        if(all_was_loaded)
        {
            setTimeout(function() {
                setMobileBoard();
            }, 1000);
        }else{
            setTimeout(function() {
                load_all_boards();
            }, 3000);
        }
    }else if(all_was_loaded_lib == "desktop")
    {
        if(all_was_loaded)
        {
            setTimeout(function() {
                setDesktopBoard();
            }, 1000);
        }else{
            setTimeout(function() {
                load_all_boards();
            }, 3000);
        }
    }
}

function get_user() {
    if(pi_user_id != "" && pi_user_code != "")
    {
        var data = {
                    'pi_user_id': pi_user_id,
                    'pi_user_code': pi_user_code,
                    'accessToken': accessToken,
                    'csrf_token': odoo.csrf_token,
                };
        $.ajaxSetup({async: false});
        return $.post( "/get-user", data).done(function(data) {
            data = JSON.parse(data);
            if(data.result)
            {
                passkey=data.passkey;
                if(data.unblocked)
                {
                    $("#pi_donate").hide();
                    $("#button_click").hide();
                    $('#chess-tab').show();
                    $('#chess-tab').click();

                    load_all_boards();
                }
                else
                {
                    $("#pi_donate").hide();
                    $("#button_click").show();
                    $('#chess-tab').hide();
                    $("#home-tab").click();
                }
            }
        }).fail(function() {

        });
    }
}

$( document ).ready(function() {
    $('.timer_white').countimer({
			autoStart : false
			});

    $('.timer_black').countimer({
			autoStart : false
			});

    $(document).ajaxStop(function() {
                $("#loading_word").hide();
            });

    Pi.init({ version: "2.0", sandbox: $("#sandbox").val() });

    async function auth() {
        $("#pi_donate").hide();
        $("#button_click").show();
        $('#chess-tab').hide();
        $("#home-tab").click();

        $("#loading_word").show();

        setTimeout(function() {
          $("#loading_word").hide();
        }, 5000);

        try {
            // Identify the user with their username / unique network-wide ID, and get permission to request payments from them.
            const scopes = ['username', 'payments'];
            function onIncompletePaymentFound(payment) {

                var data = {
                        'action': 'complete',
                        'paymentId': payment.identifier,
                        'txid': payment.transaction.txid,
                        'app_client': 'auth_platform',
                        'accessToken': accessToken,
                        'pi_user_code': pi_user_code,
                        'pi_user_id': pi_user_id,
                        'csrf_token': odoo.csrf_token,
                    };
                  return $.post( "/pi-api", data).done(function(data) {
                                    $("#button_click").prop( "disabled", false );
                                    try {
                                        data = JSON.parse(data);
                                        if(data.result && data.completed)
                                        {
                                            alert("A payment was registered. Reload the page to view the changes.");
                                        }
                                    } catch (e) {
                                    }
                                }).fail(function() {
                                    $("#button_click").prop( "disabled", false );
                                });
            }; // Read more about this in the SDK reference

            Pi.authenticate(scopes, onIncompletePaymentFound).then(function(auth) {
                pi_user_id = auth.user.uid;
                pi_user_code = auth.user.username;
                accessToken = auth.accessToken;

                //get_user();
                set_points(0);
                get_user();

              $( "#button_click" ).click(function() {
                    if(parseFloat($("#pi_donate").val()) > 0)
                    {
                        $("#button_click").prop( "disabled", true );
                        /*setTimeout(function ()
                        {
                            $("#button_click").prop( "disabled", false );
                        }, 10000);*/
                        transfer();
                    }
                    //alert("Click");
                });
            }).catch(function(error) {
                //Pi.openShareDialog("Error", error);
                //alert(err);

                console.error(error);
            });
        } catch (err) {
            //Pi.openShareDialog("Error", err);
            //alert(err);
            console.error(err);
            // Not able to fetch the user
        }
    }

    async function transfer() {
        try {
            const payment = Pi.createPayment({
              // Amount of π to be paid:
              amount: parseFloat($("#pi_donate").val()),
              // An explanation of the payment - will be shown to the user:
              memo: "Pay to unlock LatinChain Games (Chess)", // e.g: "Digital kitten #1234",
              // An arbitrary developer-provided metadata object - for your own usage:
              metadata: { paymentType: "donation" /* ... */ }, // e.g: { kittenId: 1234 }
            }, {
                  // Callbacks you need to implement - read more about those in the detailed docs linked below:
                  onReadyForServerApproval: function(paymentId) {

                    var data = {
                                'action': 'approve',
                                'paymentId': paymentId,
                                "txid": '',
                                'app_client': 'auth_platform',
                                'csrf_token': odoo.csrf_token,
                                'accessToken': accessToken,
                                'pi_user_code': pi_user_code,
                                'pi_user_id': pi_user_id,
                            };
                      return $.post( "/pi-api", data).done(function(data) {
                                    $("#button_click").prop( "disabled", false );
                                }).fail(function() {
                                    $("#button_click").prop( "disabled", false );
                                });
                  },
                  onReadyForServerCompletion: function(paymentId, txid) {

                        var data = {
                                'action': 'complete',
                                'paymentId': paymentId,
                                "txid": txid,
                                'app_client': 'auth_platform',
                                'csrf_token': odoo.csrf_token,
                                'accessToken': accessToken,
                                'pi_user_code': pi_user_code,
                                'pi_user_id': pi_user_id,
                            };
                      return $.post( "/pi-api", data).done(function(data) {
                                    $("#button_click").prop( "disabled", false );
                                    location.reload();
                                }).fail(function() {
                                    $("#button_click").prop( "disabled", false );
                                });
                  },
                  onCancel: function(paymentId) { $("#button_click").prop( "disabled", false ); /* ... */ },
                  onError: function(error, payment) { $("#button_click").prop( "disabled", false ); /* ... */ },
                });
        } catch(err) {
            //Pi.openShareDialog("Error", err);
            // alert(err);
            $("#button_click").prop( "disabled", false );
            console.error(err);
            // Technical problem (eg network failure). Please try again
        }
    }

    auth();

    $(".numeric-decimal").on("keypress keyup blur",function (event) {
        //this.value = this.value.replace(/[^0-9\.]/g,'');
        //$(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });

    $(".numeric").on("keypress keyup blur",function (event) {
        var val = $(this).val().replace(/[^\d].+/, "");
        if(val.length > 1)
            val = val.substring(0, 1);
        $(this).val(val);
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });

    $(".sudoku-list").on("keypress keyup blur",function (event) {
        //this.value = this.value.replace(/[^0-9\.]/g,'');
        //$(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46) && (event.which < 49 || event.which > 57)) {
            event.preventDefault();
        }
    });

});
<commit_msg>Upgrade<commit_after>var pi_user_id = "";
var pi_user_code = "";
var accessToken = "";
var passkey = "";
const Pi = window.Pi;

function set_points(points) {
    if(pi_user_id != "" && pi_user_code != "")
    {
        var data = {
            'pi_user_id': pi_user_id,
            'pi_user_code': pi_user_code,
            'points': points,
            'app_client': 'auth_platform',
            'passkey': passkey,
            'accessToken': accessToken,
            'csrf_token': odoo.csrf_token,
        };
        $.ajaxSetup({async: false});
        return $.post( "/pi-points", data).done(function(data) {
            data = JSON.parse(data);
            if(data.result && points > 0)
                alert("You won " + points + " points");
        }).fail(function() {

        });
    }
}

function load_all_boards()
{
    if(all_was_loaded_lib == "mobile")
    {
        if(all_was_loaded)
        {
            setTimeout(function() {
                setMobileBoard();
            }, 1000);
        }else{
            setTimeout(function() {
                load_all_boards();
            }, 5000);
        }
    }else if(all_was_loaded_lib == "desktop")
    {
        if(all_was_loaded)
        {
            setTimeout(function() {
                setDesktopBoard();
            }, 1000);
        }else{
            setTimeout(function() {
                load_all_boards();
            }, 5000);
        }
    }
}

function get_user() {
    if(pi_user_id != "" && pi_user_code != "")
    {
        var data = {
                    'pi_user_id': pi_user_id,
                    'pi_user_code': pi_user_code,
                    'accessToken': accessToken,
                    'csrf_token': odoo.csrf_token,
                };
        $.ajaxSetup({async: false});
        return $.post( "/get-user", data).done(function(data) {
            data = JSON.parse(data);
            if(data.result)
            {
                passkey=data.passkey;
                if(data.unblocked)
                {
                    $("#pi_donate").hide();
                    $("#button_click").hide();
                    $('#chess-tab').show();
                    $('#chess-tab').click();

                    load_all_boards();
                }
                else
                {
                    $("#pi_donate").hide();
                    $("#button_click").show();
                    $('#chess-tab').hide();
                    $("#home-tab").click();
                }
            }
        }).fail(function() {

        });
    }
}

$( document ).ready(function() {
    $('.timer_white').countimer({
			autoStart : false
			});

    $('.timer_black').countimer({
			autoStart : false
			});

    $(document).ajaxStop(function() {
                $("#loading_word").hide();
            });

    Pi.init({ version: "2.0", sandbox: $("#sandbox").val() });

    async function auth() {
        $("#pi_donate").hide();
        $("#button_click").show();
        $('#chess-tab').hide();
        $("#home-tab").click();

        $("#loading_word").show();

        setTimeout(function() {
          $("#loading_word").hide();
        }, 5000);

        try {
            // Identify the user with their username / unique network-wide ID, and get permission to request payments from them.
            const scopes = ['username', 'payments'];
            function onIncompletePaymentFound(payment) {

                var data = {
                        'action': 'complete',
                        'paymentId': payment.identifier,
                        'txid': payment.transaction.txid,
                        'app_client': 'auth_platform',
                        'accessToken': accessToken,
                        'pi_user_code': pi_user_code,
                        'pi_user_id': pi_user_id,
                        'csrf_token': odoo.csrf_token,
                    };
                  return $.post( "/pi-api", data).done(function(data) {
                                    $("#button_click").prop( "disabled", false );
                                    try {
                                        data = JSON.parse(data);
                                        if(data.result && data.completed)
                                        {
                                            alert("A payment was registered. Reload the page to view the changes.");
                                        }
                                    } catch (e) {
                                    }
                                }).fail(function() {
                                    $("#button_click").prop( "disabled", false );
                                });
            }; // Read more about this in the SDK reference

            Pi.authenticate(scopes, onIncompletePaymentFound).then(function(auth) {
                pi_user_id = auth.user.uid;
                pi_user_code = auth.user.username;
                accessToken = auth.accessToken;

                //get_user();
                set_points(0);
                get_user();

              $( "#button_click" ).click(function() {
                    if(parseFloat($("#pi_donate").val()) > 0)
                    {
                        $("#button_click").prop( "disabled", true );
                        /*setTimeout(function ()
                        {
                            $("#button_click").prop( "disabled", false );
                        }, 10000);*/
                        transfer();
                    }
                    //alert("Click");
                });
            }).catch(function(error) {
                //Pi.openShareDialog("Error", error);
                //alert(err);

                console.error(error);
            });
        } catch (err) {
            //Pi.openShareDialog("Error", err);
            //alert(err);
            console.error(err);
            // Not able to fetch the user
        }
    }

    async function transfer() {
        try {
            const payment = Pi.createPayment({
              // Amount of π to be paid:
              amount: parseFloat($("#pi_donate").val()),
              // An explanation of the payment - will be shown to the user:
              memo: "Pay to unlock LatinChain Games (Chess)", // e.g: "Digital kitten #1234",
              // An arbitrary developer-provided metadata object - for your own usage:
              metadata: { paymentType: "donation" /* ... */ }, // e.g: { kittenId: 1234 }
            }, {
                  // Callbacks you need to implement - read more about those in the detailed docs linked below:
                  onReadyForServerApproval: function(paymentId) {

                    var data = {
                                'action': 'approve',
                                'paymentId': paymentId,
                                "txid": '',
                                'app_client': 'auth_platform',
                                'csrf_token': odoo.csrf_token,
                                'accessToken': accessToken,
                                'pi_user_code': pi_user_code,
                                'pi_user_id': pi_user_id,
                            };
                      return $.post( "/pi-api", data).done(function(data) {
                                    $("#button_click").prop( "disabled", false );
                                }).fail(function() {
                                    $("#button_click").prop( "disabled", false );
                                });
                  },
                  onReadyForServerCompletion: function(paymentId, txid) {

                        var data = {
                                'action': 'complete',
                                'paymentId': paymentId,
                                "txid": txid,
                                'app_client': 'auth_platform',
                                'csrf_token': odoo.csrf_token,
                                'accessToken': accessToken,
                                'pi_user_code': pi_user_code,
                                'pi_user_id': pi_user_id,
                            };
                      return $.post( "/pi-api", data).done(function(data) {
                                    $("#button_click").prop( "disabled", false );
                                    location.reload();
                                }).fail(function() {
                                    $("#button_click").prop( "disabled", false );
                                });
                  },
                  onCancel: function(paymentId) { $("#button_click").prop( "disabled", false ); /* ... */ },
                  onError: function(error, payment) { $("#button_click").prop( "disabled", false ); /* ... */ },
                });
        } catch(err) {
            //Pi.openShareDialog("Error", err);
            // alert(err);
            $("#button_click").prop( "disabled", false );
            console.error(err);
            // Technical problem (eg network failure). Please try again
        }
    }

    auth();

    $(".numeric-decimal").on("keypress keyup blur",function (event) {
        //this.value = this.value.replace(/[^0-9\.]/g,'');
        //$(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });

    $(".numeric").on("keypress keyup blur",function (event) {
        var val = $(this).val().replace(/[^\d].+/, "");
        if(val.length > 1)
            val = val.substring(0, 1);
        $(this).val(val);
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });

    $(".sudoku-list").on("keypress keyup blur",function (event) {
        //this.value = this.value.replace(/[^0-9\.]/g,'');
        //$(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46) && (event.which < 49 || event.which > 57)) {
            event.preventDefault();
        }
    });

});
<|endoftext|>


<commit_before>'use strict';

import Backbone from 'backbone';
import moment from 'moment';

class LayersCollection extends Backbone.Collection {

  url() {
    return `${config.apiUrl}/layers`;
  }

  parse(data) {
    return data.map(layerSpec => {
      switch(layerSpec.slug) {
        case 'amount-of-money':
          layerSpec.timeline = {
            speed: 10,
            interval: {
              unit: 'week',
              count: 2
            }
          };
          break;
        case 'number-of-donors':
          layerSpec.timeline = {
            speed: 40,
            interval: {
              unit: 'month',
              count: 1
            }
          };
          break;
        case 'projects':
          layerSpec.timeline = {
            speed: 5,
            interval: {
              unit: 'year',
              count: 1
            }
          };
          break;
        case 'refugee-assistance':
          layerSpec.timeline = {
            speed: 5,
            interval: {
              unit: 'year',
              count: 1
            }
          };
          break;
      }

      layerSpec.domain = [
        layerSpec.start_date,
        layerSpec.end_date
      ];
      delete layerSpec.start_date;
      delete layerSpec.end_date;

      return layerSpec;
    });
  }

  /* Within the category "mode", set the layer "slug" as active and all the
   * other inactive */
  setActiveLayer(mode, slug) {
    let specs = this.toJSON();
    specs.filter(layer => layer.category === mode)
      .forEach(layer => layer.active = layer.slug === slug);
    this.set(specs);
    this.trigger('change');
  }

  /* Return the active layer for the current mode, if exists */
  getActiveLayer(mode) {
    return this.findWhere({
      active: true,
      category: mode
    });
  }

  /* Return a range formed by the minimum date contained into the domain
   * property of the layers and the maximum one */
  getDataDomain() {
    return this.toJSON()
      .map(layer => layer.domain.map(date => moment.utc(date, 'YYYY-MM-DD').toDate()))
      .reduce((res, domain) => {
        if(+res[0] > +domain[0]) res[0] = domain[0];
        if(+res[1] < +domain[1]) res[1] = domain[1];
        return res;
      }, [Infinity, -Infinity]);
  }

}

export default new LayersCollection();
<commit_msg>changing timeline frecuency to match between layers of the same mode<commit_after>'use strict';

import Backbone from 'backbone';
import moment from 'moment';

class LayersCollection extends Backbone.Collection {

  url() {
    return `${config.apiUrl}/layers`;
  }

  parse(data) {
    return data.map(layerSpec => {
      switch(layerSpec.slug) {
        case 'amount-of-money':
          layerSpec.timeline = {
            speed: 10,
            interval: {
              unit: 'month',
              count: 1
            }
          };
          break;
        case 'number-of-donors':
          layerSpec.timeline = {
            speed: 40,
            interval: {
              unit: 'month',
              count: 1
            }
          };
          break;
        case 'projects':
          layerSpec.timeline = {
            speed: 5,
            interval: {
              unit: 'year',
              count: 1
            }
          };
          break;
        case 'refugee-assistance':
          layerSpec.timeline = {
            speed: 5,
            interval: {
              unit: 'year',
              count: 1
            }
          };
          break;
      }

      layerSpec.domain = [
        layerSpec.start_date,
        layerSpec.end_date
      ];
      delete layerSpec.start_date;
      delete layerSpec.end_date;

      return layerSpec;
    });
  }

  /* Within the category "mode", set the layer "slug" as active and all the
   * other inactive */
  setActiveLayer(mode, slug) {
    let specs = this.toJSON();
    specs.filter(layer => layer.category === mode)
      .forEach(layer => layer.active = layer.slug === slug);
    this.set(specs);
    this.trigger('change');
  }

  /* Return the active layer for the current mode, if exists */
  getActiveLayer(mode) {
    return this.findWhere({
      active: true,
      category: mode
    });
  }

  /* Return a range formed by the minimum date contained into the domain
   * property of the layers and the maximum one */
  getDataDomain() {
    return this.toJSON()
      .map(layer => layer.domain.map(date => moment.utc(date, 'YYYY-MM-DD').toDate()))
      .reduce((res, domain) => {
        if(+res[0] > +domain[0]) res[0] = domain[0];
        if(+res[1] < +domain[1]) res[1] = domain[1];
        return res;
      }, [Infinity, -Infinity]);
  }

}

export default new LayersCollection();
<|endoftext|>