<commit_before>var sel_ques = null;
var sel_line = '';
var sel_dir = '';
var dir_lookup = {};

var sel_args = {
    qnum : "",
    vehicle: "",
    day : "",
    tod : "",
    rte : "",
    dir : "",
    travel: "",
    satisfaction: ""
    }

//function for expanding/collapsing div content

function toggle_tb(div_id_tb){
    var div = $(div_id_tb);
    $('#toggle').unbind("click").click(function(){
         //div.slideToggle('fast');

         if ($(this).attr('value') == 'Hide') {
            console.log(this + 'hide selected')
            div.animate({
                height: '0%'
                }).hide()
            $(this).attr('value','Show')

        } else {
            console.log(this + 'show selected')
            div.animate({
                height: '100%'
                }).show()
            $(this).attr('value','Hide')

            }
       });
}

//append a svg file based on selected question num to div-id: line-chart

function append_img(div_id){
    var div = $(div_id);
    var qnum = questionkey[sel_ques]
    div.empty().prepend('<object data='+ base + 'static/image/' + 'q' + qnum + '.svg?' + Math.random() + ' type="image/svg+xml" width="100%" />');
}

//build table using JSON data in jquery
function build_table(data,tb_id){

    var table = $(tb_id)
    console.log(table)
    $(".data-row").empty()
    for(var i = 0;i < data.length; i++){
        console.log(data[i]);
        var row = $("
",{class: "data-row"});
        for(var j = 0; j < data[i].length; j++){
            var cell = $("", {align:"center",valign:"middle"}).text(data[i][j]);
            //console.log(cell);
            console.log(data[i][j])
            row.append(cell)
        }
        table.append(row)
    }
}

var questionkey = buildkey(questions);

for (var key in questionkey){
    var val = questionkey[key];
    console.log("Key: "+key+" Value:"+val);
}

//builds reference questionkey list
function buildkey(questions){
    var questionkey = {};
    for (var i = 0; i < questions.length; i++){
        questionkey[questions[i][1]] = questions[i][0];
    }

    return questionkey
}

var routeskey = buildkey(routes);

for (var key in routeskey){
    var val = routeskey[key];
    console.log("Key: "+key+" Value:"+val);
}

//builds reference routeskey list
function buildkey(routes){
    var routeskey = {};
    for (var i = 0; i < routes.length; i++){
        routeskey[routes[i][1]] = routes[i][0];
    }
    return routeskey
}

function reset(){
    $("#line-chart").hide();
    $("#button-header").hide();
    $("#toggle").attr('value','Hide');
    $("#satisfaction").hide();
    $("#origin").hide();
    $("#destination").hide();
    $("#travelchange").hide();
    $("#gasoline").hide();
    $("#ridership").hide();
    $("#rideyears").hide();
    $("#approval").hide();
    $("#onechange").hide();
    $("#age").hide();
    $("#gender").hide();
    $("#race").hide();
    $("#transit").hide();
    $("#vehicle").hide();
    $("#house").hide();
    $("#vecount").hide();
    $("#income").hide();
}

//set when a route, direction or user is selected from dropdowns
$(directions).each(function(index, item) {
    //console.log(directions);
    if(!dir_lookup.hasOwnProperty(item.rte)) {
        dir_lookup[item.rte] = [null, null];
    }
    dir_lookup[item.rte][item.dir] = item;

});

//console.log(dir_lookup);

$('#filter_line a').on('click', function() {
    sel_line = $(this).attr('rte');
    console.log(sel_line);
    sel_args.rte = sel_line;
    sel_dir = '';
    console.log(sel_dir);
    sel_args.dir = sel_dir;
    console.log(sel_args);
    $("#line_btn").text(this.text+' ').append('');

    if (this.text == "All") {
        //resert direction
        //show directions even the select is all
        $(".direction_cls").show();
        sel_args.rte = '';
    }
    else {
        //update direction dropdown with correct names
        var dir = dir_lookup[sel_line];
        console.log(this.text);
        //console.log(dir_lookup);
        $("#outbound_link").text(dir[0].dir_desc).attr("dir", dir[0].dir).show();
        //console.log(dir);
        $("#inbound_link").text(dir[1].dir_desc).attr("dir", dir[1].dir).show();
        $(".direction_cls").show();
    }

    $("#dir_btn").text('All ').append('');

    if (sel_line == 'All') {
        sel_line = '';
        sel_dir = '';
        sel_args.rte = '';
        sel_args.dir = '';
    }
    requestdata();
});
//function for when direction for a route is selected
$('#filter_dir a').on('click', function() {
    sel_dir = $(this).attr("dir");
    console.log("sel_dir: " + sel_dir);
    sel_args.dir = sel_dir;
    console.log(sel_args);
    $("#dir_btn").text(this.text+' ').append('');

    if (sel_dir == 'All') {
        sel_dir = '';
        sel_args.dir = '';
    }
    console.log(sel_dir);
    console.log(sel_args);
    requestdata();
});

$('#filter_ques a').on('click', function() {
    reset();
    sel_ques = this.text
    console.log(sel_ques)
    console.log(questionkey[sel_ques])
    var qnum = questionkey[sel_ques];
    //var args = {"qnum":(questionkey[sel_ques])};
    sel_args.qnum = questionkey[sel_ques];
    console.log("qnum: " + qnum)
    $("#ques_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_day a').on('click', function() {
    reset();
    var sel_day = this.text
    console.log("day selected: " + sel_day)
    if (sel_day == 'All') {
        sel_args.day = null;
    }
    else {
    sel_args.day = sel_day;
    }
    $("#day_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_vehicle a').on('click', function() {
    reset();
    var sel_vehicle = this.text
    console.log("vehicle selected: " + sel_vehicle)
    if (sel_vehicle == 'All') {
        sel_args.vehicle = null;
    }
    else {
    sel_args.vehicle = sel_vehicle;
    }
    $("#vehicle_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_travel a').on('click', function() {
    reset();
    var sel_travel = this.text
    console.log("travel change selected: " + sel_travel)
    if (sel_travel == 'All') {
        sel_args.travel = null;
    }
    else {
    sel_args.travel = sel_travel;
    }
    $("#travel_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_tod a').on('click', function() {
    reset();
    var sel_tod = this.text
    console.log("time of day selected: " + sel_tod)
    if (sel_tod == 'All') {
        sel_args.tod = null;
    }
    else {
    sel_args.tod = sel_tod;
    }
    $("#tod_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_satisfaction a').on('click', function() {
    reset();
    var sel_satisfaction = this.text
    console.log("satisfaction selected: " + sel_satisfaction)
    if (sel_satisfaction == 'All') {
        sel_args.satisfaction = null;
    }
    else {
    sel_args.satisfaction = sel_satisfaction;
    }
    $("#satisfaction_btn").text(this.text+' ').append('');
    requestdata();

});

function requestdata() {
    $.getJSON('/results/_data', sel_args, function(data) {
        console.log(data);
        div_id_ln = "#line-chart"
        div_id = "#" + data.metadata.id
        tb_id = div_id + "-table"
        data = data.data;

        build_table(data,tb_id);
        append_img(div_id_ln);
        toggle_tb(div_id);
        $(div_id).show();
        $("#line-chart").show();
        $("#button-header").show();

    });

}
<commit_msg>changed args for satisfaction to satis<commit_after>var sel_ques = null;
var sel_line = '';
var sel_dir = '';
var dir_lookup = {};

var sel_args = {
    qnum : "",
    vehicle: "",
    day : "",
    tod : "",
    rte : "",
    dir : "",
    travel: "",
    satis: ""
    }

//function for expanding/collapsing div content

function toggle_tb(div_id_tb){
    var div = $(div_id_tb);
    $('#toggle').unbind("click").click(function(){
         //div.slideToggle('fast');

         if ($(this).attr('value') == 'Hide') {
            console.log(this + 'hide selected')
            div.animate({
                height: '0%'
                }).hide()
            $(this).attr('value','Show')

        } else {
            console.log(this + 'show selected')
            div.animate({
                height: '100%'
                }).show()
            $(this).attr('value','Hide')

            }
       });
}

//append a svg file based on selected question num to div-id: line-chart

function append_img(div_id){
    var div = $(div_id);
    var qnum = questionkey[sel_ques]
    div.empty().prepend('<object data='+ base + 'static/image/' + 'q' + qnum + '.svg?' + Math.random() + ' type="image/svg+xml" width="100%" />');
}

//build table using JSON data in jquery
function build_table(data,tb_id){

    var table = $(tb_id)
    console.log(table)
    $(".data-row").empty()
    for(var i = 0;i < data.length; i++){
        console.log(data[i]);
        var row = $("
",{class: "data-row"});
        for(var j = 0; j < data[i].length; j++){
            var cell = $("", {align:"center",valign:"middle"}).text(data[i][j]);
            //console.log(cell);
            console.log(data[i][j])
            row.append(cell)
        }
        table.append(row)
    }
}

var questionkey = buildkey(questions);

for (var key in questionkey){
    var val = questionkey[key];
    console.log("Key: "+key+" Value:"+val);
}

//builds reference questionkey list
function buildkey(questions){
    var questionkey = {};
    for (var i = 0; i < questions.length; i++){
        questionkey[questions[i][1]] = questions[i][0];
    }

    return questionkey
}

var routeskey = buildkey(routes);

for (var key in routeskey){
    var val = routeskey[key];
    console.log("Key: "+key+" Value:"+val);
}

//builds reference routeskey list
function buildkey(routes){
    var routeskey = {};
    for (var i = 0; i < routes.length; i++){
        routeskey[routes[i][1]] = routes[i][0];
    }
    return routeskey
}

function reset(){
    $("#line-chart").hide();
    $("#button-header").hide();
    $("#toggle").attr('value','Hide');
    $("#satisfaction").hide();
    $("#origin").hide();
    $("#destination").hide();
    $("#travelchange").hide();
    $("#gasoline").hide();
    $("#ridership").hide();
    $("#rideyears").hide();
    $("#approval").hide();
    $("#onechange").hide();
    $("#age").hide();
    $("#gender").hide();
    $("#race").hide();
    $("#transit").hide();
    $("#vehicle").hide();
    $("#house").hide();
    $("#vecount").hide();
    $("#income").hide();
}

//set when a route, direction or user is selected from dropdowns
$(directions).each(function(index, item) {
    //console.log(directions);
    if(!dir_lookup.hasOwnProperty(item.rte)) {
        dir_lookup[item.rte] = [null, null];
    }
    dir_lookup[item.rte][item.dir] = item;

});

//console.log(dir_lookup);

$('#filter_line a').on('click', function() {
    sel_line = $(this).attr('rte');
    console.log(sel_line);
    sel_args.rte = sel_line;
    sel_dir = '';
    console.log(sel_dir);
    sel_args.dir = sel_dir;
    console.log(sel_args);
    $("#line_btn").text(this.text+' ').append('');

    if (this.text == "All") {
        //resert direction
        //show directions even the select is all
        $(".direction_cls").show();
        sel_args.rte = '';
    }
    else {
        //update direction dropdown with correct names
        var dir = dir_lookup[sel_line];
        console.log(this.text);
        //console.log(dir_lookup);
        $("#outbound_link").text(dir[0].dir_desc).attr("dir", dir[0].dir).show();
        //console.log(dir);
        $("#inbound_link").text(dir[1].dir_desc).attr("dir", dir[1].dir).show();
        $(".direction_cls").show();
    }

    $("#dir_btn").text('All ').append('');

    if (sel_line == 'All') {
        sel_line = '';
        sel_dir = '';
        sel_args.rte = '';
        sel_args.dir = '';
    }
    requestdata();
});
//function for when direction for a route is selected
$('#filter_dir a').on('click', function() {
    sel_dir = $(this).attr("dir");
    console.log("sel_dir: " + sel_dir);
    sel_args.dir = sel_dir;
    console.log(sel_args);
    $("#dir_btn").text(this.text+' ').append('');

    if (sel_dir == 'All') {
        sel_dir = '';
        sel_args.dir = '';
    }
    console.log(sel_dir);
    console.log(sel_args);
    requestdata();
});

$('#filter_ques a').on('click', function() {
    reset();
    sel_ques = this.text
    console.log(sel_ques)
    console.log(questionkey[sel_ques])
    var qnum = questionkey[sel_ques];
    //var args = {"qnum":(questionkey[sel_ques])};
    sel_args.qnum = questionkey[sel_ques];
    console.log("qnum: " + qnum)
    $("#ques_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_day a').on('click', function() {
    reset();
    var sel_day = this.text
    console.log("day selected: " + sel_day)
    if (sel_day == 'All') {
        sel_args.day = null;
    }
    else {
    sel_args.day = sel_day;
    }
    $("#day_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_vehicle a').on('click', function() {
    reset();
    var sel_vehicle = this.text
    console.log("vehicle selected: " + sel_vehicle)
    if (sel_vehicle == 'All') {
        sel_args.vehicle = null;
    }
    else {
    sel_args.vehicle = sel_vehicle;
    }
    $("#vehicle_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_travel a').on('click', function() {
    reset();
    var sel_travel = this.text
    console.log("travel change selected: " + sel_travel)
    if (sel_travel == 'All') {
        sel_args.travel = null;
    }
    else {
    sel_args.travel = sel_travel;
    }
    $("#travel_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_tod a').on('click', function() {
    reset();
    var sel_tod = this.text
    console.log("time of day selected: " + sel_tod)
    if (sel_tod == 'All') {
        sel_args.tod = null;
    }
    else {
    sel_args.tod = sel_tod;
    }
    $("#tod_btn").text(this.text+' ').append('');
    requestdata();

});

$('#filter_satisfaction a').on('click', function() {
    reset();
    var sel_satisfaction = this.text
    console.log("satisfaction selected: " + sel_satisfaction)
    if (sel_satisfaction == 'All') {
        sel_args.satis = null;
    }
    else {
    sel_args.satis = sel_satisfaction;
    }
    $("#satisfaction_btn").text(this.text+' ').append('');
    requestdata();

});

function requestdata() {
    $.getJSON('/results/_data', sel_args, function(data) {
        console.log(data);
        div_id_ln = "#line-chart"
        div_id = "#" + data.metadata.id
        tb_id = div_id + "-table"
        data = data.data;

        build_table(data,tb_id);
        append_img(div_id_ln);
        toggle_tb(div_id);
        $(div_id).show();
        $("#line-chart").show();
        $("#button-header").show();

    });

}
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    require("nehan");
    var AbstractView = require("modules/view/AbstractView");

    var EventsDetailView = AbstractView.extend({
        template : require("ldsh!/app/templates/events/eventsDetail"),
        serialize : function() {
            return {
                model : this.model
            };
        },
        beforeRendered : function() {

        },

        afterRendered : function() {
            // data-nehan属性を持つ要素全てに
            // nehan.jsを適用する
            this.$el.find('[data-nehan]')
                .each(function () {
                    var $el = $(this);

                    var engine = Nehan.setup({
                        layout: {
                            "flow": "tb-rl",
                            "width": 600,
                            "height": 600,
                            fontSize: 32
                        }
                    });

                    var content = $el.html();

                    $el.empty();

                    engine
                        .createPageStream(content)
                        .asyncGet({
                            onProgress: function (stream, tree) {
                                var page = stream.getPage(tree.pageNo);

                                $el.append(page.element);
                            }
                        });
                });
        },
        /**
         * 初期化処理
         */
        initialize : function() {

        }

    });

    module.exports = EventsDetailView;
});
<commit_msg>NAM-65 イベント:イベント表示 JSHintの警告を解消する<commit_after>/* global Nehan */
define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    require("nehan");
    var AbstractView = require("modules/view/AbstractView");

    var EventsDetailView = AbstractView.extend({
        template : require("ldsh!/app/templates/events/eventsDetail"),
        serialize : function() {
            return {
                model : this.model
            };
        },
        beforeRendered : function() {

        },

        afterRendered : function() {
            // data-nehan属性を持つ要素全てに
            // nehan.jsを適用する
            this.$el.find('[data-nehan]')
                .each(function () {
                    var $el = $(this);

                    var engine = Nehan.setup({
                        layout: {
                            "flow": "tb-rl",
                            "width": 600,
                            "height": 600,
                            fontSize: 32
                        }
                    });

                    var content = $el.html();

                    $el.empty();

                    engine
                        .createPageStream(content)
                        .asyncGet({
                            onProgress: function (stream, tree) {
                                var page = stream.getPage(tree.pageNo);

                                $el.append(page.element);
                            }
                        });
                });
        },
        /**
         * 初期化処理
         */
        initialize : function() {

        }

    });

    module.exports = EventsDetailView;
});
<|endoftext|>


<commit_before>
/*   Copyright (c) 2010-2011, Diaspora Inc.  This file is
*   licensed under the Affero General Public License version 3 or later.  See
*   the COPYRIGHT file.
*/

(function() {
  var Notifications = function() {
    var self = this;

    this.subscribe("widget/ready", function(evt, notificationArea, badge) {
      $.extend(self, {
        badge: badge,
        count: parseInt(badge.html()) || 0,
        notificationArea: notificationArea
      });

      $(".stream_element.unread").live("mousedown", function() {
        self.decrementCount();

        $.ajax({
          url: "notifications/" + $(this).removeClass("unread").data("guid"),
          type: "PUT"
        });
      });

      $("a.more").live("click", function(evt) {
        evt.preventDefault();
        $(this).hide()
          .next(".hidden")
          .removeClass("hidden");
      });
    });

    this.showNotification = function(notification) {
      $(notification.html).prependTo(this.notificationArea)
				.fadeIn(200)
				.delay(8000)
				.fadeOut(200, function() {
	  			$(this).detach();
				});

      if(typeof notification.incrementCount === "undefined" || notification.incrementCount) {
				this.incrementCount();
      }
    };

    this.changeNotificationCount = function(change) {
      self.count += change;

      if(self.badge.text() !== "") {
				self.badge.text(self.count);

				if(self.count === 0) {
	  			self.badge.addClass("hidden");
				}
				else if(self.count === 1) {
	  			self.badge.removeClass("hidden");
				}
      }
    };

    this.decrementCount = function() {
      self.changeNotificationCount(-1);
    };

    this.incrementCount = function() {
      self.changeNotificationCount(1);
    };
  };

  Diaspora.Widgets.Notifications = Notifications;
})();
<commit_msg>clicking on notifications takes note of the current UI state and makes sure that the resulting 'read' state matches the users expectation.<commit_after>
/*   Copyright (c) 2010-2011, Diaspora Inc.  This file is
*   licensed under the Affero General Public License version 3 or later.  See
*   the COPYRIGHT file.
*/

(function() {
  var Notifications = function() {
    var self = this;

    this.subscribe("widget/ready", function(evt, notificationArea, badge) {
      $.extend(self, {
        badge: badge,
        count: parseInt(badge.html()) || 0,
        notificationArea: notificationArea
      });

      $(".stream_element.unread,.stream_element.read").live("mousedown", function() {
        if ( $(this).hasClass("unread") ) {
          self.decrementCount();
          $(this).removeClass("unread").addClass( "read" )
        }
        else {
          self.incrementCount();
          $(this).removeClass("read").addClass( "unread" )
        }
        $.ajax({
          url: "notifications/" + $(this).data("guid"),
          data: { is_unread: $(this).hasClass("unread") },
          type: "PUT"
        });
      });

      $("a.more").live("click", function(evt) {
        evt.preventDefault();
        $(this).hide()
          .next(".hidden")
          .removeClass("hidden");
      });
    });

    this.showNotification = function(notification) {
      $(notification.html).prependTo(this.notificationArea)
				.fadeIn(200)
				.delay(8000)
				.fadeOut(200, function() {
	  			$(this).detach();
				});

      if(typeof notification.incrementCount === "undefined" || notification.incrementCount) {
				this.incrementCount();
      }
    };

    this.changeNotificationCount = function(change) {
      self.count += change;

      if(self.badge.text() !== "") {
				self.badge.text(self.count);

				if(self.count === 0) {
	  			self.badge.addClass("hidden");
				}
				else if(self.count === 1) {
	  			self.badge.removeClass("hidden");
				}
      }
    };

    this.decrementCount = function() {
      self.changeNotificationCount(-1);
    };

    this.incrementCount = function() {
      self.changeNotificationCount(1);
    };
  };

  Diaspora.Widgets.Notifications = Notifications;
})();
<|endoftext|>


<commit_before>/**
 * VIE - Vienna IKS Editables
 * (c) 2011 Henri Bergius, IKS Consortium
 */
(function() {
    // Export the VIE namespace for both CommonJS and the browser
    var VIE;
    if (typeof exports !== 'undefined') {
        VIE = exports;
    } else {
        VIE = this.VIE = {};
    }

    // Require underscore using CommonJS require if it isn't yet loaded
    var _ = this._;
    if (!_ && (typeof require !== 'undefined')) { _ = require('underscore')._; }
    if (!_) {
        throw 'VIE requires underscore.js to be available';
    }

    // Require Backbone using CommonJS require if it isn't yet loaded
    var Backbone = this.Backbone;
    if (!Backbone && (typeof require !== 'undefined')) { Backbone = require('backbone'); }
    if (!Backbone) {
        throw 'VIE requires Backbone.js to be available';
    }

    // Require jQuery using CommonJS require if it isn't yet loaded
    var jQuery = this.jQuery;
    if (!jQuery && (typeof require !== 'undefined')) { jQuery = require('jquery'); }
    if (!jQuery) {
        throw 'VIE requires jQuery to be available';
    }

    // Backbone Model for RDF entities
    VIE.RDFEntity = Backbone.Model.extend({
        namespaces: {},
        type: '',

        toJSONLD: function() {
            var instance = this;
            var instanceLD = {};
            var property;

            if (typeof instance.id !== 'undefined') {
                instanceLD['@'] = '<' + instance.id + '>';
            } else {
                instanceLD['@'] = instance.cid.replace('c', '_:bnode');
            }

            if (instance.namespaces.length > 0) {
                instanceLD['#'] = instance.namespaces;
            }

            if (instance.type) {
                instanceLD.a = instance.type;
            }

            for (property in instance.attributes) {
                if (instance.attributes.hasOwnProperty(property)) { //  && typeof instance.attributes[property] != "function"
                    if (['id'].indexOf(property) === -1) {
                        instanceLD[property] = instance.attributes[property];
                    }
                }
            }
            return instanceLD;
        }
    });

    // Backbone View for RDF entities represented in RDFa
    VIE.RDFaView = Backbone.View.extend({
        // Ensure view gets updated when properties of the entity change
        initialize: function() {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
        },

        render: function() {
            VIE.RDFa.writeEntity(this.el, this.model.toJSONLD());
            return this;
        }
    });

    // Entity Manager keeps track of all RDFa entities loaded via VIE
    VIE.EntityManager = {
        Entities: {},
        allEntities: [],

        Types: {},

        getBySubject: function(id) {
            if (typeof VIE.EntityManager.Entities[id] === 'undefined') {
                return null;
            }
            return VIE.EntityManager.Entities[id];
        },

        getByJSONLD: function(jsonld) {
            var entityInstance;
            var properties;

            properties = VIE.EntityManager._JSONtoProperties(jsonld);

            if (typeof jsonld['@'] !== 'undefined') {
                entityInstance = VIE.EntityManager.getBySubject(jsonld['@']);
                if (entityInstance) {
                    entityInstance.set(properties);
                    return entityInstance;
                }
            }

            entityInstance = new VIE.RDFEntity(properties);

            if (typeof jsonld['#'] !== 'undefined') {
                entityInstance.namespaces = jsonld['#'];
            }

            if (typeof jsonld.a !== 'undefined') {
                entityInstance.type = jsonld.a;
            }

            if (typeof jsonld['@'] !== 'undefined') {
                entityInstance.id = jsonld['@'];
                VIE.EntityManager.Entities[entityInstance.id] = entityInstance;
            }

            VIE.EntityManager.allEntities.push(entityInstance);

            return entityInstance;
        },

        // Clean up JSON-LD so that it can be used as properties in a Backbone Model
        _JSONtoProperties: function(jsonld) {
            var properties;
            properties = jQuery.extend({}, jsonld);
            delete properties['@'];
            delete properties.a;
            delete properties['#'];
            return properties;
        }
    };

    // Mapping between RDFa and Backbone models
    VIE.RDFaEntities = {
        Views: [],

        // Create a Backbone model instance for a RDFa-marked element
        getInstance: function(element) {
            element = jQuery(element);
            var entityInstance;
            var viewInstance;
            var jsonld;

            jsonld = VIE.RDFa.readEntity(element);
            if (!jsonld) {
                return null;
            }

            entityInstance = VIE.EntityManager.getByJSONLD(jsonld);

            jQuery.each(VIE.RDFaEntities.Views, function() {
                // Check whether we already have this view instantiated for the element
                if (this.el.get(0) === element.get(0)) {
                    viewInstance = this;
                    return false;
                }
            });

            if (!viewInstance) {
                // Create a view for the RDFa
                viewInstance = new VIE.RDFaView({
                    model: entityInstance,
                    el: element,
                    tagName: element.get(0).nodeName
                });
                VIE.RDFaEntities.Views.push(viewInstance);
            }

            return entityInstance;
        },

        // Get a list of Backbone model instances for all RDFa-marked content in an element
        getInstances: function(element) {
            var entities = [];
            var entity;

            if (typeof element === 'undefined') {
                // We're working with the full document scope
                element = jQuery(document);
            }

            jQuery(VIE.RDFa.subjectSelector, element).add(jQuery(element).filter(VIE.RDFa.subjectSelector)).each(function() {
                entity = VIE.RDFaEntities.getInstance(this);
                if (entity) {
                    entities.push(entity);
                }
            });

            return entities;
        }
    };

    // RDFa reading and writing utilities
    VIE.RDFa = {
        // Resolved prefix->namespace pairs
        Namespaces: {},

        subjectSelector: '[about],[typeof],[src],html',
        predicateSelector: '[property],[rel]',

        // Get a JSON-LD en
        readEntity: function(element) {
            var entity;
            var subject;
            var namespaces = {};
            var namespace;
            var type;
            var propertyName;

            subject = VIE.RDFa.getSubject(element);

            // Read properties from element
            entity = VIE.RDFa._getElementProperties(subject, element, false);
            if (jQuery.isEmptyObject(entity)) {
                // No properties, skip creating entity
                return null;
            }

            // Resolve namespaces
            for (propertyName in entity) {
                if (entity.hasOwnProperty(propertyName)) {
                    var propertyParts = propertyName.split(':');
                    if (propertyParts.length === 2) {
                        namespace = VIE.RDFa._resolveNamespace(propertyParts[0], element);
                        if (namespace) {
                            namespaces[propertyParts[0]] = namespace;
                        }
                    }
                }
            }
            if (!jQuery.isEmptyObject(namespaces)) {
                entity['#'] = namespaces;
            }

            // Read typeof from element
            type = VIE.RDFa._getElementValue(element, 'typeof');
            if (type) {
                entity.a = type;
            }

            if (typeof subject === 'string') {
                entity['@'] = subject;
            }
            return entity;
        },

        readEntities: function(element) {
            var entities = [];
            var entity;

            if (typeof element === 'undefined') {
                // We're working with the full document scope
                element = jQuery(document);
            }

            jQuery(VIE.RDFa.subjectSelector, element).add(jQuery(element).filter(VIE.RDFa.subjectSelector)).each(function() {
                entity = VIE.RDFa.readEntity(this);
                if (entity) {
                    entities.push(entity);
                }
            });

            return entities;
        },

        writeEntity: function(element, jsonld) {
            VIE.RDFa.findElementProperties(VIE.RDFa.getSubject(element), element, true).each(function() {
                var propertyElement = jQuery(this);
                var propertyName = propertyElement.attr('property');

                if (typeof jsonld[propertyName] === 'undefined') {
                    // Entity doesn't contain this property
                    return true;
                }

                if (jsonld[propertyName] instanceof Array) {
                    // For now we don't deal with multivalued properties in Views
                    return true;
                }

                if (VIE.RDFa._readPropertyValue(propertyElement) !== jsonld[propertyName]) {
                    VIE.RDFa._writePropertyValue(propertyElement, jsonld[propertyName]);
                }
            });
            return this;
        },

        _readPropertyValue: function(element) {
            // Property has machine-readable content value
            var content = element.attr('content');
            if (content) {
                return content;
            }
            var resource = element.attr('resource');
            if (resource) {
                return '<' + resource + '>';
            }
            var href = element.attr('href');
            if (href) {
                return '<' + href + '>';
            }

            if (element.attr('rel')) {
                // Relation, we should look for identified child objects
                var value = [];
                jQuery(element).children(VIE.RDFa.subjectSelector).each(function() {
                    var subject = VIE.RDFa.getSubject(this);
                    if (typeof subject === 'string') {
                        value.push('<' + subject + '>');
                    }
                });
                return value;
            }

            // Property has inline value
            return element.html();
        },

        _writePropertyValue: function(element, value) {
            // Property has machine-readable content value
            var content = element.attr('content');
            if (content) {
                element.attr('content', value);
                return;
            }
            var resource = element.attr('resource');
            if (resource) {
                element.attr('resource', value);
            }

            // Property has inline value
            element.html(value);
        },

        getSubject: function(element) {
            if (typeof document !== 'undefined') {
                if (element === document) {
                    return document.baseURI;
                }
            }
            var subject;
            jQuery(element).closest(VIE.RDFa.subjectSelector).each(function() {
                if (jQuery(this).attr('about')) {
                    subject = jQuery(this).attr('about');
                    return true;
                }
                if (jQuery(this).attr('src')) {
                    subject = jQuery(this).attr('src');
                    return true;
                }
                if (jQuery(this).attr('typeof')) {
                    subject = this;
                    return true;
                }

                // Handle baseURL also outside browser context
                if (jQuery(this).get(0).nodeName === 'HTML') {
                    jQuery(this).find('base').each(function() {
                        subject = jQuery(this).attr('href');
                    });
                }
            });

            return subject;
        },

        _resolveNamespace: function(prefix, element) {
            if (typeof VIE.RDFa.Namespaces[prefix] !== 'undefined') {
                return VIE.RDFa.Namespaces[prefix];
            }

            jQuery('[xmlns\\:' + prefix + ']').each(function() {
                VIE.RDFa.Namespaces[prefix] = jQuery(this).attr('xmlns:' + prefix);
            });

            return VIE.RDFa.Namespaces[prefix];
        },

        // Get the value of attribute from the element or from one of its children
        _getElementValue: function(element, propertyName) {
            element = jQuery(element);
            if (typeof element.attr(propertyName) !== 'undefined')
            {
                // Direct match with container
                return element.attr(propertyName);
            }
            return element.children('[' + propertyName + ']').attr(propertyName);
        },

        findElementProperties: function(subject, element, allowPropertiesInProperties) {
            return jQuery(element).find(VIE.RDFa.predicateSelector).add(jQuery(element).filter(VIE.RDFa.predicateSelector)).filter(function() {
                if (VIE.RDFa.getSubject(this) !== subject) {
                    // The property is under another entity, skip
                    return false;
                }

                if (!allowPropertiesInProperties) {
                    if (!jQuery(this).parents('[property]').length) {
                        return true;
                    }
                    // This property is under another property, skip
                    return false;
                }

                return true;
            });
        },

        _getElementProperties: function(subject, element, emptyValues) {
            var containerProperties = {};

            VIE.RDFa.findElementProperties(subject, element, true).each(function() {
                var propertyName;
                var propertyValue;
                var objectProperty = jQuery(this);

                propertyName = objectProperty.attr('property');
                if (!propertyName) {
                    propertyName = objectProperty.attr('rel');
                }

                propertyValue = VIE.RDFa._readPropertyValue(objectProperty);

                if (typeof containerProperties[propertyName] !== 'undefined') {
                    if (containerProperties[propertyName] instanceof Array) {
                        if (emptyValues) {
                            return;
                        }
                        containerProperties[propertyName].push(propertyValue);
                        return;
                    }
                    // Multivalued property, convert to Array
                    var previousValue = containerProperties[propertyName];
                    containerProperties[propertyName] = [];

                    if (emptyValues) {
                        return;
                    }

                    containerProperties[propertyName].push(previousValue);
                    containerProperties[propertyName].push(propertyValue);
                    return;
                }

                if (emptyValues) {
                    containerProperties[propertyName] = '';
                    return;
                }

                containerProperties[propertyName] = propertyValue;
            });

            return containerProperties;
        }
    };

    VIE.cleanup = function() {
        VIE.EntityManager.Entities = {};
        VIE.EntityManager.allEntities = [];
        VIE.EntityManager.Types = {};
        VIE.RDFaEntities.Views = [];
        VIE.RDFa.Namespaces = {};
    };

}).call(this);
<commit_msg>Started documenting VIE in literate style<commit_after>//     VIE - Vienna IKS Editables
//     (c) 2011 Henri Bergius, IKS Consortium
//     VIE may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://wiki.iks-project.eu/index.php/VIE
//
//  [VIE](http://wiki.iks-project.eu/index.php/VIE) enables you to make
//  [RDFa](http://en.wikipedia.org/wiki/RDFa) -annotated content on your
//  web pages editable.
//
//  For example, if your page contains the following mark-up:
//
//

//       In his latest book
//       Wikinomics,
//       Don Tapscott
//       explains deep changes in technology,
//       demographics and business.
//       The book is due to be published in
//       October 2006.
//

//
// Then with VIE you can get a proper Backbone Model object for that. First
// scan your page for RDFa entities:
//
//     VIE.RDFaEntities.getInstances();
//
// And then just access the entity by subject:
//
//     var myBook = VIE.EntityManager.getBySubject('http://www.example.com/books/wikinomics');
//     alert(objectInstance.get('dc:title')); // "Wikinomics"
//
// Properties of the entity may also be modified, and these changes will
// also happen on the page itself:
//
//     myBook.set({'dc:title':'Wikinomics, Second Edition'});
//
// You can also access the entities via the `VIE.EntityManager.allEntities` array.
(function() {
    // Initial setup
    // -------------
    //
    // The VIE library is fully contained inside a `VIE` namespace. The
    // namespace is available in both CommonJS and the browser.
    var VIE;
    if (typeof exports !== 'undefined') {
        VIE = exports;
    } else {
        VIE = this.VIE = {};
    }

    // ### Handle dependencies
    //
    // VIE tries to load its dependencies automatically.
    // Please note that this autoloading functionality only works on the server.
    // On browser Backbone needs to be included manually.

    // Require [underscore.js](http://documentcloud.github.com/underscore/)
    // using CommonJS require if it isn't yet loaded.
    //
    // On node.js underscore.js can be installed via:
    //
    //     npm install underscore
    var _ = this._;
    if (!_ && (typeof require !== 'undefined')) { _ = require('underscore')._; }
    if (!_) {
        throw 'VIE requires underscore.js to be available';
    }

    // Require [Backbone.js](http://documentcloud.github.com/backbone/)
    // using CommonJS require if it isn't yet loaded.
    //
    // On node.js Backbone.js can be installed via:
    //
    //     npm install backbone
    var Backbone = this.Backbone;
    if (!Backbone && (typeof require !== 'undefined')) { Backbone = require('backbone'); }
    if (!Backbone) {
        throw 'VIE requires Backbone.js to be available';
    }

    // Require [jQuery](http://jquery.com/) using CommonJS require if it
    // isn't yet loaded.
    //
    // On node.js jQuery can be installed via:
    //
    //     npm install jquery
    var jQuery = this.jQuery;
    if (!jQuery && (typeof require !== 'undefined')) { jQuery = require('jquery'); }
    if (!jQuery) {
        throw 'VIE requires jQuery to be available';
    }

    // VIE.RDFEntity
    // -------------
    //
    // VIE.RDFEntity defines a common [Backbone Model](http://documentcloud.github.com/backbone/#Model)
    // for RDF entities handled in VIE.
    VIE.RDFEntity = Backbone.Model.extend({
        namespaces: {},
        type: '',

        // VIE's entities have a method for generating [JSON-LD](http://json-ld.org/)
        // representations of themselves. JSON-LD is a lightweight format for handling
        // Linked Data (RDF) information.
        //
        // Using the book example from above, we could call:
        //
        //     myBook.toJSONLD();
        //
        // And we would get a JSON object looking like the following:
        //
        //     {
        //         '@': '<http://www.example.com/books/wikinomics>',
        //         'dc:title': 'Wikinomics',
        //         'dc:creator': 'Don Tapscott',
        //         'dc:date': '2006-10-01'
        //     }
        //
        // Calling `JSON.stringify()` for this object would produce:
        //
        //
        //     {
        //         "@": "<http://www.example.com/books/wikinomics>",
        //         "dc:title": "Wikinomics",
        //         "dc:creator": "Don Tapscott",
        //         "dc:date": "2006-10-01"
        //     }
        toJSONLD: function() {
            var instance = this;
            var instanceLD = {};
            var property;

            if (typeof instance.id !== 'undefined') {
                instanceLD['@'] = '<' + instance.id + '>';
            } else {
                instanceLD['@'] = instance.cid.replace('c', '_:bnode');
            }

            if (instance.namespaces.length > 0) {
                instanceLD['#'] = instance.namespaces;
            }

            if (instance.type) {
                instanceLD.a = instance.type;
            }

            for (property in instance.attributes) {
                if (instance.attributes.hasOwnProperty(property)) {
                    if (['id'].indexOf(property) === -1) {
                        instanceLD[property] = instance.attributes[property];
                    }
                }
            }
            return instanceLD;
        }
    });

    // VIE.RDFaView
    // -------------
    //
    // VIE.RDFEntity defines a common [Backbone View](http://documentcloud.github.com/backbone/#View)
    // for all RDFa -annotated elements on a page that have been loaded as
    // `VIE.RDFEntity` objects.
    VIE.RDFaView = Backbone.View.extend({

        // We ensure view gets updated when properties of the Entity change.
        initialize: function() {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
        },

        // Rendering a view means writing the properties of the Entity back to
        // the element containing our RDFa annotations.
        render: function() {
            VIE.RDFa.writeEntity(this.el, this.model.toJSONLD());
            return this;
        }
    });

    // VIE.EntityManager
    // -------------
    //
    // VIE.EntityManager keeps track of all RDFa entities loaded via VIE. This
    // means that entities matched by a common subject can be treated as singletons.
    //
    // It is possible to access all loaded entities via the
    // `VIE.EntityManager.allEntities` array.
    VIE.EntityManager = {
        Entities: {},
        allEntities: [],

        Types: {},

        // ### VIE.EntityManager.getBySubject
        //
        // It is possible to get an entity that has been loaded from the page
        // via the `getBySubject` method. If the entity cannot be found this method
        // will return `null`.
        //
        // The entities accessed this way are singletons, so multiple calls to same
        // subject will all return the same `VIE.RDFEntity` instance.
        //
        // Example:
        //
        //     var myBook = VIE.EntityManager.getBySubject('http://www.example.com/books/wikinomics');
        getBySubject: function(id) {
            if (typeof VIE.EntityManager.Entities[id] === 'undefined') {
                return null;
            }
            return VIE.EntityManager.Entities[id];
        },

        // ### VIE.EntityManager.getByJSONLD
        //
        // Another way to get or load entities is by passing EntityManager a valid
        // JSON-LD object.
        //
        // This can be either called with a JavaScript object representing JSON-LD,
        // or with a JSON-LD string.
        //
        // Example:
        //
        //     var json = '{"@": "<http://www.example.com/books/wikinomics>","dc:title": "Wikinomics","dc:creator": "Don Tapscott","dc:date": "2006-10-01"}';
        //     var objectInstance = VIE.EntityManager.getByJSONLD(json);
        //
        // The entities accessed this way are singletons, so multiple calls to same
        // subject (`@` in JSON-LD) will all return the same `VIE.RDFEntity` instance.
        getByJSONLD: function(jsonld) {
            var entityInstance;
            var properties;

            if (typeof jsonld !== 'object') {
                try {
                    jsonld = jQuery.parseJSON(jsonld);
                } catch (e) {
                    return null;
                }
            }

            properties = VIE.EntityManager._JSONtoProperties(jsonld);

            if (typeof jsonld['@'] !== 'undefined') {
                entityInstance = VIE.EntityManager.getBySubject(jsonld['@']);
                if (entityInstance) {
                    entityInstance.set(properties);
                    return entityInstance;
                }
            }

            entityInstance = new VIE.RDFEntity(properties);

            if (typeof jsonld['#'] !== 'undefined') {
                entityInstance.namespaces = jsonld['#'];
            }

            if (typeof jsonld.a !== 'undefined') {
                entityInstance.type = jsonld.a;
            }

            if (typeof jsonld['@'] !== 'undefined') {
                entityInstance.id = jsonld['@'];
                VIE.EntityManager.Entities[entityInstance.id] = entityInstance;
            }

            VIE.EntityManager.allEntities.push(entityInstance);

            return entityInstance;
        },

        // Helper for cleaning up JSON-LD so that it can be used as properties
        // of a Backbone Model
        _JSONtoProperties: function(jsonld) {
            var properties;
            properties = jQuery.extend({}, jsonld);
            delete properties['@'];
            delete properties.a;
            delete properties['#'];
            return properties;
        }
    };

    // Mapping between RDFa and Backbone models
    VIE.RDFaEntities = {
        Views: [],

        // Create a Backbone model instance for a RDFa-marked element
        getInstance: function(element) {
            element = jQuery(element);
            var entityInstance;
            var viewInstance;
            var jsonld;

            jsonld = VIE.RDFa.readEntity(element);
            if (!jsonld) {
                return null;
            }

            entityInstance = VIE.EntityManager.getByJSONLD(jsonld);

            jQuery.each(VIE.RDFaEntities.Views, function() {
                // Check whether we already have this view instantiated for the element
                if (this.el.get(0) === element.get(0)) {
                    viewInstance = this;
                    return false;
                }
            });

            if (!viewInstance) {
                // Create a view for the RDFa
                viewInstance = new VIE.RDFaView({
                    model: entityInstance,
                    el: element,
                    tagName: element.get(0).nodeName
                });
                VIE.RDFaEntities.Views.push(viewInstance);
            }

            return entityInstance;
        },

        // Get a list of Backbone model instances for all RDFa-marked content in an element
        getInstances: function(element) {
            var entities = [];
            var entity;

            if (typeof element === 'undefined') {
                // We're working with the full document scope
                element = jQuery(document);
            }

            jQuery(VIE.RDFa.subjectSelector, element).add(jQuery(element).filter(VIE.RDFa.subjectSelector)).each(function() {
                entity = VIE.RDFaEntities.getInstance(this);
                if (entity) {
                    entities.push(entity);
                }
            });

            return entities;
        }
    };

    // RDFa reading and writing utilities
    VIE.RDFa = {
        // Resolved prefix->namespace pairs
        Namespaces: {},

        subjectSelector: '[about],[typeof],[src],html',
        predicateSelector: '[property],[rel]',

        // Get a JSON-LD en
        readEntity: function(element) {
            var entity;
            var subject;
            var namespaces = {};
            var namespace;
            var type;
            var propertyName;

            subject = VIE.RDFa.getSubject(element);

            // Read properties from element
            entity = VIE.RDFa._getElementProperties(subject, element, false);
            if (jQuery.isEmptyObject(entity)) {
                // No properties, skip creating entity
                return null;
            }

            // Resolve namespaces
            for (propertyName in entity) {
                if (entity.hasOwnProperty(propertyName)) {
                    var propertyParts = propertyName.split(':');
                    if (propertyParts.length === 2) {
                        namespace = VIE.RDFa._resolveNamespace(propertyParts[0], element);
                        if (namespace) {
                            namespaces[propertyParts[0]] = namespace;
                        }
                    }
                }
            }
            if (!jQuery.isEmptyObject(namespaces)) {
                entity['#'] = namespaces;
            }

            // Read typeof from element
            type = VIE.RDFa._getElementValue(element, 'typeof');
            if (type) {
                entity.a = type;
            }

            if (typeof subject === 'string') {
                entity['@'] = subject;
            }
            return entity;
        },

        readEntities: function(element) {
            var entities = [];
            var entity;

            if (typeof element === 'undefined') {
                // We're working with the full document scope
                element = jQuery(document);
            }

            jQuery(VIE.RDFa.subjectSelector, element).add(jQuery(element).filter(VIE.RDFa.subjectSelector)).each(function() {
                entity = VIE.RDFa.readEntity(this);
                if (entity) {
                    entities.push(entity);
                }
            });

            return entities;
        },

        writeEntity: function(element, jsonld) {
            VIE.RDFa.findElementProperties(VIE.RDFa.getSubject(element), element, true).each(function() {
                var propertyElement = jQuery(this);
                var propertyName = propertyElement.attr('property');

                if (typeof jsonld[propertyName] === 'undefined') {
                    // Entity doesn't contain this property
                    return true;
                }

                if (jsonld[propertyName] instanceof Array) {
                    // For now we don't deal with multivalued properties in Views
                    return true;
                }

                if (VIE.RDFa._readPropertyValue(propertyElement) !== jsonld[propertyName]) {
                    VIE.RDFa._writePropertyValue(propertyElement, jsonld[propertyName]);
                }
            });
            return this;
        },

        _readPropertyValue: function(element) {
            // Property has machine-readable content value
            var content = element.attr('content');
            if (content) {
                return content;
            }
            var resource = element.attr('resource');
            if (resource) {
                return '<' + resource + '>';
            }
            var href = element.attr('href');
            if (href) {
                return '<' + href + '>';
            }

            if (element.attr('rel')) {
                // Relation, we should look for identified child objects
                var value = [];
                jQuery(element).children(VIE.RDFa.subjectSelector).each(function() {
                    var subject = VIE.RDFa.getSubject(this);
                    if (typeof subject === 'string') {
                        value.push('<' + subject + '>');
                    }
                });
                return value;
            }

            // Property has inline value
            return element.html();
        },

        _writePropertyValue: function(element, value) {
            // Property has machine-readable content value
            var content = element.attr('content');
            if (content) {
                element.attr('content', value);
                return;
            }
            var resource = element.attr('resource');
            if (resource) {
                element.attr('resource', value);
            }

            // Property has inline value
            element.html(value);
        },

        getSubject: function(element) {
            if (typeof document !== 'undefined') {
                if (element === document) {
                    return document.baseURI;
                }
            }
            var subject;
            jQuery(element).closest(VIE.RDFa.subjectSelector).each(function() {
                if (jQuery(this).attr('about')) {
                    subject = jQuery(this).attr('about');
                    return true;
                }
                if (jQuery(this).attr('src')) {
                    subject = jQuery(this).attr('src');
                    return true;
                }
                if (jQuery(this).attr('typeof')) {
                    subject = this;
                    return true;
                }

                // Handle baseURL also outside browser context
                if (jQuery(this).get(0).nodeName === 'HTML') {
                    jQuery(this).find('base').each(function() {
                        subject = jQuery(this).attr('href');
                    });
                }
            });

            return subject;
        },

        _resolveNamespace: function(prefix, element) {
            if (typeof VIE.RDFa.Namespaces[prefix] !== 'undefined') {
                return VIE.RDFa.Namespaces[prefix];
            }

            jQuery('[xmlns\\:' + prefix + ']').each(function() {
                VIE.RDFa.Namespaces[prefix] = jQuery(this).attr('xmlns:' + prefix);
            });

            return VIE.RDFa.Namespaces[prefix];
        },

        // Get the value of attribute from the element or from one of its children
        _getElementValue: function(element, propertyName) {
            element = jQuery(element);
            if (typeof element.attr(propertyName) !== 'undefined')
            {
                // Direct match with container
                return element.attr(propertyName);
            }
            return element.children('[' + propertyName + ']').attr(propertyName);
        },

        findElementProperties: function(subject, element, allowPropertiesInProperties) {
            return jQuery(element).find(VIE.RDFa.predicateSelector).add(jQuery(element).filter(VIE.RDFa.predicateSelector)).filter(function() {
                if (VIE.RDFa.getSubject(this) !== subject) {
                    // The property is under another entity, skip
                    return false;
                }

                if (!allowPropertiesInProperties) {
                    if (!jQuery(this).parents('[property]').length) {
                        return true;
                    }
                    // This property is under another property, skip
                    return false;
                }

                return true;
            });
        },

        _getElementProperties: function(subject, element, emptyValues) {
            var containerProperties = {};

            VIE.RDFa.findElementProperties(subject, element, true).each(function() {
                var propertyName;
                var propertyValue;
                var objectProperty = jQuery(this);

                propertyName = objectProperty.attr('property');
                if (!propertyName) {
                    propertyName = objectProperty.attr('rel');
                }

                propertyValue = VIE.RDFa._readPropertyValue(objectProperty);

                if (typeof containerProperties[propertyName] !== 'undefined') {
                    if (containerProperties[propertyName] instanceof Array) {
                        if (emptyValues) {
                            return;
                        }
                        containerProperties[propertyName].push(propertyValue);
                        return;
                    }
                    // Multivalued property, convert to Array
                    var previousValue = containerProperties[propertyName];
                    containerProperties[propertyName] = [];

                    if (emptyValues) {
                        return;
                    }

                    containerProperties[propertyName].push(previousValue);
                    containerProperties[propertyName].push(propertyValue);
                    return;
                }

                if (emptyValues) {
                    containerProperties[propertyName] = '';
                    return;
                }

                containerProperties[propertyName] = propertyValue;
            });

            return containerProperties;
        }
    };

    VIE.cleanup = function() {
        VIE.EntityManager.Entities = {};
        VIE.EntityManager.allEntities = [];
        VIE.EntityManager.Types = {};
        VIE.RDFaEntities.Views = [];
        VIE.RDFa.Namespaces = {};
    };

}).call(this);
<|endoftext|>


<commit_before>import { shape, render, play } from './tmp';

const from = {
  type: 'circle',
  cx: 25,
  cy: 25,
  r: 25,
  fill: '#E54',
};

const to = {
  type: 'path',
  d: 'M75,75l10-5l15,20v10h-10l-5-5l-10,5z',
  fill: '#0FA',
  moveIndex: 1,
  reverse: true,
};

const animation = shape( from, to );

render({ selector: '.svg' }, animation );

play( animation, {
  alternate: true,
  duration: 2000,
  iterations: Infinity,
});
<commit_msg>docs(examples): remove reverse from morph example shape<commit_after>import { shape, render, play } from './tmp';

const from = {
  type: 'circle',
  cx: 25,
  cy: 25,
  r: 25,
  fill: '#E54',
};

const to = {
  type: 'path',
  d: 'M75,75l10-5l15,20v10h-10l-5-5l-10,5z',
  fill: '#0FA',
  moveIndex: 1,
};

const animation = shape( from, to );

render({ selector: '.svg' }, animation );

play( animation, {
  alternate: true,
  duration: 2000,
  iterations: Infinity,
});
<|endoftext|>


<commit_before>export default {
  en: {
    about: {
      title: 'ABOUT',
      subtitle: 'Some info about me',

      introTitle: 'Me',

      intro: 'Hi. I\'m Arturo Coronel (you can call me Yayu). I\'m 21 años, I live at Tijuana, MX and I ❤ web development.',

      work: 'I work as a frontend developer, I study Computer Engineering, help on research projects and sometimes I do freelance. But my main job is to learn and share every single day.',

      openSource: 'I love to share almost every projects I made on my Github account, with MIT license, so anyone can use my work as inspiration. I also publish there tools and modules that I\'ve developed to make my job easier; in that way other people can be more productive and learn from what I do as well',

      hobbies: 'My hobbies are watching anime, listening to podcasts, learn about my favorite voice actresses, write about frontend and help other people to improve their skills',

      contactTitle: 'Contact',

      contactText: 'Want to know more about me or contract my services? Do you have any idea or suggestion to improve this site? Want to talk about web develoment or chinese cartoons? Contact me!'
    }
  },

  es: {
    about: {
      title: 'INFO',
      subtitle: 'Algo de informacion acerca de mi',

      introTitle: 'YO',

      intro: 'Hola. Soy Arturo Coronel (puedes llamarme Yayu), tengo 21 años, vivo en Tijuana, MX y amo el desarrollo web ♥.',

      work: 'Trabajo haciendo frontend, soy estudiante de ingeniería en computación en la UABC, ayudo en proyectos de investigación y de vez en cuando hago freelance. Pero ante todo me dedico a aprender por mi cuenta todos los días.',

      openSource: 'Me gusta compartir casi todo lo que hago en mi cuenta de Github, con licencia de MIT para que cualquiera pueda inspirarse; así como herramientas y librerías que he desarrollado para hacer más fácil mi trabajo, así otros pueden hacer más fácil el suyo y aprender de mi código.',

      hobbies: 'Mis hobbies son ver anime, escuchar podcasts, stalkear aprender acerca de mis actrices de voz favoritas, escribir acerca de javascript y ayudar a los demás a aprender.',

      contactTitle: 'Contacto',

      contactText: '¿Quieres saber más de mí o contratar mis servicios? ¿Tienes alguna idea o sugerencia para mejorar este blog? ¿Deseas platicar de tecnologías web o monas chinas? ¡Contáctame!'
    }
  }
}
<commit_msg>Updated about copy<commit_after>export default {
  en: {
    about: {
      title: 'ABOUT',
      subtitle: 'Some info about me',

      introTitle: 'Me',

      intro: 'Hi! I\'m Arturo Coronel (you can call me Yayu). I\'m 21 years old, I live at Tijuana, MX and I ❤ web development.',

      work: 'I work as a frontend developer, I study Computer Engineering, help on research projects and sometimes I do freelance. But my main job is to learn and share every single day.',

      openSource: 'I love to share almost every projects I made on my Github account, with MIT license, so anyone can use my work as inspiration. I also publish there tools and modules that I\'ve developed to make my job easier; in that way other people can be more productive and learn from what I do as well.',

      hobbies: 'My hobbies are watching anime, listening to podcasts, learn about my favorite voice actresses, write about frontend and help other people to improve their skills.',

      contactTitle: 'Contact',

      contactText: 'Want to know more about me or contract my services? Do you have any idea or suggestion to improve this site? Want to talk about web develoment or chinese cartoons? Contact me!'
    }
  },

  es: {
    about: {
      title: 'INFO',
      subtitle: 'Algo de informacion acerca de mi',

      introTitle: 'YO',

      intro: 'Hola. Soy Arturo Coronel (puedes llamarme Yayu), tengo 21 años, vivo en Tijuana, MX y amo el desarrollo web ❤.',

      work: 'Trabajo como desarrollador de front-end, estudio ingeniería en computación, ayudo en proyectos de investigación y hago freelance. Pero mi trabajo principal es aprender y compartir todos los días.',

      openSource: 'Me gusta compartir casi todo lo que hago en mi cuenta de Github, con licencia de MIT para que cualquiera pueda inspirarse; así como herramientas y librerías que he desarrollado para hacer más fácil mi trabajo, así otros pueden hacer más fácil el suyo y aprender de mi código.',

      hobbies: 'Mis hobbies son ver anime, escuchar podcasts, aprender acerca de mis actrices de voz favoritas, escribir acerca de frontend y ayudar a los demás a mejorar sus habilidades.',

      contactTitle: 'Contacto',

      contactText: '¿Quieres saber más de mí o contratar mis servicios? ¿Tienes alguna idea o sugerencia para mejorar este blog? ¿Deseas platicar de tecnologías web o monas chinas? ¡Contáctame!'
    }
  }
}
<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Extends the table widget to a column toggle menu and responsive column visibility
//>>label: Table: Column Toggle
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.table.columntoggle.css

define( [ "jquery", "./jquery.mobile.table", "../jquery.mobile.buttonMarkup", "./popup" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.mobile.table.prototype.options.mode = "columntoggle";

$.mobile.table.prototype.options.columnBtnClass = "";

$.mobile.table.prototype.options.columnBtnText = "Columns...";

$.mobile.table.prototype.options.classes = $.extend(
   $.mobile.table.prototype.options.classes,
   {
      popup: "ui-table-columntoggle-popup",
      columnsButton: "ui-table-columntoggle-btn",
      priorityPrefix: "ui-table-priority-",
      columnToggleTable: "ui-table-columntoggle"
   }
);

$( document ).delegate( ":jqmData(role='table')", "tablecreate", function() {

   var $table = $( this ),
      self = $table.jqmData( "table" ),
      o = self.options;

   if( o.mode !== "columntoggle" ){
      return;
   }

   self.element.addClass( o.classes.columnToggleTable );

   var id = ( $table.attr( "id" ) || self.options.classes.popup ) + "-popup", //TODO BETTER FALLBACK ID HERE
      $menuButton = $( "" + o.columnBtnText + "" ),
      $popup = $( "

"),
      $menu = $("<fieldset data-role='controlgroup'></fieldset>").appendTo( $popup );

   // create the hide/show toggles
   self._headers.not( "td" ).each(function(){

      var priority = $( this ).jqmData( "priority" ),
         $cells = $( this ).add( $( this ).jqmData( "cells" ) );

      if( priority !== "persist" ){

         $cells.addClass( o.classes.priorityPrefix + priority );

         $("<input type='checkbox' checked />" + $( this ).text() + "" )
            .appendTo( $menu )
            .children( 0 )
            .jqmData( "cells", $cells )
            .checkboxradio();
      }
   });

   $menuButton
      .insertBefore( $table )
      .buttonMarkup();

   $popup
      .insertBefore( $table )
      .popup();

   // bind change event listeners to inputs - TODO: move to a private method?
   $menu.on( "change", "input", function( e ){
      if( this.checked ){
         $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-hidden" ).addClass( "ui-table-cell-visible" );
      }
      else {
         $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-visible" ).addClass( "ui-table-cell-hidden" );
      }
   } );

   function refreshMenu(){
      $menu.find( "input" ).each( function(){
            this.checked = $( this ).jqmData( "cells" ).eq(0).is( ":visible" );
            $( this ).checkboxradio( "refresh" );
      } );
   }

   refreshMenu();

   $( window ).on( "throttledresize", refreshMenu );

});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>removed data-priority persist<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Extends the table widget to a column toggle menu and responsive column visibility
//>>label: Table: Column Toggle
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.table.columntoggle.css

define( [ "jquery", "./jquery.mobile.table", "../jquery.mobile.buttonMarkup", "./popup" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.mobile.table.prototype.options.mode = "columntoggle";

$.mobile.table.prototype.options.columnBtnClass = "";

$.mobile.table.prototype.options.columnBtnText = "Columns...";

$.mobile.table.prototype.options.classes = $.extend(
   $.mobile.table.prototype.options.classes,
   {
      popup: "ui-table-columntoggle-popup",
      columnsButton: "ui-table-columntoggle-btn",
      priorityPrefix: "ui-table-priority-",
      columnToggleTable: "ui-table-columntoggle"
   }
);

$( document ).delegate( ":jqmData(role='table')", "tablecreate", function() {

   var $table = $( this ),
      self = $table.jqmData( "table" ),
      o = self.options;

   if( o.mode !== "columntoggle" ){
      return;
   }

   self.element.addClass( o.classes.columnToggleTable );

   var id = ( $table.attr( "id" ) || self.options.classes.popup ) + "-popup", //TODO BETTER FALLBACK ID HERE
      $menuButton = $( "" + o.columnBtnText + "" ),
      $popup = $( "

"),
      $menu = $("<fieldset data-role='controlgroup'></fieldset>").appendTo( $popup );

   // create the hide/show toggles
   self._headers.not( "td" ).each(function(){

      var priority = $( this ).jqmData( "priority" ),
         $cells = $( this ).add( $( this ).jqmData( "cells" ) );

      if( priority ){

         $cells.addClass( o.classes.priorityPrefix + priority );

         $("<input type='checkbox' checked />" + $( this ).text() + "" )
            .appendTo( $menu )
            .children( 0 )
            .jqmData( "cells", $cells )
            .checkboxradio();
      }
   });

   $menuButton
      .insertBefore( $table )
      .buttonMarkup();

   $popup
      .insertBefore( $table )
      .popup();

   // bind change event listeners to inputs - TODO: move to a private method?
   $menu.on( "change", "input", function( e ){
      if( this.checked ){
         $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-hidden" ).addClass( "ui-table-cell-visible" );
      }
      else {
         $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-visible" ).addClass( "ui-table-cell-hidden" );
      }
   } );

   function refreshMenu(){
      $menu.find( "input" ).each( function(){
            this.checked = $( this ).jqmData( "cells" ).eq(0).is( ":visible" );
            $( this ).checkboxradio( "refresh" );
      } );
   }

   $( window ).on( "throttledresize", refreshMenu );

   refreshMenu();

});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>var ProLog = require('../lib/prolog').ProLog;
var $ = require('chalk');

function makeFormat(level, messageColor) {
  return '<% if (date) { %>' + $.gray('${date}') + '<% } %>' +
    level + ' ' +
    '<% if (padding) { %>' + $.gray('${padding}') + '<% } %>' +
    $[messageColor]('${message}') +
    '<% if (debug) { %>' + $.gray('${debug}') + '<% } %>';
}

// Instantiate logger with custom levels.
var parentLog = new ProLog({
  levels: {
    header:     {priority: 0, format: makeFormat('>>>', 'underline')},
    log:        {priority: 1, format: makeFormat('log', 'reset')},
    parentonly: {priority: 2, format: makeFormat($.green('par'), 'green')},
    error:      {priority: 3, format: makeFormat($.red('err'), 'red')},
  },
});

// This child logger will send all logging messages to its parent. Note that
// the "output" option is set to false by default for child loggers.
var childLogs = [];
var childLog = new ProLog(parentLog, {
  levels: {
    // Don't inherit the parent-only level.
    parentonly: null,
    // Create a child-only level.
    childonly: {priority: 2, format: makeFormat($.cyan('chi'), 'cyan')},
  },
  // Totally custom output just for the child logger.
  // Push un-colored formatted message onto an array.
  output: function(data) {
    childLogs.push($.stripColor(this.format(data)));
  },
  // Don't split output across multiple lines.
  format: function(data) {
    return data.format(this.dataPlus(data));
  },
  // Show date and debugging info.
  formatDate: true,
  formatDebug: true,
  // Simplify padding.
  formatPadding: function(data) {
    return new Array(data.indent + 1).join('  ');
  },
});

console.log('===== Parent and Child Logs =====\n');

function parentExample() {
  parentLog.group('Logging levels that don\'t exist on a logger can\'t be called.');
  parentLog.log('This log message comes from the parent.');
  parentLog.parentonly('This "parentonly" message comes from the parent.');
  try {
    parentLog.childonly('This will throw an exception.');
  } catch (err) {
    parentLog.error('Exception: %s', err.message);
  }
  parentLog.groupEnd();
}

function childExample() {
  childLog.group('But will be passed-through.');
  childLog.log('This log message comes from the child.');
  childLog.childonly('This "childonly" message comes from the child.');
  try {
    childLog.parentonly('This will throw an exception.');
  } catch (err) {
    childLog.error('Exception: %s', err.message);
  }
  childLog.groupEnd();
}

function groupingExample() {
  parentLog.header('Note that indentation is cumulative.');
  parentLog.log('This parent log message should not be indented.');
  childLog.log('This child log message should not be indented.');
  parentLog.group('[1] Increase parentLog indent');
  parentLog.log('This parent log message should be indented once.');
  childLog.log('This child log message should be indented once.');
  childLog.group('[2] Increase childLog indent');
  parentLog.log('This parent log message should still be indented once.');
  childLog.log('This child log message should be indented twice.');
  childLog.log([['This array will be indented twice'], ['and logged over'], ['multiple lines.']]);
  childLog.log('Testing twice-indented child log message %s: %d, %j.', 'A', 1, {a: 1});
  childLog.groupEnd();
  childLog.header('[2] Decrease childLog indent');
  parentLog.log('This parent log message should still be indented once.');
  childLog.log('This child log message should be indented once.');
  parentLog.groupEnd();
  parentLog.header('[1] Decrease parentLog indent');
  parentLog.log('This parent log message should not be indented.');
  childLog.log('This child log message should not be indented.');
  childLog.group('[3] Increase childLog indent');
  parentLog.log('This parent log message should not be indented.');
  childLog.log('This child log message should be indented once.');
  childLog.groupEnd();
  childLog.header('[3] Decrease childLog indent');
}

parentExample();
childExample();

// Help differentiate childLog messages visually.
childLog.filter = function(data) {
  data.message = this.eachLine(data.message, $.yellow);
};
childLog.log('All childlog messages should now be yellow.');

groupingExample();

console.log('\n===== Just Child Logs =====\n');
console.log(childLogs.join('\n'));
<commit_msg>Minor tweaks.<commit_after>var ProLog = require('../lib/prolog').ProLog;
var $ = require('chalk');

function makeFormat(level, messageColor) {
  return '<% if (date) { %>' + $.gray('${date}') + '<% } %>' +
    level + ' ' +
    '<% if (padding) { %>' + $.gray('${padding}') + '<% } %>' +
    $[messageColor]('${message}') +
    '<% if (debug) { %>' + $.gray('${debug}') + '<% } %>';
}

// Instantiate logger with custom levels.
var parentLog = new ProLog({
  levels: {
    header:     {priority: 0, format: makeFormat('>>>', 'underline')},
    log:        {priority: 1, format: makeFormat('log', 'reset')},
    parentonly: {priority: 2, format: makeFormat($.green('par'), 'green')},
    error:      {priority: 3, format: makeFormat($.red('err'), 'red')},
  },
});

// This child logger will send all logging messages to its parent. Note that
// the "output" option is set to false by default for child loggers.
var childLogs = [];
var childLog = new ProLog(parentLog, {
  levels: {
    // Don't inherit the parent-only level.
    parentonly: null,
    // Create a child-only level.
    childonly: {priority: 2, format: makeFormat($.cyan('chi'), 'cyan')},
  },
  // Totally custom output just for the child logger.
  // Push un-colored formatted message onto an array.
  output: function(data) {
    childLogs.push($.stripColor(this.format(data)));
  },
  // Don't split output across multiple lines.
  format: function(data) {
    return data.format(this.dataPlus(data));
  },
  // Show date and debugging info.
  formatDate: true,
  formatDebug: true,
  // Simplify padding.
  formatPadding: function(data) {
    return new Array(data.indent + 1).join('  ');
  },
});

console.log('===== Parent and Child Logs =====\n');

function parentExample() {
  parentLog.group('Logging levels that don\'t exist on a logger can\'t be called.');
  parentLog.log('This log message comes from the parent.');
  parentLog.parentonly('This "parentonly" message comes from the parent.');
  try {
    parentLog.childonly('This will throw an exception.');
  } catch (err) {
    parentLog.error('Exception: %s', err.message);
  }
  parentLog.groupEnd();
}

function childExample() {
  childLog.group('But will be passed-through.');
  childLog.log('This log message comes from the child.');
  childLog.childonly('This "childonly" message comes from the child.');
  try {
    childLog.parentonly('This will throw an exception.');
  } catch (err) {
    childLog.error('Exception: %s', err.message);
  }
  childLog.groupEnd();
}

function groupingExample() {
  parentLog.header('Note that indentation is cumulative.');
  parentLog.log('This parent log message should not be indented.');
  childLog.log('This child log message should not be indented.');
  parentLog.group('[1] Increase parentLog indent');
  parentLog.log('This parent log message should be indented once.');
  childLog.log('This child log message should be indented once.');
  childLog.group('[2] Increase childLog indent');
  parentLog.log('This parent log message should still be indented once.');
  childLog.log('This child log message should be indented twice.');
  childLog.log([['This array will be indented twice'], ['and logged over'], ['multiple lines.']]);
  childLog.log('Testing twice-indented child log message %s: %d, %j.', 'A', 1, {a: 1});
  childLog.groupEnd();
  childLog.header('[2] Decrease childLog indent');
  parentLog.log('This parent log message should still be indented once.');
  childLog.log('This child log message should be indented once.');
  parentLog.groupEnd();
  parentLog.header('[1] Decrease parentLog indent');
  parentLog.log('This parent log message should not be indented.');
  childLog.log('This child log message should not be indented.');
  childLog.group('[3] Increase childLog indent');
  parentLog.log('This parent log message should not be indented.');
  childLog.log('This child log message should be indented once.');
  childLog.groupEnd();
  childLog.header('[3] Decrease childLog indent');
}

parentExample();
childExample();

// Differentiate childLog messages visually when logged through parentLog.
parentLog.filter = function(data) {
  if (data.logger !== this) {
    data.message = this.eachLine(data.message, $.yellow);
  }
};
childLog.log('All childlog messages logged via parentLog should now be yellow.');

groupingExample();

console.log('\n===== Just Child Logs =====\n');
console.log(childLogs.join('\n'));
<|endoftext|>