<commit_before>// ### Part of the [Rosy Framework](http://github.com/ff0000/rosy)
/* site.js */

// Custom [JSLint](http://jslint.com) settings.
/*global $: true, console: true, Class: true */
/*jslint browser: true, onevar: true */

// ## The RED Namespace
var RED = RED || {};

// ## Local Namespace
// Example Site object, controls global functionality and instantiates the Example Default Page.
// You should replace the namespace "Example" with your own Site namespace, this is only an example.
var Example = Example || {};

// Site shell object

// Model manager and shell manager
RED.SITE = $.extend(true, Example, RED, function () {

	return {

		init : function () {
			$(document).ready(this.onReady.call(this));
		},

		onReady : function () {
			var body = $("body"),
			    // Use `attr("data-page-class")` if < jQuery 1.6
				pageClass = body.data("pageClass");

			// creates `Page()` based on `<div data-page-class="Home">`
			if (pageClass && typeof Example.Page[pageClass] === "function") {
				this.page = new Example.Page[pageClass]();
			// defaults to `Example.Page();`
			} else {
				this.page = new Example.Page();
			}

			console.group("page", pageClass, this.page);
		},

		setDOMReferences : function () {

		}

	};
}());<commit_msg>Removing cruft.<commit_after>// ### Part of the [Rosy Framework](http://github.com/ff0000/rosy)
/* site.js */

// Custom [JSLint](http://jslint.com) settings.
/*global $: true, console: true, Class: true */
/*jslint browser: true, onevar: true */

// ## The RED Namespace
var RED = RED || {};

// ## Local Namespace
// Example Site object, controls global functionality and instantiates the Example Default Page.
// You should replace the namespace "Example" with your own Site namespace, this is only an example.
var Example = Example || {};

// Site shell object

// Model manager and shell manager
RED.SITE = $.extend(true, Example, RED, function () {

	return {

		init : function () {
			$(document).ready(this.onReady.call(this));
		},

		onReady : function () {
			var body = $("body"),
			    // Use `attr("data-page-class")` if < jQuery 1.6
				pageClass = body.data("pageClass");

			// creates `Page()` based on `<div data-page-class="Home">`
			if (pageClass && typeof Example.Page[pageClass] === "function") {
				this.page = new Example.Page[pageClass]();
			// defaults to `Example.Page();`
			} else {
				this.page = new Example.Page();
			}
		}
	};
}());<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require listings
//= require_tree .

// Test for triggered 'loaded' event
// $(function() {
//   $('.listing').on('listings:loaded', function(event, el) {
//     console.log('Loaded');
//     console.log(el);
//   });
// });

$(function(){

  $('.listing').on('change', '#date-filter', function(){
    var listings = $(this).closest('.listing')
    var filter = $(this);

    if (filter.val() == '') {
      listings.trigger("listings:filter:key:clear", filter.data('filter-key'))
    } else {
      listings.trigger("listings:filter:key:set", [filter.data('filter-key'), filter.val()])
    }
  });
});

<commit_msg>Apply formatting<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require listings
//= require_tree .

// Test for triggered 'loaded' event
// $(function() {
//   $('.listing').on('listings:loaded', function(event, el) {
//     console.log('Loaded');
//     console.log(el);
//   });
// });

$(function () {

  $('.listing').on('change', '#date-filter', function () {
    var listings = $(this).closest('.listing')
    var filter = $(this);

    if (filter.val() == '') {
      listings.trigger("listings:filter:key:clear", filter.data('filter-key'))
    } else {
      listings.trigger("listings:filter:key:set", [filter.data('filter-key'), filter.val()])
    }
  });
});

<|endoftext|>


<commit_before>// Count and sum the scores of a bowling game for one player (in JavaScript).
// A bowling game consists of 10 frames in which the player tries to knock down
// the 10 pins. In every frame the player can roll one or two times.
// The actual number depends on strikes and spares. The score of a frame is the
// number of knocked down pins plus bonuses for strikes and spares.
// After every frame the 10 pins are reset.
'use strict';

describe('Frame', function() {
  var frame;
  beforeEach(function() {
    frame = new Frame();
  });

  it("exists", function(){
    expect(frame).toBeDefined();
  });

  it("contains roll1 and roll2", function(){
    var _roll1;
    var _roll2
    expect(frame._roll1).toBeDefined();
    expect(frame._roll2).toBeDefined();
  });

  it("has a score", function(){
    var _score;
    expect(frame._score).toBeDefined();
  });

  it("has a bonus", function(){
    var _bonus;
    expect(frame._bonus).toBeDefined();
  });

});
<commit_msg>Testing for existence of a roll1 method in frame<commit_after>// Count and sum the scores of a bowling game for one player (in JavaScript).
// A bowling game consists of 10 frames in which the player tries to knock down
// the 10 pins. In every frame the player can roll one or two times.
// The actual number depends on strikes and spares. The score of a frame is the
// number of knocked down pins plus bonuses for strikes and spares.
// After every frame the 10 pins are reset.
'use strict';

describe('Frame', function() {
  var frame;
  beforeEach(function() {
    frame = new Frame();
  });

  it("exists", function(){
    expect(frame).toBeDefined();
  });

  it("contains roll1 and roll2", function(){
    var _roll1;
    var _roll2
    expect(frame._roll1).toBeDefined();
    expect(frame._roll2).toBeDefined();
  });

  it("has a score", function(){
    var _score;
    expect(frame._score).toBeDefined();
  });

  it("has a bonus", function(){
    var _bonus;
    expect(frame._bonus).toBeDefined();
  });

  it("has a roll1 method", function(){
    expect(frame.roll1).toBeDefined();
  });

});
<|endoftext|>


<commit_before>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI          = require('ui'),
Vector2         = require('vector2'),
placeHolderList = require('placeHolderList'),
main = new UI.Card({
  title: 'Honeybees',
  icon: 'images/logo28.png',
  subtitle: 'Hello World!',
  body: 'Press any button.'
}),
cardNoTasks = new UI.Card({
  title: 'Honeybees',
  icon: 'images/logo28.png',
  subtitle: 'Hello World!',
  body: 'You\'re good, for now.'
}),
newMenu = new UI.Menu({
  sections: [{
    title: 'Finished Task?',
    items: [{
      title: 'Completed',
      icon: 'IMAGE_CHECK',
      subtitle: 'I love you Rob!'
    }, {
      title: 'Later',
      icon: 'IMAGE_X',
      subtitle: 'Superdry'
    }]
  }]
});

main.show();

main.on('click', 'select', function (e) {
  var menu;
  if (!menu && placeHolderList.length) {
    menu = new UI.Menu({
      sections: [{
        title: 'Get yo ship together',
        items: refreshTaskList(placeHolderList)
      }]
    }]
  });
  menu.on('select', function (e) {
    var card = new UI.Card({
      title: e.item.title,
      subtitle: e.item.subtitle,
      body: 'I want to buy a something and that thing may or may not be this thing',
      scrollable: true
    });
    card.on('click', 'select', function () {
      var newMenu = new UI.Menu({
        sections: [{
          title: 'Finished Task?',
          items: [{
            title: 'Completed',
            icon: 'IMAGE_CHECK',
            subtitle: 'I love you Rob!'
          }, {
            title: 'Later',
            icon: 'IMAGE_X',
            subtitle: 'Superdry'
          }]
        }]
      });
      newMenu.show();
    });
    card.show();
  });
  menu.show();
});

main.on('click', 'up', function (e) {
  var wind = new UI.Window({
    fullscreen: true
  });
  var textfield = new UI.Text({
    position: new Vector2(0, 65),
    size: new Vector2(144, 30),
    font: 'Gothic 14',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function (e) {
  var cardLogo = new UI.Card({
    // title: 'Honeybees',
    icon: 'IMAGE_ICON_LARGE',
    // subtitle: 'Hello World!',
    // body: 'Press any button.'
  });
  cardLogo.show();
});
<commit_msg>Create task deletion functionality.<commit_after>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI          = require('ui'),
Vector2         = require('vector2'),
placeHolderList = require('placeHolderList'),
main = new UI.Card({
  title: 'Honeybees',
  icon: 'images/logo28.png',
  subtitle: 'Hello World!',
  body: 'Press any button.'
}),
cardNoTasks = new UI.Card({
  title: 'Honeybees',
  icon: 'images/logo28.png',
  subtitle: 'Hello World!',
  body: 'You\'re good, for now.'
}),
newMenu = new UI.Menu({
  sections: [{
    title: 'Finished Task?',
    items: [{
      title: 'Completed',
      icon: 'IMAGE_CHECK',
      subtitle: 'I love you Rob!'
    }, {
      title: 'Later',
      icon: 'IMAGE_X',
      subtitle: 'Superdry'
    }]
  }]
});

main.show();

main.on('click', 'select', function (e) {
  var menu;
  if (!menu && placeHolderList.length) {
    menu = new UI.Menu({
      sections: [{
        title: 'Get yo ship together',
        items: refreshTaskList(placeHolderList)
      }]
    });
  } else {
    cardNoTasks.show();
  }

  menu.on('select', function (e) {
    // console.log(JSON.stringify(e.item));
    var card;
    if (!card) {
      card = new UI.Card({
        taskId: e.item.taskId,
        title: e.item.title,
        subtitle: e.item.subtitle,
        body: e.item.body,
        scrollable: true
      });
    }
    card.on('click', 'select', function (e) {
      console.log(JSON.stringify(e));
      newMenu.show();
      newMenu.on('select', function (e) {
        // console.log(JSON.stringify(card));
        placeHolderList = removeTask(card.state.taskId, placeHolderList);
        newMenu.hide();
        card.hide();
        console.log(JSON.stringify(card));
        menu.items(0, placeHolderList); // Finds section of index 0 and replaces its items array.

        if (!placeHolderList.length) {
          menu.hide();
          cardNoTasks.show();
        }
        // console.log(JSON.stringify(menu.items(0)));
        // console.log(JSON.stringify(placeHolderList));
      });
    });
    card.show();
  });
  menu.show();
});

main.on('click', 'up', function (e) {
  var wind = new UI.Window({
    fullscreen: true
  });
  var textfield = new UI.Text({
    position: new Vector2(0, 65),
    size: new Vector2(144, 30),
    font: 'Gothic 14',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function (e) {
  var cardLogo = new UI.Card({
    // title: 'Honeybees',
    icon: 'IMAGE_ICON_LARGE',
    // subtitle: 'Hello World!',
    // body: 'Press any button.'
  });
  cardLogo.show();
});

function refreshTaskList (taskList) {
  var items = [];
  for (var i = 0; i < taskList.length; i++) {
    items.push(taskList[i]);
  }
  return items;
}

function removeTask (id, taskList) {
  for (var i = 0; i < taskList.length; i++) {
    if (taskList[i].taskId === id) {
      taskList.splice(i, 1); // Remove the element from array task list.
    }
  }
  return taskList;
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';
const { merge, run } = Ember;

export default function startApp(attrs) {
  let attributes = merge({}, config.APP);
  attributes = merge(attributes, attrs); // use defaults, but you can override;

  return run(() => {
    let application = Application.create(attributes);
    application.setupForTesting();
    application.injectTestHelpers();
    return application;
  });
}
<commit_msg>Const<commit_after>import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';
const { merge, run } = Ember;

export default function startApp(attrs) {
  let attributes = merge({}, config.APP);
  attributes = merge(attributes, attrs); // use defaults, but you can override;

  return run(() => {
    const application = Application.create(attributes);
    application.setupForTesting();
    application.injectTestHelpers();
    return application;
  });
}
<|endoftext|>


<commit_before>
// Global flag used for checking whether to hide the visible menu
// after a small timeout has passed when mousing out from a menu.
var onMenu;

$(function() {

    // Empty out the breadcrumbs div and add the menu into it.
    $('.breadcrumbs').html('')
                     .append($('.dropdown-menu').show())
                     .css({display: 'inline-block'});

    var primaryMenuItems = $('.dropdown-menu a');

    primaryMenuItems.mouseover(function() {
        var menu = $(this).parent().find('.dropdown-menu-menu').clone();
        // If we're over a primary menu link, clone the child menu and
        // show it.
        if (menu.length == 1) {
            onMenu = true;
            $('.cloned').remove();
            $('body').append(menu);
            // Position the child menu under its parent.
            var pos = {
                top: $(this).offset().top + $(this).height(),
                left: $(this).offset().left,
                position: 'absolute'
            }
            menu.css(pos).addClass('cloned').show();
            // Ensure the menu stays visible when we mouse onto
            // another item in it.
            menu.mouseover(function() {
                onMenu = true;
            });
            // Trigger the parent mouseout if we mouseout of the menu.
            menu.mouseout(function() {
                $('.dropdown-menu a').mouseout();
            });
        }
    });

    // Set a timeout to hide visible menus on mouseout of primary
    // menu item.
    primaryMenuItems.mouseout(function() {
        if ($(this).parent().find('.dropdown-menu-menu').length == 1) {
            onMenu = false;
            window.setTimeout(function() {
                if (!onMenu) {
                    $('.cloned').remove();
                }
            }, 1000);
        }
    });

     // If the primary menu item is clicked, go to the URL for
     // its first child.
     primaryMenuItems.click(function() {
        var thisHref = $(this).attr('href');
        if (thisHref && thisHref != '#') {
            return true;
        }
        var first = $(this).parent().find('.dropdown-menu-menu a:first');
        var firstHref = first.attr('href');
        if (firstHref) {
            location = firstHref;
        }
        return false;
    });

    // Give the drop-down menu items elements the same hover
    // state and click event as their anchors.
    var subMenuItems = $('.dropdown-menu-menu li');

    subMenuItems.live('mouseover', function() {
        $(this).addClass('dropdown-menu-hover');
    });

    subMenuItems.live('mouseout', function() {
        $(this).removeClass('dropdown-menu-hover');
    });

    subMenuItems.live('click', function() {
        location = $(this).find('a').attr('href');
    });

    // Provides link to site.
    $('#user-tools li:last').before('
' + window.__home_link + '
');

});

// Remove extraneous ``template`` forms from inline formsets since
// Mezzanine has its own method of dynamic inlines.
$(function() {
    var removeRows = {};
    $.each($('*[name*=__prefix__]'), function(i, e) {
        var row = $(e).parent();
        if (!row.attr('id')) {
            row.attr('id', 'remove__prefix__' + i);
        }
        removeRows[row.attr('id')] = true;
    });
    for (var rowID in removeRows) {
        $('#' + rowID).remove();
    }
});
<commit_msg>Allows regular link Cmd+Click behaviour on OS X<commit_after>
// Global flag used for checking whether to hide the visible menu
// after a small timeout has passed when mousing out from a menu.
var onMenu;

$(function() {

    // Empty out the breadcrumbs div and add the menu into it.
    $('.breadcrumbs').html('')
                     .append($('.dropdown-menu').show())
                     .css({display: 'inline-block'});

    var primaryMenuItems = $('.dropdown-menu a');

    primaryMenuItems.mouseover(function() {
        var menu = $(this).parent().find('.dropdown-menu-menu').clone();
        // If we're over a primary menu link, clone the child menu and
        // show it.
        if (menu.length == 1) {
            onMenu = true;
            $('.cloned').remove();
            $('body').append(menu);
            // Position the child menu under its parent.
            var pos = {
                top: $(this).offset().top + $(this).height(),
                left: $(this).offset().left,
                position: 'absolute'
            }
            menu.css(pos).addClass('cloned').show();
            // Ensure the menu stays visible when we mouse onto
            // another item in it.
            menu.mouseover(function() {
                onMenu = true;
            });
            // Trigger the parent mouseout if we mouseout of the menu.
            menu.mouseout(function() {
                $('.dropdown-menu a').mouseout();
            });
        }
    });

    // Set a timeout to hide visible menus on mouseout of primary
    // menu item.
    primaryMenuItems.mouseout(function() {
        if ($(this).parent().find('.dropdown-menu-menu').length == 1) {
            onMenu = false;
            window.setTimeout(function() {
                if (!onMenu) {
                    $('.cloned').remove();
                }
            }, 1000);
        }
    });

     // If the primary menu item is clicked, go to the URL for
     // its first child.
     primaryMenuItems.click(function(e) {
        if (e.isDefaultPrevented() || e.metaKey || e.ctrlKey) {
            // Don't open the clicked link when Cmd+Click is used on OS X
            // Regular LMB click pass-through works as intended
            // #TODO: test on other platforms and browsers
            return;
        }

        var thisHref = $(this).attr('href');
        if (thisHref && thisHref != '#') {
            return true;
        }
        var first = $(this).parent().find('.dropdown-menu-menu a:first');
        var firstHref = first.attr('href');
        if (firstHref) {
            location = firstHref;
        }
        return false;
    });

    // Give the drop-down menu items elements the same hover
    // state and click event as their anchors.
    var subMenuItems = $('.dropdown-menu-menu li');

    subMenuItems.live('mouseover', function() {
        $(this).addClass('dropdown-menu-hover');
    });

    subMenuItems.live('mouseout', function() {
        $(this).removeClass('dropdown-menu-hover');
    });

    subMenuItems.live('click', function(e) {
        if (e.isDefaultPrevented() || e.metaKey || e.ctrlKey) {
            // Don't open the clicked link when Cmd+Click is used on OS X
            return;
        }

        location = $(this).find('a').attr('href');
    });

    // Provides link to site.
    $('#user-tools li:last').before('
' + window.__home_link + '
');

});

// Remove extraneous ``template`` forms from inline formsets since
// Mezzanine has its own method of dynamic inlines.
$(function() {
    var removeRows = {};
    $.each($('*[name*=__prefix__]'), function(i, e) {
        var row = $(e).parent();
        if (!row.attr('id')) {
            row.attr('id', 'remove__prefix__' + i);
        }
        removeRows[row.attr('id')] = true;
    });
    for (var rowID in removeRows) {
        $('#' + rowID).remove();
    }
});
<|endoftext|>


<commit_before>"use strict";

var SoapRequest = require('./SoapRequest');

function Message(service) {
    this._service = service;
    this._recipients = [];
	this._id = null;
	this._syncState = null;
	this._defaultFields = [
		'item:Attachments'
	];
	this._additionalFields = [];
	this._attachments = [];
}

Message.prototype.Bind = function (id) {
	this._id = id;
};

Message.prototype.setSyncState = function (syncState) {
	this._syncState = syncState;
};

Message.prototype.SendAndSaveCopy = function SendAndSaveCopy (callback) {
    this._messageDisposition = 'SendAndSaveCopy';
    this._sendSaveAction(callback);
};

Message.prototype.Send = function Send (callback) {
    this._messageDisposition = 'SendOnly';
    this._sendSaveAction(callback);
};

Message.prototype.Save = function Save (callback) {
    this._messageDisposition = 'SaveOnly';
    this._sendSaveAction(callback);
};

Message.prototype.addRecipient = function addRecipient(recipient) {
    this._recipients.push(recipient);
};

Message.prototype.sendItemAction = function _sendSaveAction (callback) {
    var soapRequest = new SoapRequest('SendItem', {
    	attributes: {
    		SaveItemToFolder: true
    	},
        ItemIds: {
            ItemId: {
		        attributes: {
		            Id: this.ItemId,
		            ChangeKey: this.ChangeKey
		        }
            }
        }
    });
    this._service.execute(soapRequest, callback);
};

Message.prototype._sendSaveAction = function _sendSaveAction (callback) {
    var soapRequest = new SoapRequest('CreateItem', {
        attributes: {
            MessageDisposition: this._messageDisposition
        },
        Items: {
            Message: {
            	Attachments: this._attachments.map(function (attachment) {
            		return {
            			FileAttachment: {
            				Name: attachment.Name,
            				IsInline: attachment.IsInline
            			}
            		};
            	}),
                ItemClass: 'IPM.Note',
                Subject: this.Subject,
                Body: {
                    attributes: {
                        BodyType: 'HTML'
                    },
                    $value: this.Body
                },
                ToRecipients: this._recipients.map(function (recipient) {
                    return {
                        Mailbox: {
                            EmailAddress: recipient
                        }
                    }
                }),
                From: {
                    Mailbox: {
                        EmailAddress: this.From
                    }
                }
            }
        }
    });

    this._service.execute(soapRequest, callback);
};

Message.prototype.BindAttachment = function (attachment) {
	this._attachments.push(attachment);
	return this;
};

Message.prototype.CreateAttachment = function (callback) {
	var soapRequest = new SoapRequest('CreateAttachment', {
        ParentItemId: {
	        attributes: {
	            Id: this.ItemId
	        }
        },
        Attachments: this._attachments.map(function (attachment) {
        	if (attachment.isInline) {
	        	return {
	        		FileAttachment: {
	        			Name: attachment.name,
	        			Content: attachment.content,
	        			IsInline: attachment.isInline,
	        			ContentId: attachment.ContentId
	        		}
	        	};
        	} else {
	        	return {
	        		FileAttachment: {
	        			Name: attachment.name,
	        			Content: attachment.content
	        		}
	        	};
        	}
        })
    });
    this._service.execute(soapRequest, callback);
};

Message.prototype.GetAttachments = function (callback) {
	var attachmentsCollection = new AttachmentCollection(this._service);
	attachmentsCollection.BindToItems(this._attachments);

	attachmentsCollection.Load(function (err, results) {
		if (!err) {
			this.Attachments = results;
		}

		callback(err, results);
	}.bind(this));
};

function MessageCollection(service) {
	this._service = service;
	this._defaultFields = [
		'item:Attachments'
	];
	this._baseShape = 'Default';
}

MessageCollection.prototype.BindToItems = function (items) {
	this._items = items;
}

MessageCollection.prototype.setBaseShape = function (baseShape) {
	this._baseShape = baseShape;
};

MessageCollection.prototype.Load = function (callback) {
	var soapRequest = new SoapRequest('GetItem', {
		ItemShape: {
			BaseShape: this._baseShape,
			IncludeMimeContent: true,
			AdditionalProperties: {
				FieldURI: this._defaultFields.map(function (field) {
					return { attributes: { FieldURI: field } };
				})
			}
		},
		ItemIds: {
			ItemId: this._items.map(function (item) {
					if (typeof item == 'string') {
						return {
							attributes: {
								Id: item,
								ChangeKey: ''
							}
						};
					}
					return {
						attributes: {
							Id: item.Id,
							ChangeKey: item.ChangeKey || ''
						}
					}
				})
		}
	});
	this._service.execute(soapRequest, callback);
};

function AttachmentCollection(service) {
	this._service = service;
	this._items = [];
}

AttachmentCollection.prototype.BindToItems = function (items) {
	this._items = items;
};

AttachmentCollection.prototype.Load = function (callback) {
	var soapRequest = new SoapRequest('GetAttachment', {
		AttachmentIds: {
			AttachmentId: this._items.map(function (attachment) {
				return { attributes: attachment };
			})
		}
	});
	this._service.execute(soapRequest, callback);
}

Message.prototype.MessageCollection = MessageCollection;
Message.prototype.AttachmentCollection  = AttachmentCollection;

module.exports = Message;

<commit_msg>fix multiple attachments<commit_after>"use strict";

var SoapRequest = require('./SoapRequest');

function Message(service) {
    this._service = service;
    this._recipients = [];
	this._id = null;
	this._syncState = null;
	this._defaultFields = [
		'item:Attachments'
	];
	this._additionalFields = [];
	this._attachments = [];
}

Message.prototype.Bind = function (id) {
	this._id = id;
};

Message.prototype.setSyncState = function (syncState) {
	this._syncState = syncState;
};

Message.prototype.SendAndSaveCopy = function SendAndSaveCopy (callback) {
    this._messageDisposition = 'SendAndSaveCopy';
    this._sendSaveAction(callback);
};

Message.prototype.Send = function Send (callback) {
    this._messageDisposition = 'SendOnly';
    this._sendSaveAction(callback);
};

Message.prototype.Save = function Save (callback) {
    this._messageDisposition = 'SaveOnly';
    this._sendSaveAction(callback);
};

Message.prototype.addRecipient = function addRecipient(recipient) {
    this._recipients.push(recipient);
};

Message.prototype.sendItemAction = function _sendSaveAction (callback) {
    var soapRequest = new SoapRequest('SendItem', {
    	attributes: {
    		SaveItemToFolder: true
    	},
        ItemIds: {
            ItemId: {
		        attributes: {
		            Id: this.ItemId,
		            ChangeKey: this.ChangeKey
		        }
            }
        }
    });
    this._service.execute(soapRequest, callback);
};

Message.prototype._sendSaveAction = function _sendSaveAction (callback) {
    var soapRequest = new SoapRequest('CreateItem', {
        attributes: {
            MessageDisposition: this._messageDisposition
        },
        Items: {
            Message: {
            	Attachments: this._attachments.map(function (attachment) {
            		return {
            			FileAttachment: {
            				Name: attachment.Name,
            				IsInline: attachment.IsInline
            			}
            		};
            	}),
                ItemClass: 'IPM.Note',
                Subject: this.Subject,
                Body: {
                    attributes: {
                        BodyType: 'HTML'
                    },
                    $value: this.Body
                },
                ToRecipients: this._recipients.map(function (recipient) {
                    return {
                        Mailbox: {
                            EmailAddress: recipient
                        }
                    }
                }),
                From: {
                    Mailbox: {
                        EmailAddress: this.From
                    }
                }
            }
        }
    });

    this._service.execute(soapRequest, callback);
};

Message.prototype.BindAttachment = function (attachment) {
	this._attachments.push(attachment);
	return this;
};

Message.prototype.CreateAttachment = function (callback) {
	var soapRequest = new SoapRequest('CreateAttachment', {
        ParentItemId: {
	        attributes: {
	            Id: this.ItemId
	        }
        },
        Attachments: {
			FileAttachment: this._attachments.map(function (attachment) {
				if (attachment.isInline) {
					return {
	        			Name: attachment.name,
	        			Content: attachment.content,
	        			IsInline: attachment.isInline,
	        			ContentId: attachment.ContentId
					};
				} else {
					return {
	        			Name: attachment.name,
	        			Content: attachment.content
					};
				}
			})
		}
    });
    this._service.execute(soapRequest, callback);
};

Message.prototype.GetAttachments = function (callback) {
	var attachmentsCollection = new AttachmentCollection(this._service);
	attachmentsCollection.BindToItems(this._attachments);

	attachmentsCollection.Load(function (err, results) {
		if (!err) {
			this.Attachments = results;
		}

		callback(err, results);
	}.bind(this));
};

function MessageCollection(service) {
	this._service = service;
	this._defaultFields = [
		'item:Attachments'
	];
	this._baseShape = 'Default';
}

MessageCollection.prototype.BindToItems = function (items) {
	this._items = items;
}

MessageCollection.prototype.setBaseShape = function (baseShape) {
	this._baseShape = baseShape;
};

MessageCollection.prototype.Load = function (callback) {
	var soapRequest = new SoapRequest('GetItem', {
		ItemShape: {
			BaseShape: this._baseShape,
			IncludeMimeContent: true,
			AdditionalProperties: {
				FieldURI: this._defaultFields.map(function (field) {
					return { attributes: { FieldURI: field } };
				})
			}
		},
		ItemIds: {
			ItemId: this._items.map(function (item) {
					if (typeof item == 'string') {
						return {
							attributes: {
								Id: item,
								ChangeKey: ''
							}
						};
					}
					return {
						attributes: {
							Id: item.Id,
							ChangeKey: item.ChangeKey || ''
						}
					}
				})
		}
	});
	this._service.execute(soapRequest, callback);
};

function AttachmentCollection(service) {
	this._service = service;
	this._items = [];
}

AttachmentCollection.prototype.BindToItems = function (items) {
	this._items = items;
};

AttachmentCollection.prototype.Load = function (callback) {
	var soapRequest = new SoapRequest('GetAttachment', {
		AttachmentIds: {
			AttachmentId: this._items.map(function (attachment) {
				return { attributes: attachment };
			})
		}
	});
	this._service.execute(soapRequest, callback);
}

Message.prototype.MessageCollection = MessageCollection;
Message.prototype.AttachmentCollection  = AttachmentCollection;

module.exports = Message;

<|endoftext|>


<commit_before>
// Namespace and closure jQuery
(function($) {
  $(document).ready(function() {

    // Create basic models for bills and categories
    var Category = Backbone.Model.extend();
    var Bill = Backbone.Model.extend();

    // Collections
    var Bills = Backbone.Collection.extend({
      model: Bill,

      filterCategory: function (category) {
        return this.filter(function (bill) {
          var found = _.filter(bill.get('categories'), function(c) {
            return c == category;
          });
          return !_.isEmpty(found);
        });
      }
    });

    // Single bill view.
    var BillView = Backbone.View.extend({
      initialize: function(d) {
        // Every function that uses 'this' as the current object should be in here
        _.bindAll(this, 'render');

        this.model = d.model || new Bill();
        this.render();
      },

      render: function() {
        // Render template
        var template = _.template($("#template-bill").html(), { bill: this.model });
        $(this.el).html(template);
        return this;
      }
    });

    // Bills list view
    var BillsListView = Backbone.View.extend({
      events: {
        'click .show-bill': 'showBill'
      },

      initialize: function(d) {
        // Every function that uses 'this' as the current object should be in here
        _.bindAll(this, 'render', 'showBill', 'showFirstBill', 'filterCategory');

        this.collection = d.collection || new Bills();
        this.billView = new BillView({ el: $('#bill-detail-container') });
      },

      render: function() {
        // Render template
        var template = _.template($("#template-bill-list").html(), { bills: this.collection.models });
        $(this.el).html(template);

        return this;
      },

      showBill: function(e) {
        e.preventDefault();
        var thisElem = $(e.currentTarget);
        this.billView.model = this.collection.getByCid(thisElem.attr('data-id'));
        this.billView.render();
        return this;
      },

      showFirstBill: function(e) {
        this.billView.model = this.collection.at(0);
        this.billView.render();
        return this;
      },

      showCategory: function(category) {
        // Render template
        var template = _.template($("#template-category").html(), { category: category });
        $('#bill-category-container').html(template);
      },

      filterCategory: function(category) {
        this.collection.reset(this.collection.filterCategory(category));
        this.showCategory(category);
        this.showFirstBill();
        this.render();
      }
    });

    // Process bill data
    $.getJSON('data/bills.json', function(data) {
      console.log(data);
      // Create bills collection
      var bills = new Bills();
      for (var i in data) {
        data[i].bill = i;
        bills.add(new Bill(data[i]));
      }

      // Handle list of bills
      var billList = new BillsListView({el: $('#bills-list-container'), collection: bills });
      billList.filterCategory('Judiciary');
    });

  });
})(jQuery);<commit_msg>Removed console.<commit_after>
// Namespace and closure jQuery
(function($) {
  $(document).ready(function() {

    // Create basic models for bills and categories
    var Category = Backbone.Model.extend();
    var Bill = Backbone.Model.extend();

    // Collections
    var Bills = Backbone.Collection.extend({
      model: Bill,

      filterCategory: function (category) {
        return this.filter(function (bill) {
          var found = _.filter(bill.get('categories'), function(c) {
            return c == category;
          });
          return !_.isEmpty(found);
        });
      }
    });

    // Single bill view.
    var BillView = Backbone.View.extend({
      initialize: function(d) {
        // Every function that uses 'this' as the current object should be in here
        _.bindAll(this, 'render');

        this.model = d.model || new Bill();
        this.render();
      },

      render: function() {
        // Render template
        var template = _.template($("#template-bill").html(), { bill: this.model });
        $(this.el).html(template);
        return this;
      }
    });

    // Bills list view
    var BillsListView = Backbone.View.extend({
      events: {
        'click .show-bill': 'showBill'
      },

      initialize: function(d) {
        // Every function that uses 'this' as the current object should be in here
        _.bindAll(this, 'render', 'showBill', 'showFirstBill', 'filterCategory');

        this.collection = d.collection || new Bills();
        this.billView = new BillView({ el: $('#bill-detail-container') });
      },

      render: function() {
        // Render template
        var template = _.template($("#template-bill-list").html(), { bills: this.collection.models });
        $(this.el).html(template);

        return this;
      },

      showBill: function(e) {
        e.preventDefault();
        var thisElem = $(e.currentTarget);
        this.billView.model = this.collection.getByCid(thisElem.attr('data-id'));
        this.billView.render();
        return this;
      },

      showFirstBill: function(e) {
        this.billView.model = this.collection.at(0);
        this.billView.render();
        return this;
      },

      showCategory: function(category) {
        // Render template
        var template = _.template($("#template-category").html(), { category: category });
        $('#bill-category-container').html(template);
      },

      filterCategory: function(category) {
        this.collection.reset(this.collection.filterCategory(category));
        this.showCategory(category);
        this.showFirstBill();
        this.render();
      }
    });

    // Process bill data
    $.getJSON('data/bills.json', function(data) {
      // Create bills collection
      var bills = new Bills();
      for (var i in data) {
        data[i].bill = i;
        bills.add(new Bill(data[i]));
      }

      // Handle list of bills
      var billList = new BillsListView({el: $('#bills-list-container'), collection: bills });
      billList.filterCategory('Judiciary');
    });

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


<commit_before>import React from "react";
import {
  SiteTitle,
  SiteTitleLink,
  SiteTitleWrapper,
  Subheading,
  VolumeNumber,
  VolumeNumbers,
  VolumeNumbersWrapper
} from "./header.styles.js";

export default class Header extends React.Component {
  render() {
    const {
      volumeNumbers,
      volumeNumber,
      siteTitle,
      siteDescription
    } = this.props;
    return (

        <SiteTitleWrapper>
          <SiteTitle>
            <SiteTitleLink to="/">{siteTitle}</SiteTitleLink>
          </SiteTitle>
          <Subheading>{siteDescription}</Subheading>
        </SiteTitleWrapper>
        {volumeNumbers && (
          <VolumeNumbersWrapper>
            <VolumeNumbers>
              {volumeNumbers.map(volumeNumber_ => (
                <React.Fragment key={volumeNumber_}>
                  {volumeNumber_ === 1 && (
                    <>
                      Vol.{" "}
                    </>
                  )}
                  <VolumeNumber
                    key={volumeNumber_}
                    partiallyActive={volumeNumber != null}
                    activeClassName={"active"}
                    to={`/${volumeNumber_}`}
                  >
                    {volumeNumber_}
                  </VolumeNumber>
                </React.Fragment>
              ))}
            </VolumeNumbers>
          </VolumeNumbersWrapper>
        )}

    );
  }
}
<commit_msg>Volume link title<commit_after>import React from "react";
import {
  SiteTitle,
  SiteTitleLink,
  SiteTitleWrapper,
  Subheading,
  VolumeNumber,
  VolumeNumbers,
  VolumeNumbersWrapper
} from "./header.styles.js";

export default class Header extends React.Component {
  render() {
    const {
      volumeNumbers,
      volumeNumber,
      siteTitle,
      siteDescription
    } = this.props;
    return (

        <SiteTitleWrapper>
          <SiteTitle>
            <SiteTitleLink to="/">{siteTitle}</SiteTitleLink>
          </SiteTitle>
          <Subheading>{siteDescription}</Subheading>
        </SiteTitleWrapper>
        {volumeNumbers && (
          <VolumeNumbersWrapper>
            <VolumeNumbers>
              {volumeNumbers.map(volumeNumber_ => (
                <React.Fragment key={volumeNumber_}>
                  {volumeNumber_ === 1 && (
                    <>
                      Vol.{" "}
                    </>
                  )}
                  <VolumeNumber
                    key={volumeNumber_}
                    partiallyActive={volumeNumber != null}
                    activeClassName={"active"}
                    to={`/${volumeNumber_}`}
                    title={`Volume ${volumeNumber_}`}
                  >
                    {volumeNumber_}
                  </VolumeNumber>
                </React.Fragment>
              ))}
            </VolumeNumbers>
          </VolumeNumbersWrapper>
        )}

    );
  }
}
<|endoftext|>


<commit_before>/*
       _     _      _     _      _     _      _     _      _     _
  (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)
   / ._. \      / ._. \      / ._. \      / ._. \      / ._. \
 __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__
(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)
   || U ||      || C ||      || A ||      || Y ||      || A ||
 _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._
(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)
 `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-' */
(function () {

  var bookletName = 'trello-bookmarklets_get-contact-from-email';

  function getNewUuid() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
  }

  function gaCollect(action, label, value) {

    var img = document.createElement('img');
    img.height = 1;
    img.width = 1;
    img.src = 'https://www.google-analytics.com/collect?v=1&t=event&tid=UA-2711526-12' +
              '&ds=trello-bookmarklets' +
              '&dl=' + encodeURIComponent(document.location.href) +
              '&dh=' + encodeURIComponent(document.location.host) +
              '&dp=' + encodeURIComponent(document.location.pathname) +
              '&dt=' + encodeURIComponent(document.title) +
              '&ul=' + (navigator && navigator.languages ? navigator.languages[0] : navigator.language) +
              '&cid=' + (localStorage ? localStorage.getItem(bookletName + '_uid') : getNewUuid()) +
              '&ec=' + bookletName +
              '&ea=' + action +
              '&el=' + label +
              '&ev=' + value;
    img.onload = img.onreadystatechange = function() {
                                                    var state = this.readyState;
                                                    state && "loaded" !== state && "complete" !== state || img.parentNode.removeChild(img);
                                                }
    document.body.appendChild(img);
  }

  var start = function() {

    if (localStorage && !localStorage.getItem(bookletName + '_uid')) {
      localStorage.setItem(bookletName + '_uid', getNewUuid())
    }

    var parts = /\/c\/([^/]+)/.exec(document.location);

    if(!parts) {
      gaCollect('start', 'get-contact-from-email failed (You\'re not on Trello card)', 0);
      alert('You\'re not on Trello card.');
      return false;
    }

    gaCollect('start', 'get-contact-from-email success', 1);

    var inputTitle = $('.card-detail-window .js-card-detail-title-input');
    // var inputDesc = $('.card-detail-window .js-desc-content textarea.field');
    // var aDec = $('.card-detail-window .js-desc-content a.js-edit-desc');
    // a.click();
    // input.val(md);

    var email = /.+@.+\..+/i.exec(inputTitle.val());
    if (email) {
      email = inputTitle.val();

      $.get('https://proxy-sauce.glitch.me/https://clearbit.com/demos/combined?email=' + encodeURIComponent(email))
      .success(function(json){

        var data = JSON.parse(json);

        var desc = '>Email: ' + email + '\n' +
                   'Bio: ' + data.person.bio + '\n' +
                   'Location: ' + data.person.location + '\n' +
                   'Role: ' + data.person.role + ' ' + data.person.seniority + '\n' +
                   'Company: ' + data.company.name + '\n';

        var token = $.cookie('token');
        var idCard = parts[1];
        $.ajax({
          url: '/1/cards/' + idCard,
          method: 'PUT',
          data: {
            token: token,
            name: data.person.name,
            desc: desc
          }
        })
        .success(function(json){
          var card = JSON.parse(json);

          if (data.person.avatar) {
            $.post('/1/cards/' + card.id + 'attachments', {
              token: token,
              url: data.person.avatar
            });
          }
        });

      });
    } else {
      alert('The card\'s name is not an email.');
    }

  };

  start();

})();
<commit_msg>Add Avatar<commit_after>/*
       _     _      _     _      _     _      _     _      _     _
  (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)
   / ._. \      / ._. \      / ._. \      / ._. \      / ._. \
 __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__
(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)
   || U ||      || C ||      || A ||      || Y ||      || A ||
 _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._
(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)
 `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-' */
(function () {

  var bookletName = 'trello-bookmarklets_get-contact-from-email';

  function getNewUuid() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
  }

  function gaCollect(action, label, value) {

    var img = document.createElement('img');
    img.height = 1;
    img.width = 1;
    img.src = 'https://www.google-analytics.com/collect?v=1&t=event&tid=UA-2711526-12' +
              '&ds=trello-bookmarklets' +
              '&dl=' + encodeURIComponent(document.location.href) +
              '&dh=' + encodeURIComponent(document.location.host) +
              '&dp=' + encodeURIComponent(document.location.pathname) +
              '&dt=' + encodeURIComponent(document.title) +
              '&ul=' + (navigator && navigator.languages ? navigator.languages[0] : navigator.language) +
              '&cid=' + (localStorage ? localStorage.getItem(bookletName + '_uid') : getNewUuid()) +
              '&ec=' + bookletName +
              '&ea=' + action +
              '&el=' + label +
              '&ev=' + value;
    img.onload = img.onreadystatechange = function() {
                                                    var state = this.readyState;
                                                    state && "loaded" !== state && "complete" !== state || img.parentNode.removeChild(img);
                                                }
    document.body.appendChild(img);
  }

  var start = function() {

    if (localStorage && !localStorage.getItem(bookletName + '_uid')) {
      localStorage.setItem(bookletName + '_uid', getNewUuid())
    }

    var parts = /\/c\/([^/]+)/.exec(document.location);

    if(!parts) {
      gaCollect('start', 'get-contact-from-email failed (You\'re not on Trello card)', 0);
      alert('You\'re not on Trello card.');
      return false;
    }

    gaCollect('start', 'get-contact-from-email success', 1);

    var inputTitle = $('.card-detail-window .js-card-detail-title-input');
    // var inputDesc = $('.card-detail-window .js-desc-content textarea.field');
    // var aDec = $('.card-detail-window .js-desc-content a.js-edit-desc');
    // a.click();
    // input.val(md);

    var email = /.+@.+\..+/i.exec(inputTitle.val());
    if (email) {
      email = inputTitle.val();

      $.get('https://proxy-sauce.glitch.me/https://clearbit.com/demos/combined?email=' + encodeURIComponent(email))
      .success(function(json){

        var data = JSON.parse(json);

        var desc = '>Email: ' + email + '\n' +
                   'Bio: ' + data.person.bio + '\n' +
                   'Location: ' + data.person.location + '\n' +
                   'Role: ' + data.person.role + ' ' + data.person.seniority + '\n' +
                   'Company: ' + data.company.name + '\n';

        var token = $.cookie('token');
        var idCard = parts[1];
        $.ajax({
          url: '/1/cards/' + idCard,
          method: 'PUT',
          data: {
            token: token,
            name: data.person.name,
            desc: desc
          }
        })
        .success(function(json){
          var card = json;

          if (data.person.avatar) {
            $.post('/1/cards/' + card.id + 'attachments', {
              token: token,
              url: data.person.avatar
            });
          }
        });

      });
    } else {
      alert('The card\'s name is not an email.');
    }

  };

  start();

})();
<|endoftext|>


<commit_before>//
//  menu.js
//
//  Author:
//       Roman M. Yagodin <roman.yagodin@gmail.com>
//
//  Copyright (c) 2015 Roman M. Yagodin
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

function splitSubMenu(controlId, columns) {
	jQuery("ul#" + controlId + " .sub").each(function (i) {
		var items = jQuery(this).find('ul');
		var blockCount = columns;
		for (var i = 0; i < items.length; i += blockCount) {
			var slice = items.slice(i, i + blockCount);
			slice.wrapAll("

");
		}
	});
}

// called by hoverIntent and on top level menu links focus
function megaHoverOver() {
    var sub = jQuery(this).find(".sub");

    // show only if not showed
    if (sub.not(':visible')) {
        sub.stop().fadeTo('fast', 1).show()
            .prev().addClass("megahover");
    }

    // hide other submenus - in all menus!
    // jQuery(this).parents ("ul.megamenu") - only this menu
    jQuery("ul.megamenu").find('.sub').each (function () {
        if (!sub.is (this)) {
            jQuery(this).stop().css("opacity", 0).hide()
                .prev().removeClass("megahover");
        }
    });
}

// called by hoverIntent
function megaHoverOut() {
    // hide only if not focused
    if (jQuery(this).find(":focus").length === 0) {
        jQuery(this).find(".sub").stop().css("opacity", 0).hide()
            .prev().removeClass("megahover");
    }
}

jQuery(document).ready(function () {

	// calculate height of top level menu and set top style for menu placement
	jQuery('ul.megamenu .sub').css('top', jQuery('ul.megamenu > li').height());

	// set hover class to parent item
    // REVIEW: Move to megaHoverOver/Out?
    /*
	jQuery('li.level0 > .sub').mouseover(function () {
        jQuery(this).closest('li.level0 > a').addClass("megahover")
    }).mouseout(function () {
        jQuery(this).closest('li.level0 > a').removeClass("megahover")
	});*/

    // open submenu by focusing
    jQuery('li.level0 > a').focus(function () {
        jQuery(this).parent().each (function () { megaHoverOver.call(this); });
    });

    // hoverIntent options
    var config = {
		sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
		interval: 100, // number = milliseconds for onMouseOver polling interval
		over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
		timeout: 100, // number = milliseconds delay before onMouseOut
		out: megaHoverOut // function = onMouseOut callback (REQUIRED)
	};

    // invoke hoverIntent
	jQuery("ul.megamenu > li").hoverIntent(config);

    // mark current tab link
    if (epsilon.breadCrumbs) {
        jQuery("ul.megamenu a").filter (function() {
            return epsilon.breadCrumbs.indexOf (parseInt(jQuery(this).attr("data-id"))) !== -1;
        }).addClass ("current");
    }
});
<commit_msg>Close submenu even if it is focused, focus menu item hovered<commit_after>//
//  menu.js
//
//  Author:
//       Roman M. Yagodin <roman.yagodin@gmail.com>
//
//  Copyright (c) 2015 Roman M. Yagodin
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

function splitSubMenu(controlId, columns) {
	jQuery("ul#" + controlId + " .sub").each(function (i) {
		var items = jQuery(this).find('ul');
		var blockCount = columns;
		for (var i = 0; i < items.length; i += blockCount) {
			var slice = items.slice(i, i + blockCount);
			slice.wrapAll("

");
		}
	});
}

// called by hoverIntent and on top level menu links focus
function megaHoverOver() {
    var sub = jQuery(this).find(".sub");

    // show only if not showed
    if (sub.not(':visible')) {
        sub.stop().fadeTo('fast', 1).show()
            .prev().addClass("megahover").focus ();
    }

    // hide other submenus - in all menus!
    // jQuery(this).parents ("ul.megamenu") - only this menu
    jQuery("ul.megamenu").find('.sub').each (function () {
        if (!sub.is (this)) {
            jQuery(this).stop().css("opacity", 0).hide()
                .prev().removeClass("megahover");
        }
    });
}

// called by hoverIntent
function megaHoverOut() {
    jQuery(this).find(".sub").stop().css("opacity", 0).hide()
        .prev().removeClass("megahover");
}

jQuery(document).ready(function () {

	// calculate height of top level menu and set top style for menu placement
	jQuery('ul.megamenu .sub').css('top', jQuery('ul.megamenu > li').height());

	// set hover class to parent item
    // REVIEW: Move to megaHoverOver/Out?
    /*
	jQuery('li.level0 > .sub').mouseover(function () {
        jQuery(this).closest('li.level0 > a').addClass("megahover")
    }).mouseout(function () {
        jQuery(this).closest('li.level0 > a').removeClass("megahover")
	});*/

    // open submenu by focusing
    jQuery('li.level0 > a').focus(function () {
        jQuery(this).parent().each (function () { megaHoverOver.call(this); });
    });

    // hoverIntent options
    var config = {
		sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
		interval: 100, // number = milliseconds for onMouseOver polling interval
		over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
		timeout: 100, // number = milliseconds delay before onMouseOut
		out: megaHoverOut // function = onMouseOut callback (REQUIRED)
	};

    // invoke hoverIntent
	jQuery("ul.megamenu > li").hoverIntent(config);

    // mark current tab link
    if (epsilon.breadCrumbs) {
        jQuery("ul.megamenu a").filter (function() {
            return epsilon.breadCrumbs.indexOf (parseInt(jQuery(this).attr("data-id"))) !== -1;
        }).addClass ("current");
    }
});
<|endoftext|>


<commit_before>(function ($) {
	$.fn.track = function(options) {
		// Set defaults
		var defaults = {
			additional: [],
			dictionary: [],
			options: {
				forms: true,
				outbound: true,
				email: true,
				phone: true,
				anchor: true,
				universal: false,
				debug: false
			}
		};
		var settings = $.extend(true, {}, defaults, options );

		$.expr[':'].external = function(obj){
			return !obj.href.match(/^mailto:/) && !obj.href.match(/^tel:/) && !obj.href.match(/^#/) && (obj.hostname.replace(/^www\./i, '') != document.location.hostname.replace(/^www\./i, ''));
		};

		var calculateLabel = function ($obj, possibilities){
			var possibilities = (typeof possibilities == 'object') ? possibilities : ["data-track-everything-name", "name", "title", "id"];
			var eventLabel = null;
			for (var i = 0; i <= (possibilities.length - 1); i++) {
				var possibility = $obj.attr(possibilities[i]);
				if(possibility && possibility.length){
					eventLabel = possibility;
					break;
				}
			}
			return eventLabel;
		},

		pushEvent = function ( eventInfo ) {
			if(settings.options.debug){ console.log(eventInfo); }
			if(settings.options.universal){
				var gauEventInfo = {
					'hitType': 'event',
					'eventCategory': eventInfo[1],
					'eventAction': eventInfo[2]
				};
				if(eventInfo[3]){
					gauEventInfo['eventLabel'] = eventInfo[3];
				}
				if(eventInfo[4]){
					gauEventInfo['eventValue'] = eventInfo[4];
				}
				if(eventInfo[5]){
					gauEventInfo['nonInteraction'] = Number(eventInfo[4]);
				}

				try {
					ga('send', gauEventInfo);
				} catch (e) {
					if(settings.options.debug){
						console.log("Google Analytics be installed and initiated for Track Everything to work");
					}
				}

			}else{

				try {
					_gaq.push(eventInfo);
				} catch (e) {
					if(settings.options.debug){
						console.log("Google Analytics be installed and initiated for Track Everything to work");
					}
				}

			}
		},

		trackSpecialLink = function (context, identifier, name) {
			var $special = $(context).find('a[href^="' + identifier + '"]');
			$special.on("click.track-everything.track-everything-default keypress.track-everything.track-everything-default", function (e) {
				var eventLabel = calculateLabel($(this), ["data-track-everything-name", "href"]);

				var elementHref = $(this).attr("href");

				if(eventLabel == elementHref){
					eventLabel = elementHref.substring(identifier.length);
				}

				var eventInfo = ['_trackEvent', 'Link', name , eventLabel];
				pushEvent(eventInfo);
			});
			if(settings.options.debug){
				$special.addClass("track-everything track-everything-default track-everything-" + name.toLowerCase());
			}
		};

		return this.each(function() {
			for (var i = settings.dictionary.length - 1; i >= 0; i--) {
				$(this).find(settings.dictionary[i].selector).attr("data-track-everything-name", settings.dictionary[i].name);
			}

			if(settings.options.forms){
				var $forms = $(this).find("form");
				$forms.on("submit.track-everything.track-everything-default", function (e) {
					var eventLabel = calculateLabel($(this));

					var eventInfo = ['_trackEvent', 'Form', 'Submission'];
					if(eventLabel !== null){
						eventInfo.push(eventLabel);
					}
					pushEvent(eventInfo);
				});
				if(settings.options.debug){
					$forms.addClass("track-everything track-everything-default track-everything-form");
				}
			}

			if(settings.options.outbound){
				var $outbound = $(this).find("a:external");
				$outbound.on("click.track-everything.track-everything-default keypress.track-everything.track-everything-default", function (e) {
					var eventLabel = calculateLabel($(this), ["data-track-everything-name", "href"]);

					var eventInfo = ['_trackEvent', 'Link', 'Outbound', eventLabel, null, true];
					pushEvent(eventInfo);
				});
				if(settings.options.debug){
					$outbound.addClass("track-everything track-everything-default track-everything-outbound");
				}
			}

			if(settings.options.email){
				trackSpecialLink(this, "mailto:", "Email");
			}

			if(settings.options.phone){
				trackSpecialLink(this, "tel:", "Phone");
			}

			if(settings.options.anchor){
				trackSpecialLink(this, "#", "Anchor");
			}

			var context = this;

			$.each(settings.additional, function (i, additional){
				var $additional = $(context).find(additional.selector);
				$additional.off(".track-everything-default");
				if(settings.options.debug){
					$additional.addClass("track-everything track-everything-additional").removeClass("track-everything-default");
				}
				var events = [];
				for (var j = additional.events.length - 1; j >= 0; j--) {
					events.push(additional.events[j] + ".track-everything.track-everything-additional");
				}
				$additional.on(events.join(" "), function () {
					if(additional.name.length){
						$(this).attr("data-track-everything-override", additional.name);
					}
					var eventLabel = calculateLabel($(this), ["data-track-everything-override", "data-track-everything-name", "name", "title", "id", "href"]);
					var eventInfo = ['_trackEvent', additional.category, additional.action, eventLabel];

					pushEvent(eventInfo);
				});
			});
		});
	};
}( jQuery ));<commit_msg>i good at english!<commit_after>(function ($) {
	$.fn.track = function(options) {
		// Set defaults
		var defaults = {
			additional: [],
			dictionary: [],
			options: {
				forms: true,
				outbound: true,
				email: true,
				phone: true,
				anchor: true,
				universal: false,
				debug: false
			}
		};
		var settings = $.extend(true, {}, defaults, options );

		$.expr[':'].external = function(obj){
			return !obj.href.match(/^mailto:/) && !obj.href.match(/^tel:/) && !obj.href.match(/^#/) && (obj.hostname.replace(/^www\./i, '') != document.location.hostname.replace(/^www\./i, ''));
		};

		var calculateLabel = function ($obj, possibilities){
			var possibilities = (typeof possibilities == 'object') ? possibilities : ["data-track-everything-name", "name", "title", "id"];
			var eventLabel = null;
			for (var i = 0; i <= (possibilities.length - 1); i++) {
				var possibility = $obj.attr(possibilities[i]);
				if(possibility && possibility.length){
					eventLabel = possibility;
					break;
				}
			}
			return eventLabel;
		},

		pushEvent = function ( eventInfo ) {
			if(settings.options.debug){ console.log(eventInfo); }
			if(settings.options.universal){
				var gauEventInfo = {
					'hitType': 'event',
					'eventCategory': eventInfo[1],
					'eventAction': eventInfo[2]
				};
				if(eventInfo[3]){
					gauEventInfo['eventLabel'] = eventInfo[3];
				}
				if(eventInfo[4]){
					gauEventInfo['eventValue'] = eventInfo[4];
				}
				if(eventInfo[5]){
					gauEventInfo['nonInteraction'] = Number(eventInfo[4]);
				}

				try {
					ga('send', gauEventInfo);
				} catch (e) {
					if(settings.options.debug){
						console.log("Google Analytics must be installed and initiated for Track Everything to work");
					}
				}

			}else{

				try {
					_gaq.push(eventInfo);
				} catch (e) {
					if(settings.options.debug){
						console.log("Google Analytics must be installed and initiated for Track Everything to work");
					}
				}

			}
		},

		trackSpecialLink = function (context, identifier, name) {
			var $special = $(context).find('a[href^="' + identifier + '"]');
			$special.on("click.track-everything.track-everything-default keypress.track-everything.track-everything-default", function (e) {
				var eventLabel = calculateLabel($(this), ["data-track-everything-name", "href"]);

				var elementHref = $(this).attr("href");

				if(eventLabel == elementHref){
					eventLabel = elementHref.substring(identifier.length);
				}

				var eventInfo = ['_trackEvent', 'Link', name , eventLabel];
				pushEvent(eventInfo);
			});
			if(settings.options.debug){
				$special.addClass("track-everything track-everything-default track-everything-" + name.toLowerCase());
			}
		};

		return this.each(function() {
			for (var i = settings.dictionary.length - 1; i >= 0; i--) {
				$(this).find(settings.dictionary[i].selector).attr("data-track-everything-name", settings.dictionary[i].name);
			}

			if(settings.options.forms){
				var $forms = $(this).find("form");
				$forms.on("submit.track-everything.track-everything-default", function (e) {
					var eventLabel = calculateLabel($(this));

					var eventInfo = ['_trackEvent', 'Form', 'Submission'];
					if(eventLabel !== null){
						eventInfo.push(eventLabel);
					}
					pushEvent(eventInfo);
				});
				if(settings.options.debug){
					$forms.addClass("track-everything track-everything-default track-everything-form");
				}
			}

			if(settings.options.outbound){
				var $outbound = $(this).find("a:external");
				$outbound.on("click.track-everything.track-everything-default keypress.track-everything.track-everything-default", function (e) {
					var eventLabel = calculateLabel($(this), ["data-track-everything-name", "href"]);

					var eventInfo = ['_trackEvent', 'Link', 'Outbound', eventLabel, null, true];
					pushEvent(eventInfo);
				});
				if(settings.options.debug){
					$outbound.addClass("track-everything track-everything-default track-everything-outbound");
				}
			}

			if(settings.options.email){
				trackSpecialLink(this, "mailto:", "Email");
			}

			if(settings.options.phone){
				trackSpecialLink(this, "tel:", "Phone");
			}

			if(settings.options.anchor){
				trackSpecialLink(this, "#", "Anchor");
			}

			var context = this;

			$.each(settings.additional, function (i, additional){
				var $additional = $(context).find(additional.selector);
				$additional.off(".track-everything-default");
				if(settings.options.debug){
					$additional.addClass("track-everything track-everything-additional").removeClass("track-everything-default");
				}
				var events = [];
				for (var j = additional.events.length - 1; j >= 0; j--) {
					events.push(additional.events[j] + ".track-everything.track-everything-additional");
				}
				$additional.on(events.join(" "), function () {
					if(additional.name.length){
						$(this).attr("data-track-everything-override", additional.name);
					}
					var eventLabel = calculateLabel($(this), ["data-track-everything-override", "data-track-everything-name", "name", "title", "id", "href"]);
					var eventInfo = ['_trackEvent', additional.category, additional.action, eventLabel];

					pushEvent(eventInfo);
				});
			});
		});
	};
}( jQuery ));<|endoftext|>


<commit_before>// Plugin:
L.Polyline.polylineEditor = L.Polyline.extend({
    /**
     * This function must be explicitly called when the polyline is ready to
     * be edited.
     */
    edit: function() {
        if(!this._map) {
            alert('Not added to map!');
            return;
        }
        /**
         * Since all point editing is done by marker events, markers
         * will be the main holder of the polyline points locations.
         * Every marker contains a reference to the newPointMarker
         * *before* him (=> the first marker has newPointMarker=null).
         */
        this._markers = [];
        var that = this;
        var points = this.getLatLngs();
        var length = points.length;
        for(var i = 0; i < length; i++) {
            this._addMarkers(i, points[i]);
        }

        var map = this._map;
        this._map.on( "zoomend", function( e ) {
            console.log( "zoom level is " + map.getZoom() )
            that._showBoundMarkers();
        });
        this._map.on( "moveend", function( e ) {
            console.log( "zoom level is " + map.getZoom() )
            that._showBoundMarkers();
        });

        return this;
    },
    /**
     * Show only markers in current map bounds *is* there are only a certain
     * number of markers. This method is called on eventy that change map
     * bounds.
     */
    _showBoundMarkers: function() {
        var that = this;
        var bounds = this._map.getBounds();
        var found = 0;
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(bounds.contains(marker.getLatLng()))
                found += 1;
        }

        console.log("found=" + found);
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(found < 100) {
                that._setMarkerVisible(marker, bounds.contains(marker.getLatLng()));
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, bounds.contains(marker.getLatLng()));
            } else {
                that._setMarkerVisible(marker, false);
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, false);
            }
        }
    },
    /**
     * Show/hide marker.
     */
    _setMarkerVisible: function(marker, show) {
        if(!marker)
            return;

        var map = this._map;
        if(show) {
            if(!marker._map) { // First show fo this marker:
                marker.addTo(map);
            } else { // Marker was already shown and hidden:
                map.addLayer(marker);
            }
            marker._visible = true;
            marker._map = map;
        } else {
            map.removeLayer(marker);
            marker._visible = false;
        }
    },
    /**
     * Add two markers (a point marker and his newPointMarker) for a
     * single point.
     *
     * Markers are not added on the map here, the marker.addTo(map) is called
     * only later when needed first time because of performance issues.
     */
    _addMarkers: function(pointNo, latLng, fixNeighbourPositions) {
        var that = this;
        var points = this.getLatLngs();
        var marker = L.marker(latLng, {draggable: true, icon: pointIcon});

        marker.newPointMarker = null;
        marker.on('dragend', function(event) {
            var marker = event.target;
            var pointNo = that._getPointNo(event.target);
            that.setLatLngs(that._getMarkerLatLngs());
            that._fixNeighbourPositions(pointNo);
        });

        if(pointNo > 0) {
            var previousPoint = points[pointNo - 1];
            var newPointMarker = L.marker([(latLng.lat + previousPoint.lat) / 2.,
                                           (latLng.lng + previousPoint.lng) / 2.],
                                          {draggable: true, icon: newPointIcon});
            marker.newPointMarker = newPointMarker;
            newPointMarker.on('dragend', function(event) {
                var marker = event.target;
                var pointNo = that._getPointNo(event.target);
                that._addMarkers(pointNo, marker.getLatLng(), true);
                that.setLatLngs(that._getMarkerLatLngs());
            });
        }

        this._markers.splice(pointNo, 0, marker);

        if(fixNeighbourPositions) {
            this._fixNeighbourPositions(pointNo);
        }
    },
    /**
     * Fix nearby new point markers when the new point is created.
     */
    _fixNeighbourPositions: function(pointNo) {
        var previousMarker = pointNo == 0 ? null : this._markers[pointNo - 1];
        var marker = this._markers[pointNo];
        var nextMarker = pointNo < this._markers.length - 1 ? this._markers[pointNo + 1] : null;
        if(marker && previousMarker) {
            marker.newPointMarker.setLatLng([(previousMarker.getLatLng().lat + marker.getLatLng().lat) / 2.,
                                             (previousMarker.getLatLng().lng + marker.getLatLng().lng) / 2.]);
        }
        if(marker && nextMarker) {
            nextMarker.newPointMarker.setLatLng([(marker.getLatLng().lat + nextMarker.getLatLng().lat) / 2.,
                                                 (marker.getLatLng().lng + nextMarker.getLatLng().lng) / 2.]);
        }
    },
    _getPointNo: function(marker) {
        for(var i = 0; i < this._markers.length; i++) {
            if(marker == this._markers[i] || marker == this._markers[i].newPointMarker) {
                console.log("Found:" + i);
                return i;
            }
        }
        console.log("Nothing found for:" + marker);
        return -1;
    },
    /**
     * Get polyline latLngs based on marker positions.
     */
    _getMarkerLatLngs: function() {
        var result = [];
        for(var i = 0; i < this._markers.length; i++)
            result.push(this._markers[i].getLatLng());
        return result;
    },
});

L.Polyline.polylineEditor.addInitHook(function () {
    //this._initMarkers();
});

L.Polyline.PolylineEditor = function(latlngs, options){
    return new L.Polyline.polylineEditor(latlngs, options);
};

var pointIcon = L.icon({
        iconUrl: 'editmarker.png',
        iconSize: [11, 11],
        iconAnchor: [6, 6],
});
var newPointIcon = L.icon({
        iconUrl: 'editmarker2.png',
        iconSize: [11, 11],
        iconAnchor: [6, 6],
});
<commit_msg>Configurable icons<commit_after>// Plugin:
L.Polyline.polylineEditor = L.Polyline.extend({
    /**
     * This function must be explicitly called when the polyline is ready to
     * be edited.
     */
    edit: function(options) {
        if(!this._map) {
            alert('Not added to map!');
            return;
        }
        /**
         * Since all point editing is done by marker events, markers
         * will be the main holder of the polyline points locations.
         * Every marker contains a reference to the newPointMarker
         * *before* him (=> the first marker has newPointMarker=null).
         */
        this._parseOptions();

        this._markers = [];
        var that = this;
        var points = this.getLatLngs();
        var length = points.length;
        for(var i = 0; i < length; i++) {
            this._addMarkers(i, points[i]);
        }

        var map = this._map;
        this._map.on( "zoomend", function( e ) {
            console.log( "zoom level is " + map.getZoom() )
            that._showBoundMarkers();
        });
        this._map.on( "moveend", function( e ) {
            console.log( "zoom level is " + map.getZoom() )
            that._showBoundMarkers();
        });

        return this;
    },
    _parseOptions: function(options) {
        if(!options)
            options = {};

        if(options.pointIcon) {
            this.pointIcon = options.pointIcon;
        } else {
            this.pointIcon = L.icon({ iconUrl: 'editmarker.png', iconSize: [11, 11], iconAnchor: [6, 6], });
        }
        if(options.newPointIcon) {
            this.newPointIcon = options.newPointIcon;
        } else {
            this.newPointIcon = L.icon({ iconUrl: 'editmarker2.png', iconSize: [11, 11], iconAnchor: [6, 6], });
        }
    },
    /**
     * Show only markers in current map bounds *is* there are only a certain
     * number of markers. This method is called on eventy that change map
     * bounds.
     */
    _showBoundMarkers: function() {
        var that = this;
        var bounds = this._map.getBounds();
        var found = 0;
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(bounds.contains(marker.getLatLng()))
                found += 1;
        }

        console.log("found=" + found);
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(found < 100) {
                that._setMarkerVisible(marker, bounds.contains(marker.getLatLng()));
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, bounds.contains(marker.getLatLng()));
            } else {
                that._setMarkerVisible(marker, false);
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, false);
            }
        }
    },
    /**
     * Show/hide marker.
     */
    _setMarkerVisible: function(marker, show) {
        if(!marker)
            return;

        var map = this._map;
        if(show) {
            if(!marker._map) { // First show fo this marker:
                marker.addTo(map);
            } else { // Marker was already shown and hidden:
                map.addLayer(marker);
            }
            marker._visible = true;
            marker._map = map;
        } else {
            map.removeLayer(marker);
            marker._visible = false;
        }
    },
    /**
     * Add two markers (a point marker and his newPointMarker) for a
     * single point.
     *
     * Markers are not added on the map here, the marker.addTo(map) is called
     * only later when needed first time because of performance issues.
     */
    _addMarkers: function(pointNo, latLng, fixNeighbourPositions) {
        var that = this;
        var points = this.getLatLngs();
        var marker = L.marker(latLng, {draggable: true, icon: this.pointIcon});

        marker.newPointMarker = null;
        marker.on('dragend', function(event) {
            var marker = event.target;
            var pointNo = that._getPointNo(event.target);
            that.setLatLngs(that._getMarkerLatLngs());
            that._fixNeighbourPositions(pointNo);
        });

        if(pointNo > 0) {
            var previousPoint = points[pointNo - 1];
            var newPointMarker = L.marker([(latLng.lat + previousPoint.lat) / 2.,
                                           (latLng.lng + previousPoint.lng) / 2.],
                                          {draggable: true, icon: this.newPointIcon});
            marker.newPointMarker = newPointMarker;
            newPointMarker.on('dragend', function(event) {
                var marker = event.target;
                var pointNo = that._getPointNo(event.target);
                that._addMarkers(pointNo, marker.getLatLng(), true);
                that.setLatLngs(that._getMarkerLatLngs());
            });
        }

        this._markers.splice(pointNo, 0, marker);

        if(fixNeighbourPositions) {
            this._fixNeighbourPositions(pointNo);
        }
    },
    /**
     * Fix nearby new point markers when the new point is created.
     */
    _fixNeighbourPositions: function(pointNo) {
        var previousMarker = pointNo == 0 ? null : this._markers[pointNo - 1];
        var marker = this._markers[pointNo];
        var nextMarker = pointNo < this._markers.length - 1 ? this._markers[pointNo + 1] : null;
        if(marker && previousMarker) {
            marker.newPointMarker.setLatLng([(previousMarker.getLatLng().lat + marker.getLatLng().lat) / 2.,
                                             (previousMarker.getLatLng().lng + marker.getLatLng().lng) / 2.]);
        }
        if(marker && nextMarker) {
            nextMarker.newPointMarker.setLatLng([(marker.getLatLng().lat + nextMarker.getLatLng().lat) / 2.,
                                                 (marker.getLatLng().lng + nextMarker.getLatLng().lng) / 2.]);
        }
    },
    _getPointNo: function(marker) {
        for(var i = 0; i < this._markers.length; i++) {
            if(marker == this._markers[i] || marker == this._markers[i].newPointMarker) {
                console.log("Found:" + i);
                return i;
            }
        }
        console.log("Nothing found for:" + marker);
        return -1;
    },
    /**
     * Get polyline latLngs based on marker positions.
     */
    _getMarkerLatLngs: function() {
        var result = [];
        for(var i = 0; i < this._markers.length; i++)
            result.push(this._markers[i].getLatLng());
        return result;
    },
});

L.Polyline.polylineEditor.addInitHook(function () {
    //this._initMarkers();
});

L.Polyline.PolylineEditor = function(latlngs, options){
    return new L.Polyline.polylineEditor(latlngs, options);
};

<|endoftext|>


<commit_before>/*!
 * Chai - overwriteMethod utility
 * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
 * MIT Licensed
 */

/**
 * ### overwriteMethod (ctx, name, fn)
 *
 * Overwites an already existing method and provides
 * access to previous function. Must return function
 * to be used for name.
 *
 *     utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) {
 *       return function (str) {
 *         var obj = utils.flag(this, 'object');
 *         if (obj instanceof Foo) {
 *           new chai.Assertion(obj.value).to.equal(str);
 *         } else {
 *           _super.apply(this, arguments);
 *         }
 *       }
 *     });
 *
 * Can also be accessed directly from `chai.Assertion`.
 *
 *     chai.Assertion.overwriteMethod('foo', fn);
 *
 * Then can be used as any other assertion.
 *
 *     expect(myFoo).to.equal('bar');
 *
 * @param {Object} ctx object whose method is to be overwritten
 * @param {String} name of method to overwrite
 * @param {Function} method function that returns a function to be used for name
 * @name overwriteMethod
 * @api public
 */

module.exports = function (ctx, name, method) {
  var _method = ctx[name]
    , _super = function () { return this; };

  if (_method && 'function' === typeof _method)
    _super = _method;

  ctx[name] = function () {
    var result = method(_super).apply(this, arguments);
    return result === undefined ? this : result;
  }
};
<commit_msg>Delete overwriteMethod.js<commit_after><|endoftext|>


<commit_before>require('perfect-scrollbar/jquery')($);

$(function () {
    $('#stream').perfectScrollbar({suppressScrollX: true});

    $('#forum-tabs a').click(function() {
        let index = $('#forum-tabs a').index(this);
        $.post(_config.settings_url, {'homepage_mode': index});
    });

    $('#reputation-tabs a').click(function() {
        let index = $('#reputation-tabs a').index(this);
        $.post(_config.settings_url, {'homepage_reputation': index});
    });
});
<commit_msg>refaktoryzacja<commit_after>require('perfect-scrollbar/jquery')($);

$(function () {
    $('#stream').perfectScrollbar({suppressScrollX: true});
    let tabs = {'forum': $('#forum-tabs').find('a'), 'reputation': $('#reputation-tabs').find('a')};

    tabs.forum.click(function() {
        let index = tabs.forum.index(this);

        $.post(_config.settings_url, {'homepage_mode': index});
    });

    tabs.reputation.click(function() {
        let index = tabs.reputation.index(this);

        $.post(_config.settings_url, {'homepage_reputation': index});
    });
});
<|endoftext|>


<commit_before>// TODO: Replace placeholder shaders by original ones (requires fixing projection matrix)
import Promise from 'bluebird'
import fetchScript from '../../utils/io/fetch-script.js'
import PromiseCache from '../../utils/promise-cache.js'
import fragmentShader from './gblock/fragment-placeholder.glsl'
import vertexShader from './gblock/vertex-placeholder.glsl'

// configs

var LEGACY_GLFT_LOADER_URL = 'https://cdn.rawgit.com/mrdoob/three.js/r86/examples/js/loaders/GLTFLoader.js'
var GBLOCK_API_GET_OFFICIAL_GLTF_URL = 'https://us-central1-gblock-api.cloudfunctions.net/get-gltf-url/?url='

// internals

var promiseCache = new PromiseCache()

// aframe module

export default {

  schema: {type: 'asset'},

  init: function () {
    this.model = null
  },

  update: function () {
    var self = this
    var el = this.el
    var src = this.data

    if (!src) { return; }

    this.remove()

    // FIXME: Replace this with an official API URL once available
    // This API call is only needed to obtain the official glTF URL of a google block model.
    // The glTF itself is not being proxied and gets fetched from https://vr.google.com/downloads/* directly.
    // https://github.com/archilogic-com/aframe-gblock/issues/1
    // API server code: server/index.js
    // try promise cache (could be in loading state)
    var promiseFromCache = promiseCache.get(src)
    var getGltfUrlPromise = promiseFromCache ? promiseFromCache : getGltfUrl(src)
    if (!promiseFromCache) promiseCache.add(src, getGltfUrlPromise)

    getGltfUrlPromise.then(function (gltfUrl) {

      // load glTF model from original URL

      createModifiedGltfLoader().then(function(gltfLoader){

        gltfLoader.load( gltfUrl, function onLoaded (gltfModel) {

          self.model = gltfModel.scene || gltfModel.scenes[0]
          // FIXME: adapt projection matrix in original shaders and do not replace materials
          self.model.traverse(function (child) {
            if (child.material) child.material = new THREE.MeshPhongMaterial({ vertexColors: THREE.VertexColors })
          })
          self.model.animations = gltfModel.animations

          el.setObject3D('mesh', self.model)
          el.emit('model-loaded', {format: 'gltf', model: self.model})

        }, function onProgress() {
          // do nothing
        }, function onError(error) {

          console.error('ERROR loading gblock gltf "'+ src +'" : ' + error)
          el.emit('model-error', { message: error })

        })

      })

    }).catch(function(errorMessage){
      console.error(errorMessage)
      el.emit('model-error', { message: errorMessage })
    })

  },

  remove: function () {
    if (!this.model) { return; }
    this.el.removeObject3D('mesh')
  }

}

// private shared methods

function getGltfUrl (src) {

  return fetch(GBLOCK_API_GET_OFFICIAL_GLTF_URL + src).then(function (response) {

    // parse response
    return response.json().then(function (message) {
      if (response.ok) {
        // return glTF URL
        return message.gltfUrl
      } else {
        // handle error response
        var status = response.status
        var errorMessage = message.message
        console.error('ERROR loading gblock model "'+ src +'" : ' + status + ' "' + errorMessage + '"')
        return Promise.reject(errorMessage)
      }
    }).catch(function(error){
      // handle server error
      var errorMessage = '3dio.js: Error parsing gblock API server JSON response: ' + error
      console.error(errorMessage)
      return Promise.reject(errorMessage)
    })

  })

}

function createModifiedGltfLoader() {

  // legacy loader will overwrite THREE.GLTFLoader so we need to keep reference to it
  THREE.___OriginalGLTFLoader = THREE.GLTFLoader

  return fetchScript(LEGACY_GLFT_LOADER_URL).then(function(){

    // keep reference to fetched legacy loader
    var LegacyGLTFLoader = THREE.GLTFLoader

    // restore current GLTFLoader
    THREE.GLTFLoader = THREE.___OriginalGLTFLoader

    // create modified GLTF loader for google blocks
    function GBlockLoader () {

      LegacyGLTFLoader.call(this)

      var self = this

      this._parse = this.parse
      this.parse = function (data, path, onLoad, onError) {
        // convert uint8 to json
        var json = JSON.parse(convertUint8ArrayToString(data))
        // use base64 shaders
        Object.keys(json.shaders).forEach(function (key, i) {
          // Replacing original shaders with placeholders
          if (key.indexOf('fragment') > -1) json.shaders[key].uri = fragmentShader.base64
          else if (key.indexOf('vertex') > -1) json.shaders[key].uri = vertexShader.base64
        })
        // convert json to uint8
        var uint8array = new TextEncoder('utf-8').encode(JSON.stringify(json))
        // parse data
        self._parse.call(self, uint8array, path, onLoad, onError)
      }

    }
    GBlockLoader.prototype = LegacyGLTFLoader.prototype

    // expose loader
    return new GBlockLoader

  })

}

// from https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/GLTFLoader.js
function convertUint8ArrayToString (array) {
  if (window.TextDecoder !== undefined) {
    return new TextDecoder().decode(array)
  }
  // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  // throws a "maximum call stack size exceeded" error for large arrays.
  var s = '';
  for (var i = 0, il = array.length; i < il; i++) {
    s += String.fromCharCode(array[i])
  }
  return s;
}
<commit_msg>improves error message<commit_after>// TODO: Replace placeholder shaders by original ones (requires fixing projection matrix)
import Promise from 'bluebird'
import fetchScript from '../../utils/io/fetch-script.js'
import PromiseCache from '../../utils/promise-cache.js'
import fragmentShader from './gblock/fragment-placeholder.glsl'
import vertexShader from './gblock/vertex-placeholder.glsl'

// configs

var LEGACY_GLFT_LOADER_URL = 'https://cdn.rawgit.com/mrdoob/three.js/r86/examples/js/loaders/GLTFLoader.js'
var GBLOCK_API_GET_OFFICIAL_GLTF_URL = 'https://us-central1-gblock-api.cloudfunctions.net/get-gltf-url/?url='

// internals

var promiseCache = new PromiseCache()

// aframe module

export default {

  schema: {type: 'asset'},

  init: function () {
    this.model = null
  },

  update: function () {
    var self = this
    var el = this.el
    var src = this.data

    if (!src) { return; }

    this.remove()

    // FIXME: Replace this with an official API URL once available
    // This API call is only needed to obtain the official glTF URL of a google block model.
    // The glTF itself is not being proxied and gets fetched from https://vr.google.com/downloads/* directly.
    // https://github.com/archilogic-com/aframe-gblock/issues/1
    // API server code: server/index.js
    // try promise cache (could be in loading state)
    var promiseFromCache = promiseCache.get(src)
    var getGltfUrlPromise = promiseFromCache ? promiseFromCache : getGltfUrl(src)
    if (!promiseFromCache) promiseCache.add(src, getGltfUrlPromise)

    getGltfUrlPromise.then(function (gltfUrl) {

      // load glTF model from original URL

      createModifiedGltfLoader().then(function(gltfLoader){

        gltfLoader.load( gltfUrl, function onLoaded (gltfModel) {

          self.model = gltfModel.scene || gltfModel.scenes[0]
          // FIXME: adapt projection matrix in original shaders and do not replace materials
          self.model.traverse(function (child) {
            if (child.material) child.material = new THREE.MeshPhongMaterial({ vertexColors: THREE.VertexColors })
          })
          self.model.animations = gltfModel.animations

          el.setObject3D('mesh', self.model)
          el.emit('model-loaded', {format: 'gltf', model: self.model})

        }, function onProgress() {
          // do nothing
        }, function onError(error) {

          console.error('ERROR loading gblock model "'+ src +'" : ' + error)
          el.emit('model-error', { message: error })

        })

      })

    }).catch(function(errorMessage){
      console.error('ERROR loading gblock model from "' + src +'" : ' + errorMessage)
      el.emit('model-error', { message: errorMessage })
    })

  },

  remove: function () {
    if (!this.model) { return; }
    this.el.removeObject3D('mesh')
  }

}

// private shared methods

function getGltfUrl (src) {

  return fetch(GBLOCK_API_GET_OFFICIAL_GLTF_URL + src).then(function (response) {

    // parse response
    return response.json().then(function (message) {
      if (response.ok) {
        // return glTF URL
        return message.gltfUrl
      } else {
        // handle error response
        var status = response.status
        var errorMessage = message.message
        console.error('ERROR loading gblock model "'+ src +'" : ' + status + ' "' + errorMessage + '"')
        return Promise.reject(errorMessage)
      }
    }).catch(function(error){
      // handle server error
      var errorMessage = '3dio.js: Error parsing gblock API server JSON response: ' + error
      console.error(errorMessage)
      return Promise.reject(errorMessage)
    })

  })

}

function createModifiedGltfLoader() {

  // legacy loader will overwrite THREE.GLTFLoader so we need to keep reference to it
  THREE.___OriginalGLTFLoader = THREE.GLTFLoader

  return fetchScript(LEGACY_GLFT_LOADER_URL).then(function(){

    // keep reference to fetched legacy loader
    var LegacyGLTFLoader = THREE.GLTFLoader

    // restore current GLTFLoader
    THREE.GLTFLoader = THREE.___OriginalGLTFLoader

    // create modified GLTF loader for google blocks
    function GBlockLoader () {

      LegacyGLTFLoader.call(this)

      var self = this

      this._parse = this.parse
      this.parse = function (data, path, onLoad, onError) {
        // convert uint8 to json
        var json = JSON.parse(convertUint8ArrayToString(data))
        // use base64 shaders
        Object.keys(json.shaders).forEach(function (key, i) {
          // Replacing original shaders with placeholders
          if (key.indexOf('fragment') > -1) json.shaders[key].uri = fragmentShader.base64
          else if (key.indexOf('vertex') > -1) json.shaders[key].uri = vertexShader.base64
        })
        // convert json to uint8
        var uint8array = new TextEncoder('utf-8').encode(JSON.stringify(json))
        // parse data
        self._parse.call(self, uint8array, path, onLoad, onError)
      }

    }
    GBlockLoader.prototype = LegacyGLTFLoader.prototype

    // expose loader
    return new GBlockLoader

  })

}

// from https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/GLTFLoader.js
function convertUint8ArrayToString (array) {
  if (window.TextDecoder !== undefined) {
    return new TextDecoder().decode(array)
  }
  // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  // throws a "maximum call stack size exceeded" error for large arrays.
  var s = '';
  for (var i = 0, il = array.length; i < il; i++) {
    s += String.fromCharCode(array[i])
  }
  return s;
}
<|endoftext|>