<commit_before>/*
 * pandaCommerce auto complete jQuery plugin
 * Author <anders at restfuldesign com>
 * Version 0.0.1
 */

/*global location jQuery setTimeout clearTimeout */

(function( $ ){
    "use strict";

    var defaults = {
	source: '/search.json', // search source
	notFound: 'not found',	// not found message
	asClass: 'asearch',     // dropdown list class
	visible: false,       	// initial visibility
	wrapper: '
',      // wrapper element type
	animate: 300,       	// animation time in ms
	search: 'q',         	// ajax search parameter
	delay: 200,         	// search pre-delay in ms
	chars: 3,            	// input threshold
	cache: {},		// result cache
	lt: 'ul',           	// list type
	li: 'li'            	// list item
    };

    // default query options
    defaults.query = {
	type: 'product',
	fields: ['title','url','thumbnail','price','meta_description','compare_at_price'],
	limit: 0
    };

    // search result mapping and normalization
    defaults.normalize = function(data){
	var list = data.results ? data.results.map(function(m) {
	    return {
		url: m.url,
		title:m.title,
		thumbnail:m.thumbnail,
		description: m.meta_description,
		price:m.price,
		compare_price:m.compare_at_price
	    };
	}) : [];

	return list;
    };

    function ajaxQuery(o,query){
	var cached = o.cache[o.source], q = {}, k;

	// check if we have a cached query
	if(cached) {
	    for(var key in cached) {
		if(key === query) {
		    // cache hit
		    render(o,cached[key],query);
		    return;
		}
	    }
	} else {
	    cached = o.cache[o.source] = {};
	}

	// merge query options
	if(o.query) {
	    q[o.search] = query;
	    query = $.extend({},o.query,q);
	}

	$.ajax({
	    url: o.source,
	    data: query,
	    method: o.method || 'get',
	    dataType: o.type || 'json'
	}).done(function(data){
            data = o.normalize(data);
	    cached[query] = data;
	    render(o,data,query);
	}).fail(function(e){
	    o.target.trigger('error',e);
	});

    }

    function performSearch(options,query){
	var execQuery = ajaxQuery;

	if(query) query = $.trim(query.toLowerCase());

	// when source is an array use that as datasource
	if(Array.isArray(options.source)) {
	    execQuery = function() {
		render(options,options.source,query);
	    };
	}

	// reset deferal timer
	if(options.timer) {
	    clearTimeout(options.timer);
	    options.timer = null;
	}

	// defer search requests
	options.timer = setTimeout(function() {
	    execQuery(options,query);
	}, options.delay);
    }

    function render(o,data,key){
	var elem = $(o.lt,o.elem);
	var content = '';

	// pass through user specified filtering
	if(key && typeof o.filter === 'function') {
	    return render(o,o.filter(data,key));
	}

	// keep results at target element for easy access
	o.elem.data('results',data);

	function renderList(list){
	    var h = '';

	    Object.keys(list).forEach(function(item,i){
		h+= '<'+o.li+'>\n';
		h+= '<'+o.lt+' title="'+item+'" data-row="' + i + '">\n';

		h+= renderLines(list[item]);

		h+= '</'+o.lt+'>\n';
		h+= '</'+o.li+'>\n';
	    });

	    return h;
	}

	function renderItem(item,i){
	    var h = '';
	    var title = item.title || ' ';
	    var url = item.url ?  location.protocol + item.url : undefined;
	    var discounted = !!item.compare_price;

	    h+= '<'+o.li+' title="'+title+'" data-row="' + i + '">\n';
	    h+= '
';
	    if(item.thumbnail) h+= '';
	    if(url) h+= '\n';
	    h+= '
' + title + '
\n';
	    if(item.description) h+= '
' + item.description + '
\n';
	    h+= '' + item.price;
	    if(item.compare_price) h+= '' + item.compare_price + '';
	    h+= '\n';
	    if(url) h+= '\n';
	    h+= '
';
	    h+= '</'+o.li+'>\n';

	    return h;
	}

	function renderLines(list){
	    var h = '';

	    if(typeof list === 'object'){

		if(Array.isArray(list)){

		    list.forEach(function(item){
			if(typeof item === 'string'){

			    h+= '<'+o.li+'>';
			    h+= item;
			    h+= '</'+o.li+'>\n';
			} else {
			    h+= renderItem(item);
			}
		    });
		} else {
		    Object.keys(list).forEach(function(item){
			h+= renderList(list[item]);
		    });
		}
	    } else {
		h+= '<'+o.li+'>';
		h+= list;
		h+= '</'+o.li+'>\n';
	    }

	    return h;
	}

	for(var i = 0, l = data.length; i < l; i++){

	    if(typeof data[i] === 'object'){
		content+= renderItem(data[i],i);
	    }
	    else{
		if(i === 0){
		    content+= '<'+o.li+'>\n';
		    content+= '<'+o.lt+'>\n';
		}

		content+= renderLines(data[i]);

		if(i === l-1){
		    content+= '</'+o.lt+'>\n';
		    content+= '</'+o.li+'>\n';
		}
	    }
	}

	// when empty insert not found
	if(!content) {
	    content+= '<'+o.li+'>\n';
	    content+= '<'+o.lt+' title="'+o.notFound+'">\n';
	    content+= '</'+o.lt+'>\n';
	    content+= '</'+o.li+'>\n';
	}

	elem.html(content);

	return this;
    }

    $.fn.aSearch = function(options) {
	options = options || {};

	// Note: An array can be used as data source for searches
	if(Array.isArray(options) || typeof options === 'string') options = {source: options};

        var o = $.extend({},defaults,options);
        var selector = [o.lt,o.li].join(' ');

	o.target = this;

        // create wrapper element
        if(o.wrapper.indexOf('id=') < 0) {
            var x = o.wrapper.indexOf('>');

            if(x < 0) throw new TypeError("wrapper");

            o.id =  o.asClass + '-wrapper';
            o.wrapper = o.wrapper.substr(0,x-1) + ' id="' + o.id + '" ' + o.wrapper.substr(x,o.wrapper.length);
        }

        // wrap target element
        this.wrap(o.wrapper);
        o.elem = $('#'+o.id);

	// result list
        $('<'+o.lt+' class="' + o.asClass + '"></'+o.lt+'>\n').appendTo(o.elem);
        o.listElem = $(o.lt,o.elem);

        // a toggle helper due to issues with jQuery toggle()
        Object.defineProperty(o,'toggle',{
            writable:false,
            readable: true,
            enumerable: false,
            value: function(state) {
		o.visible = state === undefined ? !o.visible : state;
		if(o.visible) o.listElem.show(o.animate);
		else o.listElem.hide(o.animate);
	    }
        });

	// toggle initial visibility
        o.toggle(o.visible);

	// if o.chars = 0, perform search on init
        if(!o.chars) performSearch(o,null);

	// attach event handlers
        o.elem.on('mousedown touchstart',selector,function(event){
            var data = o.elem.data('results');
	    var row = $(this).attr('data-row');

            o.target.trigger('selected',data[row]);
        }).on('keyup','input',function(event) {
            var keyCode = event.keyCode || event.which,
		validKey =
		    (keyCode == 8)                   || // backspace
		    (keyCode > 47 && keyCode < 58)   || // number keys
		    (keyCode > 64 && keyCode < 91)   || // letter keys
		    (keyCode > 95 && keyCode < 112)  || // numpad keys
		    (keyCode > 186 && keyCode < 192);   // =,-./

	    if(validKey) {
		if(this.value.length >= o.chars){
                    performSearch(o,this.value);
                    o.toggle(true);
		} else o.toggle(false);
            }
        }).on('click touchend','input',function(event){
            if(this.value.length >= o.chars) o.toggle();
	}).on('blur','input',function(event){
            o.toggle(false);
	});

	return this;
    };
}( jQuery ));
<commit_msg>enclose list items around  instead of
 when having target url<commit_after>/*
 * pandaCommerce auto complete jQuery plugin
 * Author <anders at restfuldesign com>
 * Version 0.0.1
 */

/*global location jQuery setTimeout clearTimeout */

(function( $ ){
    "use strict";

    var defaults = {
	source: '/search.json', // search source
	notFound: 'not found',	// not found message
	asClass: 'asearch',     // dropdown list class
	visible: false,       	// initial visibility
	wrapper: '
',      // wrapper element type
	animate: 300,       	// animation time in ms
	search: 'q',         	// ajax search parameter
	delay: 200,         	// search pre-delay in ms
	chars: 3,            	// input threshold
	cache: {},		// result cache
	lt: 'ul',           	// list type
	li: 'li'            	// list item
    };

    // default query options
    defaults.query = {
	type: 'product',
	fields: ['title','url','thumbnail','price','meta_description','compare_at_price'],
	limit: 0
    };

    // search result mapping and normalization
    defaults.normalize = function(data){
	var list = data.results ? data.results.map(function(m) {
	    return {
		url: m.url,
		title:m.title,
		thumbnail:m.thumbnail,
		description: m.meta_description,
		price:m.price,
		compare_price:m.compare_at_price
	    };
	}) : [];

	return list;
    };

    function ajaxQuery(o,query){
	var cached = o.cache[o.source], q = {}, k;

	// check if we have a cached query
	if(cached) {
	    for(var key in cached) {
		if(key === query) {
		    // cache hit
		    render(o,cached[key],query);
		    return;
		}
	    }
	} else {
	    cached = o.cache[o.source] = {};
	}

	// merge query options
	if(o.query) {
	    q[o.search] = query;
	    query = $.extend({},o.query,q);
	}

	$.ajax({
	    url: o.source,
	    data: query,
	    method: o.method || 'get',
	    dataType: o.type || 'json'
	}).done(function(data){
            data = o.normalize(data);
	    cached[query] = data;
	    render(o,data,query);
	}).fail(function(e){
	    o.target.trigger('error',e);
	});

    }

    function performSearch(options,query){
	var execQuery = ajaxQuery;

	if(query) query = $.trim(query.toLowerCase());

	// when source is an array use that as datasource
	if(Array.isArray(options.source)) {
	    execQuery = function() {
		render(options,options.source,query);
	    };
	}

	// reset deferal timer
	if(options.timer) {
	    clearTimeout(options.timer);
	    options.timer = null;
	}

	// defer search requests
	options.timer = setTimeout(function() {
	    execQuery(options,query);
	}, options.delay);
    }

    function render(o,data,key){
	var elem = $(o.lt,o.elem);
	var content = '';

	// pass through user specified filtering
	if(key && typeof o.filter === 'function') {
	    return render(o,o.filter(data,key));
	}

	// keep results at target element for easy access
	o.elem.data('results',data);

	function renderList(list){
	    var h = '';

	    Object.keys(list).forEach(function(item,i){
		h+= '<'+o.li+'>\n';
		h+= '<'+o.lt+' title="'+item+'" data-row="' + i + '">\n';

		h+= renderLines(list[item]);

		h+= '</'+o.lt+'>\n';
		h+= '</'+o.li+'>\n';
	    });

	    return h;
	}

	function renderItem(item,i){
	    var h = '';
	    var title = item.title || ' ';
	    var url = item.url ?  location.protocol + item.url : undefined;
	    var discounted = !!item.compare_price;

	    h+= '<'+o.li+' title="'+title+'" data-row="' + i + '">\n';
            if(url) h+= '\n';
	    else h+= '
';
	    if(item.thumbnail) h+= '';

	    h+= '
' + title + '
\n';
	    if(item.description) h+= '
' + item.description + '
\n';
	    h+= '' + item.price;
	    if(item.compare_price) h+= '' + item.compare_price + '';
	    h+= '\n';
	    if(url) h+= '\n';
	    else h+= '
';
	    h+= '</'+o.li+'>\n';

	    return h;
	}

	function renderLines(list){
	    var h = '';

	    if(typeof list === 'object'){

		if(Array.isArray(list)){

		    list.forEach(function(item){
			if(typeof item === 'string'){

			    h+= '<'+o.li+'>';
			    h+= item;
			    h+= '</'+o.li+'>\n';
			} else {
			    h+= renderItem(item);
			}
		    });
		} else {
		    Object.keys(list).forEach(function(item){
			h+= renderList(list[item]);
		    });
		}
	    } else {
		h+= '<'+o.li+'>';
		h+= list;
		h+= '</'+o.li+'>\n';
	    }

	    return h;
	}

	for(var i = 0, l = data.length; i < l; i++){

	    if(typeof data[i] === 'object'){
		content+= renderItem(data[i],i);
	    }
	    else{
		if(i === 0){
		    content+= '<'+o.li+'>\n';
		    content+= '<'+o.lt+'>\n';
		}

		content+= renderLines(data[i]);

		if(i === l-1){
		    content+= '</'+o.lt+'>\n';
		    content+= '</'+o.li+'>\n';
		}
	    }
	}

	// when empty insert not found
	if(!content) {
	    content+= '<'+o.li+'>\n';
	    content+= '<'+o.lt+' title="'+o.notFound+'">\n';
	    content+= '</'+o.lt+'>\n';
	    content+= '</'+o.li+'>\n';
	}

	elem.html(content);

	return this;
    }

    $.fn.aSearch = function(options) {
	options = options || {};

	// Note: An array can be used as data source for searches
	if(Array.isArray(options) || typeof options === 'string') options = {source: options};

        var o = $.extend({},defaults,options);
        var selector = [o.lt,o.li].join(' ');

	o.target = this;

        // create wrapper element
        if(o.wrapper.indexOf('id=') < 0) {
            var x = o.wrapper.indexOf('>');

            if(x < 0) throw new TypeError("wrapper");

            o.id =  o.asClass + '-wrapper';
            o.wrapper = o.wrapper.substr(0,x-1) + ' id="' + o.id + '" ' + o.wrapper.substr(x,o.wrapper.length);
        }

        // wrap target element
        this.wrap(o.wrapper);
        o.elem = $('#'+o.id);

	// result list
        $('<'+o.lt+' class="' + o.asClass + '"></'+o.lt+'>\n').appendTo(o.elem);
        o.listElem = $(o.lt,o.elem);

        // a toggle helper due to issues with jQuery toggle()
        Object.defineProperty(o,'toggle',{
            writable:false,
            readable: true,
            enumerable: false,
            value: function(state) {
		o.visible = state === undefined ? !o.visible : state;
		if(o.visible) o.listElem.show(o.animate);
		else o.listElem.hide(o.animate);
	    }
        });

	// toggle initial visibility
        o.toggle(o.visible);

	// if o.chars = 0, perform search on init
        if(!o.chars) performSearch(o,null);

	// attach event handlers
        o.elem.on('mousedown touchstart',selector,function(event){
            var data = o.elem.data('results');
	    var row = $(this).attr('data-row');

            o.target.trigger('selected',data[row]);
        }).on('keyup','input',function(event) {
            var keyCode = event.keyCode || event.which,
		validKey =
		    (keyCode == 8)                   || // backspace
		    (keyCode > 47 && keyCode < 58)   || // number keys
		    (keyCode > 64 && keyCode < 91)   || // letter keys
		    (keyCode > 95 && keyCode < 112)  || // numpad keys
		    (keyCode > 186 && keyCode < 192);   // =,-./

	    if(validKey) {
		if(this.value.length >= o.chars){
                    performSearch(o,this.value);
                    o.toggle(true);
		} else o.toggle(false);
            }
        }).on('click touchend','input',function(event){
            if(this.value.length >= o.chars) o.toggle();
	}).on('blur','input',function(event){
            o.toggle(false);
	});

	return this;
    };
}( jQuery ));
<|endoftext|>


<commit_before>
//Back/Neck/Waist
addItem(1, {'slot': 'back', 'type': 'cloak', 'name': 'Plain Cloak', 'bonuses': {'+evasion': 1, '+armor': 1, '+maxHealth': 6}, icon: 'cloak'});
addItem(2, {'slot': 'back', 'type': 'quiver', 'name': 'Quiver', 'bonuses': {'+bow:minPhysicalDamage': 2, '+bow:maxPhysicalDamage': 4}, icon: 'quiver'});
addItem(3, {'slot': 'back', 'type': 'scabbard', 'name': 'Scabbard', 'bonuses': {'+dagger:minPhysicalDamage': 1, '+dagger:maxPhysicalDamage': 2, '+sword:minPhysicalDamage': 2, '+sword:maxPhysicalDamage': 3, '+greatsword:minPhysicalDamage': 3, '+greatsword:maxPhysicalDamage': 4}, icon: 'scabbard'});
addItem(4, {'slot': 'back', 'type': 'baldric', 'name': 'Baldric', 'bonuses': {'+axe:minPhysicalDamage': 2, '+axe:maxPhysicalDamage': 3, '+polearm:minPhysicalDamage': 3, '+polearm:maxPhysicalDamage': 5}, icon: 'scabbard'});
addItem(5, {'slot': 'back', 'type': 'amulet', 'name': 'Runed Amulet', 'bonuses': {'+wand:minMagicDamage': 1, '+wand:maxMagicDamage': 2, '+staff:minMagicDamage': 2, '+staff:maxMagicDamage': 3}, icon: 'amulet'});
addItem(15, {'slot': 'back', 'type': 'cloak', 'name': 'Travelers Cloak', 'bonuses': {'+evasion': 10}, icon: 'cloak'});
addItem(16, {'slot': 'back', 'type': 'cloak', 'name': 'Fur Cloak', 'bonuses': {'+block': 10}, icon: 'cloak'});
addItem(17, {'slot': 'back', 'type': 'cloak', 'name': 'Plated Cloak', 'bonuses': {'+armor': 10}, icon: 'cloak'});

//Rings
addItem(1, {'slot': 'ring', 'type': 'ring', 'name': 'Iron Band', 'bonuses': {'+minPhysicalDamage': 2, '+maxPhysicalDamage': 4}, icon: 'band'});
addItem(2, {'slot': 'ring', 'type': 'ring', 'name': 'Gold Band', 'bonuses': {'+minMagicDamage': 1, '+maxMagicDamage': 2}, icon: 'band'});
addItem(4, {'slot': 'ring', 'type': 'ring', 'name': 'Ruby Ring', 'bonuses': {'+strength': 6}, icon: 'ring'});
addItem(5, {'slot': 'ring', 'type': 'ring', 'name': 'Emerald Ring', 'bonuses': {'+dexterity': 6}, icon: 'ring'});
addItem(6, {'slot': 'ring', 'type': 'ring', 'name': 'Sapphire Ring', 'bonuses': {'+intelligence': 6}, icon: 'ring'});
addItem(10, {'slot': 'ring', 'type': 'ring', 'name': 'Etched Band', 'bonuses': {'+magicBlock': 10}, icon: 'band'});
addItem(12, {'slot': 'ring', 'type': 'ring', 'name': 'Topaz Ring', 'bonuses': {'+strength': 3, '+dexterity': 3}, icon: 'ring'});
addItem(13, {'slot': 'ring', 'type': 'ring', 'name': 'Aquamarine Ring', 'bonuses': {'+intelligence': 3, '+dexterity': 3}, icon: 'ring'});
addItem(14, {'slot': 'ring', 'type': 'ring', 'name': 'Amethyst Ring', 'bonuses': {'+strength': 3, '+intelligence': 3}, icon: 'ring'});
addItem(19, {'slot': 'ring', 'type': 'ring', 'name': 'Diamond Ring', 'bonuses': {'+strength': 2, '+dexterity': 2, '+intelligence': 2}, icon: 'ring'});
addItem(20, {'slot': 'ring', 'type': 'ring', 'name': 'Jade Band', 'bonuses': {'+healthRegen': 5}, icon: 'band'});
addItem(22, {'slot': 'ring', 'type': 'ring', 'name': 'Meteoric Band', 'bonuses': {'%physicalDamage': .2}, icon: 'band'});
addItem(23, {'slot': 'ring', 'type': 'ring', 'name': 'Orichalcum Band', 'bonuses': {'%magicDamage': .2}, icon: 'band'});
addItem(24, {'slot': 'ring', 'type': 'ring', 'name': 'Adamantium Band', 'bonuses': {'%melee:damage': .2}, icon: 'band'});
addItem(25, {'slot': 'ring', 'type': 'ring', 'name': 'Dragonbone Band', 'bonuses': {'%ranged:damage': .2}, icon: 'band'});<commit_msg>changed quiver to affect thrown weapons<commit_after>
//Back/Neck/Waist
addItem(1, {'slot': 'back', 'type': 'cloak', 'name': 'Plain Cloak', 'bonuses': {'+evasion': 1, '+armor': 1, '+maxHealth': 6}, icon: 'cloak'});
addItem(2, {'slot': 'back', 'type': 'quiver', 'name': 'Quiver', 'bonuses': {'+bow:minPhysicalDamage': 2, '+bow:maxPhysicalDamage': 4, '+thrown:minPhysicalDamage': 2, '+thrown:maxPhysicalDamage': 3}, icon: 'quiver'});
addItem(3, {'slot': 'back', 'type': 'scabbard', 'name': 'Scabbard', 'bonuses': {'+dagger:minPhysicalDamage': 1, '+dagger:maxPhysicalDamage': 2, '+sword:minPhysicalDamage': 2, '+sword:maxPhysicalDamage': 3, '+greatsword:minPhysicalDamage': 3, '+greatsword:maxPhysicalDamage': 4}, icon: 'scabbard'});
addItem(4, {'slot': 'back', 'type': 'baldric', 'name': 'Baldric', 'bonuses': {'+axe:minPhysicalDamage': 2, '+axe:maxPhysicalDamage': 3, '+polearm:minPhysicalDamage': 3, '+polearm:maxPhysicalDamage': 5}, icon: 'scabbard'});
addItem(5, {'slot': 'back', 'type': 'amulet', 'name': 'Runed Amulet', 'bonuses': {'+wand:minMagicDamage': 1, '+wand:maxMagicDamage': 2, '+staff:minMagicDamage': 2, '+staff:maxMagicDamage': 3}, icon: 'amulet'});
addItem(15, {'slot': 'back', 'type': 'cloak', 'name': 'Travelers Cloak', 'bonuses': {'+evasion': 10}, icon: 'cloak'});
addItem(16, {'slot': 'back', 'type': 'cloak', 'name': 'Fur Cloak', 'bonuses': {'+block': 10}, icon: 'cloak'});
addItem(17, {'slot': 'back', 'type': 'cloak', 'name': 'Plated Cloak', 'bonuses': {'+armor': 10}, icon: 'cloak'});

//Rings
addItem(1, {'slot': 'ring', 'type': 'ring', 'name': 'Iron Band', 'bonuses': {'+minPhysicalDamage': 2, '+maxPhysicalDamage': 4}, icon: 'band'});
addItem(2, {'slot': 'ring', 'type': 'ring', 'name': 'Gold Band', 'bonuses': {'+minMagicDamage': 1, '+maxMagicDamage': 2}, icon: 'band'});
addItem(4, {'slot': 'ring', 'type': 'ring', 'name': 'Ruby Ring', 'bonuses': {'+strength': 6}, icon: 'ring'});
addItem(5, {'slot': 'ring', 'type': 'ring', 'name': 'Emerald Ring', 'bonuses': {'+dexterity': 6}, icon: 'ring'});
addItem(6, {'slot': 'ring', 'type': 'ring', 'name': 'Sapphire Ring', 'bonuses': {'+intelligence': 6}, icon: 'ring'});
addItem(10, {'slot': 'ring', 'type': 'ring', 'name': 'Etched Band', 'bonuses': {'+magicBlock': 10}, icon: 'band'});
addItem(12, {'slot': 'ring', 'type': 'ring', 'name': 'Topaz Ring', 'bonuses': {'+strength': 3, '+dexterity': 3}, icon: 'ring'});
addItem(13, {'slot': 'ring', 'type': 'ring', 'name': 'Aquamarine Ring', 'bonuses': {'+intelligence': 3, '+dexterity': 3}, icon: 'ring'});
addItem(14, {'slot': 'ring', 'type': 'ring', 'name': 'Amethyst Ring', 'bonuses': {'+strength': 3, '+intelligence': 3}, icon: 'ring'});
addItem(19, {'slot': 'ring', 'type': 'ring', 'name': 'Diamond Ring', 'bonuses': {'+strength': 2, '+dexterity': 2, '+intelligence': 2}, icon: 'ring'});
addItem(20, {'slot': 'ring', 'type': 'ring', 'name': 'Jade Band', 'bonuses': {'+healthRegen': 5}, icon: 'band'});
addItem(22, {'slot': 'ring', 'type': 'ring', 'name': 'Meteoric Band', 'bonuses': {'%physicalDamage': .2}, icon: 'band'});
addItem(23, {'slot': 'ring', 'type': 'ring', 'name': 'Orichalcum Band', 'bonuses': {'%magicDamage': .2}, icon: 'band'});
addItem(24, {'slot': 'ring', 'type': 'ring', 'name': 'Adamantium Band', 'bonuses': {'%melee:damage': .2}, icon: 'band'});
addItem(25, {'slot': 'ring', 'type': 'ring', 'name': 'Dragonbone Band', 'bonuses': {'%ranged:damage': .2}, icon: 'band'});<|endoftext|>


<commit_before>import gulp from 'gulp';
import chalk from 'chalk';
import touch from 'gulp-touch';
import bump from 'gulp-bump';
import semver from 'semver';

import {pkgJson} from '../config';
import onError from '../onError';
import {args, hasBumpType} from '../commandLineArgs';

/**
 * Bumps version in package.json.
 * Used in release task.
 */
function bumpVersion() {
	if (!hasBumpType()) {
		onError(new Error(chalk.red('Please specify release type: gulp release --bump (major|minor|patch)')));
	}

	pkgJson.version = semver.inc(pkgJson.version, args.bump, args['prerelease-identifier']);

	return gulp.src('./package.json')
		.pipe(bump({
			type: args.bump,
			preid: args['prerelease-identifier']
		}))
		.on('error', onError)
		.pipe(gulp.dest('./'))
		.pipe(touch());
}

export default bumpVersion;
<commit_msg>fix(release): Bump version number in package-lock.json as well<commit_after>import gulp from 'gulp';
import chalk from 'chalk';
import touch from 'gulp-touch';
import bump from 'gulp-bump';
import semver from 'semver';

import {pkgJson} from '../config';
import onError from '../onError';
import {args, hasBumpType} from '../commandLineArgs';

/**
 * Bumps version in package.json.
 * Used in release task.
 */
function bumpVersion() {
	if (!hasBumpType()) {
		onError(new Error(chalk.red('Please specify release type: gulp release --bump (major|minor|patch)')));
	}

	pkgJson.version = semver.inc(pkgJson.version, args.bump, args['prerelease-identifier']);

	return gulp.src(['./package.json', './package-lock.json'])
		.pipe(bump({
			type: args.bump,
			preid: args['prerelease-identifier']
		}))
		.on('error', onError)
		.pipe(gulp.dest('./'))
		.pipe(touch());
}

export default bumpVersion;
<|endoftext|>


<commit_before>// This module returns the accented version(s) of a word.

var vowels = ['a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y'];
var consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'z'];
var longs = ['ā', 'ē', 'ī', 'ō', 'ū', 'ȳ', 'Ā', 'Ē', 'Ī', 'Ō', 'Ū', 'Ȳ'];
var breves = ['ă', 'ĕ', 'ĭ', 'ŏ', 'ŭ', 'ў', 'Ă', 'Ĕ', 'Ĭ', 'Ŏ', 'Ŭ', 'Ў'];
var accented = ['á', 'é', 'í', 'ó', 'ú', 'ý'];
var uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z'];
var lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z'];

function accentify(word, uppercase){
    var found = search_quantified(word);
    if(found.length == 0){
        // If uppercase, lowercase and retry:
        if(uppercase){
            found = search_quantified(to_lowercase(word));
            for(var f in found){
                if(f != ''){
                    found.push(to_uppercase(found[f]));
                }
            }
        }
    }

    // If enclitics, remove enclitic and retry:
    // -que:
    if(word.indexOf('que') == word.length - 3){
        var sub_word = word.substring(0, word.length - 3);
        var sub_found = search_quantified(sub_word);
        if(sub_found.length != 0){
            found.push(last_long(sub_word) + 'quĕ');
        }
        // If uppercase, lowercase and retry:
        else if(uppercase){
            sub_found = search_quantified(to_lowercase(sub_word));
            if(sub_found.length != 0){
                found.push(last_long(sub_word) + 'quĕ');
            }
        }
    }
    // -ne:
    if(word.indexOf('ne') == word.length - 2){
        var sub_word = word.substring(0, word.length - 2);
        var sub_found = search_quantified(sub_word);
        if(sub_found.length != 0){
            found.push(last_long(sub_word) + 'nĕ');
        }
        // If uppercase, lowercase and retry:
        else if(uppercase){
            sub_found = search_quantified(to_lowercase(sub_word));
            if(sub_found.length != 0){
                found.push(last_long(sub_word) + 'nĕ');
            }
        }
    }
    // -ve:
    if(word.indexOf('ve') == word.length - 2){
        var sub_word = word.substring(0, word.length - 2);
        var sub_found = search_quantified(sub_word);
        if(sub_found.length != 0){
            found.push(last_long(sub_word) + 'vĕ');
        }
        // If uppercase, lowercase and retry:
        else if(uppercase){
            sub_found = search_quantified(to_lowercase(sub_word));
            if(sub_found.length != 0){
                found.push(last_long(sub_word) + 'vĕ');
            }
        }
    }

    if(found.length == 0){
        if(word.search(/[!?:;]/) == -1 && count_vowels(word) > 2){
            found.push('' + word + '');
        }
        else{
            found.push(word);
        }
    }
    else{
        for(var f in found){
            found[f] = qty_to_accent(word, found[f])[1];
        }
    }
    return(reduce(found));
}

// Returns an array of all the combinations of roots and terminations that can give word:
function search_quantified(word){
    // We successively split the word into 2 splinters, like this for a word of five letters:
    // |12345, then 1|2345, then 12|345, then 123|45, then 1234|5, then 12345,
    // and each time we search if we find these 2 splinters
    // in our roots' and terminations' Objects:
    var found = [];
    for(var i = 0; i <= word.length; i++){
        var root = word.substring(0, i);
        var term = word.substring(i, word.length);
        if(roots[root] != null && terminations[term] != null){
            for(var sub_root in roots[root]){
                r = roots[root][sub_root]
                var quantified = r[0];
                var model = r[1];
                var num_root = r[2];
                if(root == word && (model == 'inv' || models[model]['roots'][num_root] == 'K')){
                    found.push(quantified);
                }
                else{
                    for(var sub_t in terminations[term]){
                        t = terminations[term][sub_t]
                        if(t[1] == model && t[2] == num_root){
                            found.push(quantified + t[0]);
                        }
                    }
                }
            }
        }
    }

    // A word in '-sti' ('-stis') can be a syncopated form ('amasti' for 'amavisti'):
    if(word.indexOf('sti') == word.length - 3 && word.length > 3){
        /(\S*)([aeiou])sti/.exec(word);
        found.push(RegExp.$1 + longs[vowels.indexOf(RegExp.$2)] + 'stī');
    }
    if(word.indexOf('stis') == word.length - 4 && word.length > 4){
        /(\S*)([aeiou])stis/.exec(word);
        found.push(RegExp.$1 + longs[vowels.indexOf(RegExp.$2)] + 'stĭs');
    }
    return(found);
}

// Converts a quantified word into an accented one:
function qty_to_accent(plain, quantified){
    var with_accents = plain;
    var plain_split = plain.split('');
    var quantified_split = quantified.split('');
    var accentable = false;
    var quantities = [quantified.length]; // Will contains something like ['0', '+', '0', '0', '-', '-'].
    var num_syllables = 0;

    // We note the quantities of all the vowels of the word, and we count the syllables:
    for(var i in quantified){
        var c = quantified[i];
        // 1. Vowels without quantities:
        if(vowels.indexOf(c) != -1){
            // Vowel without quantity is considered as a breve, except 'u' after 'q' and 'e' after 'ā' (because 'sāeculum' is different of 'āĕris'):
            if((plain[i] == 'u' && ['Q', 'q'].indexOf(plain[i - 1]) != -1) || (c == 'e' && quantified[i - 1] == 'ā')){
                quantities[i] = '0';
            }
            else{
                quantities[i] = '-';
            }

            // If c is not the second letter of 'au', 'eu', 'ae', 'oe', 'qu', 'gu', add a syllable:
            if((['e', 'u'].indexOf(plain[i]) != -1 && ['a', 'e', 'o', 'A', 'E', 'q', 'g'].indexOf(plain[i - 1]) != -1) == false){
                num_syllables ++;
            }
        }

        // 2. Vowels with quantities:
        else if(longs.indexOf(c) != -1){
            quantities[i] = '+';
            num_syllables ++;
        }
        else if(breves.indexOf(c) != -1){
            quantities[i] = '-';
            num_syllables ++;
        }
        else if(c == '\u0306'){ // Combining breve => there are two quantities, and we set the 1st to 'breve'.
            quantities[i - 1] = '-';
            quantities[i] = 'c';
        }

        // 3. Others (consonantics):
        else{
            quantities[i] = '0';
        }
    }

    // We remove the combining breve characters:
    var quantities = quantities.filter(function(item){
        return item != 'c';
    });
    var quantified_split = quantified_split.filter(function(item){
        return item != '\u0306';
    });

    // Then we accentify:
    if(num_syllables > 2){ // Ignore words of less than 3 syllables (never accented).
        accentable = true;
        var nb_vowels = 0; // Will count the 3 last syllables (antepenult., penult., ult.).
        var accent_pos = 0; // Will contain the position of accent.
        for(var i in quantities){
            var qty = quantities[quantities.length -i - 1];
            var prev_qty = quantities[quantities.length -i - 2];
            if(qty != '0'){ // Not a consonantic.
                nb_vowels ++;
                if((nb_vowels == 2 && qty == '+') || (nb_vowels == 3 && accent_pos == 0)){
                    if(['e', 'u'].indexOf(plain_split[quantities.length - i - 1]) != -1 && ['a', 'e', 'o', 'A', 'E', 'U'].indexOf(plain_split[quantities.length - i - 2]) != -1){ // 'ae', 'oe', 'au': accent on the first letter (except diphtongs).
                        if(qty == '-' && prev_qty == '+'){
                            accent_pos = quantities.length - i;
                        }
                        else if(qty == '0' && prev_qty == '-'){
                            accent_pos = quantities.length - i;
                        }
                        else{
                            accent_pos = quantities.length - i - 1;
                        }
                    }
                    else{
                        accent_pos = quantities.length - i;
                    }
                }
            }
        }

        if(vowels.indexOf(plain[accent_pos - 1]) < 6 && num_syllables > 2){ // Never accentify an uppercase, nor a word of less than 3 syllables (elsewhere, for ex., coepit will be accented on 'oe').
            plain_split[accent_pos - 1] = accented[vowels.indexOf(plain[accent_pos - 1])];

            // áe (if e has no quantity):
            if(plain_split[accent_pos - 1] == 'á' && quantified_split[accent_pos] == 'e'){
                plain_split[accent_pos - 1] = '\u01FD';
                plain_split[accent_pos] = '';
            }
            // óe (if e has no quantity):
            if(plain_split[accent_pos - 1] == 'ó' && quantified_split[accent_pos] == 'e'){
                plain_split[accent_pos - 1] = 'œ\u0301';
                plain_split[accent_pos] = '';
            }
        }
    }

    // ae and oe => æ and œ (if e has no quantity):
    for(var i = 0; i < plain_split.length; i++){
        if(plain_split[i] == 'a' && quantified_split[i + 1] == 'e'){
            plain_split[i] = 'æ';
            plain_split[i + 1] = '';
        }
        if(plain_split[i] == 'o' && quantified_split[i + 1] == 'e'){
            plain_split[i] = 'œ';
            plain_split[i + 1] = '';
        }
    }
    with_accents = plain_split.join('');
    return([accentable, with_accents]);
}

// Counts the number of vowels in a word:
function count_vowels(word){
    var num_v = 0;
    for(var i in word){
        if(vowels.indexOf(word[i]) != -1){
            if(!(word[i] == 'u'  && ['q', 'g'].indexOf(word[i - 1]) != -1)){
                num_v ++;
            }
        }
    }
    return(num_v);
}

// Returns true if the first letter of 'word' is uppercase:
function is_uppercase(word){
    return(uppercase.indexOf(word.charAt(0)) != -1 ? true : false);
}

// Word => word:
function to_lowercase(word){
    var word_split = word.split('');
    word_split[0] = lowercase[uppercase.indexOf(word[0])];
    return(word_split.join(''));
}

// word => Word:
function to_uppercase(word){
    var word_split = word.split('');

    // Case of an initial 'A' which becomes a long or a breve 'a':
    if(longs.indexOf(word_split[0]) != -1){
        word_split[0] = vowels[longs.indexOf(word_split[0])];
    }
    if(breves.indexOf(word_split[0]) != -1){
        word_split[0] = vowels[breves.indexOf(word_split[0])];
    }

    word_split[0] = uppercase[lowercase.indexOf(word_split[0])];
    return(word_split.join(''));
}

// Eliminates all the redundances in an array of accented words:
function reduce(this_array){
    var result = [];
    for(var i in this_array){
        if(result.indexOf(this_array[i]) == -1){
            result.push(this_array[i]);
        }
    }
    return(result);
}

// Returns a word with his last vowel long (useful with enclitics):
function last_long(word){
    /(\S*)([aeiouy])([bcdfghjklmnpqrstvxz]*)/.exec(word)
    return(RegExp.$1 + longs[vowels.indexOf(RegExp.$2)] + RegExp.$3);
}

<commit_msg>Secondary forms treated ('aff-' for 'adf-', 'ex-' for 'exs-').<commit_after>// This module returns the accented version(s) of a word.

var vowels = ['a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y'];
var consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'z'];
var longs = ['ā', 'ē', 'ī', 'ō', 'ū', 'ȳ', 'Ā', 'Ē', 'Ī', 'Ō', 'Ū', 'Ȳ'];
var breves = ['ă', 'ĕ', 'ĭ', 'ŏ', 'ŭ', 'ў', 'Ă', 'Ĕ', 'Ĭ', 'Ŏ', 'Ŭ', 'Ў'];
var accented = ['á', 'é', 'í', 'ó', 'ú', 'ý'];
var uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z'];
var lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z'];

function accentify(word, uppercase){
    var found = search_quantified(word);

    // If fail, try something else:
    // If uppercase, lowercase and retry:
    if(found.length == 0 && uppercase){
        var sub_found = search_quantified(to_lowercase(word));
        for(var s in sub_found){
            if(s != ''){
                found.push(to_uppercase(sub_found[s]));
            }
        }
    }

    // If word begins with 'ex-', it can be a secondary form ('expecto' for 'exspecto'):
    if(found.length == 0 && word.indexOf('ex') == 0){
        var sub_found = search_quantified(word.replace(/^ex/g, 'exs'));
        for(var s in sub_found){
            if(s != ''){
                found.push(sub_found[s].replace(/^([ēĕ])xs/g, '$1x'));
            }
        }
    }

    // If word begins with 'aff-', it can be a secondary form ('affero' for 'adfero'):
    if(found.length == 0 && word.indexOf('aff') == 0){
        var sub_found = search_quantified(word.replace(/^aff/g, 'adf'));
        for(var s in sub_found){
            if(s != ''){
                found.push(sub_found[s].replace(/^([āă])df/g, '$1ff'));
            }
        }
    }

    // If enclitics, remove enclitic and retry:
    // -que:
    if(word.indexOf('que') == word.length - 3){
        var sub_word = word.substring(0, word.length - 3);
        var sub_found = search_quantified(sub_word);
        if(sub_found.length != 0){
            found.push(last_long(sub_word) + 'quĕ');
        }
        // If uppercase, lowercase and retry:
        else if(uppercase){
            sub_found = search_quantified(to_lowercase(sub_word));
            if(sub_found.length != 0){
                found.push(last_long(sub_word) + 'quĕ');
            }
        }
    }
    // -ne:
    if(word.indexOf('ne') == word.length - 2){
        var sub_word = word.substring(0, word.length - 2);
        var sub_found = search_quantified(sub_word);
        if(sub_found.length != 0){
            found.push(last_long(sub_word) + 'nĕ');
        }
        // If uppercase, lowercase and retry:
        else if(uppercase){
            sub_found = search_quantified(to_lowercase(sub_word));
            if(sub_found.length != 0){
                found.push(last_long(sub_word) + 'nĕ');
            }
        }
    }
    // -ve:
    if(word.indexOf('ve') == word.length - 2){
        var sub_word = word.substring(0, word.length - 2);
        var sub_found = search_quantified(sub_word);
        if(sub_found.length != 0){
            found.push(last_long(sub_word) + 'vĕ');
        }
        // If uppercase, lowercase and retry:
        else if(uppercase){
            sub_found = search_quantified(to_lowercase(sub_word));
            if(sub_found.length != 0){
                found.push(last_long(sub_word) + 'vĕ');
            }
        }
    }

    if(found.length == 0){
        if(word.search(/[!?:;]/) == -1 && count_vowels(word) > 2){
            found.push('' + word + '');
        }
        else{
            found.push(word);
        }
    }
    else{
        for(var f in found){
            found[f] = qty_to_accent(word, found[f])[1];
        }
    }
    return(reduce(found));
}

// Returns an array of all the combinations of roots and terminations that can give word:
function search_quantified(word){
    // We successively split the word into 2 splinters, like this for a word of five letters:
    // |12345, then 1|2345, then 12|345, then 123|45, then 1234|5, then 12345,
    // and each time we search if we find these 2 splinters
    // in our roots' and terminations' Objects:
    var found = [];
    for(var i = 0; i <= word.length; i++){
        var root = word.substring(0, i);
        var term = word.substring(i, word.length);
        if(roots[root] != null && terminations[term] != null){
            for(var sub_root in roots[root]){
                r = roots[root][sub_root]
                var quantified = r[0];
                var model = r[1];
                var num_root = r[2];
                if(root == word && (model == 'inv' || models[model]['roots'][num_root] == 'K')){
                    found.push(quantified);
                }
                else{
                    for(var sub_t in terminations[term]){
                        t = terminations[term][sub_t]
                        if(t[1] == model && t[2] == num_root){
                            found.push(quantified + t[0]);
                        }
                    }
                }
            }
        }
    }

    // A word in '-sti' ('-stis') can be a syncopated form ('amasti' for 'amavisti'):
    if(word.indexOf('sti') == word.length - 3 && word.length > 3){
        /(\S*)([aeiou])sti/.exec(word);
        found.push(RegExp.$1 + longs[vowels.indexOf(RegExp.$2)] + 'stī');
    }
    if(word.indexOf('stis') == word.length - 4 && word.length > 4){
        /(\S*)([aeiou])stis/.exec(word);
        found.push(RegExp.$1 + longs[vowels.indexOf(RegExp.$2)] + 'stĭs');
    }
    return(found);
}

// Converts a quantified word into an accented one:
function qty_to_accent(plain, quantified){
    var with_accents = plain;
    var plain_split = plain.split('');
    var quantified_split = quantified.split('');
    var accentable = false;
    var quantities = [quantified.length]; // Will contains something like ['0', '+', '0', '0', '-', '-'].
    var num_syllables = 0;

    // We note the quantities of all the vowels of the word, and we count the syllables:
    for(var i in quantified){
        var c = quantified[i];
        // 1. Vowels without quantities:
        if(vowels.indexOf(c) != -1){
            // Vowel without quantity is considered as a breve, except 'u' after 'q' and 'e' after 'ā' (because 'sāeculum' is different of 'āĕris'):
            if((plain[i] == 'u' && ['Q', 'q'].indexOf(plain[i - 1]) != -1) || (c == 'e' && quantified[i - 1] == 'ā')){
                quantities[i] = '0';
            }
            else{
                quantities[i] = '-';
            }

            // If c is not the second letter of 'au', 'eu', 'ae', 'oe', 'qu', 'gu', add a syllable:
            if((['e', 'u'].indexOf(plain[i]) != -1 && ['a', 'e', 'o', 'A', 'E', 'q', 'g'].indexOf(plain[i - 1]) != -1) == false){
                num_syllables ++;
            }
        }

        // 2. Vowels with quantities:
        else if(longs.indexOf(c) != -1){
            quantities[i] = '+';
            num_syllables ++;
        }
        else if(breves.indexOf(c) != -1){
            quantities[i] = '-';
            num_syllables ++;
        }
        else if(c == '\u0306'){ // Combining breve => there are two quantities, and we set the 1st to 'breve'.
            quantities[i - 1] = '-';
            quantities[i] = 'c';
        }

        // 3. Others (consonantics):
        else{
            quantities[i] = '0';
        }
    }

    // We remove the combining breve characters:
    var quantities = quantities.filter(function(item){
        return item != 'c';
    });
    var quantified_split = quantified_split.filter(function(item){
        return item != '\u0306';
    });

    // Then we accentify:
    if(num_syllables > 2){ // Ignore words of less than 3 syllables (never accented).
        accentable = true;
        var nb_vowels = 0; // Will count the 3 last syllables (antepenult., penult., ult.).
        var accent_pos = 0; // Will contain the position of accent.
        for(var i in quantities){
            var qty = quantities[quantities.length -i - 1];
            var prev_qty = quantities[quantities.length -i - 2];
            if(qty != '0'){ // Not a consonantic.
                nb_vowels ++;
                if((nb_vowels == 2 && qty == '+') || (nb_vowels == 3 && accent_pos == 0)){
                    if(['e', 'u'].indexOf(plain_split[quantities.length - i - 1]) != -1 && ['a', 'e', 'o', 'A', 'E', 'U'].indexOf(plain_split[quantities.length - i - 2]) != -1){ // 'ae', 'oe', 'au': accent on the first letter (except diphtongs).
                        if(qty == '-' && prev_qty == '+'){
                            accent_pos = quantities.length - i;
                        }
                        else if(qty == '0' && prev_qty == '-'){
                            accent_pos = quantities.length - i;
                        }
                        else{
                            accent_pos = quantities.length - i - 1;
                        }
                    }
                    else{
                        accent_pos = quantities.length - i;
                    }
                }
            }
        }

        if(vowels.indexOf(plain[accent_pos - 1]) < 6 && num_syllables > 2){ // Never accentify an uppercase, nor a word of less than 3 syllables (elsewhere, for ex., coepit will be accented on 'oe').
            plain_split[accent_pos - 1] = accented[vowels.indexOf(plain[accent_pos - 1])];

            // áe (if e has no quantity):
            if(plain_split[accent_pos - 1] == 'á' && quantified_split[accent_pos] == 'e'){
                plain_split[accent_pos - 1] = '\u01FD';
                plain_split[accent_pos] = '';
            }
            // óe (if e has no quantity):
            if(plain_split[accent_pos - 1] == 'ó' && quantified_split[accent_pos] == 'e'){
                plain_split[accent_pos - 1] = 'œ\u0301';
                plain_split[accent_pos] = '';
            }
        }
    }

    // ae and oe => æ and œ (if e has no quantity):
    for(var i = 0; i < plain_split.length; i++){
        if(plain_split[i] == 'a' && quantified_split[i + 1] == 'e'){
            plain_split[i] = 'æ';
            plain_split[i + 1] = '';
        }
        if(plain_split[i] == 'o' && quantified_split[i + 1] == 'e'){
            plain_split[i] = 'œ';
            plain_split[i + 1] = '';
        }
    }
    with_accents = plain_split.join('');
    return([accentable, with_accents]);
}

// Counts the number of vowels in a word:
function count_vowels(word){
    var num_v = 0;
    for(var i in word){
        if(vowels.indexOf(word[i]) != -1){
            if(!(word[i] == 'u'  && ['q', 'g'].indexOf(word[i - 1]) != -1)){
                num_v ++;
            }
        }
    }
    return(num_v);
}

// Returns true if the first letter of 'word' is uppercase:
function is_uppercase(word){
    return(uppercase.indexOf(word.charAt(0)) != -1 ? true : false);
}

// Word => word:
function to_lowercase(word){
    var word_split = word.split('');
    word_split[0] = lowercase[uppercase.indexOf(word[0])];
    return(word_split.join(''));
}

// word => Word:
function to_uppercase(word){
    var word_split = word.split('');

    // Case of an initial 'A' which becomes a long or a breve 'a':
    if(longs.indexOf(word_split[0]) != -1){
        word_split[0] = vowels[longs.indexOf(word_split[0])];
    }
    if(breves.indexOf(word_split[0]) != -1){
        word_split[0] = vowels[breves.indexOf(word_split[0])];
    }

    word_split[0] = uppercase[lowercase.indexOf(word_split[0])];
    return(word_split.join(''));
}

// Eliminates all the redundances in an array of accented words:
function reduce(this_array){
    var result = [];
    for(var i in this_array){
        if(result.indexOf(this_array[i]) == -1){
            result.push(this_array[i]);
        }
    }
    return(result);
}

// Returns a word with his last vowel long (useful with enclitics):
function last_long(word){
    /(\S*)([aeiouy])([bcdfghjklmnpqrstvxz]*)/.exec(word)
    return(RegExp.$1 + longs[vowels.indexOf(RegExp.$2)] + RegExp.$3);
}

<|endoftext|>


<commit_before>'use strict';
(function (angular) {
  angular
    .module('eventsManualPluginContent')
    .controller('ContentEventCtrl', ['$scope', '$routeParams', 'Buildfire', 'DataStore', 'TAG_NAMES', 'ADDRESS_TYPE', '$location', 'Utils', '$timeout',
      function ($scope, $routeParams, Buildfire, DataStore, TAG_NAMES, ADDRESS_TYPE, $location, Utils, $timeout) {
        var ContentEvent = this;
        var _data = {
          "title": "",
          "listImage": "",
          "deepLinkUrl": "",
          "carouselImages": [],
          "startDate": "",
          "endDate": "",
          "isAllDay": "",
          "timezone": "",
          "timeDisplay": {},
          "repeat": {},
          "addressTitle": "",
          "address": {},
          "description": "",
          "links": []

        };

        ContentEvent.event = {
          data: angular.copy(_data)
        };
        ContentEvent.isUpdating = false;
        ContentEvent.isNewEventInserted = false;
        ContentEvent.unchangedData = true;
        ContentEvent.displayTiming = "SELECTED";

        function isValidEvent(event) {
          return event.startDate || event.title;
        }

        updateMasterEvent(ContentEvent.event);

        function updateMasterEvent(event) {
          ContentEvent.masterEvent = angular.copy(event);
        }

        function isUnchanged(event) {
          return angular.equals(event, ContentEvent.masterEvent);
        }

        ContentEvent.getItem = function (id) {
          var successEvents = function (result) {
            ContentEvent.event = result;
            if (ContentEvent.event.data.startDate)
              ContentEvent.event.data.startDate = new Date(result.data.startDate);
            if (ContentEvent.event.data.endDate)
              ContentEvent.event.data.endDate = new Date(result.data.endDate);
            if (ContentEvent.event.data.startTime)
              ContentEvent.event.data.startTime = new Date(result.data.startTime);
            if (ContentEvent.event.data.endTime)
              ContentEvent.event.data.endTime = new Date(result.data.endTime);
            if (ContentEvent.event.data.address && ContentEvent.event.data.address.location) {
              ContentEvent.currentAddress = ContentEvent.event.data.address.location;
              ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
            }
            _data.dateCreated = result.data.dateCreated;
            updateMasterEvent(ContentEvent.event);
          }, errorEvents = function () {
            throw console.error('There was a problem fetching your data', err);
          };
          DataStore.getById(id, TAG_NAMES.EVENTS_MANUAL).then(successEvents, errorEvents);
        };

        if ($routeParams.id) {
          ContentEvent.getItem($routeParams.id);
        }

        ContentEvent.TimeZoneDropdownOptions = [
          {name: "(GMT -12:00) Eniwetok, Kwajalein", value: "-12.0"},
          {name: "(GMT -11:00) Midway Island, Samoa", value: "-11.0"},
          {name: "(GMT -10:00) Hawaii", value: "-10.0"},
          {name: "(GMT -9:00) Alaska", value: "-9.0"},
          {name: "(GMT -8:00) Pacific Time (US & Canada)", value: "-8.0"},
          {name: "(GMT -7:00) Mountain Time (US & Canada)", value: "-7:00"},
          {
            name: "(GMT -6:00) Central Time (US & Canada), Mexico City",
            value: "-6:00"
          },
          {
            name: "(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima",
            value: "-5:00"
          },
          {
            name: "(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz",
            value: "-4:00"
          },
          {name: "(GMT -3:30) Newfoundland", value: "-3:30"},
          {
            name: "(GMT -3:00) Brazil, Buenos Aires, Georgetown",
            value: "-3:00"
          },
          {name: "(GMT -2:00) Mid-Atlantic", value: "-2:00"},
          {name: "(GMT -1:00) Azores, Cape Verde Islands", value: "-1:00"},
          {
            name: "(GMT) Western Europe Time, London, Lisbon, Casablanca",
            value: "0.0"
          },
          {
            name: "(GMT +1:00 hour) Brussels, Copenhagen, Madrid, Paris",
            value: "1.0"
          },
          {name: "(GMT +2:00) Kaliningrad, South Africa", value: "2:00"},
          {
            name: "(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg",
            value: "3:00"
          },
          {name: "(GMT +3:30) Tehran", value: "3:30"},
          {name: "(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi", value: "4:00"},
          {name: "(GMT +4:30) Kabul", value: "4:30"},
          {
            name: "(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent",
            value: "5:00"
          },
          {
            name: "(GMT +5:30) Bombay, Calcutta, Madras, New Delhi",
            value: '5:30'
          },
          {name: "(GMT +5:45) Kathmandu", value: "5:45"},
          {name: "(GMT +6:00) Almaty, Dhaka, Colombo", value: '6:00'},
          {name: "(GMT +7:00) Bangkok, Hanoi, Jakarta", value: "7:00"},
          {
            name: "(GMT +8:00) Beijing, Perth, Singapore, Hong Kong",
            value: "8:00"
          },
          {
            name: "(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk",
            value: "9:00"
          },
          {name: "(GMT +9:30) Adelaide, Darwin", value: "9:30"},
          {
            name: "(GMT +10:00) Eastern Australia, Guam, Vladivostok",
            value: "10:00"
          },
          {
            name: "(GMT +11:00) Magadan, Solomon Islands, New Caledonia",
            value: "11:00"
          },
          {
            name: "(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka",
            value: "12:00"
          }

        ];

        ContentEvent.descriptionWYSIWYGOptions = {
          plugins: 'advlist autolink link image lists charmap print preview',
          skin: 'lightgray',
          trusted: true,
          theme: 'modern'
        };

        /**
         * link and sortable options
         */
        var linkOptions = {"icon": "true"};
        ContentEvent.linksSortableOptions = {
          handle: '> .cursor-grab'
        };

        ContentEvent.validCoordinatesFailure = false;

        // create a new instance of the buildfire carousel editor
        var editor = new Buildfire.components.carousel.editor("#carousel");
        // this method will be called when a new item added to the list
        editor.onAddItems = function (items) {
          if (!ContentEvent.event.carouselImages)
            ContentEvent.event.carouselImages = [];
          ContentEvent.event.carouselImages.push.apply(ContentEvent.event.carouselImages, items);
          $scope.$digest();
        };
        // this method will be called when an item deleted from the list
        editor.onDeleteItem = function (item, index) {
          ContentEvent.event.carouselImages.splice(index, 1);
          $scope.$digest();
        };
        // this method will be called when you edit item details
        editor.onItemChange = function (item, index) {
          ContentEvent.event.carouselImages.splice(index, 1, item);
          $scope.$digest();
        };
        // this method will be called when you change the order of items
        editor.onOrderChange = function (item, oldIndex, newIndex) {
          var temp = ContentEvent.event.carouselImages[oldIndex];
          ContentEvent.event.carouselImages[oldIndex] = ContentEvent.event.carouselImages[newIndex];
          ContentEvent.event.carouselImages[newIndex] = temp;
          $scope.$digest();
        };

        ContentEvent.addNewEvent = function () {
          ContentEvent.isNewEventInserted = true;
          ContentEvent.event.data.dateCreated = +new Date();
          var successEvents = function (result) {
            console.log("Inserted", result.id);
            ContentEvent.isUpdating = false;
            ContentEvent.event.id = result.id;
            _data.dateCreated = ContentEvent.event.data.dateCreated;
            updateMasterEvent(ContentEvent.event);
            ContentEvent.event.data.deepLinkUrl = Buildfire.deeplink.createLink({id: result.id});
          }, errorEvents = function () {
            ContentEvent.isNewEventInserted = false;
            return console.error('There was a problem saving your data');
          };
          DataStore.insert(ContentEvent.event.data, TAG_NAMES.EVENTS_MANUAL).then(successEvents, errorEvents);
        };

        ContentEvent.updateEventData = function () {
          DataStore.update(ContentEvent.event.id, ContentEvent.event.data, TAG_NAMES.EVENTS_MANUAL, function (err) {
            ContentEvent.isUpdating = false;
            if (err)
              return console.error('There was a problem saving your data');
          })
        };

        var tmrDelayForEvent = null;

        var updateItemsWithDelay = function (event) {
          clearTimeout(tmrDelayForEvent);
          ContentEvent.isUpdating = false;
          ContentEvent.unchangedData = angular.equals(_data, ContentEvent.event.data);

          ContentEvent.isEventValid = isValidEvent(ContentEvent.event.data);
          if (!ContentEvent.isUpdating && !isUnchanged(ContentEvent.event) && ContentEvent.isEventValid) {
            tmrDelayForEvent = setTimeout(function () {
              if (event.id) {
                ContentEvent.updateEventData();
              } else if (!ContentEvent.isNewEventInserted) {
                ContentEvent.addNewEvent();
              }
            }, 300);
          }
        };

        ContentEvent.changeTimeZone = function (timezone) {
          ContentEvent.event.timezone = timezone;
        };

        ContentEvent.changeRepeatType = function (type) {
          ContentEvent.event.repeat = {};
          ContentEvent.event.repeat.isRepeating = true;
          ContentEvent.event.repeat.repeatType = type;
        };

        /**
         * Add dynamic link
         */

        ContentEvent.addLink = function () {
          var options = {showIcons: false};
          var callback = function (error, result) {
            if (error) {
              return console.error('Error:', error);
            }
            if (!ContentEvent.event.data.links)
              ContentEvent.event.data.links = [];
            ContentEvent.event.data.links.push(result);
            $scope.$digest();
          };
          Buildfire.actionItems.showDialog(null, options, callback);
        };

        /**
         * Remove dynamic link
         */

        ContentEvent.removeLink = function (index) {
          if (ContentEvent.event.data && ContentEvent.event.data.links) {
            ContentEvent.event.data.links.splice(index, 1);
          }
        };

        /**
         * Edit dynamic link
         */

        ContentEvent.editLink = function (link, index) {
          Buildfire.actionItems.showDialog(link, linkOptions, function editLinkCallback(error, result) {
            if (error) {
              return console.error('Error:', error);
            }
            if (!ContentEvent.event.data.links) {
              ContentEvent.event.data.links = [];
            }
            if (result === null) {
              return console.error('Error:Can not save data, Null record found.');
            }
            ContentEvent.event.data.links.splice(index, 1, result);
            $scope.$digest();
          });
        };

        /**
         * Save selected place from google autocomplete as address
         */

        ContentEvent.setLocation = function (data) {
          ContentEvent.event.data.address = {
            type: ADDRESS_TYPE.LOCATION,
            location: data.location,
            location_coordinates: data.coordinates
          };
          ContentEvent.currentAddress = ContentEvent.event.data.address.location;
          ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
          $scope.$digest();
        };

        /**
         * Change the address and map to dragged marker location
         */

        ContentEvent.setDraggedLocation = function (data) {
          ContentEvent.event.data.address = {
            type: ADDRESS_TYPE.LOCATION,
            location: data.location,
            location_coordinates: data.coordinates
          };
          ContentEvent.currentAddress = ContentEvent.event.data.address.location;
          ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
          $scope.$digest();
        };

        /* Build fire thumbnail component to add thumbnail image*/
        var listImage = new Buildfire.components.images.thumbnail("#listImage", {title: "List Image"});

        listImage.onChange = function (url) {
          ContentEvent.event.data.listImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        listImage.onDelete = function (url) {
          ContentEvent.event.data.listImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        ContentEvent.deleteEvent = function () {
          var event = ContentEvent.event;
          if (event.id) {
            Buildfire.datastore.delete(event.id, TAG_NAMES.EVENTS_MANUAL, function (err, result) {
              if (err)
                return;
              $location.path('/');
            });
          }
        };

        ContentEvent.clearAddress = function () {
          if (!ContentEvent.currentAddress) {
            ContentEvent.event.data.address = null;
            ContentEvent.currentCoordinates = null;
          }
        };

        ContentEvent.setCoordinates = function () {
          function successCallback(resp) {
            if (resp) {
              ContentEvent.event.data.address = {
                type: ADDRESS_TYPE.COORDINATES,
                location: resp.formatted_address || ContentEvent.currentAddress,
                location_coordinates: [ContentEvent.currentAddress.split(",")[0].trim(), ContentEvent.currentAddress.split(",")[1].trim()]
              };
              ContentEvent.currentAddress = ContentEvent.event.data.address.location;
              ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
            } else {
              errorCallback();
            }
          }

          function errorCallback(err) {
            ContentEvent.validCoordinatesFailure = true;
            $timeout(function () {
              ContentEvent.validCoordinatesFailure = false;
            }, 5000);
          }

          Utils.validLongLats(ContentEvent.currentAddress).then(successCallback, errorCallback);
        };

        $scope.$watch(function () {
          return ContentEvent.event;
        }, updateItemsWithDelay, true);

      }]);
})(window.angular);
<commit_msg>Show icon image in edit mode<commit_after>'use strict';
(function (angular) {
  angular
    .module('eventsManualPluginContent')
    .controller('ContentEventCtrl', ['$scope', '$routeParams', 'Buildfire', 'DataStore', 'TAG_NAMES', 'ADDRESS_TYPE', '$location', 'Utils', '$timeout',
      function ($scope, $routeParams, Buildfire, DataStore, TAG_NAMES, ADDRESS_TYPE, $location, Utils, $timeout) {
        var ContentEvent = this;
        var _data = {
          "title": "",
          "listImage": "",
          "deepLinkUrl": "",
          "carouselImages": [],
          "startDate": "",
          "endDate": "",
          "isAllDay": "",
          "timezone": "",
          "timeDisplay": {},
          "repeat": {},
          "addressTitle": "",
          "address": {},
          "description": "",
          "links": []

        };

        ContentEvent.event = {
          data: angular.copy(_data)
        };
        ContentEvent.isUpdating = false;
        ContentEvent.isNewEventInserted = false;
        ContentEvent.unchangedData = true;
        ContentEvent.displayTiming = "SELECTED";

        function isValidEvent(event) {
          return event.startDate || event.title;
        }

        updateMasterEvent(ContentEvent.event);

        function updateMasterEvent(event) {
          ContentEvent.masterEvent = angular.copy(event);
        }

        function isUnchanged(event) {
          return angular.equals(event, ContentEvent.masterEvent);
        }

        ContentEvent.getItem = function (id) {
          var successEvents = function (result) {
            ContentEvent.event = result;
            if (ContentEvent.event.data.startDate)
              ContentEvent.event.data.startDate = new Date(result.data.startDate);
            if (ContentEvent.event.data.endDate)
              ContentEvent.event.data.endDate = new Date(result.data.endDate);
            if (ContentEvent.event.data.startTime)
              ContentEvent.event.data.startTime = new Date(result.data.startTime);
            if (ContentEvent.event.data.endTime)
              ContentEvent.event.data.endTime = new Date(result.data.endTime);
            if (ContentEvent.event.data.address && ContentEvent.event.data.address.location) {
              ContentEvent.currentAddress = ContentEvent.event.data.address.location;
              ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
            }
            if (ContentEvent.event.data.listImage) {
              listImage.loadbackground(ContentEvent.event.data.listImage);
            }
            _data.dateCreated = result.data.dateCreated;
            updateMasterEvent(ContentEvent.event);
          }, errorEvents = function () {
            throw console.error('There was a problem fetching your data', err);
          };
          DataStore.getById(id, TAG_NAMES.EVENTS_MANUAL).then(successEvents, errorEvents);
        };

        if ($routeParams.id) {
          ContentEvent.getItem($routeParams.id);
        }

        ContentEvent.TimeZoneDropdownOptions = [
          {name: "(GMT -12:00) Eniwetok, Kwajalein", value: "-12.0"},
          {name: "(GMT -11:00) Midway Island, Samoa", value: "-11.0"},
          {name: "(GMT -10:00) Hawaii", value: "-10.0"},
          {name: "(GMT -9:00) Alaska", value: "-9.0"},
          {name: "(GMT -8:00) Pacific Time (US & Canada)", value: "-8.0"},
          {name: "(GMT -7:00) Mountain Time (US & Canada)", value: "-7:00"},
          {
            name: "(GMT -6:00) Central Time (US & Canada), Mexico City",
            value: "-6:00"
          },
          {
            name: "(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima",
            value: "-5:00"
          },
          {
            name: "(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz",
            value: "-4:00"
          },
          {name: "(GMT -3:30) Newfoundland", value: "-3:30"},
          {
            name: "(GMT -3:00) Brazil, Buenos Aires, Georgetown",
            value: "-3:00"
          },
          {name: "(GMT -2:00) Mid-Atlantic", value: "-2:00"},
          {name: "(GMT -1:00) Azores, Cape Verde Islands", value: "-1:00"},
          {
            name: "(GMT) Western Europe Time, London, Lisbon, Casablanca",
            value: "0.0"
          },
          {
            name: "(GMT +1:00 hour) Brussels, Copenhagen, Madrid, Paris",
            value: "1.0"
          },
          {name: "(GMT +2:00) Kaliningrad, South Africa", value: "2:00"},
          {
            name: "(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg",
            value: "3:00"
          },
          {name: "(GMT +3:30) Tehran", value: "3:30"},
          {name: "(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi", value: "4:00"},
          {name: "(GMT +4:30) Kabul", value: "4:30"},
          {
            name: "(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent",
            value: "5:00"
          },
          {
            name: "(GMT +5:30) Bombay, Calcutta, Madras, New Delhi",
            value: '5:30'
          },
          {name: "(GMT +5:45) Kathmandu", value: "5:45"},
          {name: "(GMT +6:00) Almaty, Dhaka, Colombo", value: '6:00'},
          {name: "(GMT +7:00) Bangkok, Hanoi, Jakarta", value: "7:00"},
          {
            name: "(GMT +8:00) Beijing, Perth, Singapore, Hong Kong",
            value: "8:00"
          },
          {
            name: "(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk",
            value: "9:00"
          },
          {name: "(GMT +9:30) Adelaide, Darwin", value: "9:30"},
          {
            name: "(GMT +10:00) Eastern Australia, Guam, Vladivostok",
            value: "10:00"
          },
          {
            name: "(GMT +11:00) Magadan, Solomon Islands, New Caledonia",
            value: "11:00"
          },
          {
            name: "(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka",
            value: "12:00"
          }

        ];

        ContentEvent.descriptionWYSIWYGOptions = {
          plugins: 'advlist autolink link image lists charmap print preview',
          skin: 'lightgray',
          trusted: true,
          theme: 'modern'
        };

        /**
         * link and sortable options
         */
        var linkOptions = {"icon": "true"};
        ContentEvent.linksSortableOptions = {
          handle: '> .cursor-grab'
        };

        ContentEvent.validCoordinatesFailure = false;

        // create a new instance of the buildfire carousel editor
        var editor = new Buildfire.components.carousel.editor("#carousel");
        // this method will be called when a new item added to the list
        editor.onAddItems = function (items) {
          if (!ContentEvent.event.carouselImages)
            ContentEvent.event.carouselImages = [];
          ContentEvent.event.carouselImages.push.apply(ContentEvent.event.carouselImages, items);
          $scope.$digest();
        };
        // this method will be called when an item deleted from the list
        editor.onDeleteItem = function (item, index) {
          ContentEvent.event.carouselImages.splice(index, 1);
          $scope.$digest();
        };
        // this method will be called when you edit item details
        editor.onItemChange = function (item, index) {
          ContentEvent.event.carouselImages.splice(index, 1, item);
          $scope.$digest();
        };
        // this method will be called when you change the order of items
        editor.onOrderChange = function (item, oldIndex, newIndex) {
          var temp = ContentEvent.event.carouselImages[oldIndex];
          ContentEvent.event.carouselImages[oldIndex] = ContentEvent.event.carouselImages[newIndex];
          ContentEvent.event.carouselImages[newIndex] = temp;
          $scope.$digest();
        };

        ContentEvent.addNewEvent = function () {
          ContentEvent.isNewEventInserted = true;
          ContentEvent.event.data.dateCreated = +new Date();
          var successEvents = function (result) {
            console.log("Inserted", result.id);
            ContentEvent.isUpdating = false;
            ContentEvent.event.id = result.id;
            _data.dateCreated = ContentEvent.event.data.dateCreated;
            updateMasterEvent(ContentEvent.event);
            ContentEvent.event.data.deepLinkUrl = Buildfire.deeplink.createLink({id: result.id});
          }, errorEvents = function () {
            ContentEvent.isNewEventInserted = false;
            return console.error('There was a problem saving your data');
          };
          DataStore.insert(ContentEvent.event.data, TAG_NAMES.EVENTS_MANUAL).then(successEvents, errorEvents);
        };

        ContentEvent.updateEventData = function () {
          DataStore.update(ContentEvent.event.id, ContentEvent.event.data, TAG_NAMES.EVENTS_MANUAL, function (err) {
            ContentEvent.isUpdating = false;
            if (err)
              return console.error('There was a problem saving your data');
          })
        };

        var tmrDelayForEvent = null;

        var updateItemsWithDelay = function (event) {
          clearTimeout(tmrDelayForEvent);
          ContentEvent.isUpdating = false;
          ContentEvent.unchangedData = angular.equals(_data, ContentEvent.event.data);

          ContentEvent.isEventValid = isValidEvent(ContentEvent.event.data);
          if (!ContentEvent.isUpdating && !isUnchanged(ContentEvent.event) && ContentEvent.isEventValid) {
            tmrDelayForEvent = setTimeout(function () {
              if (event.id) {
                ContentEvent.updateEventData();
              } else if (!ContentEvent.isNewEventInserted) {
                ContentEvent.addNewEvent();
              }
            }, 300);
          }
        };

        ContentEvent.changeTimeZone = function (timezone) {
          ContentEvent.event.timezone = timezone;
        };

        ContentEvent.changeRepeatType = function (type) {
          ContentEvent.event.repeat = {};
          ContentEvent.event.repeat.isRepeating = true;
          ContentEvent.event.repeat.repeatType = type;
        };

        /**
         * Add dynamic link
         */

        ContentEvent.addLink = function () {
          var options = {showIcons: false};
          var callback = function (error, result) {
            if (error) {
              return console.error('Error:', error);
            }
            if (!ContentEvent.event.data.links)
              ContentEvent.event.data.links = [];
            ContentEvent.event.data.links.push(result);
            $scope.$digest();
          };
          Buildfire.actionItems.showDialog(null, options, callback);
        };

        /**
         * Remove dynamic link
         */

        ContentEvent.removeLink = function (index) {
          if (ContentEvent.event.data && ContentEvent.event.data.links) {
            ContentEvent.event.data.links.splice(index, 1);
          }
        };

        /**
         * Edit dynamic link
         */

        ContentEvent.editLink = function (link, index) {
          Buildfire.actionItems.showDialog(link, linkOptions, function editLinkCallback(error, result) {
            if (error) {
              return console.error('Error:', error);
            }
            if (!ContentEvent.event.data.links) {
              ContentEvent.event.data.links = [];
            }
            if (result === null) {
              return console.error('Error:Can not save data, Null record found.');
            }
            ContentEvent.event.data.links.splice(index, 1, result);
            $scope.$digest();
          });
        };

        /**
         * Save selected place from google autocomplete as address
         */

        ContentEvent.setLocation = function (data) {
          ContentEvent.event.data.address = {
            type: ADDRESS_TYPE.LOCATION,
            location: data.location,
            location_coordinates: data.coordinates
          };
          ContentEvent.currentAddress = ContentEvent.event.data.address.location;
          ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
          $scope.$digest();
        };

        /**
         * Change the address and map to dragged marker location
         */

        ContentEvent.setDraggedLocation = function (data) {
          ContentEvent.event.data.address = {
            type: ADDRESS_TYPE.LOCATION,
            location: data.location,
            location_coordinates: data.coordinates
          };
          ContentEvent.currentAddress = ContentEvent.event.data.address.location;
          ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
          $scope.$digest();
        };

        /* Build fire thumbnail component to add thumbnail image*/
        var listImage = new Buildfire.components.images.thumbnail("#listImage", {title: "List Image"});

        listImage.onChange = function (url) {
          ContentEvent.event.data.listImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        listImage.onDelete = function (url) {
          ContentEvent.event.data.listImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        ContentEvent.deleteEvent = function () {
          var event = ContentEvent.event;
          if (event.id) {
            Buildfire.datastore.delete(event.id, TAG_NAMES.EVENTS_MANUAL, function (err, result) {
              if (err)
                return;
              $location.path('/');
            });
          }
        };

        ContentEvent.clearAddress = function () {
          if (!ContentEvent.currentAddress) {
            ContentEvent.event.data.address = null;
            ContentEvent.currentCoordinates = null;
          }
        };

        ContentEvent.setCoordinates = function () {
          function successCallback(resp) {
            if (resp) {
              ContentEvent.event.data.address = {
                type: ADDRESS_TYPE.COORDINATES,
                location: resp.formatted_address || ContentEvent.currentAddress,
                location_coordinates: [ContentEvent.currentAddress.split(",")[0].trim(), ContentEvent.currentAddress.split(",")[1].trim()]
              };
              ContentEvent.currentAddress = ContentEvent.event.data.address.location;
              ContentEvent.currentCoordinates = ContentEvent.event.data.address.location_coordinates;
            } else {
              errorCallback();
            }
          }

          function errorCallback(err) {
            ContentEvent.validCoordinatesFailure = true;
            $timeout(function () {
              ContentEvent.validCoordinatesFailure = false;
            }, 5000);
          }

          Utils.validLongLats(ContentEvent.currentAddress).then(successCallback, errorCallback);
        };

        $scope.$watch(function () {
          return ContentEvent.event;
        }, updateItemsWithDelay, true);

      }]);
})(window.angular);
<|endoftext|>


<commit_before>wwt.app.factory(
  'Localization',
  [
    '$http',
    '$q',
    'Util',

    function($http, $q, util) {
      var api = {
	setLanguage: setLanguage,
	getString: getString,
	getFromEn: getFromEn,
	getAvailableLanguages: getAvailableLanguages
      };

      var langCode,
	  englishData,
	  englishArray,
	  locData,
	  locArray,
	  lpacks;

      function getString(id, s) {
	return locArray && locArray[id] ? locArray[id] : s ? s : '';
      }

      function getFromEn(s) {
	if (langCode === 'EN') {
	  return s;
	} else {
	  return getString($.inArray(s, englishArray), s);
	}
      }

      function getAvailableLanguages() {
	var deferred = $q.defer();

	initPromise.then(function() {
	  var langArray = [];

	  lpacks.find('languagepack').each(function(i, pack) {
	    langArray.push({
              label: $(pack).attr('name'),
              code: $(pack).attr('code')
            });
	  });

	  deferred.resolve(langArray);
	});

	return deferred.promise;
      }

      function setLanguage(code) {
	var deferred = $q.defer();

	initPromise.then(function () {
	  langCode = code;

	  if (code === 'EN') {
	    locData = englishData;
	    locArray = locData.split('\n');
	    deferred.resolve(true);
	    return;
	  }

	  var url = lpacks.find('languagepack[code=' + code + ']').attr('url');
	  util.log(url);

	  $http.get(url).
	    success(function(data) {
	      data = transformLanguagePack(data);
	      locData = data;
	      locArray = [];

	      $.each(data.split('\n'), function (i,item) {
		var spl = item.split('\t');
		var ind = parseInt(spl[0], 10);
		if (spl.length === 2 && !isNaN(ind)) {
		  locArray[ind] = spl[1];
		}
	      });

	      deferred.resolve(true);
	    });
	});

	return deferred.promise;
      }

      var init = function () {
	var deferred = $q.defer();

	$q.all([
	  $http.get(wwtlib.URLHelpers.singleton.coreStaticUrl('/wwtweb/catalog.aspx?X=Languages'))
	    .success(function(data) {
	      lpacks = $(data);
	    })
	    .error(function(data, status, headers, config) {
	      util.log(data, status, headers, config);
	    }),

	  $http.get(wwtlib.URLHelpers.singleton.coreStaticUrl('/wwtweb/catalog.aspx?Q=lang_en'))
	    .success(function(data) {
	      data = transformLanguagePack(data);
	      englishData = data;
	      var dsplit = data.split('\n');

	      englishArray = [];
	      $.each(dsplit, function () {
		var s1 = this.split('\t')[1];
		if (s1) {
		  s1 = s1.split('\r')[0];
		}
		englishArray[parseInt(this.split('\t')[0])] = s1;
	      });

	    })
	]).then(function() {
	  deferred.resolve(true);
	});

	return deferred.promise;
      };

      var transformLanguagePack = function (data) {
	if (data.charAt(0) == 1) {
	  return data;
	}

	var re1 = new RegExp(data.charAt(0), "g");
	var re2 = new RegExp(data.charAt(3), "g");
	return data.replace(re1, '').replace(re2, '');
      };

      var initPromise = init();
      return api;
    }
  ]
);
<commit_msg>factories/Localization.js: another URL that needs rewriting<commit_after>wwt.app.factory(
  'Localization',
  [
    '$http',
    '$q',
    'Util',

    function($http, $q, util) {
      var api = {
	setLanguage: setLanguage,
	getString: getString,
	getFromEn: getFromEn,
	getAvailableLanguages: getAvailableLanguages
      };

      var langCode,
	  englishData,
	  englishArray,
	  locData,
	  locArray,
	  lpacks;

      function getString(id, s) {
	return locArray && locArray[id] ? locArray[id] : s ? s : '';
      }

      function getFromEn(s) {
	if (langCode === 'EN') {
	  return s;
	} else {
	  return getString($.inArray(s, englishArray), s);
	}
      }

      function getAvailableLanguages() {
	var deferred = $q.defer();

	initPromise.then(function() {
	  var langArray = [];

	  lpacks.find('languagepack').each(function(i, pack) {
	    langArray.push({
              label: $(pack).attr('name'),
              code: $(pack).attr('code')
            });
	  });

	  deferred.resolve(langArray);
	});

	return deferred.promise;
      }

      function setLanguage(code) {
	var deferred = $q.defer();

	initPromise.then(function () {
	  langCode = code;

	  if (code === 'EN') {
	    locData = englishData;
	    locArray = locData.split('\n');
	    deferred.resolve(true);
	    return;
	  }

	  var url = wwtlib.URLHelpers.singleton.rewrite(lpacks.find('languagepack[code=' + code + ']').attr('url'));
	  util.log(url);

	  $http.get(url).
	    success(function(data) {
	      data = transformLanguagePack(data);
	      locData = data;
	      locArray = [];

	      $.each(data.split('\n'), function (i,item) {
		var spl = item.split('\t');
		var ind = parseInt(spl[0], 10);
		if (spl.length === 2 && !isNaN(ind)) {
		  locArray[ind] = spl[1];
		}
	      });

	      deferred.resolve(true);
	    });
	});

	return deferred.promise;
      }

      var init = function () {
	var deferred = $q.defer();

	$q.all([
	  $http.get(wwtlib.URLHelpers.singleton.coreStaticUrl('/wwtweb/catalog.aspx?X=Languages'))
	    .success(function(data) {
	      lpacks = $(data);
	    })
	    .error(function(data, status, headers, config) {
	      util.log(data, status, headers, config);
	    }),

	  $http.get(wwtlib.URLHelpers.singleton.coreStaticUrl('/wwtweb/catalog.aspx?Q=lang_en'))
	    .success(function(data) {
	      data = transformLanguagePack(data);
	      englishData = data;
	      var dsplit = data.split('\n');

	      englishArray = [];
	      $.each(dsplit, function () {
		var s1 = this.split('\t')[1];
		if (s1) {
		  s1 = s1.split('\r')[0];
		}
		englishArray[parseInt(this.split('\t')[0])] = s1;
	      });

	    })
	]).then(function() {
	  deferred.resolve(true);
	});

	return deferred.promise;
      };

      var transformLanguagePack = function (data) {
	if (data.charAt(0) == 1) {
	  return data;
	}

	var re1 = new RegExp(data.charAt(0), "g");
	var re2 = new RegExp(data.charAt(3), "g");
	return data.replace(re1, '').replace(re2, '');
      };

      var initPromise = init();
      return api;
    }
  ]
);
<|endoftext|>


<commit_before>/*global systemDictionary:true */
'use strict';

systemDictionary = {
    "Date": {                            "en": "Date",                                            "de": "Datum",                                           "ru": "Дата",                                            "pt": "Encontro",                                        "nl": "Datum",                                           "fr": "Rendez-vous amoureux",                            "it": "Data",                                            "es": "Fecha",                                           "pl": "Data"},
    "Description": {                     "en": "Description",                                     "de": "Beschreibung",                                    "ru": "Описание",                                        "pt": "Descrição",                                       "nl": "Beschrijving",                                    "fr": "La description",                                  "it": "Descrizione",                                     "es": "Descripción",                                     "pl": "Opis"},
    "German Holidays Adapter settings": {"en": "German Holidays Adapter settings",                "de": "Deutsche Feiertage Adapter Einstellungen",        "ru": "Настройки Deutsche Feiertage Adapter",            "pt": "Configurações do German Holidays Adapter",        "nl": "Duitse feestdagen Adapterinstellingen",           "fr": "Paramètres de l'adaptateur Vacances allemandes",  "it": "Impostazioni dell'adattatore Vacanze tedesche",   "es": "Configuración del adaptador de vacaciones alemán","pl": "Niemieckie ustawienia adapterów świątecznych"},
    "Holidays": {                        "en": "Holidays",                                        "de": "Feiertage",                                       "ru": "Праздники",                                       "pt": "Feriados",                                        "nl": "Vakantie",                                        "fr": "Vacances",                                        "it": "Vacanze",                                         "es": "Vacaciones",                                      "pl": "Wakacje"},
    "Select": {                          "en": "Select",                                          "de": "Auswahl",                                         "ru": "Выбрать",                                         "pt": "Selecione",                                       "nl": "kiezen",                                          "fr": "Sélectionner",                                    "it": "Selezionare",                                     "es": "Seleccionar",                                     "pl": "Wybierz"},
    "Select holidays": {                 "en": "Select holidays",                                 "de": "Feiertage auswählen",                             "ru": "Выбрать праздники",                               "pt": "Selecione férias",                                "nl": "Selecteer feestdagen",                            "fr": "Sélectionnez les vacances",                       "it": "Seleziona le vacanze",                            "es": "Seleccione vacaciones",                           "pl": "Wybierz święta"},
    "calendrical holiday": {             "en": "calendrical holiday",                             "de": "kalendarischer Feiertag",                         "ru": "календарный праздник",                            "pt": "feriado calendrical",                             "nl": "kalendervakantie",                                "fr": "vacances calendriques",                           "it": "vacanza calendaria",                              "es": "vacaciones calendáricas",                         "pl": "wakacje kalendarzowe"},
    "political holiday": {               "en": "political holiday",                               "de": "politischer Feiertag",                            "ru": "политический праздник",                           "pt": "feriado político",                                "nl": "politieke feestdag",                              "fr": "vacances politiques",                             "it": "vacanza politica",                                "es": "fiesta política",                                 "pl": "święto polityczne"},
    "religous holiday": {                "en": "religous holiday",                                "de": "kirchlicher Feiertag",                            "ru": "религиозный праздник",                            "pt": "feriado religioso",                               "nl": "religieuze vakantie",                             "fr": "fête religieuse",                                 "it": "feste religiose",                                 "es": "vacaciones religiosas",                           "pl": "święto religijne"},
};
<commit_msg>Update words.js<commit_after>/*global systemDictionary:true */
"use strict";

systemDictionary = {
    "Date": {                            "en": "Date",                                            "de": "Datum",                                           "ru": "Дата",                                            "pt": "Encontro",                                        "nl": "Datum",                                           "fr": "Rendez-vous amoureux",                            "it": "Data",                                            "es": "Fecha",                                           "pl": "Data"},
    "Description": {                     "en": "Description",                                     "de": "Beschreibung",                                    "ru": "Описание",                                        "pt": "Descrição",                                       "nl": "Beschrijving",                                    "fr": "La description",                                  "it": "Descrizione",                                     "es": "Descripción",                                     "pl": "Opis"},
    "German Holidays Adapter settings": {"en": "German Holidays Adapter settings",                "de": "Deutsche Feiertage Adapter Einstellungen",        "ru": "Настройки Deutsche Feiertage Adapter",            "pt": "Configurações do German Holidays Adapter",        "nl": "Duitse feestdagen Adapterinstellingen",           "fr": "Paramètres de l'adaptateur Vacances allemandes",  "it": "Impostazioni dell'adattatore Vacanze tedesche",   "es": "Configuración del adaptador de vacaciones alemán","pl": "Niemieckie ustawienia adapterów świątecznych"},
    "Holidays": {                        "en": "Holidays",                                        "de": "Feiertage",                                       "ru": "Праздники",                                       "pt": "Feriados",                                        "nl": "Vakantie",                                        "fr": "Vacances",                                        "it": "Vacanze",                                         "es": "Vacaciones",                                      "pl": "Wakacje"},
    "Select": {                          "en": "Select",                                          "de": "Auswahl",                                         "ru": "Выбрать",                                         "pt": "Selecione",                                       "nl": "kiezen",                                          "fr": "Sélectionner",                                    "it": "Selezionare",                                     "es": "Seleccionar",                                     "pl": "Wybierz"},
    "Select holidays": {                 "en": "Select holidays",                                 "de": "Feiertage auswählen",                             "ru": "Выбрать праздники",                               "pt": "Selecione férias",                                "nl": "Selecteer feestdagen",                            "fr": "Sélectionnez les vacances",                       "it": "Seleziona le vacanze",                            "es": "Seleccione vacaciones",                           "pl": "Wybierz święta"},
    "calendrical holiday": {             "en": "calendrical holiday",                             "de": "kalendarischer Feiertag",                         "ru": "календарный праздник",                            "pt": "feriado calendrical",                             "nl": "kalendervakantie",                                "fr": "vacances calendriques",                           "it": "vacanza calendaria",                              "es": "vacaciones calendáricas",                         "pl": "wakacje kalendarzowe"},
    "political holiday": {               "en": "political holiday",                               "de": "politischer Feiertag",                            "ru": "политический праздник",                           "pt": "feriado político",                                "nl": "politieke feestdag",                              "fr": "vacances politiques",                             "it": "vacanza politica",                                "es": "fiesta política",                                 "pl": "święto polityczne"},
    "religous holiday": {                "en": "religous holiday",                                "de": "kirchlicher Feiertag",                            "ru": "религиозный праздник",                            "pt": "feriado religioso",                               "nl": "religieuze vakantie",                             "fr": "fête religieuse",                                 "it": "feste religiose",                                 "es": "vacaciones religiosas",                           "pl": "święto religijne"},
};
<|endoftext|>