<commit_before>import {
    EventEmitter
} from 'events'
import Immutable from 'immutable'
import Promise from 'promise';
import UUID from 'node-uuid';
import * as _ from 'lodash';
import AppDispatcher from '../dispatcher/AppDispatcher'
import * as GifConstants from '../constants/GifConstants'
import * as GifAPI from '../apis/GifAPI';
import * as GiphyAPI from '../apis/GiphyAPI';

const CHANGE_EVENT = 'change';

var _gifs = new Immutable.List([]),
    _tmp = null;

const findIndexById = (id) => {
    return _gifs.findIndex((val) => {
        if (val.id === id) {
            return true;
        } else {
            return false;
        }
    });
};

const uploadToGiphy = (name, url) => {
    return new Promise((resolve, reject) => {
        GiphyAPI.upload(name, url)
            .then((body) => {
                var id = body.data.id;

                GiphyAPI.get(id)
                    .then((body) => {
                        let data = body.data;

                        resolve({
                            url: data.images.downsized.url,
                            still_url: data.images.downsized_still.url
                        });
                    })
                    .catch((error) => {
                        reject({
                            name: 'Giphy',
                            status: error.status,
                            msg: error.msg
                        });
                    });
            })
            .catch((error) => {
                reject({
                    name: 'Giphy',
                    status: error.status,
                    msg: error.msg
                });
            });
    });
};

const create = (url, name = url, still_url) => {
    return new Promise((resolve, reject) => {
        let gif = {
            id: UUID.v4(),
            name: name,
            url: url,
            still_url: still_url
        };

        if (!still_url && !GiphyAPI.isGiphyUrl(url)) {
            uploadToGiphy(name, url)
                .then((data) => {
                    gif = Object.assign({}, gif, data);

                    _gifs = _gifs.push(gif);
                    GifAPI.update(_gifs.toArray());

                    resolve();
                })
                .catch((error) => {
                    console.error(error);

                    toastr.warning('Failed to upload to Giphy'); //eslint-disable-line no-undef

                    _gifs = _gifs.push(gif);
                    GifAPI.update(_gifs.toArray());

                    resolve();
                });

        } else if (!still_url && GiphyAPI.isGiphyUrl(url)) {
            gif.still_url = GiphyAPI.getStillFromUrl(url)

            _gifs = _gifs.push(gif);
            GifAPI.update(_gifs.toArray());

            resolve();
        } else {
            _gifs = _gifs.push(gif);
            GifAPI.update(_gifs.toArray());

            resolve();
        }
    });
};

const update = (id, updates) => {
    return new Promise((resolve) => {
        let index = findIndexById(id),
            gif = _gifs.get(index);

        _gifs = _gifs.set(index, Object.assign({}, gif, updates));
        GifAPI.update(_gifs.toArray());

        resolve();
    });
};

const upload = (id) => {
    return new Promise((resolve, reject) => {
        let index = findIndexById(id),
            gif = _gifs.get(index);

        if (!GiphyAPI.isGiphyUrl(gif.url)) {
            uploadToGiphy(gif.name, gif.url)
                .then((data) => {

                    _gifs = _gifs.set(index, Object.assign({}, gif, data));
                    GifAPI.update(_gifs.toArray());

                    resolve();
                })
                .catch(reject);

        } else if (!gif.still_url && GiphyAPI.isGiphyUrl(gif.url)) {
            _gifs = _gifs.set(index, Object.assign({}, gif, {
                still_url:  GiphyAPI.getStillFromUrl(gif.url)
            }));
            GifAPI.update(_gifs.toArray());

            resolve();
        } else {
            resolve();
        }
    });
};

const remove = (id) => {
    return new Promise((resolve) => {
        let index = findIndexById(id);

        _gifs = _gifs.delete(index);
        GifAPI.update(_gifs.toArray());

        resolve();
    });
};

const loadGifs = () => {
    return new Promise((resolve) => {
        let data = GifAPI.loadData();

        _gifs = new Immutable.List(data);

        resolve();
    });
};

const importGifs = (data) => {
    return new Promise((resolve) => {
        _gifs = new Immutable.List(data);
        GifAPI.update(_gifs.toArray());
        resolve();
    });
};

const filter = (text) => {
    if (text !== '') {
        if (!_tmp) _tmp = _gifs;

        let re = new RegExp(text, 'gi');

        _gifs = _tmp.filter((val) => {
            return val.name.match(re);
        });
    } else {
        _gifs = _tmp;
    }
};

const GifStore = Object.assign({}, EventEmitter.prototype, {
    getAll: () => {
        return _.sortBy(_gifs.toArray(), 'name');
    },
    size: () => {
        return _gifs.size;
    },
    emitChange: () => {
        GifStore.emit(CHANGE_EVENT);
    },
    addChangeListener: (callback) => {
        GifStore.on(CHANGE_EVENT, callback);
    },
    removeChangeListener: (callback) => {
        GifStore.removeListener(CHANGE_EVENT, callback);
    }
});

const handleReject = (error, title) => {
    toastr.error(error.msg || error, error.name); //eslint-disable-line no-undef
    console.error(error);
};

AppDispatcher.register((action) => {
    switch (action.type) {
        case GifConstants.GIF_CREATE:
            create(action.url, action.name, action.still_url)
                .then(() => {
                    toastr.success('GIF added!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_UPDATE:
            update(action.id, action.updates)
                .then(() => {
                    toastr.success('GIF updated!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_UPLOAD:
            upload(action.id)
                .then(() => {
                    toastr.success('GIF uploaded!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_REMOVE:
            remove(action.id)
                .then(() => {
                    toastr.success('GIF removed!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_LOAD:
            loadGifs()
                .then(() => {
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_IMPORT:
            importGifs(action.data)
                .then(() => {
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_FILTER:
            filter(action.text);
            GifStore.emitChange();
            break;
        default:
            return true;
    }
});

export default GifStore;<commit_msg>Better error notifications<commit_after>import {
    EventEmitter
} from 'events'
import Immutable from 'immutable'
import Promise from 'promise';
import UUID from 'node-uuid';
import * as _ from 'lodash';
import AppDispatcher from '../dispatcher/AppDispatcher'
import * as GifConstants from '../constants/GifConstants'
import * as GifAPI from '../apis/GifAPI';
import * as GiphyAPI from '../apis/GiphyAPI';

const CHANGE_EVENT = 'change';

var _gifs = new Immutable.List([]),
    _tmp = null;

const findIndexById = (id) => {
    return _gifs.findIndex((val) => {
        if (val.id === id) {
            return true;
        } else {
            return false;
        }
    });
};

const uploadToGiphy = (name, url) => {
    return new Promise((resolve, reject) => {
        GiphyAPI.upload(name, url)
            .then((body) => {
                var id = body.data.id;

                GiphyAPI.get(id)
                    .then((body) => {
                        let data = body.data;

                        resolve({
                            url: data.images.downsized.url,
                            still_url: data.images.downsized_still.url
                        });
                    })
                    .catch((error) => {
                        reject({
                            name: 'Giphy',
                            status: error.status,
                            msg: error.msg
                        });
                    });
            })
            .catch((error) => {
                reject({
                    name: 'Giphy',
                    status: error.status,
                    msg: error.msg
                });
            });
    });
};

const create = (url, name = url, still_url) => {
    return new Promise((resolve, reject) => {
        let gif = {
            id: UUID.v4(),
            name: name,
            url: url,
            still_url: still_url
        };

        if (!still_url && !GiphyAPI.isGiphyUrl(url)) {
            uploadToGiphy(name, url)
                .then((data) => {
                    gif = Object.assign({}, gif, data);

                    _gifs = _gifs.push(gif);
                    GifAPI.update(_gifs.toArray());

                    resolve();
                })
                .catch((error) => {
                    console.error(error);

                    _gifs = _gifs.push(gif);
                    GifAPI.update(_gifs.toArray());

                    resolve();
                });

        } else if (!still_url && GiphyAPI.isGiphyUrl(url)) {
            gif.still_url = GiphyAPI.getStillFromUrl(url)

            _gifs = _gifs.push(gif);
            GifAPI.update(_gifs.toArray());

            resolve();
        } else {
            _gifs = _gifs.push(gif);
            GifAPI.update(_gifs.toArray());

            resolve();
        }
    });
};

const update = (id, updates) => {
    return new Promise((resolve) => {
        let index = findIndexById(id),
            gif = _gifs.get(index);

        _gifs = _gifs.set(index, Object.assign({}, gif, updates));
        GifAPI.update(_gifs.toArray());

        resolve();
    });
};

const upload = (id) => {
    return new Promise((resolve, reject) => {
        let index = findIndexById(id),
            gif = _gifs.get(index);

        if (!GiphyAPI.isGiphyUrl(gif.url)) {
            uploadToGiphy(gif.name, gif.url)
                .then((data) => {

                    _gifs = _gifs.set(index, Object.assign({}, gif, data));
                    GifAPI.update(_gifs.toArray());

                    resolve();
                })
                .catch(reject);

        } else if (!gif.still_url && GiphyAPI.isGiphyUrl(gif.url)) {
            _gifs = _gifs.set(index, Object.assign({}, gif, {
                still_url:  GiphyAPI.getStillFromUrl(gif.url)
            }));
            GifAPI.update(_gifs.toArray());

            resolve();
        } else {
            resolve();
        }
    });
};

const remove = (id) => {
    return new Promise((resolve) => {
        let index = findIndexById(id);

        _gifs = _gifs.delete(index);
        GifAPI.update(_gifs.toArray());

        resolve();
    });
};

const loadGifs = () => {
    return new Promise((resolve) => {
        let data = GifAPI.loadData();

        _gifs = new Immutable.List(data);

        resolve();
    });
};

const importGifs = (data) => {
    return new Promise((resolve) => {
        _gifs = new Immutable.List(data);
        GifAPI.update(_gifs.toArray());
        resolve();
    });
};

const filter = (text) => {
    if (text !== '') {
        if (!_tmp) _tmp = _gifs;

        let re = new RegExp(text, 'gi');

        _gifs = _tmp.filter((val) => {
            return val.name.match(re);
        });
    } else {
        _gifs = _tmp;
    }
};

const GifStore = Object.assign({}, EventEmitter.prototype, {
    getAll: () => {
        return _.sortBy(_gifs.toArray(), 'name');
    },
    size: () => {
        return _gifs.size;
    },
    emitChange: () => {
        GifStore.emit(CHANGE_EVENT);
    },
    addChangeListener: (callback) => {
        GifStore.on(CHANGE_EVENT, callback);
    },
    removeChangeListener: (callback) => {
        GifStore.removeListener(CHANGE_EVENT, callback);
    }
});

const handleReject = (error) => {
    toastr.error(error.msg, error.name); //eslint-disable-line no-undef
    console.error(error);
};

AppDispatcher.register((action) => {
    switch (action.type) {
        case GifConstants.GIF_CREATE:
            create(action.url, action.name, action.still_url)
                .then(() => {
                    toastr.success('GIF added!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_UPDATE:
            update(action.id, action.updates)
                .then(() => {
                    toastr.success('GIF updated!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_UPLOAD:
            upload(action.id)
                .then(() => {
                    toastr.success('GIF uploaded!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_REMOVE:
            remove(action.id)
                .then(() => {
                    toastr.success('GIF removed!'); //eslint-disable-line no-undef
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_LOAD:
            loadGifs()
                .then(() => {
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_IMPORT:
            importGifs(action.data)
                .then(() => {
                    GifStore.emitChange();
                })
                .catch(handleReject);
            break;
        case GifConstants.GIF_FILTER:
            filter(action.text);
            GifStore.emitChange();
            break;
        default:
            return true;
    }
});

export default GifStore;<|endoftext|>


<commit_before>$(function() {

    var img = ""

    $(".pagination#alpha a").on("click", function(e) {
        var url = location.href,
            letter = $(this).data("letter");
        if (/letter/.test(url)){
          url = url.replace(/letter=?./,"letter=" + letter);
        }
        else {
          if (/\?/.test(url)) {
            url += "&letter=" + letter
          }
          else {
            url += "?letter=" + letter
          }
        }
        $('#pagination_table').load(url + " #pagination_table");
        jQuery(".pagination").html(img);
        history.pushState(null, document.title, url);
        e.preventDefault();
    });

    // Let navigate the browser throught the AJAX history
});

$(window).bind("popstate", function() {
      $('#pagination_table').load(location.href + " #pagination_table");
});

<commit_msg>javascript loading fix<commit_after>$(function() {
    var once = false;

    var img = ""

    $(document).on("click", ".pagination#alpha a", function(e) {
        var url = location.href,
            letter = $(this).data("letter");
        if (/letter/.test(url)){
          url = url.replace(/letter=?./,"letter=" + letter);
        }
        else {
          if (/\?/.test(url)) {
            url += "&letter=" + letter
          }
          else {
            url += "?letter=" + letter
          }
        }
        $(".pagination").html(img);
        //$.load(url + " #pagination_table");
        $.get(url, function(result) {
          $(".pagination").html($(".pagination", result));
          $("#pagination_table").html($("#pagination_table", result));
        });
        history.pushState(null, document.title, url);
        e.preventDefault();
    });

 // let navigate the browser throught the ajax history
$(window).bind("popstate", function() {
  if (once) {
    $(".pagination").html(img);
    $.get(location.href, function(result) {
      $(".pagination").html($(".pagination", result));
        $("#pagination_table").html($("#pagination_table", result));
      });
    } else {
      once = true;
    }
});

});
<|endoftext|>


<commit_before>const PLAYERSTEPX = 100;
const PLAYERSTEPY = 85;
// Enemies our player must avoid
var Enemy = function() {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started

    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    var enemyXpos = [-100,-75,-45,-20,0];
    var enemyYpos = [55,145,225];
    this.sprite = 'images/enemy-bug.png';
    this.x = enemyXpos[Math.floor(Math.random() * 5)];
    this.y = enemyYpos[Math.floor(Math.random() * 3)];
    this.width = 171;
    this.height = 101;
    var enemySpeed = [100,150,190,220,280];
    this.speed = enemySpeed[Math.floor(Math.random() * 5)];
}

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.
    this.x += this.speed*dt;
    if(this.x > 800){
        this.x = 0;
    }
}

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);

}

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.
var Player = function() {
    this.sprite = 'images/char-horn-girl.png';
    this.x = 200;
    this.y = 390;
    this.width = 171;
    this.height = 101;
}

Player.prototype.update = function() {
    if(this.x <= 0){
        this.x = 0;
    }
    if(this.x >= 405){
        this.x = 405;
    }
    if(this.y <= 50){
        this.y = 50;
    }
    if(this.y >= 390){
        this.y = 390;
    }
}

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

Player.prototype.handleInput = function (keys) {
    if(keys == 'left'){
        this.x -= PLAYERSTEPX;
    }
    if(keys == 'right'){
        this.x += PLAYERSTEPX;
    }
    if(keys == 'up'){
        this.y -= PLAYERSTEPY;
    }
    if(keys == 'down'){
        this.y += PLAYERSTEPY;
    }

}

function checkCollisions(enemy, player) {

}

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies

var enemy_1 = new Enemy();
var enemy_2 = new Enemy();
var enemy_3 = new Enemy();
var enemy_4 = new Enemy();
var enemy_5 = new Enemy();
var enemy_6 = new Enemy();
    allEnemies = [enemy_1, enemy_2, enemy_3, enemy_4, enemy_5,enemy_6];

// Place the player object in a variable called player
var player = new Player();

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});
<commit_msg>collision added<commit_after>// Enemies our player must avoid
var Enemy = function() {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started

    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    var enemyXpos = [-100,-75,-45,-20,0];
    var enemyYpos = [55,145,225];
    this.sprite = 'images/enemy-bug.png';
    this.x = enemyXpos[Math.floor(Math.random() * 5)];
    this.y = enemyYpos[Math.floor(Math.random() * 3)];
    this.width = 171;
    this.height = 101;
    var enemySpeed = [100,150,190,220,280];
    this.speed = enemySpeed[Math.floor(Math.random() * 5)];
}

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.
    this.x += this.speed*dt;
    if(this.x > 800){
        this.x = 0;
    }
}

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);

}

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.
var Player = function() {
    this.sprite = 'images/char-horn-girl.png';
    this.x = 200;
    this.y = 390;
    this.width = 171;
    this.height = 101;
    this.perStepX = 100;
    this.perStepY = 85;
}

Player.prototype.update = function() {
    if(this.x <= 0){
        this.x = 0;
    }
    if(this.x >= 405){
        this.x = 405;
    }
    if(this.y <= 50){
        this.y = 50;
    }
    if(this.y >= 390){
        this.y = 390;
    }
}

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

Player.prototype.handleInput = function (keys) {
    if(keys == 'left'){
        this.x -= this.perStepX;
    }
    if(keys == 'right'){
        this.x += this.perStepX;
    }
    if(keys == 'up'){
        this.y -= this.perStepY;
    }
    if(keys == 'down'){
        this.y += this.perStepY;
    }

}

function checkCollisions() {
    for(var i=0; i < allEnemies.length; i++){
        if (!boundingBoxCollide(allEnemies[i], player)){
            player.x = 200;
            player.y = 390;
        }
    }
}

function boundingBoxCollide(object1, object2) {

    var left1 = object1.x;
    var left2 = object2.x;
    var right1 = object1.x + object1.width/2;
    var right2 = object2.x + object2.width/2;
    var top1 = object1.y;
    var top2 = object2.y;
    var bottom1 = object1.y + object1.height/2;
    var bottom2 = object2.y + object2.height/2;

    if (bottom1 < top2) return(false);
    if (top1 > bottom2) return(false);

    if (right1 < left2) return(false);
    if (left1 > right2) return(false);

    return(true);
}

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies

var enemy_1 = new Enemy();
var enemy_2 = new Enemy();
var enemy_3 = new Enemy();
var enemy_4 = new Enemy();
var enemy_5 = new Enemy();
var enemy_6 = new Enemy();
var allEnemies = [enemy_1, enemy_2, enemy_3, enemy_4, enemy_5,enemy_6];

// Place the player object in a variable called player
var player = new Player();

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});
<|endoftext|>


<commit_before>module.exports = function () {
  return {
    files: [
      'node_modules/chai/chai.js',
      'workshops/01_controller_service_filter_directive_testing/lib/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'workshops/01_controller_service_filter_directive_testing/src/*.js',
      'workshops/01_controller_service_filter_directive_testing/test/*.js'
    ],
    tests: [
      'workshops/01_controller_service_filter_directive_testing/tests/*.js'
    ]
  };
};
<commit_msg>changed path in wallaby<commit_after>module.exports = function () {
  return {
    files: [
      'node_modules/chai/chai.js',
      'workshops/01_controller_service_filter_directive_testing/solution/lib/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'workshops/01_controller_service_filter_directive_testing/solution/src/*.js',
      'workshops/01_controller_service_filter_directive_testing/solution/test/*.js'
    ],
    tests: [
      'workshops/01_controller_service_filter_directive_testing/solution/tests/*.js'
    ]
  };
};
<|endoftext|>


<commit_before>(function (global, factory) {
	if (typeof define === 'function') {
		define('gmaps-polygon-manager', ['exports'], factory);
	} else if (typeof exports !== 'undefined') {
		factory(exports);
	} else {
		var mod = {
			exports: {}
		};
		factory(mod.exports);
		global.gmapsPolygonManager = mod.exports;
	}
})(this, function (exports) {
	'use strict';

	Object.defineProperty(exports, '__esModule', {
		value: true
	});

	var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

	function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

	var Dot = (function () {
		function Dot(latLng, map) {
			var options = arguments[2] === undefined ? {} : arguments[2];

			_classCallCheck(this, Dot);

			this.latLng = latLng;
			this.markerObj = new google.maps.Marker({ position: this.latLng, map: map });
			this.events = new Array();

			this.callbackContext = options['callbackContext'] || this;
			this.callbacks = {
				dot_clicked: options['onDotClicked']
			};

			this._addListeners();
		}

		_createClass(Dot, [{
			key: 'getLatLng',
			value: function getLatLng() {
				return this.latLng;
			}
		}, {
			key: 'getMarketObj',
			value: function getMarketObj() {
				return this.markerObj;
			}
		}, {
			key: 'remove',
			value: function remove() {
				this.markerObj.setMap(null);
				this._removeListeners();
			}
		}, {
			key: 'on',
			value: function on(event_name, callback) {
				this.callbacks[event_name] = callback;
			}
		}, {
			key: '_trigger',
			value: function _trigger() {
				if (arguments.length == 0) {
					return true;
				}

				var args = new Array();
				Array.prototype.push.apply(args, arguments);

				var event_name = args.shift();
				if (this.callbacks[event_name] !== null && this.callbacks[event_name] !== undefined) {
					return this.callbacks[event_name].apply(this.callbackContext, args);
				} else {
					return true;
				}
			}
		}, {
			key: '_addListeners',
			value: function _addListeners() {
				var _this2 = this;

				this.events.push(google.maps.event.addListener(this.markerObj, 'click', function () {
					_this2._trigger('dot_clicked', _this2);
				}));
			}
		}, {
			key: '_removeListeners',
			value: function _removeListeners() {
				this.events.forEach(function (event) {
					google.maps.event.removeListener(event);
				});

				this.events = new Array();
			}
		}]);

		return Dot;
	})();

	exports.Dot = Dot;

	var Line = (function () {
		function Line(listOfDots, map, color) {
			var _this3 = this;

			_classCallCheck(this, Line);

			this.listOfDots = listOfDots;
			this.map = map;
			this.color = color;
			this.coords = new Array();

			if (this.listOfDots.length > 1) {
				this.listOfDots.forEach(function (dot) {
					_this3.coords.push(dot.getLatLng());
				});
				this.polylineObj = new google.maps.Polyline({
					path: this.coords,
					strokeColor: this.color,
					strokeOpacity: 1,
					strokeWeight: 2,
					map: this.map
				});
			}
		}

		_createClass(Line, [{
			key: 'setColor',
			value: function setColor(color) {
				this.color = color;
				this.polylineObj.setOptions({ strokeColor: this.color });
			}
		}, {
			key: 'remove',
			value: function remove() {
				this.polylineObj.setMap(null);
			}
		}]);

		return Line;
	})();

	exports.Line = Line;

	var Pen = (function () {
		function Pen(map) {
			var options = arguments[1] === undefined ? {} : arguments[1];

			_classCallCheck(this, Pen);

			this.map = map;
			this.callbackContext = options['callbackContext'] || this;
			this.color = options['color'] || '#000';
			this.listOfDots = new Array();
			this.isDrawing = false;

			this.callbacks = {
				start_draw: options['onStartDraw'],
				finish_draw: options['onFinishDraw'],
				cancel_draw: options['onCancelDraw'],
				dot_added: options['onDotAdded']
			};

			this._addListeners();
		}

		_createClass(Pen, [{
			key: 'draw',
			value: function draw(latLng) {
				this.isDrawing = true;
				if (this.currentDot !== null && this.currentDot !== undefined && this.listOfDots.length > 1 && this.currentDot.latLng == this.listOfDots[0].latLng) {
					this._trigger('finish_draw', this);
					this.clear();
					this.isDrawing = false;
				} else {
					if (this.polyline !== null && this.polyline !== undefined) {
						this.polyline.remove();
					}

					var dot = new Dot(latLng, this.map, {
						callbackContext: this,
						onDotClicked: this._dotClicked
					});

					this.listOfDots.push(dot);

					if (this.listOfDots.length == 1) {
						this._trigger('start_draw', this);
					}

					if (this.listOfDots.length > 1) {
						var _this = this;
						this.polyline = new Line(this.listOfDots, this.map, this.color);
					}
					this._trigger('dot_added', dot);
				}
			}
		}, {
			key: 'getListOfDots',
			value: function getListOfDots() {
				this.listOfDots;
			}
		}, {
			key: 'clear',
			value: function clear() {
				this.listOfDots.forEach(function (dot) {
					dot.remove();
				});

				this.listOfDots = new Array();

				if (this.polyline !== null && this.polyline !== undefined) {
					this.polyline.remove();
					this.polyline = null;
				}
			}
		}, {
			key: 'remove',
			value: function remove() {
				this.clear();
				this._removeListeners();

				this.events = new Array();
			}
		}, {
			key: 'on',
			value: function on(event_name, callback) {
				this.callbacks[event_name] = callback;
			}
		}, {
			key: '_trigger',
			value: function _trigger() {
				if (arguments.length == 0) {
					return true;
				}

				var args = new Array();
				Array.prototype.push.apply(args, arguments);

				var event_name = args.shift();
				if (this.callbacks[event_name] !== null && this.callbacks[event_name] !== undefined) {
					return this.callbacks[event_name].apply(this.callbackContext, args);
				} else {
					return true;
				}
			}
		}, {
			key: '_setCurrentDot',
			value: function _setCurrentDot(dot) {
				this.currentDot = dot;
			}
		}, {
			key: '_dotClicked',
			value: function _dotClicked(dot) {
				this._setCurrentDot(dot);
				this.draw(dot.getMarketObj().getPosition());
			}
		}, {
			key: '_addListeners',
			value: function _addListeners() {
				var _this4 = this;

				this.events = new Array();

				this.events.push(google.maps.event.addDomListener(this.map, 'click', function (event) {
					_this4.draw(event.latLng);
				}));
				this.events.push(google.maps.event.addDomListener(this.map, 'keyup', function (event) {
					var code = event.keyCode ? event.keyCode : event.which;
					switch (code) {
						case 27:
							_this4._trigger('cancel_draw');
					}
				}));
			}
		}, {
			key: '_removeListeners',
			value: function _removeListeners() {
				this.events.forEach(function (event) {
					google.maps.event.removeListener(event);
				});
			}
		}]);

		return Pen;
	})();

	exports.Pen = Pen;

	var Polygon = (function () {
		function Polygon(listOfDots) {
			var _this5 = this;

			var options = arguments[1] === undefined ? {} : arguments[1];

			_classCallCheck(this, Polygon);

			this.coords = new Array();
			this.events = new Array();
			this.listOfDots = listOfDots;
			this.map = options['map'];
			this.id = options['id'];
			this.isDragging = false;
			this.callbackContext = options['callbackContext'] || this;
			this.callbacks = {
				polygon_changed: options['onPolygonChanged'],
				polygon_clicked: options['onPolygonClicked'],
				polygon_selected: options['onPolygonSelected'],
				polygon_deselected: options['onPolygonDeselected'],
				polygon_removed: options['onPolygonRemoved']
			};

			var color = options['color'] || '#f00';

			this.listOfDots.forEach(function (dot) {
				_this5.addDot(dot);
			});

			this.polygonObj = new google.maps.Polygon({
				draggable: true,
				editable: options['editable'] || false,
				paths: this.coords,
				strokeOpacity: options['strokeOpacity'] || 0.8,
				strokeWeight: options['strokeWeight'] || 2,
				fillOpacity: options['fillOpacity'] || 0.35,
				fillColor: color,
				strokeColor: color,
				map: this.map
			});

			this._addListeners();
		}

		_createClass(Polygon, [{
			key: 'getData',
			value: function getData() {
				var data = new Array();
				var paths = this.getPlots();

				paths.getAt(0).forEach(function (path) {
					data.push({ lat: path.A, lng: path.F });
				});
				return data;
			}
		}, {
			key: 'getPolygonObj',
			value: function getPolygonObj() {
				return this.polygonObj;
			}
		}, {
			key: 'getListOfDots',
			value: function getListOfDots() {
				return this.listOfDots;
			}
		}, {
			key: 'getPlots',
			value: function getPlots() {
				return this.polygonObj.getPaths();
			}
		}, {
			key: 'isEditable',
			value: function isEditable() {
				return this.polygonObj.editable;
			}
		}, {
			key: 'setColor',
			value: function setColor() {
				var color = arguments[0] === undefined ? '#f00' : arguments[0];

				this.polygonObj.setOptions({
					fillColor: color,
					strokeColor: color
				});
			}
		}, {
			key: 'setEditable',
			value: function setEditable(editable) {
				this.polygonObj.setOptions({
					editable: editable,
					draggable: editable
				});
			}
		}, {
			key: 'setMap',
			value: function setMap(map) {
				this.map = map;
				this.polygonObj.setMap(this.map);
			}
		}, {
			key: 'addDot',
			value: function addDot(value) {
				var latLng = value instanceof Dot ? value.latLng : value;
				this.coords.push(latLng);
			}
		}, {
			key: 'select',
			value: function select() {
				this.setEditable(true);
				this._trigger('polygon_selected', this);
			}
		}, {
			key: 'deselect',
			value: function deselect() {
				this.setEditable(false);
				this._trigger('polygon_deselected', this);
			}
		}, {
			key: 'remove',
			value: function remove() {
				this.polygonObj.setMap(null);
				this._removeListeners();
				this._trigger('polygon_removed', this);
			}
		}, {
			key: 'on',
			value: function on(event_name, callback) {
				this.callbacks[event_name] = callback;
			}
		}, {
			key: '_trigger',
			value: function _trigger() {
				if (arguments.length == 0) {
					return true;
				}

				var args = [];
				Array.prototype.push.apply(args, arguments);

				var event_name = args.shift();
				if (this.callbacks[event_name] !== null && this.callbacks[event_name] !== undefined) {
					return this.callbacks[event_name].apply(this.callbackContext, args);
				} else {
					return true;
				}
			}
		}, {
			key: '_addListeners',
			value: function _addListeners() {
				var _this6 = this;

				var polygonPath = this.polygonObj.getPath();

				this.events.push(google.maps.event.addListener(polygonPath, 'insert_at', function (event) {
					if (!_this6.isDragging) {
						_this6._trigger('polygon_changed', _this6, 'insert');
					}
				}));

				this.events.push(google.maps.event.addListener(polygonPath, 'set_at', function (event) {
					if (!_this6.isDragging) {
						_this6._trigger('polygon_changed', _this6, 'move');
					}
				}));

				this.events.push(google.maps.event.addListener(polygonPath, 'remove_at', function (event) {
					if (!_this6.isDragging) {
						_this6._trigger('polygon_changed', _this6, 'remove');
					}
				}));

				this.events.push(google.maps.event.addListener(this.polygonObj, 'dragstart', function (event) {
					_this6.isDragging = true;
				}));

				this.events.push(google.maps.event.addListener(this.polygonObj, 'dragend', function (event) {
					_this6.isDragging = false;
					_this6._trigger('polygon_changed', _this6, 'drag');
				}));

				this.events.push(google.maps.event.addDomListener(this.polygonObj, 'click', function (event) {
					if (!_this6.isDragging) {
						_this6._trigger('polygon_clicked', _this6, event, false);
					}
				}));

				this.events.push(google.maps.event.addDomListener(this.polygonObj, 'rightclick', function (event) {
					if (event.vertex !== null && event.vertex !== undefined) {
						if (polygonPath.length == 2) {
							_this6.remove();
						} else {
							polygonPath.removeAt(event.vertex);
						}
					} else {
						_this6._trigger('polygon_clicked', _this6, event, true);
					}
				}));
			}
		}, {
			key: '_removeListeners',
			value: function _removeListeners() {
				this.events.forEach(function (event) {
					google.maps.event.removeListener(event);
				});

				this.events = new Array();
			}
		}]);

		return Polygon;
	})();

	exports.Polygon = Polygon;

	var PolygonManager = (function () {
		function PolygonManager(map) {
			var _this7 = this;

			var options = arguments[1] === undefined ? {} : arguments[1];

			_classCallCheck(this, PolygonManager);

			if (map === null || map === undefined) {
				throw 'You must pass a google map object as the first argument';
			}
			this.map = map;
			this.polygons = new Array();
			this.selectedPolygons = new Array();
			this.events = new Array();
			this.drawColor = options['drawColor'] || '#000';
			this.newPolygonColor = options['newPolygonColor'];
			this.selectMultiple = options['selectMultiple'] || false;

			if (options['editable'] !== null && options['editable'] !== undefined) {
				this.editable = options['editable'];
			} else {
				this.editable = true;
			}

			this.callbackContext = options['callbackContext'] || this;
			this.callbacks = {
				ready: options['onReady'],
				start_draw: options['onStartDraw'],
				finish_draw: options['onFinishDraw'],
				cancel_draw: options['onCancelDraw'],
				dot_added: options['onDotAdded'],
				before_add_polygon: options['beforeAddPolygon'],
				polygon_added: options['onPolygonAdded'],
				polygon_changed: options['onPolygonChanged'],
				polygon_clicked: options['onPolygonClicked'],
				polygon_selected: options['onPolygonSelected'],
				polygon_deselected: options['onPolygonDeselected'],
				polygon_removed: options['onPolygonRemoved']
			};

			if (options['polygons'] !== null && options['polygons'] !== undefined) {
				this.addPolygons(options['polygons']);
			}

			if (!this.editable) {
				this.polygons.forEach(function (polygon) {
					polygon.setEditable(false);
				});
			}

			this.events.push(google.maps.event.addDomListener(this.map, 'click', function (event) {
				if (_this7.pen === null || _this7.pen === undefined) {
					_this7.deselectAll();
				}
			}));

			this._trigger('ready', this);
		}

		_createClass(PolygonManager, [{
			key: 'enableDraw',
			value: function enableDraw() {
				var color = arguments[0] === undefined ? null : arguments[0];
				var newPolygonColor = arguments[1] === undefined ? null : arguments[1];

				if (!this.editable) {
					return;
				}

				this.deselectAll();

				this.pen = new Pen(this.map, {
					color: color || this.drawColor,
					callbackContext: this,
					onStartDraw: this.callbacks['start_draw'],
					onFinishDraw: this._finishDraw,
					onCancelDraw: this._cancelDraw,
					onDotAdded: this.callbacks['dot_added']
				});

				this.map.setOptions({ draggableCursor: 'pointer' });
			}
		}, {
			key: 'setPolygons',
			value: function setPolygons(polygons) {
				this.reset();
				this.addPolygons(polygons);
			}
		}, {
			key: 'addPolygon',
			value: function addPolygon(polygon_or_object) {
				var runCallback = arguments[1] === undefined ? true : arguments[1];

				var polygon = polygon_or_object instanceof Polygon ? polygon_or_object : this._objectToPolygon(polygon_or_object);

				if (this._trigger('before_add_polygon', polygon)) {
					polygon.setMap(this.map);
					polygon.callbackContext = this;
					polygon.on('polygon_changed', this.callbacks['polygon_changed']);
					polygon.on('polygon_clicked', this._polygonClicked);
					polygon.on('polygon_selected', this.callbacks['polygon_selected']);
					polygon.on('polygon_deselected', this.callbacks['polygon_deselected']);
					polygon.on('polygon_removed', this.callbacks['polygon_removed']);
					this.polygons.push(polygon);

					if (runCallback) {
						this._trigger('polygon_added', polygon);
					}

					return polygon;
				}
			}
		}, {
			key: 'addPolygons',
			value: function addPolygons(polygons) {
				var _this8 = this;

				var runIndividualCallbacks = arguments[1] === undefined ? true : arguments[1];

				polygons.forEach(function (polygon) {
					_this8.addPolygon(polygon, runIndividualCallbacks);
				});
			}
		}, {
			key: 'getPolygonById',
			value: function getPolygonById(id) {
				this.polygons.forEach(function (polygon) {
					if (polygon.id === id) {
						return polygon;
					}
				});
			}
		}, {
			key: 'getSelectedPolygon',
			value: function getSelectedPolygon() {
				return this.selectedPolygons[0];
			}
		}, {
			key: 'getSelectedPolygons',
			value: function getSelectedPolygons() {
				return this.selectedPolygons;
			}
		}, {
			key: 'deselectPolygon',
			value: function deselectPolygon(polygon) {
				polygon.deselect();
				this._removeFromArray(this.selectedPolygons, polygon);
			}
		}, {
			key: 'deselectPolygons',
			value: function deselectPolygons(polygonArr) {
				var _this9 = this;

				var polygons = polygonArr.slice(0);
				polygons.forEach(function (polygon) {
					_this9.deselectPolygon(polygon);
				});
			}
		}, {
			key: 'deselectAll',
			value: function deselectAll() {
				this.deselectPolygons(this.selectedPolygons);
			}
		}, {
			key: 'selectPolygon',
			value: function selectPolygon(polygon) {
				var deselectOthers = arguments[1] === undefined ? true : arguments[1];

				if (!this.editable) {
					return polygon;
				}

				if (deselectOthers) {
					this.deselectAll();
				}

				polygon.select();
				this.selectedPolygons.push(polygon);
				return polygon;
			}
		}, {
			key: 'selectPolygons',
			value: function selectPolygons(polygons) {
				var _this10 = this;

				if (!this.selectMultiple) {
					return;
				}

				this.deselectAll();
				polygons.forEach(function (polygon) {
					_this10.selectPolygon(polygon);
				});
				return polygons;
			}
		}, {
			key: 'removePolygon',
			value: function removePolygon(polygon) {
				this.deselectPolygon(polygon);
				polygon.remove();
				this._removeFromArray(this.polygons, polygon);
			}
		}, {
			key: 'removePolygons',
			value: function removePolygons(polygonArr) {
				var _this11 = this;

				var polygons = polygonArr.slice(0);

				polygons.forEach(function (polygon) {
					_this11.removePolygon(polygon);
				});
			}
		}, {
			key: 'reset',
			value: function reset() {
				this.polygons.forEach(function (polygon) {
					if (polygon !== null && polygon !== undefined) {
						polygon.remove();
					}
				});
				this.polygons = new Array();
				this._resetCursor();
			}
		}, {
			key: 'destroy',
			value: function destroy() {
				this.reset();
				this.events.forEach(function (event) {
					google.maps.event.removeListener(event);
				});
			}
		}, {
			key: 'on',
			value: function on(event_name, callback) {
				this.callbacks[event_name] = callback;
			}
		}, {
			key: '_trigger',
			value: function _trigger() {
				if (arguments.length == 0) {
					return true;
				}

				var args = new Array();
				Array.prototype.push.apply(args, arguments);

				var event_name = args.shift();

				if (this.callbacks[event_name] !== null && this.callbacks[event_name] !== undefined) {
					return this.callbacks[event_name].apply(this.callbackContext, args);
				} else {
					return true;
				}
			}
		}, {
			key: '_removeFromArray',
			value: function _removeFromArray(array, obj) {
				var i = array.indexOf(obj);
				var res = new Array();
				if (i != -1) {
					res = array.splice(i, 1);
				}
				return res[0];
			}
		}, {
			key: '_cancelDraw',
			value: function _cancelDraw(pen) {
				if (this.pen !== null && this.pen !== undefined) {
					this.pen.remove();
					this.pen = null;
				}
			}
		}, {
			key: '_finishDraw',
			value: function _finishDraw(pen) {
				this._resetCursor();
				var polygon = new Polygon(this.pen.listOfDots, {
					color: this.newPolygonColor
				});

				this.addPolygon(polygon);
				this.selectPolygon(polygon);
				this.pen.remove();
				this.pen = null;
			}
		}, {
			key: '_polygonClicked',
			value: function _polygonClicked(polygon, event, rightClick) {
				if (polygon.isEditable() || rightClick) {
					this._trigger('polygon_clicked', this, event.latLng, rightClick);
				} else {
					var selectMultiple = this.selectMultiple && (event.eb.metaKey || event.eb.shiftKey || event.eb.ctrlKey);
					if (polygon.isEditable()) {
						this.deselectPolygon(polygon);
					} else {
						this.selectPolygon(polygon, !selectMultiple);
					}
				}
			}
		}, {
			key: '_mapClicked',
			value: function _mapClicked(event) {
				if (this.pen !== null && this.pen !== undefined) {
					this.pen.draw(event.latLng);
				}
			}
		}, {
			key: '_resetCursor',
			value: function _resetCursor() {
				this.map.setOptions({ draggableCursor: 'url(http://maps.gstatic.com/mapfiles/openhand_8_8.cur) 8 8, default ' });
			}
		}, {
			key: '_objectToPolygon',
			value: function _objectToPolygon(obj) {
				return new Polygon(obj['coords'], { id: obj['id'], color: obj['color'] });
			}
		}]);

		return PolygonManager;
	})();

	exports.PolygonManager = PolygonManager;
	exports['default'] = {
		version: '0.1.0',
		Dot: Dot,
		Line: Line,
		Pen: Pen,
		Polygon: Polygon,
		PolygonManager: PolygonManager
	};
});

//# sourceMappingURL=gmaps-polygon-manager.js.map<commit_msg>remove old polygon-manager js file<commit_after><|endoftext|>


<commit_before>var PromiseFSM = (function() {
	"use strict";

	function StateMachine(name, options) {
		this.name = name;
		this.states = [];
		this.transitions = [];
		this.listeners = [];

		this.locked = false;
		//this.transitioning = false;

		if (options.actions) this.actions = options.actions;
		if (options.states) this.states = options.states;
		this.verbose = options.verbose || false;

		this.interface = {
			$getState: this.getState.bind(this),
			$addTransition: this.addTransition.bind(this),
			$removeTransition: this.removeTransition.bind(this),
			$addEventListener: this.addEventlistener.bind(this),
			$removeEventListener: this.removeEventListener.bind(this)
		};

		if(this.verbose === true) {
			log("Initializing state machine \"" + this.name + "\"");
		}

		if(!promiseAdapter) {
			throw new Error("PromiseFSM - No promise adapter. Promise adapter must be set through PromiseFSM.setPromiseAdapter() before initialization");
		}

		if(options.states && Object.prototype.toString.call(this.states) === '[object Array]' && options.states.length > 1) {
			this.states = options.states;
		} else {
			throw new Error("PromiseFSM - You have to define at least two states. E.g. options.states = [\"state1\", \"state2\"]");
		}

		if(options.actions && Object.prototype.toString.call(this.actions) === '[object Object]' && Object.keys(options.actions).length > 0) {
			this.actions = options.actions;
			for(var key in this.actions) {
				this.interface[key] = this.transition.bind(this, this.actions[key].from, this.actions[key].to);
			}
		} else {
			throw new Error("PromiseFSM - You have to define at least one action. E.g. options.actions = { myAction: { from: \"state1\", to: \"state2\" } }");
		}

		if(options.initialState) {
			this.initialState = this.state = options.initialState;
		} else {
			this.initialState = this.state = this.states[0];
		}
	}

	StateMachine.prototype.getState = function() {
		return this.state;
	};

	StateMachine.prototype.transition = function(from, to) {
		var deferred = promiseAdapter.defer();
		if(this.locked) {
			if(this.verbose) {
				warn("State change failed - machine is locked");
			}

			deferred.reject(new Error(errorNames.LOCKED));
			return deferred.promise;
		}

		if(!this.isSwitchLegal(from, to)) {
			if(this.verbose) {
				warn("State change failed - illegal transition attempt from \"" + this.state + "\" to \"" + newState + "\"");
			}

			deferred.reject(new Error(errorNames.ILLEGAL_TRANSITION));
			return deferred.promise;
		}

		this.locked = true;
		this.dispatchEvent(new StateMachineEvent(eventNames.LOCKED, from, to));

		// TODO add guards here
		this.dispatchEvent(new StateMachineEvent(eventNames.EXIT_STATE, from, to));
		//this.transitioning = true;

		if(this.verbose) {
			log("\"" + from + "\" -> \"" + to + "\"");
		}

		var callbacks = [];
		var i = this.transitions.length;
		while(i--) {
			if(this.transitions[i].from === from && this.transitions[i].to === to) {
				callbacks.push(this.transitions[i].callback);
			}
		}

		if(callbacks.length > 0) {
			if(this.verbose) {
				log("Pending state change from \"" + from + "\" -> \"" + to + "\"...");
			}

			var subPromises = [];
			var subDeferred;
			i = callbacks.length;
			while(i--) {
				subDeferred = promiseAdapter.defer();
				subPromises.push(subDeferred.promise);
				callbacks[i](subDeferred.resolve);
			}

			var promise = promiseAdapter.all(subPromises);
			promise.then(this.completeSwitch.bind(this, to));
			return promise;
		} else {
			this.completeSwitch(to);
			deferred.resolve();
			return deferred.promise;
		}
	};

	StateMachine.prototype.completeSwitch = function(to) {
		var from = this.state;
		this.state = to;
		this.dispatchEvent(new StateMachineEvent(eventNames.ENTER_STATE, from, to));

		this.locked = false;
		this.dispatchEvent(new StateMachineEvent(eventNames.UNLOCKED, from, to));

		//this.transitioning = false;
		this.dispatchEvent(new StateMachineEvent(eventNames.STATE_CHANGED, from, to));

		if(this.verbose) {
			log("Transition completed. New state is \"" + to + "\".");
		}
	};

	StateMachine.prototype.isSwitchLegal = function(from, to) {
		if(from !== this.state) {
			return false;
		}

		if (from === to) {
			return false;
		}

		if (this.states.indexOf(to) === -1) {
			console.log('doesnt exist');
			return false;
		}

		for(var i in this.actions) {
			if (this.actions[i].to === to) {
				if (typeof this.actions[i].from === 'string' && (this.actions[i].from === from || this.actions[i].from === '*')) {
					return true;
				} else if (Object.prototype.toString.call(this.actions[i].from) === '[object Array]') {
					var toArray = this.actions[i].from;
					var j = toArray.length;
					while (j--) {
						if (toArray[j] === from) {
							return true;
						}
					}
				}
			}
		}

		return false;
	};

	StateMachine.prototype.addTransition = function(from, to, callback) {
		if(this.getTransitionIndex(from, to, callback) > -1) {
			warn("Duplicate transition added, only the first will be called");
		} else {
			this.transitions.push({
				from: from,
				to: to,
				callback: callback
			});
		}
	};

	StateMachine.prototype.removeTransition = function(from, to, callback) {
		var i = this.getTransitionIndex(from, to, callback);
		if(i > -1) {
			this.transitions.splice(i, 1);
		}
	};

	StateMachine.prototype.getTransitionIndex = function(from, to, callback) {
		var i = this.transitions.length;
		while(i--) {
			if(this.transitions[i].from === from && this.transitions[i].to === to && this.transitions[i].callback === callback) {
				return i;
			}
		}
		return -1;
	};

	StateMachine.prototype.addEventlistener = function(type, callback) {
		this.listeners.push({
			type: type,
			callback: callback
		});
	};

	StateMachine.prototype.removeEventListener = function(type, callback) {
		var i = this.listeners.length;
		while(i--) {
			if(this.listeners[i].type === type && this.listeners[i].callback === callback) {
				this.listeners.splice(i, 1);
			}
		}
	};

	StateMachine.prototype.dispatchEvent = function(evt) {
		var i = this.listeners.length;
		while(i--) {
			if(this.listeners[i].type === evt.type) {
				this.listeners[i].callback(evt);
			}
		}
	};

	StateMachine.prototype.getInterface = function() {
		return this.interface;
	};

	function log(text) {
		if(console) {
			console.log("%cPromiseFSM", "color: #00f", text);
		}
	}

	function warn(text) {
		if(console) {
			console.warn("%cPromiseFSM", "color: #00f", text);
		}
	}

	var eventNames = {
		LOCKED: "PromiseFSM/events/locked",
		EXIT_STATE: "PromiseFSM/events/exitState",
		ENTER_STATE: "PromiseFSM/events/enterState",
		UNLOCKED: "PromiseFSM/events/unlocked",
		STATE_CHANGED: "PromiseFSM/events/stateChanged"
	};

	var errorNames = {
		ILLEGAL_TRANSITION: "ILLEGAL_TRANSITION",
		LOCKED: "LOCKED"
	};

	function StateMachineEvent(type, from, to) {
		this.type = type;
		this.from = from;
		this.to = to;
	}

	var promiseAdapter;
  var machines = {};

	return {
		EVENTS: eventNames,
		ERRORS: errorNames,
		setPromiseAdapter: function(adapter) {
			promiseAdapter = adapter;
		},
		create: function(name, options) {
			machines[name] = new StateMachine(name, options);
			return machines[name].getInterface();
		},
		getMachine: function(name) {
			var machine = machines[name];
			if(machine) {
				return machine.getInterface();
			} else {
				return undefined;
			}
		}
	};

}());<commit_msg>fixed an 'undefined' error in the code for the debug message that is sent if state change is illegal<commit_after>var PromiseFSM = (function() {
	"use strict";

	function StateMachine(name, options) {
		this.name = name;
		this.states = [];
		this.transitions = [];
		this.listeners = [];

		this.locked = false;
		//this.transitioning = false;

		if (options.actions) this.actions = options.actions;
		if (options.states) this.states = options.states;
		this.verbose = options.verbose || false;

		this.interface = {
			$getState: this.getState.bind(this),
			$addTransition: this.addTransition.bind(this),
			$removeTransition: this.removeTransition.bind(this),
			$addEventListener: this.addEventlistener.bind(this),
			$removeEventListener: this.removeEventListener.bind(this)
		};

		if(this.verbose === true) {
			log("Initializing state machine \"" + this.name + "\"");
		}

		if(!promiseAdapter) {
			throw new Error("PromiseFSM - No promise adapter. Promise adapter must be set through PromiseFSM.setPromiseAdapter() before initialization");
		}

		if(options.states && Object.prototype.toString.call(this.states) === '[object Array]' && options.states.length > 1) {
			this.states = options.states;
		} else {
			throw new Error("PromiseFSM - You have to define at least two states. E.g. options.states = [\"state1\", \"state2\"]");
		}

		if(options.actions && Object.prototype.toString.call(this.actions) === '[object Object]' && Object.keys(options.actions).length > 0) {
			this.actions = options.actions;
			for(var key in this.actions) {
				this.interface[key] = this.transition.bind(this, this.actions[key].from, this.actions[key].to);
			}
		} else {
			throw new Error("PromiseFSM - You have to define at least one action. E.g. options.actions = { myAction: { from: \"state1\", to: \"state2\" } }");
		}

		if(options.initialState) {
			this.initialState = this.state = options.initialState;
		} else {
			this.initialState = this.state = this.states[0];
		}
	}

	StateMachine.prototype.getState = function() {
		return this.state;
	};

	StateMachine.prototype.transition = function(from, to) {
		var deferred = promiseAdapter.defer();
		if(this.locked) {
			if(this.verbose) {
				warn("State change failed - machine is locked");
			}

			deferred.reject(new Error(errorNames.LOCKED));
			return deferred.promise;
		}

		if(!this.isSwitchLegal(from, to)) {
			if(this.verbose) {
				warn("State change failed - illegal transition attempt from \"" + from + "\" to \"" + to + "\"");
			}

			deferred.reject(new Error(errorNames.ILLEGAL_TRANSITION));
			return deferred.promise;
		}

		this.locked = true;
		this.dispatchEvent(new StateMachineEvent(eventNames.LOCKED, from, to));

		// TODO add guards here
		this.dispatchEvent(new StateMachineEvent(eventNames.EXIT_STATE, from, to));
		//this.transitioning = true;

		if(this.verbose) {
			log("\"" + from + "\" -> \"" + to + "\"");
		}

		var callbacks = [];
		var i = this.transitions.length;
		while(i--) {
			if(this.transitions[i].from === from && this.transitions[i].to === to) {
				callbacks.push(this.transitions[i].callback);
			}
		}

		if(callbacks.length > 0) {
			if(this.verbose) {
				log("Pending state change from \"" + from + "\" -> \"" + to + "\"...");
			}

			var subPromises = [];
			var subDeferred;
			i = callbacks.length;
			while(i--) {
				subDeferred = promiseAdapter.defer();
				subPromises.push(subDeferred.promise);
				callbacks[i](subDeferred.resolve);
			}

			var promise = promiseAdapter.all(subPromises);
			promise.then(this.completeSwitch.bind(this, to));
			return promise;
		} else {
			this.completeSwitch(to);
			deferred.resolve();
			return deferred.promise;
		}
	};

	StateMachine.prototype.completeSwitch = function(to) {
		var from = this.state;
		this.state = to;
		this.dispatchEvent(new StateMachineEvent(eventNames.ENTER_STATE, from, to));

		this.locked = false;
		this.dispatchEvent(new StateMachineEvent(eventNames.UNLOCKED, from, to));

		//this.transitioning = false;
		this.dispatchEvent(new StateMachineEvent(eventNames.STATE_CHANGED, from, to));

		if(this.verbose) {
			log("Transition completed. New state is \"" + to + "\".");
		}
	};

	StateMachine.prototype.isSwitchLegal = function(from, to) {
		if(from !== this.state) {
			return false;
		}

		if (from === to) {
			return false;
		}

		if (this.states.indexOf(to) === -1) {
			console.log('doesnt exist');
			return false;
		}

		for(var i in this.actions) {
			if (this.actions[i].to === to) {
				if (typeof this.actions[i].from === 'string' && (this.actions[i].from === from || this.actions[i].from === '*')) {
					return true;
				} else if (Object.prototype.toString.call(this.actions[i].from) === '[object Array]') {
					var toArray = this.actions[i].from;
					var j = toArray.length;
					while (j--) {
						if (toArray[j] === from) {
							return true;
						}
					}
				}
			}
		}

		return false;
	};

	StateMachine.prototype.addTransition = function(from, to, callback) {
		if(this.getTransitionIndex(from, to, callback) > -1) {
			warn("Duplicate transition added, only the first will be called");
		} else {
			this.transitions.push({
				from: from,
				to: to,
				callback: callback
			});
		}
	};

	StateMachine.prototype.removeTransition = function(from, to, callback) {
		var i = this.getTransitionIndex(from, to, callback);
		if(i > -1) {
			this.transitions.splice(i, 1);
		}
	};

	StateMachine.prototype.getTransitionIndex = function(from, to, callback) {
		var i = this.transitions.length;
		while(i--) {
			if(this.transitions[i].from === from && this.transitions[i].to === to && this.transitions[i].callback === callback) {
				return i;
			}
		}
		return -1;
	};

	StateMachine.prototype.addEventlistener = function(type, callback) {
		this.listeners.push({
			type: type,
			callback: callback
		});
	};

	StateMachine.prototype.removeEventListener = function(type, callback) {
		var i = this.listeners.length;
		while(i--) {
			if(this.listeners[i].type === type && this.listeners[i].callback === callback) {
				this.listeners.splice(i, 1);
			}
		}
	};

	StateMachine.prototype.dispatchEvent = function(evt) {
		var i = this.listeners.length;
		while(i--) {
			if(this.listeners[i].type === evt.type) {
				this.listeners[i].callback(evt);
			}
		}
	};

	StateMachine.prototype.getInterface = function() {
		return this.interface;
	};

	function log(text) {
		if(console) {
			console.log("%cPromiseFSM", "color: #00f", text);
		}
	}

	function warn(text) {
		if(console) {
			console.warn("%cPromiseFSM", "color: #00f", text);
		}
	}

	var eventNames = {
		LOCKED: "PromiseFSM/events/locked",
		EXIT_STATE: "PromiseFSM/events/exitState",
		ENTER_STATE: "PromiseFSM/events/enterState",
		UNLOCKED: "PromiseFSM/events/unlocked",
		STATE_CHANGED: "PromiseFSM/events/stateChanged"
	};

	var errorNames = {
		ILLEGAL_TRANSITION: "ILLEGAL_TRANSITION",
		LOCKED: "LOCKED"
	};

	function StateMachineEvent(type, from, to) {
		this.type = type;
		this.from = from;
		this.to = to;
	}

	var promiseAdapter;
  var machines = {};

	return {
		EVENTS: eventNames,
		ERRORS: errorNames,
		setPromiseAdapter: function(adapter) {
			promiseAdapter = adapter;
		},
		create: function(name, options) {
			machines[name] = new StateMachine(name, options);
			return machines[name].getInterface();
		},
		getMachine: function(name) {
			var machine = machines[name];
			if(machine) {
				return machine.getInterface();
			} else {
				return undefined;
			}
		}
	};

}());<|endoftext|>


<commit_before>(function() {
    CodeMirror.defineOption("queryAutoSpace", false, function(cm, val, old) {
		if (old != CodeMirror.Init && old)
			cm.removeKeyMap("queryAutoSpace");
		if (!val) return;

		cm.addKeyMap(buildKeymap());
	  });

	function startswith(str, prefix) {
		return str.search(prefix) === 0;
	}

	function buildKeymap() {
		return {
			name : "queryAutoSpace",
			Space: function (cm) {
				var cur = cm.getCursor(), token = cm.getTokenAt(cur), line = cm.getLine(cur.line);

				if (cur.ch === token.end && token.type !== null) {
					var nextToken = cm.getTokenAt(CodeMirror.Pos(cur.line, cur.ch + 1)), start = cur, end, literal = ',';

					if (line[cur.ch] === ';')
						literal = ';';

					if (token.type !== 'quote' && !startswith(token.type, 'error'))
						literal = '';

					literal = literal + ' ';

					// If quote, replace the full literal.
					if (token.type === 'quote') {
						var state = token.state,
							  key = state.lastKey;

						literal = key + ' ' + state.dict[key].operator + ' ' + state.dict[key].value + literal;
						start = CodeMirror.Pos(cur.line, state.lastKeyStart);
					}

					// Set the end of the replacement.
					if (nextToken.start === token.start) // End of line.
						end = cur;
					else if (nextToken.type === null) // There are spaces and saperators after this token.
						end = CodeMirror.Pos(cur.line, nextToken.end);
					else
						end = CodeMirror.Pos(cur.line, nextToken.start);

					// Replace.
					cm.replaceRange(literal, start, end);

					return;
				}
				return CodeMirror.Pass;
			},
		};
	}
})();
<commit_msg>Resolves #1: Disable auto-space after broken value.<commit_after>(function() {
    CodeMirror.defineOption("queryAutoSpace", false, function(cm, val, old) {
		if (old != CodeMirror.Init && old)
			cm.removeKeyMap("queryAutoSpace");
		if (!val) return;

		cm.addKeyMap(buildKeymap());
	  });

	function startswith(str, prefix) {
		return str.search(prefix) === 0;
	}

	var BROKEN_VALUE_ERROR = 'error broken-value';

	function buildKeymap() {
		return {
			name : "queryAutoSpace",
			Space: function (cm) {
				var cur = cm.getCursor(), token = cm.getTokenAt(cur), line = cm.getLine(cur.line);

				if (cur.ch === token.end && token.type !== null && token.type !== BROKEN_VALUE_ERROR) {
					var nextToken = cm.getTokenAt(CodeMirror.Pos(cur.line, cur.ch + 1)), start = cur, end, literal = ',';

					if (line[cur.ch] === ';')
						literal = ';';

					if (token.type !== 'quote' && !startswith(token.type, 'error'))
						literal = '';

					literal = literal + ' ';

					// If quote, replace the full literal.
					if (token.type === 'quote') {
						var state = token.state,
							  key = state.lastKey;

						literal = key + ' ' + state.dict[key].operator + ' ' + state.dict[key].value + literal;
						start = CodeMirror.Pos(cur.line, state.lastKeyStart);
					}

					// Set the end of the replacement.
					if (nextToken.start === token.start) // End of line.
						end = cur;
					else if (nextToken.type === null) // There are spaces and saperators after this token.
						end = CodeMirror.Pos(cur.line, nextToken.end);
					else
						end = CodeMirror.Pos(cur.line, nextToken.start);

					// Replace.
					cm.replaceRange(literal, start, end);

					return;
				}
				return CodeMirror.Pass;
			},
		};
	}
})();
<|endoftext|>


<commit_before>/*
*     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
*     S.A.Unipersonal (Telefonica I+D)
*
*     This file is part of Morfeo EzWeb Platform.
*
*     Morfeo EzWeb Platform 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.
*
*     Morfeo EzWeb Platform 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 Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
*
*     Info about members and contributors of the MORFEO project
*     is available at
*
*     http://morfeo-project.org
 */

/**
 * @author luismarcos.ayllon
 */

// This module provides a set of gadgets which can be deployed into dragboard as gadget instances
var ShowcaseFactory = function () {

    // *********************************
    // SINGLETON INSTANCE
    // *********************************
    var instance = null;

    // *********************************
    // CONSTRUCTOR
    // *********************************
    function Showcase () {

        // ******************
        // STATIC VARIABLES
        // ******************
        Showcase.prototype.MODULE_HTML_ID = "showcase";
        Showcase.prototype.NUM_CELLS = 4;

        // ****************
        // CALLBACK METHODS
        // ****************

        this.parseGadgets = function (receivedData_) {
            var i, jsonGadgetList, jsonGadget, gadget, gadgetId, gadgetFullId,
                currentGadgetVersions, sortedGadgets, key;

            jsonGadgetList = JSON.parse(receivedData_.responseText);
            this.gadgets = new Hash();
            this.gadgetVersions = {};

            // Load all gadgets from persitence system
            for (i = 0; i < jsonGadgetList.length; i += 1) {
                jsonGadget = jsonGadgetList[i];

                gadget = new Gadget(jsonGadget, null);
                gadgetId = gadget.getVendor() + '_' + gadget.getName()
                gadgetFullId = gadgetId + '_' + gadget.getVersion().text;

                if (this.gadgetVersions[gadgetId] === undefined) {
                    this.gadgetVersions[gadgetId] = [];
                }
                this.gadgetVersions[gadgetId].push(gadget);

                // Insert gadget object in showcase object model
                this.gadgets[gadgetFullId] = gadget;
            }

            for (key in this.gadgetVersions) {
                currentGadgetVersions = this.gadgetVersions[key];
                sortedGadgets = currentGadgetVersions.sort(function(gadget1, gadget2) {
                    return -gadget1.getVersion().compareTo(gadget2.getVersion());
                });

                for (i = 0; i < currentGadgetVersions.length; i += 1) {
                    gadget = currentGadgetVersions[i];
                    gadget.setLastVersion(sortedGadgets[0].getVersion());
                }
            }
        }

        Showcase.prototype.reload = function (workspace_id) {

            var id = workspace_id;

            var onSuccess = function (receivedData_) {

                this.parseGadgets(receivedData_);

                opManager = OpManagerFactory.getInstance();

                opManager.changeActiveWorkSpace(opManager.workSpaceInstances[id]);
            }

            var onError = function (transport, e) {
                var msg, logManager = LogManagerFactory.getInstance();
                msg = logManager.formatError(gettext("Error retrieving showcase data: %(errorMsg)s."), transport, e);
                logManager.log(msg);
                LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            }

            // Initial load from persitence system
            this.persistenceEngine.send_get(URIs.GET_GADGETS, this, onSuccess, onError);
        }

        Showcase.prototype.init = function () {

            // Load gadgets from persistence system
            var onSuccess = function (receivedData_) {

                this.parseGadgets(receivedData_);

                // Showcase loaded
                this.opManager.continueLoadingGlobalModules(Modules.prototype.SHOWCASE);

            }

            // Error callback (empty gadget list)
            var onError = function (transport, e) {
                var msg, logManager = LogManagerFactory.getInstance();
                msg = logManager.formatError(gettext("Error retrieving showcase data: %(errorMsg)s."), transport, e);
                logManager.log(msg);
                LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            }

            // Initial load from persitence system
            this.persistenceEngine.send_get(URIs.GET_GADGETS, this, onSuccess, onError);
        }

        // *******************************
        // PRIVATE METHODS AND VARIABLES
        // *******************************
        this.gadgets = new Hash();
        this.opManager = OpManagerFactory.getInstance();
        this.persistenceEngine = PersistenceEngineFactory.getInstance();

        // ****************
        // PUBLIC METHODS
        // ****************

        // Add a new gadget from Internet
        Showcase.prototype.addGadget = function (vendor_, name_, version_, url_, options_) {
            var gadgetId = vendor_ + '_' + name_ + '_' + version_;
            var gadget = this.gadgets[gadgetId];

            if (gadget == null) {
                gadget = new Gadget (null, url_, options_);
            } else {
                this.opManager.addInstance(gadgetId, options_);
            }
        }

        // Add a new parameterized gadget from Internet
        // Help:
        //     - igadget_name_: String. New name for the iGadget
        //     - variable_values_: Object. New values for the user preferences.
        //         Example:
        //             variable_values = {"var1":"value1", "var2": "value2"};
        Showcase.prototype.addParameterizedGadget = function (vendor_, name_, version_, igadget_name_, variable_values_, url_) {
            var url_ = (url_)?url_:null;
            var options = {
                "igadgetName": igadget_name_,
                "setDefaultValues" : function(igadgetId_){
                    var varManager = OpManagerFactory.getInstance().activeWorkSpace.getVarManager();
                    $H(variable_values_).each(function(pair) {
                        var msg = "";
                        var variable = varManager.getVariableByName(igadgetId_, pair.key);
                        if (variable) {
                            if(variable.vardef.aspect == Variable.prototype.USER_PREF) {
                                variable.annotate(pair.value);
                                variable.set(pair.value);
                            }
                            else {
                                msg = gettext("\"%(variable)s\" variable is not an User Preference");
                            }
                        }
                        else {
                            msg = gettext("\"%(variable)s\" variable doesn't exists");
                        }
                        if (msg != "") {
                            msg = interpolate(msg, {"variable": pair.key}, true);
                            OpManagerFactory.getInstance().logIGadgetError(igadgetId_, msg, Constants.Logging.WARN_MSG);
                        }
                    });
                }
            }
            this.addGadget(vendor_, name_, version_, url_, options);
        }

        // Insert gadget object in showcase object model
        Showcase.prototype.gadgetToShowcaseGadgetModel = function(gadget_, options_) {
            var gadgetId = gadget_.getId();

            this.gadgets[gadgetId] = gadget_;
            this.opManager.addInstance(gadgetId, options_);
        }

        // Remove a Showcase gadget
        Showcase.prototype.deleteGadget = function (gadgetId_) {
            var gadget = this.gadgets.remove(gadgetId_);
            //gadget.remove();
        }

        // Update a Showcase gadget
        Showcase.prototype.updateGadget = function (gadgetId_, url_) {
            this.remove(gadgetId_);
            this.addGadget(url_);
        }

        // Get a gadget by its gadgetID
        Showcase.prototype.getGadget = function (gadgetId_) {
            return this.gadgets[gadgetId_];
        }

        //Get all the gadgets name and vendor
        Showcase.prototype.getGadgetsData = function () {
            var data = [];
            var keys = this.gadgets.keys();
            for (var i=0;i<keys.length;i++){
                var g = this.gadgets[keys[i]];
                data.push({"name":g.getName(), "vendor":g.getVendor(), "version":g.getVersion().text});
            }
            return data;
        }

        //Get all the gadgets name and vendor
        Showcase.prototype.setGadgetsState = function (data) {
            var i, j, key, resource, versions, sortedVersions, currentGadgets, updated = false;

            for (i = 0; i < data.length; i += 1) {
                resource = data[i];
                key = resource.getVendor() + '_' + resource.getName();
                if (key in this.gadgetVersions) {
                    versions = resource.getAllVersions();
                    sortedVersions = versions.sort(function(version1, version2) {
                        return -version1.compareTo(version2);
                    });

                    currentGadgets = this.gadgetVersions[key];
                    for (j = 0; j < currentGadgets.length; j += 1) {
                        updated = currentGadgets[j].setLastVersion(sortedVersions[0]) || updated;
                    }
                }
            }

            if (updated) {
                this.opManager.checkForGadgetUpdates();
            }
        }

        // Set gadget properties (User Interface)
        Showcase.prototype.setGadgetProperties = function (gadgetId_, imageSrc_, tags_) {
            var gadget = this.gadgets[gadgetId_];

            gadget.setImage(imageSrc_);
            gadget.setTags(tags_);
        }

        // Add a tag to a Showcase gadget
        Showcase.prototype.tagGadget = function (gadgetId_, tags_) {
            for (var i = 0; i<tags_.length; i++) {
                var tag = tags_[i];
                this.gadgets[gadgetId_].addTag(tag);
            }
        }

        // Deploy a Showcase gadget into dragboard as gadget instance
        Showcase.prototype.addInstance = function (gadgetId_) {
            var gadget = this.gadgets[gadgetId_];
            this.opManager.addInstance (gadget);
        }
    }

    // *********************************
    // SINGLETON GET INSTANCE
    // *********************************
    return new function() {
        this.getInstance = function() {
            if (instance == null) {
                instance = new Showcase();
            }
            return instance;
        }
    }
}();
<commit_msg>refs #68. Simplify the Showcase.setGadgetsState method<commit_after>/*
*     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
*     S.A.Unipersonal (Telefonica I+D)
*
*     This file is part of Morfeo EzWeb Platform.
*
*     Morfeo EzWeb Platform 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.
*
*     Morfeo EzWeb Platform 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 Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
*
*     Info about members and contributors of the MORFEO project
*     is available at
*
*     http://morfeo-project.org
 */

/**
 * @author luismarcos.ayllon
 */

// This module provides a set of gadgets which can be deployed into dragboard as gadget instances
var ShowcaseFactory = function () {

    // *********************************
    // SINGLETON INSTANCE
    // *********************************
    var instance = null;

    // *********************************
    // CONSTRUCTOR
    // *********************************
    function Showcase () {

        // ******************
        // STATIC VARIABLES
        // ******************
        Showcase.prototype.MODULE_HTML_ID = "showcase";
        Showcase.prototype.NUM_CELLS = 4;

        // ****************
        // CALLBACK METHODS
        // ****************

        this.parseGadgets = function (receivedData_) {
            var i, jsonGadgetList, jsonGadget, gadget, gadgetId, gadgetFullId,
                currentGadgetVersions, sortedGadgets, key;

            jsonGadgetList = JSON.parse(receivedData_.responseText);
            this.gadgets = new Hash();
            this.gadgetVersions = {};

            // Load all gadgets from persitence system
            for (i = 0; i < jsonGadgetList.length; i += 1) {
                jsonGadget = jsonGadgetList[i];

                gadget = new Gadget(jsonGadget, null);
                gadgetId = gadget.getVendor() + '_' + gadget.getName()
                gadgetFullId = gadgetId + '_' + gadget.getVersion().text;

                if (this.gadgetVersions[gadgetId] === undefined) {
                    this.gadgetVersions[gadgetId] = [];
                }
                this.gadgetVersions[gadgetId].push(gadget);

                // Insert gadget object in showcase object model
                this.gadgets[gadgetFullId] = gadget;
            }

            for (key in this.gadgetVersions) {
                currentGadgetVersions = this.gadgetVersions[key];
                sortedGadgets = currentGadgetVersions.sort(function(gadget1, gadget2) {
                    return -gadget1.getVersion().compareTo(gadget2.getVersion());
                });

                for (i = 0; i < currentGadgetVersions.length; i += 1) {
                    gadget = currentGadgetVersions[i];
                    gadget.setLastVersion(sortedGadgets[0].getVersion());
                }
            }
        }

        Showcase.prototype.reload = function (workspace_id) {

            var id = workspace_id;

            var onSuccess = function (receivedData_) {

                this.parseGadgets(receivedData_);

                opManager = OpManagerFactory.getInstance();

                opManager.changeActiveWorkSpace(opManager.workSpaceInstances[id]);
            }

            var onError = function (transport, e) {
                var msg, logManager = LogManagerFactory.getInstance();
                msg = logManager.formatError(gettext("Error retrieving showcase data: %(errorMsg)s."), transport, e);
                logManager.log(msg);
                LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            }

            // Initial load from persitence system
            this.persistenceEngine.send_get(URIs.GET_GADGETS, this, onSuccess, onError);
        }

        Showcase.prototype.init = function () {

            // Load gadgets from persistence system
            var onSuccess = function (receivedData_) {

                this.parseGadgets(receivedData_);

                // Showcase loaded
                this.opManager.continueLoadingGlobalModules(Modules.prototype.SHOWCASE);

            }

            // Error callback (empty gadget list)
            var onError = function (transport, e) {
                var msg, logManager = LogManagerFactory.getInstance();
                msg = logManager.formatError(gettext("Error retrieving showcase data: %(errorMsg)s."), transport, e);
                logManager.log(msg);
                LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            }

            // Initial load from persitence system
            this.persistenceEngine.send_get(URIs.GET_GADGETS, this, onSuccess, onError);
        }

        // *******************************
        // PRIVATE METHODS AND VARIABLES
        // *******************************
        this.gadgets = new Hash();
        this.opManager = OpManagerFactory.getInstance();
        this.persistenceEngine = PersistenceEngineFactory.getInstance();

        // ****************
        // PUBLIC METHODS
        // ****************

        // Add a new gadget from Internet
        Showcase.prototype.addGadget = function (vendor_, name_, version_, url_, options_) {
            var gadgetId = vendor_ + '_' + name_ + '_' + version_;
            var gadget = this.gadgets[gadgetId];

            if (gadget == null) {
                gadget = new Gadget (null, url_, options_);
            } else {
                this.opManager.addInstance(gadgetId, options_);
            }
        }

        // Add a new parameterized gadget from Internet
        // Help:
        //     - igadget_name_: String. New name for the iGadget
        //     - variable_values_: Object. New values for the user preferences.
        //         Example:
        //             variable_values = {"var1":"value1", "var2": "value2"};
        Showcase.prototype.addParameterizedGadget = function (vendor_, name_, version_, igadget_name_, variable_values_, url_) {
            var url_ = (url_)?url_:null;
            var options = {
                "igadgetName": igadget_name_,
                "setDefaultValues" : function(igadgetId_){
                    var varManager = OpManagerFactory.getInstance().activeWorkSpace.getVarManager();
                    $H(variable_values_).each(function(pair) {
                        var msg = "";
                        var variable = varManager.getVariableByName(igadgetId_, pair.key);
                        if (variable) {
                            if(variable.vardef.aspect == Variable.prototype.USER_PREF) {
                                variable.annotate(pair.value);
                                variable.set(pair.value);
                            }
                            else {
                                msg = gettext("\"%(variable)s\" variable is not an User Preference");
                            }
                        }
                        else {
                            msg = gettext("\"%(variable)s\" variable doesn't exists");
                        }
                        if (msg != "") {
                            msg = interpolate(msg, {"variable": pair.key}, true);
                            OpManagerFactory.getInstance().logIGadgetError(igadgetId_, msg, Constants.Logging.WARN_MSG);
                        }
                    });
                }
            }
            this.addGadget(vendor_, name_, version_, url_, options);
        }

        // Insert gadget object in showcase object model
        Showcase.prototype.gadgetToShowcaseGadgetModel = function(gadget_, options_) {
            var gadgetId = gadget_.getId();

            this.gadgets[gadgetId] = gadget_;
            this.opManager.addInstance(gadgetId, options_);
        }

        // Remove a Showcase gadget
        Showcase.prototype.deleteGadget = function (gadgetId_) {
            var gadget = this.gadgets.remove(gadgetId_);
            //gadget.remove();
        }

        // Update a Showcase gadget
        Showcase.prototype.updateGadget = function (gadgetId_, url_) {
            this.remove(gadgetId_);
            this.addGadget(url_);
        }

        // Get a gadget by its gadgetID
        Showcase.prototype.getGadget = function (gadgetId_) {
            return this.gadgets[gadgetId_];
        }

        //Get all the gadgets name and vendor
        Showcase.prototype.getGadgetsData = function () {
            var data = [];
            var keys = this.gadgets.keys();
            for (var i=0;i<keys.length;i++){
                var g = this.gadgets[keys[i]];
                data.push({"name":g.getName(), "vendor":g.getVendor(), "version":g.getVersion().text});
            }
            return data;
        }

        //Get all the gadgets name and vendor
        Showcase.prototype.setGadgetsState = function (data) {
            var i, j, key, resource, versions, last_version, currentGadgets, updated = false;

            for (i = 0; i < data.length; i += 1) {
                resource = data[i];
                key = resource.getVendor() + '_' + resource.getName();
                if (key in this.gadgetVersions) {
                    last_version = resource.getLastVersion();

                    currentGadgets = this.gadgetVersions[key];
                    for (j = 0; j < currentGadgets.length; j += 1) {
                        updated = currentGadgets[j].setLastVersion(last_version) || updated;
                    }
                }
            }

            if (updated) {
                this.opManager.checkForGadgetUpdates();
            }
        }

        // Set gadget properties (User Interface)
        Showcase.prototype.setGadgetProperties = function (gadgetId_, imageSrc_, tags_) {
            var gadget = this.gadgets[gadgetId_];

            gadget.setImage(imageSrc_);
            gadget.setTags(tags_);
        }

        // Add a tag to a Showcase gadget
        Showcase.prototype.tagGadget = function (gadgetId_, tags_) {
            for (var i = 0; i<tags_.length; i++) {
                var tag = tags_[i];
                this.gadgets[gadgetId_].addTag(tag);
            }
        }

        // Deploy a Showcase gadget into dragboard as gadget instance
        Showcase.prototype.addInstance = function (gadgetId_) {
            var gadget = this.gadgets[gadgetId_];
            this.opManager.addInstance (gadget);
        }
    }

    // *********************************
    // SINGLETON GET INSTANCE
    // *********************************
    return new function() {
        this.getInstance = function() {
            if (instance == null) {
                instance = new Showcase();
            }
            return instance;
        }
    }
}();
<|endoftext|>


<commit_before>"use strict";

var Document = require("substance-document");

var Figure = function(node, document) {
  Document.Composite.call(this, node, document);
};

Figure.type = {
  "parent": "content",
  "properties": {
    "image": "image",
    "caption": "paragraph"
  }
};

Figure.Prototype = function() {

  this.insertOperation = function(startChar, text) {
    return null;
  };

  this.deleteOperation = function(startChar, endChar) {
    return null;
  };

  this.hasCaption = function() {
    return (!!this.properties.caption);
  };

  this.getNodes = function() {
    var nodes = [this.properties.image];
    if (this.properties.caption) nodes.push(this.properties.caption);
    return nodes;
  };

  this.getImage = function() {
    if (this.properties.image) return this.document.get(this.properties.image);
  };

  this.getCaption = function() {
    if (this.properties.caption) return this.document.get(this.properties.caption);
  };
};

Figure.Prototype.prototype = Document.Composite.prototype;
Figure.prototype = new Figure.Prototype();
Figure.prototype.constructor = Figure;

Document.Node.defineProperties(Figure.prototype, ["image", "caption"]);

module.exports = Figure;
<commit_msg>Back again: figure has url instead of referencing a primitive image node.<commit_after>"use strict";

var Document = require("substance-document");

var Figure = function(node, document) {
  Document.Composite.call(this, node, document);
};

Figure.type = {
  "parent": "content",
  "properties": {
    "url": "string",
    "caption": "paragraph"
  }
};

Figure.Prototype = function() {

  this.insertOperation = function(startChar, text) {
    return null;
  };

  this.deleteOperation = function(startChar, endChar) {
    return null;
  };

  this.hasCaption = function() {
    return (!!this.properties.caption);
  };

  this.getNodes = function() {
    var nodes = [];
    if (this.properties.caption) nodes.push(this.properties.caption);
    return nodes;
  };

  this.getCaption = function() {
    if (this.properties.caption) return this.document.get(this.properties.caption);
  };
};

Figure.Prototype.prototype = Document.Composite.prototype;
Figure.prototype = new Figure.Prototype();
Figure.prototype.constructor = Figure;

// a factory method to create nodes more conveniently
// Supported
//  - id: unique id
//  - url: a relative path or a web URL
//  - caption: a string used as caption
Figure.create = function(data) {

  var result = {};

  var figId = data.id;
  var figure = {
    id: figId,
    type: "text",
    url: data.url
  };

  if (data.caption) {
    var captionId = "caption_" + data.id;
    var caption = {
      id: captionId,
      type: "text",
      content: data.caption
    };
    result[captionId] = caption;
    figure.caption = captionId;
  }

  result[figId] = figure;
  return result;
};

Document.Node.defineProperties(Figure.prototype, ["url", "caption"]);

module.exports = Figure;
<|endoftext|>


<commit_before>Rickshaw.namespace('Rickshaw.Fixtures.Color');

Rickshaw.Fixtures.Color = function() {

	this.schemes = {};

	this.schemes.spectrum14 = [
		'#ecb796',
		'#dc8f70',
		'#b2a470',
		'#92875a',
		'#716c49',
		'#d2ed82',
		'#bbe468',
		'#a1d05d',
		'#e7cbe6',
		'#d8aad6',
		'#a888c2',
		'#9dc2d3',
		'#649eb9',
		'#387aa3'
	].reverse();

	this.schemes.spectrum2000 = [
		'#57306f',
		'#514c76',
		'#646583',
		'#738394',
		'#6b9c7d',
		'#84b665',
		'#a7ca50',
		'#bfe746',
		'#e2f528',
		'#fff726',
		'#ecdd00',
		'#d4b11d',
		'#de8800',
		'#de4800',
		'#c91515',
		'#9a0000',
		'#7b0429',
		'#580839',
		'#31082b'
	];

	this.schemes.spectrum2001 = [
		'#2f243f',
		'#3c2c55',
		'#4a3768',
		'#565270',
		'#6b6b7c',
		'#72957f',
		'#86ad6e',
		'#a1bc5e',
		'#b8d954',
		'#d3e04e',
		'#ccad2a',
		'#cc8412',
		'#c1521d',
		'#ad3821',
		'#8a1010',
		'#681717',
		'#531e1e',
		'#3d1818',
		'#320a1b'
    ];

	this.schemes.classic9 = [
		'#423d4f',
		'#4a6860',
		'#848f39',
		'#a2b73c',
		'#ddcb53',
		'#c5a32f',
		'#7d5836',
		'#963b20',
		'#7c2626',
		'#491d37',
		'#2f254a'
	].reverse();

	this.schemes.httpStatus = {
		503: '#ea5029',
		502: '#d23f14',
		500: '#bf3613',
		410: '#efacea',
		409: '#e291dc',
		403: '#f457e8',
		408: '#e121d2',
		401: '#b92dae',
		405: '#f47ceb',
		404: '#a82a9f',
		400: '#b263c6',
		301: '#6fa024',
		302: '#87c32b',
		307: '#a0d84c',
		304: '#28b55c',
		200: '#1a4f74',
		206: '#27839f',
		201: '#52adc9',
		202: '#7c979f',
		203: '#a5b8bd',
		204: '#c1cdd1'
	};

	this.schemes.colorwheel = [
		'#b5b6a9',
		'#858772',
		'#785f43',
		'#96557e',
		'#4682b4',
		'#65b9ac',
		'#73c03a',
		'#cb513a'
	].reverse();

	this.schemes.cool = [
		'#5e9d2f',
		'#73c03a',
		'#4682b4',
		'#7bc3b8',
		'#a9884e',
		'#c1b266',
		'#a47493',
		'#c09fb5'
	];
};
<commit_msg>Added color-scheme "Munin".<commit_after>Rickshaw.namespace('Rickshaw.Fixtures.Color');

Rickshaw.Fixtures.Color = function() {

	this.schemes = {};

	this.schemes.spectrum14 = [
		'#ecb796',
		'#dc8f70',
		'#b2a470',
		'#92875a',
		'#716c49',
		'#d2ed82',
		'#bbe468',
		'#a1d05d',
		'#e7cbe6',
		'#d8aad6',
		'#a888c2',
		'#9dc2d3',
		'#649eb9',
		'#387aa3'
	].reverse();

	this.schemes.spectrum2000 = [
		'#57306f',
		'#514c76',
		'#646583',
		'#738394',
		'#6b9c7d',
		'#84b665',
		'#a7ca50',
		'#bfe746',
		'#e2f528',
		'#fff726',
		'#ecdd00',
		'#d4b11d',
		'#de8800',
		'#de4800',
		'#c91515',
		'#9a0000',
		'#7b0429',
		'#580839',
		'#31082b'
	];

	this.schemes.spectrum2001 = [
		'#2f243f',
		'#3c2c55',
		'#4a3768',
		'#565270',
		'#6b6b7c',
		'#72957f',
		'#86ad6e',
		'#a1bc5e',
		'#b8d954',
		'#d3e04e',
		'#ccad2a',
		'#cc8412',
		'#c1521d',
		'#ad3821',
		'#8a1010',
		'#681717',
		'#531e1e',
		'#3d1818',
		'#320a1b'
	];

	this.schemes.classic9 = [
		'#423d4f',
		'#4a6860',
		'#848f39',
		'#a2b73c',
		'#ddcb53',
		'#c5a32f',
		'#7d5836',
		'#963b20',
		'#7c2626',
		'#491d37',
		'#2f254a'
	].reverse();

	this.schemes.httpStatus = {
		503: '#ea5029',
		502: '#d23f14',
		500: '#bf3613',
		410: '#efacea',
		409: '#e291dc',
		403: '#f457e8',
		408: '#e121d2',
		401: '#b92dae',
		405: '#f47ceb',
		404: '#a82a9f',
		400: '#b263c6',
		301: '#6fa024',
		302: '#87c32b',
		307: '#a0d84c',
		304: '#28b55c',
		200: '#1a4f74',
		206: '#27839f',
		201: '#52adc9',
		202: '#7c979f',
		203: '#a5b8bd',
		204: '#c1cdd1'
	};

	this.schemes.colorwheel = [
		'#b5b6a9',
		'#858772',
		'#785f43',
		'#96557e',
		'#4682b4',
		'#65b9ac',
		'#73c03a',
		'#cb513a'
	].reverse();

	this.schemes.cool = [
		'#5e9d2f',
		'#73c03a',
		'#4682b4',
		'#7bc3b8',
		'#a9884e',
		'#c1b266',
		'#a47493',
		'#c09fb5'
	];

	this.schemes.munin = [
		'#00cc00',
		'#0066b3',
		'#ff8000',
		'#ffcc00',
		'#330099',
		'#990099',
		'#ccff00',
		'#ff0000',
		'#808080',
		'#008f00',
		'#00487d',
		'#b35a00',
		'#b38f00',
		'#6b006b',
		'#8fb300',
		'#b30000',
		'#bebebe',
		'#80ff80',
		'#80c9ff',
		'#ffc080',
		'#ffe680',
		'#aa80ff',
		'#ee00cc',
		'#ff8080',
		'#666600',
		'#ffbfff',
		'#00ffcc',
		'#cc6699',
		'#999900'
	];
};
<|endoftext|>