<commit_before>var scatter_target          = d3.select("#scatterplot");
var schools_table_target    = d3.select("#datatable");
var all_math_target         = d3.select("#bar-all-math");
//var filtered_schools      = d3.select("#bar-filtered-schools");
var one_school_math_target  = d3.select("#one-school-math");
var one_school_com_target   = d3.select("#one-school-com");

d3.csv("/datos/09_ESCUELAS_EMS2013.csv", function(data){
  //Clean up data first
  data.forEach(function(v,i,a){
    if(isNaN(+v['Matemáticas: Excelente'])){ v['Matemáticas: Excelente']=0}
    if(isNaN(+v['Matemáticas: Bueno'])){ v['Matemáticas: Bueno']=0}
    if(isNaN(+v['Comunicación: Excelente'])){ v['Comunicación: Excelente']=0}
    if(isNaN(+v['Comunicación: Bueno'])){ v['Comunicación: Bueno']=0}
  });

  var schools = crossfilter(data);
  /* ************************ Convenience Variables *****************/
  // These will be used to construct some of the visualizations.
  // If you want to exclude them from the vizs just add or remove them here

  var math_categories = ['Matemáticas: Excelente',
                         'Matemáticas: Bueno',
                         'Matemáticas: Elemental',
                         'Matemáticas: Insuficiente'];

  var com_categories = ['Comunicación: Excelente',
                        'Comunicación: Bueno',
                        'Comunicación: Elemental',
                        'Comunicación: Insuficiente'];
  // ******************** Dimensions ********************************/
  // DRY Dimensions
  var dimension_names = ['Nombre De La Escuela',
                         'Turno', 'Delegación','Colonia',
                         'Sostenimiento', 'Modalidad'];
  var dimensions = [];

  dimension_names.forEach(function(name){
      dimensions[name] = schools.dimension(function(d){return d[name];})
      });

  // Other dimensions
  dimensions['Matemáticas'] = schools.dimension(
      function(d){
        return (d['Matemáticas: Excelente']*1.2 + d['Matemáticas: Bueno'])
      }
  )

  /*******************  Initialize Charts  ***********************************/
  var scatter_chart = d3.sv_scatter()
         .keyfunc(school_key)
         .x_accessor(function(d) {
             return (+d["Matemáticas: Excelente"]*1.2 + (+d["Matemáticas: Bueno"]))
             })
         .y_accessor(function(d) {
             return (+d["Comunicación: Excelente"]*1.2+ (+d["Comunicación: Bueno"]))
             })
         .x_domain([0, 120])
         .y_domain([0, 120])
         //.mouseover_func(scatter_mouseover_func)
         //.mouseout_func(scatter_mouseout_func)
         .click_func(scatter_click_func);

  var data_table = d3.sv_table()
                     .column_names(['Nombre De La Escuela',
                                    'Colonia',
                                    'Turno',
                                    'Sostenimiento',
                                    'Matemáticas: Excelente'])

  var all_math_bar        = d3.sv_side_bar().chart_width(100),
      all_com_bar         = d3.sv_side_bar().chart_width(100),
      filtered_math_bar   = d3.sv_side_bar().chart_width(100),
      filtered_com_bar    = d3.sv_side_bar().chart_width(100),
      one_school_math     = d3.sv_side_bar().chart_width(100),
      one_school_com      = d3.sv_side_bar().chart_width(100);

  /* ************************ Bind initial data to charts *********************/
  schools_table_target.datum(dimensions['Nombre De La Escuela'].bottom(Infinity))
               .call(data_table);

  scatter_target.datum(dimensions['Nombre De La Escuela'].top(Infinity))
                .call(scatter_chart);

  /* ** Side by side bar charts ****/
  // TODO Make sure this function is called in an init function that is called
  // before any filters are applied to `schools`
  var all_schools_math_summary = make_summary(math_categories);
  all_math_target.datum(all_schools_math_summary).call(all_math_bar);

  /* ********************* Helper Functions ***************/

  function make_summary(categories){
  // **Warning!**
  // Returns an array same length as `categories` where each item
  // is the sum of all members of `schools` of each category
  //`schools` is a crossfilter, so calling this function will return different
  //values depending on the state of the crossfilter.
    var summary = [];
    for (var i=0; i<categories.length; i++) {
      summary[i] = schools.groupAll().reduceSum(function(d){
          return d[categories[i]];
      }).value()
    }
    return summary;
  }

  function make_school_summary(categories,school){
    var summary = [];
    for (var i=0; i<categories.length; i++){
      summary[i] = school[categories[i]];
    }
    return summary
  }

  function school_key(d){
    // This function returns a key for the school data.
    return d["Nombre De La Escuela"];
  }
//  function scatter_mouseover_func(d){
//    div.transition()
//      .duration(200)
//      .style("opacity",.9);
//    div.style("left", (d3.event.pageX) + "px")
//      .style("top", (d3.event.pageY - 28) + "px");
//    div.append("ul")
//      .append("li").text(d['NOMBRE DE LA ESCUELA'])
//      .append("li").text(d['COM EXCEL'])
//      .append("li").text(d['MAT EXCEL'])
//      .append("li").text(Number(d.mat_buen)+Number(d.mat_excel));
//  }
//
//  function scatter_mouseout_func(d) {
//    div.transition()
//      .duration(500)
//      .style("opacity", 0);
//    div.select("ul").remove();
//  }

  function scatter_click_func(d){
    //this is the function the scatterplot will call when a point is clicked
    on_school_select(d);
  }

  function on_school_select(school){
    //call this function with an identifier. This function will then redraw
    //those charts that have one-school behavior
    //returns the school object

    var identifier = school_key(school);
    //Let's add the .clicked class to the selected element in the scatterplot
    scatter_target.selectAll('.data_elem')
                  .classed('clicked', function(d){
                    return school_key(d)===identifier;
                    });

    //Let's add class .success to the row belonging to the selected element
    schools_table_target.selectAll('.data_elem')
                        .classed('success', function(d){
                          return school_key(d)===identifier;
                        });

    //Let's re-draw the individual math plot
    one_school_math_target.datum(make_school_summary(math_categories,school))
                          .call(one_school_math);

    //Lets' re-draw the individual comm plot
    one_school_com_target.datum(make_school_summary(com_categories,school))
                         .call(one_school_com);
  }

  var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);
})
<commit_msg>Added the popover back to the scatterplot<commit_after>var scatter_target          = d3.select("#scatterplot");
var schools_table_target    = d3.select("#datatable");
var all_math_target         = d3.select("#bar-all-math");
//var filtered_schools      = d3.select("#bar-filtered-schools");
var one_school_math_target  = d3.select("#one-school-math");
var one_school_com_target   = d3.select("#one-school-com");

d3.csv("/datos/09_ESCUELAS_EMS2013.csv", function(data){
  //Clean up data first
  data.forEach(function(v,i,a){
    if(isNaN(+v['Matemáticas: Excelente'])){ v['Matemáticas: Excelente']=0}
    if(isNaN(+v['Matemáticas: Bueno'])){ v['Matemáticas: Bueno']=0}
    if(isNaN(+v['Comunicación: Excelente'])){ v['Comunicación: Excelente']=0}
    if(isNaN(+v['Comunicación: Bueno'])){ v['Comunicación: Bueno']=0}
  });

  var schools = crossfilter(data);
  /* ************************ Convenience Variables *****************/
  // These will be used to construct some of the visualizations.
  // If you want to exclude them from the vizs just add or remove them here

  var math_categories = ['Matemáticas: Excelente',
                         'Matemáticas: Bueno',
                         'Matemáticas: Elemental',
                         'Matemáticas: Insuficiente'];

  var com_categories = ['Comunicación: Excelente',
                        'Comunicación: Bueno',
                        'Comunicación: Elemental',
                        'Comunicación: Insuficiente'];
  // ******************** Dimensions ********************************/
  // DRY Dimensions
  var dimension_names = ['Nombre De La Escuela',
                         'Turno', 'Delegación','Colonia',
                         'Sostenimiento', 'Modalidad'];
  var dimensions = [];

  dimension_names.forEach(function(name){
      dimensions[name] = schools.dimension(function(d){return d[name];})
      });

  // Other dimensions
  dimensions['Matemáticas'] = schools.dimension(
      function(d){
        return (d['Matemáticas: Excelente']*1.2 + d['Matemáticas: Bueno'])
      }
  )

  /*******************  Initialize Charts  ***********************************/
  var scatter_chart = d3.sv_scatter()
         .keyfunc(school_key)
         .x_accessor(function(d) {
             return (+d["Matemáticas: Excelente"]*1.2 + (+d["Matemáticas: Bueno"]))
             })
         .y_accessor(function(d) {
             return (+d["Comunicación: Excelente"]*1.2+ (+d["Comunicación: Bueno"]))
             })
         .x_domain([0, 120])
         .y_domain([0, 120])
         .mouseover_func(scatter_mouseover_func)
         .mouseout_func(scatter_mouseout_func)
         .click_func(scatter_click_func);

  var data_table = d3.sv_table()
                     .column_names(['Nombre De La Escuela',
                                    'Colonia',
                                    'Turno',
                                    'Sostenimiento',
                                    'Matemáticas: Excelente'])

  var all_math_bar        = d3.sv_side_bar().chart_width(100),
      all_com_bar         = d3.sv_side_bar().chart_width(100),
      filtered_math_bar   = d3.sv_side_bar().chart_width(100),
      filtered_com_bar    = d3.sv_side_bar().chart_width(100),
      one_school_math     = d3.sv_side_bar().chart_width(100),
      one_school_com      = d3.sv_side_bar().chart_width(100);

  /* ************************ Bind initial data to charts *********************/
  schools_table_target.datum(dimensions['Nombre De La Escuela'].bottom(Infinity))
               .call(data_table);

  scatter_target.datum(dimensions['Nombre De La Escuela'].top(Infinity))
                .call(scatter_chart);

  /* ** Side by side bar charts ****/
  // TODO Make sure this function is called in an init function that is called
  // before any filters are applied to `schools`
  var all_schools_math_summary = make_summary(math_categories);
  all_math_target.datum(all_schools_math_summary).call(all_math_bar);

  /* ********************* Helper Functions ***************/

  function make_summary(categories){
  // **Warning!**
  // Returns an array same length as `categories` where each item
  // is the sum of all members of `schools` of each category
  //`schools` is a crossfilter, so calling this function will return different
  //values depending on the state of the crossfilter.
    var summary = [];
    for (var i=0; i<categories.length; i++) {
      summary[i] = schools.groupAll().reduceSum(function(d){
          return d[categories[i]];
      }).value()
    }
    return summary;
  }

  function make_school_summary(categories,school){
    var summary = [];
    for (var i=0; i<categories.length; i++){
      summary[i] = school[categories[i]];
    }
    return summary
  }

  function school_key(d){
    // This function returns a key for the school data.
    return d["Nombre De La Escuela"];
  }
  function scatter_mouseover_func(d){
    div.transition()
      .duration(200)
      .style("opacity",.9);
    div.style("left", (d3.event.pageX) + "px")
      .style("top", (d3.event.pageY - 28) + "px");
    div.append("ul")
      .append("li").text(d['Nombre De La Escuela'])
      .append("li").text(Number(d.mat_buen)+Number(d.mat_excel));
  }

  function scatter_mouseout_func(d) {
    div.transition()
      .duration(500)
      .style("opacity", 0);
    div.select("ul").remove();
  }

  function scatter_click_func(d){
    //this is the function the scatterplot will call when a point is clicked
    on_school_select(d);
  }

  function on_school_select(school){
    //call this function with an identifier. This function will then redraw
    //those charts that have one-school behavior
    //returns the school object

    var identifier = school_key(school);
    //Let's add the .clicked class to the selected element in the scatterplot
    scatter_target.selectAll('.data_elem')
                  .classed('clicked', function(d){
                    return school_key(d)===identifier;
                    });

    //Let's add class .success to the row belonging to the selected element
    schools_table_target.selectAll('.data_elem')
                        .classed('success', function(d){
                          return school_key(d)===identifier;
                        });

    //Let's re-draw the individual math plot
    one_school_math_target.datum(make_school_summary(math_categories,school))
                          .call(one_school_math);

    //Lets' re-draw the individual comm plot
    one_school_com_target.datum(make_school_summary(com_categories,school))
                         .call(one_school_com);
  }

  var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);
})
<|endoftext|>


<commit_before>/**
 * Created with RubyMine.
 * User: teamco
 * Date: 2/27/14
 * Time: 11:46 PM
 */

define([

], function defineWidgetControllerBase() {

    var WidgetController = function WidgetController() {

    };

    return WidgetController.extend({

        /**
         * Init widget
         */
        initWidget: function initWidget() {

            this.observer.publish(
                this.eventmanager.eventList.loadPreferences
            );

            this.observer.publish(
                this.eventmanager.eventList.successCreated
            );

            this.observer.publish(
                this.eventmanager.eventList.defineContainer
            );

            this.observer.publish(
                this.eventmanager.eventList.updateTranslations, [
                    'plugins/widgets/',
                    this.constructor.name.toLowerCase(),
                    '/translations/en-us'
                ].join('')
            );

            this.view.render();
        },

        /**
         * Define container
         */
        defineContainer: function defineContainer() {

            /**
             * Define widget
             * @type {*}
             */
            var widget = this.controller.getContainment();

            /**
             * Define $container
             * @type {modules.view.elements.$content|*|element.page.page.element}
             */
            this.view.elements.$container =
                widget.view.elements.$content;
        },

        /**
         * Get preferences
         * @returns {{}}
         */
        getPreferences: function getPreferences() {

            return this.model.preferences;
        },

        /**
         * Update prefs
         * @param $input
         */
        updatePreferences: function updatePreferences($modal) {

            var $inputs = $('input', $modal.$);

            $inputs.each(function each(index, input) {

                /**
                 * Transform input name
                 * @type {string|jQuery}
                 */
                var name = input.name.toCamel().capitalize();

                /**
                 * Define method name
                 * @type {string}
                 */
                var setter = 'set' + name,
                    value;

                if (typeof(this.model[setter]) === 'function') {

                    /**
                     * Define input value
                     * @type {*|jQuery}
                     */
                    value = input.value;

                    this.model[setter](value);

                    this.scope.observer.publish(
                        this.scope.eventmanager.eventList.transferPreferences,
                        [input.name, value]
                    );

                } else {

                    this.logger.error('Undefined setter', [name, setter]);
                }

            }.bind(this));

            this.scope.view['render' + this.constructor.name]();

            $modal.selfDestroy();

            this.store();
        },

        /**
         * Load prefs
         */
        loadPreferences: function loadPreferences() {

            /**
             * Load prefs
             * @type {*}
             */
            var widget = this.controller.getContainment(),
                prefs = widget.model.getConfig('preferences');

            $.each(prefs, function each(index, value) {

                /**
                 * Define method name
                 * @type {string}
                 */
                var setter = 'set' + index.toCamel().capitalize();

                if (typeof(this.model[setter]) === 'function') {

                    this.model[setter](value);

                } else {

                    this.logger.debug('Skip', setter);
                }

            }.bind(this));
        },

        /**
         * Transfer preferences to containment
         * @param index
         * @param value
         */
        transferPreferences: function transferPreferences(index, value) {

            /**
             * Define widget
             * @type {*}
             */
            var widget = this.controller.getContainment();

            /**
             * Define prefs
             * @type {{}}
             */
            var prefs = {};

            prefs[index] = value;
            widget.model.updatePreferences(prefs);
        }

    });

});<commit_msg>fix scope<commit_after>/**
 * Created with RubyMine.
 * User: teamco
 * Date: 2/27/14
 * Time: 11:46 PM
 */

define([

], function defineWidgetControllerBase() {

    var WidgetController = function WidgetController() {

    };

    return WidgetController.extend({

        /**
         * Init widget
         */
        initWidget: function initWidget() {

            this.observer.publish(
                this.eventmanager.eventList.loadPreferences
            );

            this.observer.publish(
                this.eventmanager.eventList.successCreated
            );

            this.observer.publish(
                this.eventmanager.eventList.defineContainer
            );

            this.observer.publish(
                this.eventmanager.eventList.updateTranslations, [
                    'plugins/widgets/',
                    this.constructor.name.toLowerCase(),
                    '/translations/en-us'
                ].join('')
            );

            this.view.render();
        },

        /**
         * Define container
         */
        defineContainer: function defineContainer() {

            /**
             * Define widget
             * @type {*}
             */
            var widget = this.controller.getContainment();

            /**
             * Define $container
             * @type {modules.view.elements.$content|*|element.page.page.element}
             */
            this.view.elements.$container =
                widget.view.elements.$content;
        },

        /**
         * Get preferences
         * @returns {{}}
         */
        getPreferences: function getPreferences() {

            return this.model.preferences;
        },

        /**
         * Update prefs
         * @param $input
         */
        updatePreferences: function updatePreferences($modal) {

            var $inputs = $('input', $modal.$),
                scope = this.scope;

            $inputs.each(function each(index, input) {

                /**
                 * Transform input name
                 * @type {string|jQuery}
                 */
                var name = input.name.toCamel().capitalize();

                /**
                 * Define method name
                 * @type {string}
                 */
                var setter = 'set' + name,
                    value;

                if (typeof(this.model[setter]) === 'function') {

                    /**
                     * Define input value
                     * @type {*|jQuery}
                     */
                    value = input.value;

                    this.model[setter](value);

                    scope.observer.publish(
                        scope.eventmanager.eventList.transferPreferences,
                        [input.name, value]
                    );

                } else {

                    scope.logger.error('Undefined setter', [name, setter]);
                }

            }.bind(this));

            scope.view['render' + scope.constructor.name]();

            $modal.selfDestroy();

            this.store();
        },

        /**
         * Load prefs
         */
        loadPreferences: function loadPreferences() {

            /**
             * Load prefs
             * @type {*}
             */
            var widget = this.controller.getContainment(),
                prefs = widget.model.getConfig('preferences');

            $.each(prefs, function each(index, value) {

                /**
                 * Define method name
                 * @type {string}
                 */
                var setter = 'set' + index.toCamel().capitalize();

                if (typeof(this.model[setter]) === 'function') {

                    this.model[setter](value);

                } else {

                    this.logger.debug('Skip', setter);
                }

            }.bind(this));
        },

        /**
         * Transfer preferences to containment
         * @param index
         * @param value
         */
        transferPreferences: function transferPreferences(index, value) {

            /**
             * Define widget
             * @type {*}
             */
            var widget = this.controller.getContainment();

            /**
             * Define prefs
             * @type {{}}
             */
            var prefs = {};

            prefs[index] = value;
            widget.model.updatePreferences(prefs);
        }

    });

});<|endoftext|>


<commit_before>// 2015 (C) Ben Lippincott

// I'm feeling anti-semicolon today

var Camelot = require('camelot')
var engine = require('engine.io').listen('9000')
var fs = require('fs')

var http = require("http")
var url = require("url")
var path = require("path")
var httpPort = process.argv[2] || 8888

var camOptions = {
  verbose: false,
  device : '/dev/video0',
  resolution : '640x480',
  png : '1',
  greyscale : false,
  controls : {
    focus : 'auto',
    brightness : 130,
    contrast : 50,
    saturation : 50,
    hue : 100,
    gamma : 130,
    sharpness : 50
  }
}

var camelot = new Camelot(camOptions);

engine.on('connection',function(socket){
  socket.on('message', function(data){
    console.log('message recieved')
    console.log(data)
    camelot.grab({},function(image){
      console.log(image)
      socket.send(image)
    })
  });
  socket.on('close',function(){})
})

http.createServer(function(request, response) {
  var uri = url.parse(request.url).pathname
	var filename = path.join(process.cwd(), uri)
  console.log(uri);
  if (uri == '/alert'){
    console.log('\007');
    response.writeHead(200)
    response.write('Sound Played!');
    response.end();

  }

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"})
      response.write("404 Not Found\n")
      response.end()
      return
    }

    if (fs.statSync(filename).isDirectory())
      filename += '/index.html'

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {
        response.writeHead(500, {"Content-Type": "text/plain"})
        response.write(err + "\n")
        response.end()
        return
      }

      response.writeHead(200)
      response.write(file, "binary")
      response.end()
    })
  })
}).listen(parseInt(httpPort, 10))
<commit_msg>Fixed unnecessary bug.<commit_after>// 2015 (C) Ben Lippincott

// I'm feeling anti-semicolon today

var util = require('util'),
    exec = require('child_process').exec,
    child;

var Camelot = require('camelot')
var engine = require('engine.io').listen('9000')
var fs = require('fs')

var http = require("http")
var url = require("url")
var path = require("path")
var httpPort = process.argv[2] || 8888

var camOptions = {
  verbose: false,
  device : '/dev/video0',
  resolution : '640x480',
  png : '1',
  greyscale : false,
  controls : {
    focus : 'auto',
    brightness : 130,
    contrast : 50,
    saturation : 50,
    hue : 100,
    gamma : 130,
    sharpness : 50
  }
}

var camelot = new Camelot(camOptions);

engine.on('connection',function(socket){
  socket.on('message', function(data){
    console.log('message recieved')
    console.log(data)
    camelot.grab({},function(image){
      console.log(image)
      socket.send(image)
    })
  });
  socket.on('close',function(){})
})

http.createServer(function(request, response) {
  var uri = url.parse(request.url).pathname
	var filename = path.join(process.cwd(), uri)
  console.log(uri);
  if (uri == '/alert'){
    child = exec('sh alert.bash', // command line argument directly in string
    function (error, stdout, stderr) {      // one easy function to capture data/errors
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
        console.log('exec error: ' + error);
      }
    });
    response.writeHead(200)
    response.write('Sound Played!');
    response.end();

  }

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"})
      response.write("404 Not Found\n")
      response.end()
      return
    }

    if (fs.statSync(filename).isDirectory())
      filename += '/index.html'

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {
        response.writeHead(500, {"Content-Type": "text/plain"})
        response.write(err + "\n")
        response.end()
        return
      }

      response.writeHead(200)
      response.write(file, "binary")
      response.end()
    })
  })
}).listen(parseInt(httpPort, 10))
<|endoftext|>


<commit_before>/*
 * JQuery UI Widget Plugin Template - Jump-start widget plugin development
 * This template was created by refer to the following resources:
 * 1) Understanding jQuery UI widgets: A tutorial - http://bililite.com/blog/understanding-jquery-ui-widgets-a-tutorial/
 *
 * Usage:
 * $(selector).className({option1: "Option of className"});
 * $(selector).extendedClassName({option1: "Option of extendedClassName"});
 * $(selector).className("method1", "123");
 * $(selector).extendedClassName("method1", "12345");
 *
 * Revision: @REVISION
 * Version: @VERSION
 * Copyright 2011 Lim Chee Kin (limcheekin@vobject.com)
 *
 * Licensed under Apache v2.0 http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * Date:
 */

var NameSpace = {
	ClassName: {
		options: { // default options. values are stored in widget's prototype
      option1: "optionValue"
        },
    _create: function() {
    	// called on construction
    	this.log('NameSpace.ClassName._create called. this.options.option1 = ' + this.options.option1);
        },
		_init: function() {
			// called on construction and re-initialization
			this.log('NameSpace.ClassName._init called.');
			this.method1('calling from NameSpace.ClassName._init');
		},
		destroy: function() {
    	// called on removal
			this.log('NameSpace.ClassName.destroy called.');
        },
    // logging to the firebug's console, put in 1 line so it can be removed easily for production
    log: function($message) { if (window.console && window.console.log) window.console.log($message); },
		method1: function(params) {
    	// plugin specific method
			this.log('NameSpace.ClassName.method1 called. params = ' + params);
        }
	}
};

$.widget('ui.className', NameSpace.ClassName);

// extends/inherits from superclass: ClassName
var NameSpace = {
		ExtendedClassName: $.extend({}, $.ui.className.prototype, {
			options: { // default options. values are stored in widget's prototype
	      option1: "ExtendedClassName.optionValue"
	        },
	    _create: function() {
	      $.ui.className.prototype._create.call(this); // call the superclass's _create function
	      // ExtendedClassName's construction code here
	      this.log('NameSpace.ExtendedClassName._create called. this.options.option1 = ' + this.options.option1);
	        },
			_init: function() {
			  $.ui.className.prototype._init.call(this); // call the superclass's _init function
			  // ExtendedClassName's construction and re-initialization code here
			  this.log('NameSpace.ExtendedClassName._init called.');
			},
			destroy: function() {
	    	// ExtendedClassName's destroy code here
				this.log('NameSpace.ExtendedClassName.destroy called.');
				$.ui.className.prototype.destroy.call(this); // call the superclass's destroy function
	        },
			method1: function(params) {
	    	// plugin specific method
				this.log('NameSpace.ExtendedClassName.method1 called. params = ' + params);
	        }
		})
};

$.widget('ui.extendedClassName', NameSpace.ExtendedClassName);<commit_msg>Format the code of jquery.ui.widget.template.js properly.<commit_after>/*
 * JQuery UI Widget Plugin Template - Jump-start widget plugin development
 * This template was created by refer to the following resources:
 * 1) Understanding jQuery UI widgets: A tutorial - http://bililite.com/blog/understanding-jquery-ui-widgets-a-tutorial/
 *
 * Usage:
 * $(selector).className({option1: "Option of className"});
 * $(selector).extendedClassName({option1: "Option of extendedClassName"});
 * $(selector).className("method1", "123");
 * $(selector).extendedClassName("method1", "12345");
 *
 * Revision: @REVISION
 * Version: @VERSION
 * Copyright 2011 Lim Chee Kin (limcheekin@vobject.com)
 *
 * Licensed under Apache v2.0 http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * Date:
 */

var NameSpace = {
  ClassName: {
    options: { // default options. values are stored in widget's prototype
      option1: "optionValue"
    },
    _create: function() {
    	// called on construction
    	this.log('NameSpace.ClassName._create called. this.options.option1 = ' + this.options.option1);
    },
	_init: function() {
			// called on construction and re-initialization
		this.log('NameSpace.ClassName._init called.');
		this.method1('calling from NameSpace.ClassName._init');
	},
	destroy: function() {
        // called on removal
		this.log('NameSpace.ClassName.destroy called.');
    },
    // logging to the firebug's console, put in 1 line so it can be removed easily for production
    log: function($message) { if (window.console && window.console.log) window.console.log($message); },
	method1: function(params) {
    	// plugin specific method
		this.log('NameSpace.ClassName.method1 called. params = ' + params);
    }
  }
};

$.widget('ui.className', NameSpace.ClassName);

// extends/inherits from superclass: ClassName
var NameSpace = {
  ExtendedClassName: $.extend({}, $.ui.className.prototype, {
    options: { // default options. values are stored in widget's prototype
	  option1: "ExtendedClassName.optionValue"
    },
	_create: function() {
	  $.ui.className.prototype._create.call(this); // call the superclass's _create function
	  // ExtendedClassName's construction code here
	  this.log('NameSpace.ExtendedClassName._create called. this.options.option1 = ' + this.options.option1);
    },
    _init: function() {
	  $.ui.className.prototype._init.call(this); // call the superclass's _init function
	  // ExtendedClassName's construction and re-initialization code here
      this.log('NameSpace.ExtendedClassName._init called.');
    },
	destroy: function() {
	  // ExtendedClassName's destroy code here
	  this.log('NameSpace.ExtendedClassName.destroy called.');
	  $.ui.className.prototype.destroy.call(this); // call the superclass's destroy function
    },
	method1: function(params) {
      // plugin specific method
	  this.log('NameSpace.ExtendedClassName.method1 called. params = ' + params);
    }
  })
};

$.widget('ui.extendedClassName', NameSpace.ExtendedClassName);<|endoftext|>


<commit_before>const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

const EXPORTED_SYMBOLS = [];

var gForceExternalHandler = false;

XPCOMUtils.defineLazyServiceGetter(this, "extProtocolSvc",
    "@mozilla.org/uriloader/external-protocol-service;1", "nsIExternalProtocolService");

var documentObserver = {
  observe: function observe(subject, topic, data) {
    if (subject instanceof Ci.nsIDOMWindow && topic == 'content-document-global-created') {
      var doc = subject.document;
      doc.addEventListener("DOMContentLoaded", function(event) {
        event.target.removeEventListener("DOMContentLoaded", arguments.callee, false);
        var links = event.target.getElementsByTagName("a");
        for (var i=0; i < links.length; i++) {
          var link = links[i];
          if (link.href.indexOf("file://") != 0) {
            continue;
          }
          link.addEventListener("click", function(link) {
            return function(event) {
              event.preventDefault();
              if (gForceExternalHandler) {
                extProtocolSvc.loadUrl(Services.io.newURI(link.href, null, null));
              } else {
                var win = Services.wm.getMostRecentWindow("navigator:browser");
                if (win) {
                  var target = "_self";
                  if (link.hasAttribute("target")) {
                    target = link.getAttribute("target");
                  }
                  // If we were told somewhere other than current, use it
                  var where = win.whereToOpenLink(event);
                  if (where != "current") {
                    win.openUILinkIn(link.href, where);
                    return;
                  }
                  switch (target) {
                    case "_blank":
                      win.openUILinkIn(link.href, "tab");
                      break;
                    case "_self":
                      link.ownerDocument.location = link.href;
                      break;
                    case "_parent":
                      link.ownerDocument.defaultView.parent.document.location = link.href;
                      break;
                    case "_top":
                      link.ownerDocument.defaultView.top.document.location = link.href;
                      break;
                    default:
                      // Attempt to find the iframe that this goes into
                      var iframe = doc.defaultView.parent.document.getElementById(target);
                      if (iframe) {
                        iframe.setAttribute("src", link.href);
                      }
                      break;
                  }
                }
              }
            }
          }(link), false);
        }
      }, false);
    }
  }
}

var CAPSCheckLoadURI = {
  observe: function observe(subject, topic, data) {
    switch (topic) {
    case "final-ui-startup":
      Services.obs.removeObserver(CAPSCheckLoadURI, "final-ui-startup", false);
      // Don't do this check before Firefox 29
      if (Services.vc.compare(Services.appinfo.version, "29") <= 0) {
        return;
      }
      var defaultCheckLoadURIPolicy = false;
      try {
        if (Services.prefs.getCharPref("capability.policy.default.checkloaduri.enabled") == "allAccess") {
          defaultCheckLoadURIPolicy = true;
        }
      } catch (e) {}
      if (defaultCheckLoadURIPolicy == false) {
        return;
      }
      gForceExternalHandler = !extProtocolSvc.isExposedProtocol('file');
      Services.obs.addObserver(documentObserver, "content-document-global-created", false);
      break;
    case "quit-application":
      Services.obs.removeObserver(CAPSCheckLoadURI, "quit-application", false);
      Services.obs.removeObserver(documentObserver, 'content-document-global-created', false);
      break;
    }
  }
}

Services.obs.addObserver(CAPSCheckLoadURI, "final-ui-startup", false);
Services.obs.addObserver(CAPSCheckLoadURI, "quit-application", false);
<commit_msg>A few more tweaks<commit_after>const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

const EXPORTED_SYMBOLS = [];

var gForceExternalHandler = false;

XPCOMUtils.defineLazyServiceGetter(this, "extProtocolSvc",
    "@mozilla.org/uriloader/external-protocol-service;1", "nsIExternalProtocolService");

var documentObserver = {
  observe: function observe(subject, topic, data) {
    if (subject instanceof Ci.nsIDOMWindow && topic == 'content-document-global-created') {
      var doc = subject.document;
      doc.addEventListener("DOMContentLoaded", function(event) {
        event.target.removeEventListener("DOMContentLoaded", arguments.callee, false);
        // If the parent document is a local file, don't do anything
        // Links will just work
        if (doc.location.href.indexOf("file://") == 0) {
          return;
        }
        var links = event.target.getElementsByTagName("a");
        for (var i=0; i < links.length; i++) {
          var link = links[i];
          if (link.href.indexOf("file://") != 0) {
            continue;
          }
          link.addEventListener("click", function(link) {
            return function(event) {
              event.preventDefault();
              if (gForceExternalHandler) {
                extProtocolSvc.loadUrl(Services.io.newURI(link.href, null, null));
              } else {
                var win = Services.wm.getMostRecentWindow("navigator:browser");
                if (win) {
                  var target = "_self";
                  if (link.hasAttribute("target")) {
                    target = link.getAttribute("target");
                  }
                  // If we were told somewhere other than current (based on modifier keys), use it
                  var where = win.whereToOpenLink(event);
                  if (where != "current") {
                    win.openUILinkIn(link.href, where);
                    return;
                  }
                  switch (target) {
                    case "_blank":
                      win.openUILinkIn(link.href, "tab");
                      break;
                    case "_self":
                      link.ownerDocument.location = link.href;
                      break;
                    case "_parent":
                      link.ownerDocument.defaultView.parent.document.location = link.href;
                      break;
                    case "_top":
                      link.ownerDocument.defaultView.top.document.location = link.href;
                      break;
                    default:
                      // Attempt to find the iframe that this goes into
                      var iframes = doc.defaultView.parent.document.getElementsByName(target);
                      if (iframes.length > 0) {
                        iframes[0].contentDocument.location = link.href;
                      } else {
                        link.ownerDocument.location = link.href;
                      }
                      break;
                  }
                }
              }
            }
          }(link), false);
        }
      }, false);
    }
  }
}

var CAPSCheckLoadURI = {
  observe: function observe(subject, topic, data) {
    switch (topic) {
    case "final-ui-startup":
      Services.obs.removeObserver(CAPSCheckLoadURI, "final-ui-startup", false);
      // Don't do this check before Firefox 29
      if (Services.vc.compare(Services.appinfo.version, "29") <= 0) {
        return;
      }
      var defaultCheckLoadURIPolicy = false;
      try {
        if (Services.prefs.getCharPref("capability.policy.default.checkloaduri.enabled") == "allAccess") {
          defaultCheckLoadURIPolicy = true;
        }
      } catch (e) {}
      if (defaultCheckLoadURIPolicy == false) {
        return;
      }
      gForceExternalHandler = !extProtocolSvc.isExposedProtocol('file');
      Services.obs.addObserver(documentObserver, "content-document-global-created", false);
      break;
    case "quit-application":
      Services.obs.removeObserver(CAPSCheckLoadURI, "quit-application", false);
      Services.obs.removeObserver(documentObserver, 'content-document-global-created', false);
      break;
    }
  }
}

Services.obs.addObserver(CAPSCheckLoadURI, "final-ui-startup", false);
Services.obs.addObserver(CAPSCheckLoadURI, "quit-application", false);
<|endoftext|>


<commit_before>/*
		El siguiente codigo en JS Contiene mucho codigo
		de las siguietes 3 fuentes:
		https://stipaltamar.github.io/dibujoCanvas/
		https://developer.mozilla.org/samples/domref/touchevents.html - https://developer.mozilla.org/es/docs/DOM/Touch_events
		http://bencentra.com/canvas/signature/signature.html - https://bencentra.com/code/2014/12/05/html5-canvas-touch-events.html
*/

(function()
{ // Comenzamos una funcion auto-ejecutable

	// Obtenenemos un intervalo regular(Tiempo) en la pamtalla
	window.requestAnimFrame = (function (callback)
	{
		return window.requestAnimationFrame ||
					window.webkitRequestAnimationFrame ||
					window.mozRequestAnimationFrame ||
					window.oRequestAnimationFrame ||
					window.msRequestAnimaitonFrame ||
					function (callback)
					{
					 	window.setTimeout(callback, 1000/60);
            // Retrasa la ejecucion de la funcion para mejorar la experiencia
					};
	})();

	// Traemos el canvas mediante el id del elemento html
	var canvas = document.getElementById("draw-canvas");
	var ctx = canvas.getContext("2d");

	// Mandamos llamar a los Elemetos interactivos de la Interfaz HTML
	var drawText = document.getElementById("draw-dataUrl");
	var drawImage = document.getElementById("draw-image");
	var clearBtn = document.getElementById("draw-clearBtn");
	var submitBtn = document.getElementById("draw-submitBtn");
	clearBtn.addEventListener("click", function (e)
	{
		// Definimos que pasa cuando el boton draw-clearBtn es pulsado
		clearCanvas();
		drawImage.setAttribute("src", "");
	}, false);
		// Definimos que pasa cuando el boton draw-submitBtn es pulsado
	submitBtn.addEventListener("click", function (e)
	{
	var dataUrl = canvas.toDataURL();
	drawText.innerHTML = dataUrl;
	drawImage.setAttribute("src", dataUrl);
	 }, false);

	// Activamos MouseEvent para nuestra pagina
	var drawing = false;
	var mousePos = { x:0, y:0 };
	var lastPos = mousePos;
	canvas.addEventListener("mousedown", function (e)
  {
    /*
      Mas alla de solo llamar a una funcion, usamos function (e){...}
      para mas versatilidad cuando ocurre un evento
    */
		var tint = document.getElementById("color");
		var punta = document.getElementById("puntero");
		console.log(e);
		drawing = true;
		lastPos = getMousePos(canvas, e);
	}, false);
	canvas.addEventListener("mouseup", function (e)
  {
		drawing = false;
	}, false);
	canvas.addEventListener("mousemove", function (e)
  {
		mousePos = getMousePos(canvas, e);
	}, false);

	// Activamos touchEvent para nuestra pagina
	canvas.addEventListener("touchstart", function (e)
	{
		mousePos = getTouchPos(canvas, e);
    console.log(mousePos);
    e.preventDefault(); // Prevent scrolling when touching the canvas
		var touch = e.touches[0];
		var mouseEvent = new MouseEvent("mousedown",
		{
			clientX: touch.clientX,
			clientY: touch.clientY
		});
		canvas.dispatchEvent(mouseEvent);
	}, false);
	canvas.addEventListener("touchend", function (e)
	{
    e.preventDefault(); // Prevent scrolling when touching the canvas
		var mouseEvent = new MouseEvent("mouseup", {});
		canvas.dispatchEvent(mouseEvent);
	}, false);
  canvas.addEventListener("touchleave", function (e)
	{
    // Realiza el mismo proceso que touchend en caso de que el dedo se deslice fuera del canvas
    e.preventDefault(); // Prevent scrolling when touching the canvas
    var mouseEvent = new MouseEvent("mouseup", {});
    canvas.dispatchEvent(mouseEvent);
  }, false);
	canvas.addEventListener("touchcancel", function (e)
	{
    // Realiza el mismo proceso que touchend en caso de que el dedo se deslice fuera del canvas
    e.preventDefault(); // Prevent scrolling when touching the canvas
    var mouseEvent = new MouseEvent("mouseup", {});
    canvas.dispatchEvent(mouseEvent);
  }, false);
	canvas.addEventListener("touchmove", function (e)
	{
    e.preventDefault(); // Prevent scrolling when touching the canvas
		var touch = e.touches[0];
		var mouseEvent = new MouseEvent("mousemove",
		{
			clientX: touch.clientX,
			clientY: touch.clientY
		});
		canvas.dispatchEvent(mouseEvent);
	}, false);

	// Get the position of the mouse relative to the canvas
	function getMousePos(canvasDom, mouseEvent)
	{
		var rect = canvasDom.getBoundingClientRect();
    /*
      Devuelve el tamaño de un elemento y su posición relativa respecto
      a la ventana de visualización (viewport).
    */
		return
		{
			x: mouseEvent.clientX - rect.left,
			y: mouseEvent.clientY - rect.top
		};
	}

	// Get the position of a touch relative to the canvas
	function getTouchPos(canvasDom, touchEvent)
	{
		var rect = canvasDom.getBoundingClientRect();
    console.log(touchEvent);
    /*
      Devuelve el tamaño de un elemento y su posición relativa respecto
      a la ventana de visualización (viewport).
    */
		return
		{
			x: touchEvent.touches[0].clientX - rect.left, // Popiedad de todo evento Touch
			y: touchEvent.touches[0].clientY - rect.top
		};
	}

	// Draw to the canvas
	function renderCanvas()
	{
		if (drawing)
		{
      var tint = document.getElementById("color");
      var punta = document.getElementById("puntero");
      ctx.strokeStyle = tint.value;
      ctx.beginPath();
			ctx.moveTo(lastPos.x, lastPos.y);
			ctx.lineTo(mousePos.x, mousePos.y);
      console.log(punta.value);
    	ctx.lineWidth = punta.value;
			ctx.stroke();
      ctx.closePath();
			lastPos = mousePos;
		}
	}

	function clearCanvas()
	{
		canvas.width = canvas.width;
	}

	// Allow for animation
	(function drawLoop ()
	{
		requestAnimFrame(drawLoop);
		renderCanvas();
	})();

})();
<commit_msg>Arreglados errores de sintaxis de los corchetes<commit_after>/*
		El siguiente codigo en JS Contiene mucho codigo
		de las siguietes 3 fuentes:
		https://stipaltamar.github.io/dibujoCanvas/
		https://developer.mozilla.org/samples/domref/touchevents.html - https://developer.mozilla.org/es/docs/DOM/Touch_events
		http://bencentra.com/canvas/signature/signature.html - https://bencentra.com/code/2014/12/05/html5-canvas-touch-events.html
*/

(function()
{ // Comenzamos una funcion auto-ejecutable

	// Obtenenemos un intervalo regular(Tiempo) en la pamtalla
	window.requestAnimFrame = (function (callback)
	{
		return window.requestAnimationFrame ||
					window.webkitRequestAnimationFrame ||
					window.mozRequestAnimationFrame ||
					window.oRequestAnimationFrame ||
					window.msRequestAnimaitonFrame ||
					function (callback)
					{
					 	window.setTimeout(callback, 1000/60);
            // Retrasa la ejecucion de la funcion para mejorar la experiencia
					};
	})();

	// Traemos el canvas mediante el id del elemento html
	var canvas = document.getElementById("draw-canvas");
	var ctx = canvas.getContext("2d");

	// Mandamos llamar a los Elemetos interactivos de la Interfaz HTML
	var drawText = document.getElementById("draw-dataUrl");
	var drawImage = document.getElementById("draw-image");
	var clearBtn = document.getElementById("draw-clearBtn");
	var submitBtn = document.getElementById("draw-submitBtn");
	clearBtn.addEventListener("click", function (e)
	{
		// Definimos que pasa cuando el boton draw-clearBtn es pulsado
		clearCanvas();
		drawImage.setAttribute("src", "");
	}, false);
		// Definimos que pasa cuando el boton draw-submitBtn es pulsado
	submitBtn.addEventListener("click", function (e)
	{
	var dataUrl = canvas.toDataURL();
	drawText.innerHTML = dataUrl;
	drawImage.setAttribute("src", dataUrl);
	 }, false);

	// Activamos MouseEvent para nuestra pagina
	var drawing = false;
	var mousePos = { x:0, y:0 };
	var lastPos = mousePos;
	canvas.addEventListener("mousedown", function (e)
  {
    /*
      Mas alla de solo llamar a una funcion, usamos function (e){...}
      para mas versatilidad cuando ocurre un evento
    */
		var tint = document.getElementById("color");
		var punta = document.getElementById("puntero");
		console.log(e);
		drawing = true;
		lastPos = getMousePos(canvas, e);
	}, false);
	canvas.addEventListener("mouseup", function (e)
  {
		drawing = false;
	}, false);
	canvas.addEventListener("mousemove", function (e)
  {
		mousePos = getMousePos(canvas, e);
	}, false);

	// Activamos touchEvent para nuestra pagina
	canvas.addEventListener("touchstart", function (e)
	{
		mousePos = getTouchPos(canvas, e);
    console.log(mousePos);
    e.preventDefault(); // Prevent scrolling when touching the canvas
		var touch = e.touches[0];
		var mouseEvent = new MouseEvent("mousedown",
		{
			clientX: touch.clientX,
			clientY: touch.clientY
		});
		canvas.dispatchEvent(mouseEvent);
	}, false);
	canvas.addEventListener("touchend", function (e)
	{
    e.preventDefault(); // Prevent scrolling when touching the canvas
		var mouseEvent = new MouseEvent("mouseup", {});
		canvas.dispatchEvent(mouseEvent);
	}, false);
  canvas.addEventListener("touchleave", function (e)
	{
    // Realiza el mismo proceso que touchend en caso de que el dedo se deslice fuera del canvas
    e.preventDefault(); // Prevent scrolling when touching the canvas
    var mouseEvent = new MouseEvent("mouseup", {});
    canvas.dispatchEvent(mouseEvent);
  }, false);
	canvas.addEventListener("touchcancel", function (e)
	{
    // Realiza el mismo proceso que touchend en caso de que el dedo se deslice fuera del canvas
    e.preventDefault(); // Prevent scrolling when touching the canvas
    var mouseEvent = new MouseEvent("mouseup", {});
    canvas.dispatchEvent(mouseEvent);
  }, false);
	canvas.addEventListener("touchmove", function (e)
	{
    e.preventDefault(); // Prevent scrolling when touching the canvas
		var touch = e.touches[0];
		var mouseEvent = new MouseEvent("mousemove",
		{
			clientX: touch.clientX,
			clientY: touch.clientY
		});
		canvas.dispatchEvent(mouseEvent);
	}, false);

	// Get the position of the mouse relative to the canvas
	function getMousePos(canvasDom, mouseEvent)
	{
		var rect = canvasDom.getBoundingClientRect();
    /*
      Devuelve el tamaño de un elemento y su posición relativa respecto
      a la ventana de visualización (viewport).
    */
		return{
			x: mouseEvent.clientX - rect.left,
			y: mouseEvent.clientY - rect.top
		};
	}

	// Get the position of a touch relative to the canvas
	function getTouchPos(canvasDom, touchEvent)
	{
		var rect = canvasDom.getBoundingClientRect();
    console.log(touchEvent);
    /*
      Devuelve el tamaño de un elemento y su posición relativa respecto
      a la ventana de visualización (viewport).
    */
		return{
			x: touchEvent.touches[0].clientX - rect.left, // Popiedad de todo evento Touch
			y: touchEvent.touches[0].clientY - rect.top
		};
	}

	// Draw to the canvas
	function renderCanvas()
	{
		if (drawing)
		{
      var tint = document.getElementById("color");
      var punta = document.getElementById("puntero");
      ctx.strokeStyle = tint.value;
      ctx.beginPath();
			ctx.moveTo(lastPos.x, lastPos.y);
			ctx.lineTo(mousePos.x, mousePos.y);
      console.log(punta.value);
    	ctx.lineWidth = punta.value;
			ctx.stroke();
      ctx.closePath();
			lastPos = mousePos;
		}
	}

	function clearCanvas()
	{
		canvas.width = canvas.width;
	}

	// Allow for animation
	(function drawLoop ()
	{
		requestAnimFrame(drawLoop);
		renderCanvas();
	})();

})();
<|endoftext|>


<commit_before>/*
 * HTMLLisible is under MIT License
 */

var HTMLLisible = function() {
    this.clean = function(html) {
        // Add missing slashes to autoclosing tags
        html = this.addMissingSlashes(html);
        // Clean HTML
        html = this.cleanHTML(html);
        // Prepare indent HTML
        html = this.reindentHTML(html);
        return html;
    };

    this.addMissingSlashes = function(html) {
        html = String(html).replace(/<(meta|br|hr|link)([^>\/]*)>/g, '<$1$2 />');
        return html;
    };

    this.cleanHTML = function(html) {
        // Replace spaces after tag
        html = String(html).replace(/>([ \t\n]+)/gm, '>');
        // Replace spaces before tag
        html = html.replace(/(\s\t\n+)</gm, '<');
        // Set one tag per line
        html = html.replace(/>([^<]*)</g, ">\n$1\n<");
        return html;
    };

    this.reindentHTML = function(html) {

        // Extract lines
        var lines = String(html).split("\n"),
            linesLength = lines.length,
            reindentedHTML = '',
            isOpening = false,
            indentLevel = 0,
            indentHTML = '',
            line = '';

        // For each line
        for (var i = 0; i < linesLength; i++) {

            line = this.trim(lines[i]);
            // Dont look at empty lines
            if (!line) {
                continue;
            }

            // Closing line
            if (line.match(/^<\//)) {
                indentLevel--;
            }

            // Prepare indentHTML
            indentHTML = this.pad(indentLevel);

            // Opening line (not unique tag)
            if (line.match(/^<([a-zA-Z])/) && !line.match(/\/>$/)) {
                indentLevel++;
            }
            reindentedHTML += indentHTML + line + "\n";
        }

        return reindentedHTML;
    };

    /* Utilities */

    // Pad a string to a given number
    this.pad = function(nb, str) {
        str = !str ? "\t" : str;
        nb = !nb ? 0 : nb;
        return new Array(nb + 1).join(str);
    };

    // Trim a string
    this.trim = function(str) {
        return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
    };
};<commit_msg>Trim content tags, cleaner process, default pad to 4 spaces<commit_after>/*
 * HTMLLisible is under MIT License
 */

var HTMLLisible = function() {

    var tagsToTrim = ['a', 'strong', 'em', 'h1', 'h2', 'h3', 'label', 'textarea', 'button', 'title'],
        tagsToTrimLength = tagsToTrim.length,
        uniqueTags = ['meta', 'br', 'hr', 'link', 'input'];

    this.clean = function(html) {
        // Add missing slashes to autoclosing tags
        html = this.addMissingSlashes(html);
        // Clean HTML
        html = this.cleanHTML(html);
        // Prepare indent HTML
        html = this.reindentHTML(html);
        // Trim content on some tags
        html = this.trimContentTags(html);
        return this.trim(html);
    };

    // Add missing slashes to unique tags
    this.addMissingSlashes = function(html) {
        var regMissing = new RegExp("<(" + uniqueTags.join('|') + ")([^>\/]*)>", 'g');
        html = String(html).replace(regMissing, '<$1$2 />');
        return html;
    };

    this.cleanHTML = function(html) {
        // Replace spaces after tag
        html = String(html).replace(/>([ \t\n]+)/gm, '>');
        // Replace spaces before tag
        html = String(html).replace(/([ \t\n]+)</gm, '<');
        return html;
    };

    this.reindentHTML = function(html) {

        // Set one tag per line
        html = html.replace(/>([^<]*)</g, ">\n$1\n<");

        // Extract lines
        var lines = String(html).split("\n"),
            linesLength = lines.length,
            reindentedHTML = '',
            isOpening = false,
            indentLevel = 0,
            indentHTML = '',
            line = '';

        // For each line
        for (var i = 0; i < linesLength; i++) {

            line = this.trim(lines[i]);
            // Dont look at empty lines
            if (!line) {
                continue;
            }

            // Closing line
            if (line.match(/^<\//)) {
                indentLevel--;
            }

            // Prepare indentHTML
            indentHTML = this.pad(indentLevel);

            // Opening line (not unique tag)
            if (line.match(/^<([a-zA-Z])/) && !line.match(/\/>$/)) {
                indentLevel++;
            }
            reindentedHTML += indentHTML + line + "\n";
        }

        return reindentedHTML;
    };

    // Trim some tag contents if they dont contain HTML
    this.trimContentTags = function(html) {
        var i = 0,
            j = 0,
            reg, tag, matches, matchesLength;

        for (; i < tagsToTrimLength; i++) {
            tag = tagsToTrim[i];
            reg = new RegExp("<" + tag + "([^>]*)>([^<]*)</" + tag + ">", 'gm');
            matches = html.match(reg);
            if (matches) {
                matchesLength = matches.length;
                for (j = 0; j < matchesLength; j++) {
                    html = html.replace(matches[j], this.cleanHTML(matches[j]));
                }
            }
        }
        return html;
    };

    /* Utilities */

    // Pad a string to a given number
    this.pad = function(nb, str) {
        str = !str ? "    " : str;
        nb = !nb ? 0 : nb;
        return new Array(nb + 1).join(str);
    };

    // Trim a string
    this.trim = function(str) {
        return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
    };
};<|endoftext|>


<commit_before>(function(){

var cat1_base64 = 'iVBORw0KGgoAAAANSUhEUgAAAMQAAABICAQAAAAD3ZJDAAAABGdBTUEAALGPC/xhBQAAAAJiS0dEAP+Hj8y/AAADEUlEQVR42u1cy3LDIAzEnfz/L7uXOkMoeoLi9czupXVghRJYDEj2cbY5jr+C8/j8rL9G4Y2c0Q4Kr683Xv80AgIvq8Jxeszcy3uCjxaXigDBtIP6+auvcF1L8+EdPIlz/Y/C03AeVAQM/nWWd/4be5+8NR4VAQL1HiFhZS4kb86jIkCgdtZYaO0eycvzqAgQvFqTz3kyqOQ9xc8Mj4oAwdGCo0yqN+44JV50VK/yvu1ntj0qAgTH2eLz3ni+Et11RrkjD9nPbHtUBAhereVGnHftrHEzIxzdz2x7VAQIPjriPHL9Sd46j4oAwcf0Z61/pWgUees8KgIEKwkJxEZQESAw85oq4Mngu8u+J3Ovwn8qAgTTLI6q0ZqNbEk2rIyJqP3+u89+h0r/qQgQvDtoR2+PRmeZ3SvtzE42xxGsKQbZfyoCBO94hNXbsw3HbDSMve45l9dOObWImeab5KNnREvPQFj2s/63RkXA4B2zXoW22rg+39mO135Wkdkc1qz/VAQIUjFrC9kc0KzdXfbv9J+KAIG4j8iictR61uzIqqMiHoD36Wt0PSyVZxHJA1qxZ0XKdtqNgIoAgeuJIW1N7XmqcsbVeFqs14oTjHWsNqJvEajyn4oAgRih0+a81fnQez+56nnaq476VftPRYDAjFlrvd+Xee8PIyeyCvP60rc3K9PuBZFY9U7/qQgQMK8JBFQECLblNVmrlsheI2O/2v9qUBEg+BePWM3Vmdmw8oV22K/0fxe0705FgODjOevMPC6dZGbeBOlpY7TvOfu523+pnR5UBAjEN5h5co2kcqmeJ7sjkj3h2U1nYit9vTE3y5uhov1GM9VRESBIv9PPgmdl4x2RHvvV/l+2s8+IW+1QESBIvdPPwh2j9Un+z9qhIkCw/Rk6K2ZQnXeE7r/UDhUBgpQitNyeFRtVOUM77Xnzu6K/DxUBAnUfYeXkRM95vpl3VOG/xtPsS+U9qAgQqHlN19/o++yqEIlpfNv/1dUWFQECcWetRdmin3k4rcXyj6wvVeX/rJ7G6U9veY94AH4BbM+OlWvRZgYAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTQtMTAtMjNUMTY6MTk6MzUtMDY6MDCRv42YAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE0LTEwLTIzVDE2OjE5OjM1LTA2OjAw4OI1JAAAAABJRU5ErkJggg==';

function get_id(i) {
	var e = document.getElementById(i);

	if (!e)
		throw ('get_id(\'' + i + '\') failed');

	return e;
}
function listener_add(el, ev, cb) {
	if (el.addEventListener)
		el.addEventListener(ev, cb, false);
	else
		el.attachEvent('on' + ev, cb);
}
function document_size() {
	return [
		document.documentElement.clientWidth,
		document.documentElement.clientHeight
	];
}
function window_size() {
	var wx, wy;
	if (window.innerWidth) {
		wx = window.innerWidth;
		wy = window.innerHeight
	}
	if (!wx && document.documentElement) {
		wx = document.documentElement.clientWidth;
		wy = document.documentElement.clientHeight;
	}
	if (!wx) {
		var body = document.body || document.getElementsByTagName('body')[0];
		if (body) {
			if (body.clientWidth) {
				wx = body.clientWidth;
				wy = body.clientHeight;
			} else if (body.offsetWidth) {
				wx = body.offsetWidth;
				wy = body.offsetHeight;
			}
		}
	}

	return [wx, wy];
}
function get_key(ev) {
	ev = ev ? ev : this.event;
	return ev.keyCode ? ev.keyCode : ev.which;
}
function window_scroll() {
	var x = 0;
	var y = 0;

	if (self.pageYOffset) {
		x = self.pageXOffset;
		y = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	} else if (document.body) {
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}

	return [x, y];
}

var obs = [];

var key_held = []; // auto set to false when key lifted
var key_pressed = []; // you have to set to false yourself when handled
var cat;
var x = 100;
var y = 100;
var astep = 0;
var stillstep = 0;
var catstate = 0;
var jumping = false;
var jumpvel = 0;
var movespeed = 4;
var bounds;

var catstates = [
	[0,    0, 28, 24],
	[28,   0, 28, 24],
	[56,   0, 28, 24],
	[84,   0, 28, 24],
	[112,  0, 28, 24],
	[140,  0, 28, 24],
	[168,  0, 28, 24],

	[0,   24, 48, 24],
	[48,  24, 48, 24],
	[96,  24, 48, 24],
	[144, 24, 48, 24],

	[0,   48, 48, 24],
	[48,  48, 48, 24],
	[96,  48, 48, 24],
	[144, 48, 48, 24]
];

(function() {
	// add a cat when CAT is typed
	var buffer = '';
	if(document.body) {
		listener_add(document, 'keydown', function(e) {
			var k = get_key(e);
			k = String.fromCharCode(k);
			if(k == 'C') {
				buffer = k;
				return;
			}

			if(!buffer.length) {
				return;
			}

			buffer += k;
			if(buffer == 'CAT') {
				catify();
				buffer = '';
			}else if(buffer.length > 3) {
				buffer = '';
			}
		});
	}
}());

function catify() {
	if(!document.createRange)
		return; // :'(

	var i;

//	listener_add(window, 'resize', resize);
//	listener_add(window, 'scroll', resize);
	setInterval(resize, 200);
	resize();

	for(i = 0; i < 255; i++) {
		key_held[i] = false;
		key_pressed[i] = false;
	}

	listener_add(document, 'keydown', function(e) {
		var k = get_key(e);
		key_held[k] = true;
		key_pressed[k] = true;
	});

	listener_add(document, 'keyup', function(e) {
		var k = get_key(e);
		key_held[k] = false;
	});

	cat = document.createElement('div');
	cat.style.position = 'absolute';
	//cat.style.backgroundImage = 'url("images/cat/atlas/cat1.png")';
	cat.style.backgroundImage = 'url("data:image/png;base64,' + cat1_base64 +'")';
	cat.style.backgroundRepeat = 'no-repeat';

	// set the cat atop a random spot on the page
	//var at = obs[Math.floor(Math.random() * obs.length)];
	//x = at.left + Math.floor(at.width * 0.5);
	//y = at.top - 1;
	x = Math.floor(bounds[0] * 0.3);
	y = 0;

	draw();
	document.body.appendChild(cat);

	setInterval(update, 16);
}

function update(force) {
	if(astep > 1000000)
		astep = 0;

	var ox = x;
	var oy = y;

	var catrect = {
		'top': y - catstates[catstate][3],
		'left': x,
		'width':catstates[catstate][2],
		'height': catstates[catstate][3],
	};
	var sitting = collide(catrect, obs);
	var cantfall = false;

	//if(y + catstates[catstate][3] >= bounds[1]) {
	if(y + 2 > bounds[1]) {
		sitting = true;
		cantfall = true;
	}

	if(key_held[37])
		x = x - movespeed;

	if(key_held[39])
		x = x + movespeed;

	if(x < 0)
		x = 0;

	if(x + catstates[catstate][2] > bounds[0])
		x = bounds[0] - catstates[catstate][2];

	if(key_held[38] && !jumping && sitting) {
		jumping = true;
		jumpvel = 10;
	}

	if(key_held[40] || (!jumping && !sitting && !cantfall)) {
		y = y + movespeed;
	}

	if(jumping) {
		y = y - jumpvel;

		if(y - catstates[catstate][3] < 0)
			y = catstates[catstate][3];

		jumpvel--;
		if(jumpvel == -1)
			jumping = false;
	}

	//if(y + catstates[catstate][3] > bounds[1]) {
	//	y = bounds[1] - catstates[catstate][3];
	//}
	if(y + 1 > bounds[1]) {
		y = bounds[1] - 1;
	}
	if(y - catstates[catstate][3] < 0) {
		y = catstates[catstate][3];
	}

	if(x == ox && y == oy) {
		if(stillstep <= 0) {
			stillstep = Math.floor(Math.random() * 20) + 20;
			astep = Math.floor(Math.random() * 100000);
		}
		stillstep--;

		catstate = astep % 7;
		draw();
		return;
	}

	astep++;

	var walka = Math.floor(astep / 2) % 4;

	if(x > ox)
		catstate = 11 + walka;
	else
		catstate = 7 + walka;

	draw();
}

function draw() {
	bg(cat, catstates[catstate]);
	cat.style.left = x+'px';
	cat.style.top = (y - catstates[catstate][3])+'px';
}

function bg(e, a) {
	e.style.width = a[2]+'px';
	e.style.height = a[3]+'px';
	e.style.backgroundPosition = (-a[0]) + 'px ' + (-a[1]) + 'px';
}

function collide(o, list) {
	var i, l;
	for(i = 0; i < list.length; i++) {
		l = list[i];
		//if(l.top > o.top + o.height)
		//	continue;
		//if(l.top + l.height < o.top)
		//	continue;
		if(o.top + o.height < l.top)
			continue;
		if(o.top + o.height > l.top + movespeed)
			continue;
		if(l.left > o.left + o.width)
			continue;
		if(l.left + l.width < o.left)
			continue;
		return true;
	}
	return false;
}

function resize() {
	var body = document.body;

	obs = [];

	var scr = window_scroll();

	all_text_nodes(body, function(e) {
		var range = document.createRange();
		range.selectNodeContents(e);
		var rects = range.getClientRects();
		var dims;
		for(var i = 0; i < rects.length; i++) {
			dims = {
				top: rects[i].top + scr[1],
				left: rects[i].left,
				width: rects[i].width,
				height: rects[i].height
			};
			obs.push(dims);

/*			d = document.createElement('div');
			d.style.position = 'absolute';
			d.style.backgroundColor = '#f00';
			d.style.opacity = 0.5;

			d.style.left = dims.left+'px';
			d.style.top = dims.top+'px';
			d.style.width = dims.width+'px';
			d.style.height = dims.height+'px';

			d.appendChild(document.createTextNode(''));
			document.body.appendChild(d);*/
		}
	});

	bounds = document_size();
	var w = window_size();
	if(bounds[1] < w[1])
		bounds[1] = w[1];
}

function all_text_nodes(element, cb)
{
	if(element.childNodes.length > 0)
		for(var i = 0; i < element.childNodes.length; i++)
			all_text_nodes(element.childNodes[i], cb);

	if(element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue))
		cb(element);
}

window.catify = catify;
})();

<commit_msg>let you focus/unfocus the cat<commit_after>(function(){
	"use strict";

var cat1_base64 = 'iVBORw0KGgoAAAANSUhEUgAAAMQAAABICAQAAAAD3ZJDAAAABGdBTUEAALGPC/xhBQAAAAJiS0dEAP+Hj8y/AAADEUlEQVR42u1cy3LDIAzEnfz/L7uXOkMoeoLi9czupXVghRJYDEj2cbY5jr+C8/j8rL9G4Y2c0Q4Kr683Xv80AgIvq8Jxeszcy3uCjxaXigDBtIP6+auvcF1L8+EdPIlz/Y/C03AeVAQM/nWWd/4be5+8NR4VAQL1HiFhZS4kb86jIkCgdtZYaO0eycvzqAgQvFqTz3kyqOQ9xc8Mj4oAwdGCo0yqN+44JV50VK/yvu1ntj0qAgTH2eLz3ni+Et11RrkjD9nPbHtUBAhereVGnHftrHEzIxzdz2x7VAQIPjriPHL9Sd46j4oAwcf0Z61/pWgUees8KgIEKwkJxEZQESAw85oq4Mngu8u+J3Ovwn8qAgTTLI6q0ZqNbEk2rIyJqP3+u89+h0r/qQgQvDtoR2+PRmeZ3SvtzE42xxGsKQbZfyoCBO94hNXbsw3HbDSMve45l9dOObWImeab5KNnREvPQFj2s/63RkXA4B2zXoW22rg+39mO135Wkdkc1qz/VAQIUjFrC9kc0KzdXfbv9J+KAIG4j8iictR61uzIqqMiHoD36Wt0PSyVZxHJA1qxZ0XKdtqNgIoAgeuJIW1N7XmqcsbVeFqs14oTjHWsNqJvEajyn4oAgRih0+a81fnQez+56nnaq476VftPRYDAjFlrvd+Xee8PIyeyCvP60rc3K9PuBZFY9U7/qQgQMK8JBFQECLblNVmrlsheI2O/2v9qUBEg+BePWM3Vmdmw8oV22K/0fxe0705FgODjOevMPC6dZGbeBOlpY7TvOfu523+pnR5UBAjEN5h5co2kcqmeJ7sjkj3h2U1nYit9vTE3y5uhov1GM9VRESBIv9PPgmdl4x2RHvvV/l+2s8+IW+1QESBIvdPPwh2j9Un+z9qhIkCw/Rk6K2ZQnXeE7r/UDhUBgpQitNyeFRtVOUM77Xnzu6K/DxUBAnUfYeXkRM95vpl3VOG/xtPsS+U9qAgQqHlN19/o++yqEIlpfNv/1dUWFQECcWetRdmin3k4rcXyj6wvVeX/rJ7G6U9veY94AH4BbM+OlWvRZgYAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTQtMTAtMjNUMTY6MTk6MzUtMDY6MDCRv42YAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE0LTEwLTIzVDE2OjE5OjM1LTA2OjAw4OI1JAAAAABJRU5ErkJggg==';

function get_id(i) {
	var e = document.getElementById(i);

	if (!e)
		throw ('get_id(\'' + i + '\') failed');

	return e;
}
function listener_add(el, ev, cb) {
	if (el.addEventListener)
		el.addEventListener(ev, cb, false);
	else
		el.attachEvent('on' + ev, cb);
}
function document_size() {
	return [
		document.documentElement.clientWidth,
		document.documentElement.clientHeight
	];
}
function window_size() {
	var wx, wy;
	if (window.innerWidth) {
		wx = window.innerWidth;
		wy = window.innerHeight;
	}
	if (!wx && document.documentElement) {
		wx = document.documentElement.clientWidth;
		wy = document.documentElement.clientHeight;
	}
	if (!wx) {
		var body = document.body || document.getElementsByTagName('body')[0];
		if (body) {
			if (body.clientWidth) {
				wx = body.clientWidth;
				wy = body.clientHeight;
			} else if (body.offsetWidth) {
				wx = body.offsetWidth;
				wy = body.offsetHeight;
			}
		}
	}

	return [wx, wy];
}
function get_key(ev) {
	ev = ev ? ev : this.event;
	return ev.keyCode ? ev.keyCode : ev.which;
}
function window_scroll() {
	var x = 0;
	var y = 0;

	if (self.pageYOffset) {
		x = self.pageXOffset;
		y = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	} else if (document.body) {
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}

	return [x, y];
}

var obs = [];

var key_held = []; // auto set to false when key lifted
var cat;
var x = 100;
var y = 100;
var astep = 0;
var stillstep = 0;
var catstate = 0;
var jumping = false;
var jumpvel = 0;
var movespeed = 4;
var bounds;
var focused = true;
var inited = false;

var catstates = [
	[0,    0, 28, 24],
	[28,   0, 28, 24],
	[56,   0, 28, 24],
	[84,   0, 28, 24],
	[112,  0, 28, 24],
	[140,  0, 28, 24],
	[168,  0, 28, 24],

	[0,   24, 48, 24],
	[48,  24, 48, 24],
	[96,  24, 48, 24],
	[144, 24, 48, 24],

	[0,   48, 48, 24],
	[48,  48, 48, 24],
	[96,  48, 48, 24],
	[144, 48, 48, 24]
];

(function() {
	// add a cat when CAT is typed
	var buffer = '';
	if(document.body) {
		listener_add(document.body, 'keydown', function(e) {
			if(document.activeElement &&
			   document.activeElement.tagName.match(/^(INPUT|TEXTAREA)$/)) {
				return;
			}

			var k = get_key(e);
			k = String.fromCharCode(k);
			if(k == 'C') {
				buffer = k;
				return;
			}

			if(!buffer.length) {
				return;
			}

			buffer += k;
			if(buffer == 'CAT') {
				catify();
				buffer = '';
			}else if(buffer.length > 3) {
				buffer = '';
			}
		});
	}
}());

function catify() {
	if(!document.createRange)
		return; // :'(

	if(!inited) {
		init();
	}

	cat = document.createElement('div');
	cat.style.position = 'absolute';
	//cat.style.backgroundImage = 'url("images/cat/atlas/cat1.png")';
	cat.style.backgroundImage = 'url("data:image/png;base64,' + cat1_base64 +'")';
	cat.style.backgroundRepeat = 'no-repeat';
	cat.className = 'catify';

	listener_add(cat, 'click', function(e) {
		focused = !focused;
	});
	listener_add(cat, 'dblclick', function(e) {
		cat.parentNode.removeChild(cat);
		cat = null;
	});

	// set the cat atop a random spot on the page
	//var at = obs[Math.floor(Math.random() * obs.length)];
	//x = at.left + Math.floor(at.width * 0.5);
	//y = at.top - 1;
	x = Math.floor(bounds[0] * 0.3);
	y = 0;

	draw();
	document.body.appendChild(cat);

	if(!inited) {
		setInterval(update, 16);
		inited = true;
	}
}

function init() {
	var i;

//	listener_add(window, 'resize', resize);
//	listener_add(window, 'scroll', resize);
	setInterval(resize, 200);
	resize();

	for(i = 0; i < 255; i++) {
		key_held[i] = false;
	}

	listener_add(document, 'keydown', function(e) {
		if(!has_focus()) { return; }

		var k = get_key(e);
		key_held[k] = true;

		if(k >= 37 && k <= 40) {
			e.returnValue = false;
		}
	});

	listener_add(document, 'keyup', function(e) {
		if(!has_focus()) { return; }

		var k = get_key(e);
		key_held[k] = false;

		if(k >= 37 && k <= 40) {
			e.returnValue = false;
		}
	});
}

function has_focus() {
	if(!focused || !cat) {
		 return false;
	}

	if(document.activeElement &&
	   document.activeElement.tagName.match(/^(INPUT|TEXTAREA)$/)) {
		return false;
	}

	return true;
}

function update(force) {
	if(astep > 1000000)
		astep = 0;

	var ox = x;
	var oy = y;

	var catrect = {
		'top': y - catstates[catstate][3],
		'left': x,
		'width':catstates[catstate][2],
		'height': catstates[catstate][3]
	};
	var sitting = collide(catrect, obs);
	var cantfall = false;

	//if(y + catstates[catstate][3] >= bounds[1]) {
	if(y + 2 > bounds[1]) {
		sitting = true;
		cantfall = true;
	}

	if(key_held[37])
		x = x - movespeed;

	if(key_held[39])
		x = x + movespeed;

	if(x < 0)
		x = 0;

	if(x + catstates[catstate][2] > bounds[0])
		x = bounds[0] - catstates[catstate][2];

	if(key_held[38] && !jumping && sitting) {
		jumping = true;
		jumpvel = 10;
	}

	if(key_held[40] || (!jumping && !sitting && !cantfall)) {
		y = y + movespeed;
	}

	if(jumping) {
		y = y - jumpvel;

		if(y - catstates[catstate][3] < 0)
			y = catstates[catstate][3];

		jumpvel--;
		if(jumpvel == -1)
			jumping = false;
	}

	//if(y + catstates[catstate][3] > bounds[1]) {
	//	y = bounds[1] - catstates[catstate][3];
	//}
	if(y + 1 > bounds[1]) {
		y = bounds[1] - 1;
	}
	if(y - catstates[catstate][3] < 0) {
		y = catstates[catstate][3];
	}

	if(x == ox && y == oy) {
		if(stillstep <= 0) {
			stillstep = Math.floor(Math.random() * 20) + 20;
			astep = Math.floor(Math.random() * 100000);
		}
		stillstep--;

		catstate = astep % 7;
		draw();
		return;
	}

	astep++;

	var walka = Math.floor(astep / 2) % 4;

	if(x > ox)
		catstate = 11 + walka;
	else
		catstate = 7 + walka;

	draw();
}

function draw() {
	bg(cat, catstates[catstate]);
	cat.style.left = x+'px';
	cat.style.top = (y - catstates[catstate][3])+'px';
}

function bg(e, a) {
	e.style.width = a[2]+'px';
	e.style.height = a[3]+'px';
	e.style.backgroundPosition = (-a[0]) + 'px ' + (-a[1]) + 'px';
}

function collide(o, list) {
	var i, l;
	for(i = 0; i < list.length; i++) {
		l = list[i];
		//if(l.top > o.top + o.height)
		//	continue;
		//if(l.top + l.height < o.top)
		//	continue;
		if(o.top + o.height < l.top)
			continue;
		if(o.top + o.height > l.top + movespeed)
			continue;
		if(l.left > o.left + o.width)
			continue;
		if(l.left + l.width < o.left)
			continue;
		return true;
	}
	return false;
}

function resize() {
	var body = document.body;

	obs = [];

	var scr = window_scroll();

	all_text_nodes(body, function(e) {
		var range = document.createRange();
		range.selectNodeContents(e);
		var rects = range.getClientRects();
		var dims;
		for(var i = 0; i < rects.length; i++) {
			dims = {
				top: rects[i].top + scr[1],
				left: rects[i].left,
				width: rects[i].width,
				height: rects[i].height
			};
			obs.push(dims);

/*			d = document.createElement('div');
			d.style.position = 'absolute';
			d.style.backgroundColor = '#f00';
			d.style.opacity = 0.5;

			d.style.left = dims.left+'px';
			d.style.top = dims.top+'px';
			d.style.width = dims.width+'px';
			d.style.height = dims.height+'px';

			d.appendChild(document.createTextNode(''));
			document.body.appendChild(d);*/
		}
	});

	bounds = document_size();
	var w = window_size();
	if(bounds[1] < w[1])
		bounds[1] = w[1];
}

function all_text_nodes(element, cb)
{
	if(element.childNodes.length > 0)
		for(var i = 0; i < element.childNodes.length; i++)
			all_text_nodes(element.childNodes[i], cb);

	if(element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue))
		cb(element);
}

window.catify = catify;
})();

<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import {formatDate} from '../../../DateUtils';
import { _t } from '../../../languageHandler';
import filesize from "filesize";
import AccessibleButton from "./AccessibleButton";
import Modal from "../../../Modal";
import * as sdk from "../../../index";
import {Key} from "../../../Keyboard";
import FocusLock from "react-focus-lock";

export default class ImageView extends React.Component {
    static propTypes = {
        src: PropTypes.string.isRequired, // the source of the image being displayed
        name: PropTypes.string, // the main title ('name') for the image
        link: PropTypes.string, // the link (if any) applied to the name of the image
        width: PropTypes.number, // width of the image src in pixels
        height: PropTypes.number, // height of the image src in pixels
        fileSize: PropTypes.number, // size of the image src in bytes
        onFinished: PropTypes.func.isRequired, // callback when the lightbox is dismissed

        // the event (if any) that the Image is displaying. Used for event-specific stuff like
        // redactions, senders, timestamps etc.  Other descriptors are taken from the explicit
        // properties above, which let us use lightboxes to display images which aren't associated
        // with events.
        mxEvent: PropTypes.object,
    };

    constructor(props) {
        super(props);
        this.state = {
            rotation: 0,
            zoom: 100,
            translationX: 0,
            translationY: 0,
            moving: false,
        };
    }

    initX = 0;
    initY = 0;
    lastX = 0;
    lastY = 0;
    minZoom = 100;
    maxZoom = 300;

    componentDidMount() {
        /* We have to use addEventListener() because the listener
         * needs to be passive in order to work with Chromium */
        this.focusLock.addEventListener('wheel', this.onWheel, { passive: false });
    }

    componentWillUnmount() {
        this.focusLock.removeEventListener('wheel', this.onWheel);
    }

    onKeyDown = (ev) => {
        if (ev.key === Key.ESCAPE) {
            ev.stopPropagation();
            ev.preventDefault();
            this.props.onFinished();
        }
    };

    onWheel = (ev) => {
        ev.stopPropagation();
        ev.preventDefault();
        const newZoom =this.state.zoom - ev.deltaY;

        if (newZoom <= this.minZoom) {
            this.setState({
                zoom: this.minZoom,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        if (newZoom >= this.maxZoom) {
            this.setState({zoom: this.maxZoom});
            return;
        }

        this.setState({
            zoom: newZoom,
        });
    }

    onRedactClick = () => {
        const ConfirmRedactDialog = sdk.getComponent("dialogs.ConfirmRedactDialog");
        Modal.createTrackedDialog('Confirm Redact Dialog', 'Image View', ConfirmRedactDialog, {
            onFinished: (proceed) => {
                if (!proceed) return;
                this.props.onFinished();
                MatrixClientPeg.get().redactEvent(
                    this.props.mxEvent.getRoomId(), this.props.mxEvent.getId(),
                ).catch(function(e) {
                    const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
                    // display error message stating you couldn't delete this.
                    const code = e.errcode || e.statusCode;
                    Modal.createTrackedDialog('You cannot delete this image.', '', ErrorDialog, {
                        title: _t('Error'),
                        description: _t('You cannot delete this image. (%(code)s)', {code: code}),
                    });
                });
            },
        });
    };

    onRotateCounterClockwiseClick = () => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur - 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onRotateClockwiseClick = () => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur + 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onZoomInClick = () => {
        if (this.state.zoom >= this.maxZoom) {
            this.setState({zoom: this.maxZoom});
            return;
        }

        this.setState({
            zoom: this.state.zoom + 10,
        });
    };

    onZoomOutClick = () => {
        if (this.state.zoom <= this.minZoom) {
            this.setState({
                zoom: this.minZoom,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        this.setState({
            zoom: this.state.zoom - 10,
        });
    }

    onZoomClick = () => {
        if (this.state.zoom <= this.minZoom) {
            this.setState({zoom: this.maxZoom});
        } else {
            this.setState({
                zoom: this.minZoom,
                translationX: 0,
                translationY: 0,
            });
        }
    }

    onStartMoving = ev => {
        ev.stopPropagation();
        ev.preventDefault();

        this.setState({moving: true});
        this.initX = ev.pageX - this.lastX;
        this.initY = ev.pageY - this.lastY;
    }

    onMoving = ev => {
        ev.stopPropagation();
        ev.preventDefault();

        if (!this.state.moving) return false;

        this.lastX = ev.pageX - this.initX;
        this.lastY = ev.pageY - this.initY;
        this.setState({
            translationX: this.lastX,
            translationY: this.lastY,
        });
    }

    onEndMoving = ev => {
        this.setState({moving: false});
    }

    render() {
        let mayRedact = false;
        const showEventMeta = !!this.props.mxEvent;

        let res;
        if (this.props.width && this.props.height) {
            res = this.props.width + "x" + this.props.height + "px";
        }

        let size;
        if (this.props.fileSize) {
            size = filesize(this.props.fileSize);
        }

        let sizeRes;
        if (size && res) {
            sizeRes = size + ", " + res;
        } else {
            sizeRes = size || res;
        }

        let metadata;
        if (showEventMeta) {
            // Figure out the sender, defaulting to mxid
            let sender = this.props.mxEvent.getSender();
            const cli = MatrixClientPeg.get();
            const room = cli.getRoom(this.props.mxEvent.getRoomId());
            if (room) {
                mayRedact = room.currentState.maySendRedactionForEvent(this.props.mxEvent, cli.credentials.userId);
                const member = room.getMember(sender);
                if (member) sender = member.name;
            }

            metadata = (

                { _t('Uploaded on %(date)s by %(user)s', {
                    date: formatDate(new Date(this.props.mxEvent.getTs())),
                    user: sender,
                }) }

);
        }

        let redactButton;
        if (mayRedact) {
            redactButton = (
                <AccessibleButton className="mx_ImageView_button" title={_t("Remove")} onClick={ this.onRedactClick }>

                </AccessibleButton>
            );
        }

        const rotationDegrees = this.state.rotation + "deg";
        const zoomPercentage = this.state.zoom/100;
        const translatePixelsX = this.state.translationX + "px";
        const translatePixelsY = this.state.translationY + "px";
        /* The order of the values is important!
         * First, we translate and only then we rotate, otherwise
         * we would apply the translation to an already rotated
         * image causing it translate in the wrong direction. */
        const style = {
            transform: `translateX(${translatePixelsX})
                        translateY(${translatePixelsY})
                        scale(${zoomPercentage})
                        rotate(${rotationDegrees})`,
        };

        return (
            <FocusLock
                returnFocus={true}
                lockProps={{
                    onKeyDown: this.onKeyDown,
                    role: "dialog",
                }}
                className="mx_ImageView"
                ref={ref => this.focusLock = ref}
            >

                            { sizeRes }
                            { metadata }

                            { redactButton }
                            <AccessibleButton className="mx_ImageView_button" title={_t("Rotate Right")} onClick={ this.onRotateClockwiseClick }>

                            </AccessibleButton>
                            <AccessibleButton className="mx_ImageView_button" title={_t("Rotate Left")} onClick={ this.onRotateCounterClockwiseClick }>

                            </AccessibleButton>
                            <AccessibleButton className="mx_ImageView_button" title={_t("Zoom out")} onClick={ this.onZoomOutClick }>

                            </AccessibleButton>
                            <AccessibleButton className="mx_ImageView_button" title={_t("Zoom in")} onClick={ this.onZoomInClick }>

                            </AccessibleButton>

                            <AccessibleButton className="mx_ImageView_button" title={_t("Close")} onClick={ this.props.onFinished }>

                            </AccessibleButton>

            </FocusLock>
        );
    }
}
<commit_msg>Remove size info<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import {formatDate} from '../../../DateUtils';
import { _t } from '../../../languageHandler';
import AccessibleButton from "./AccessibleButton";
import Modal from "../../../Modal";
import * as sdk from "../../../index";
import {Key} from "../../../Keyboard";
import FocusLock from "react-focus-lock";

export default class ImageView extends React.Component {
    static propTypes = {
        src: PropTypes.string.isRequired, // the source of the image being displayed
        name: PropTypes.string, // the main title ('name') for the image
        link: PropTypes.string, // the link (if any) applied to the name of the image
        width: PropTypes.number, // width of the image src in pixels
        height: PropTypes.number, // height of the image src in pixels
        fileSize: PropTypes.number, // size of the image src in bytes
        onFinished: PropTypes.func.isRequired, // callback when the lightbox is dismissed

        // the event (if any) that the Image is displaying. Used for event-specific stuff like
        // redactions, senders, timestamps etc.  Other descriptors are taken from the explicit
        // properties above, which let us use lightboxes to display images which aren't associated
        // with events.
        mxEvent: PropTypes.object,
    };

    constructor(props) {
        super(props);
        this.state = {
            rotation: 0,
            zoom: 100,
            translationX: 0,
            translationY: 0,
            moving: false,
        };
    }

    initX = 0;
    initY = 0;
    lastX = 0;
    lastY = 0;
    minZoom = 100;
    maxZoom = 300;

    componentDidMount() {
        /* We have to use addEventListener() because the listener
         * needs to be passive in order to work with Chromium */
        this.focusLock.addEventListener('wheel', this.onWheel, { passive: false });
    }

    componentWillUnmount() {
        this.focusLock.removeEventListener('wheel', this.onWheel);
    }

    onKeyDown = (ev) => {
        if (ev.key === Key.ESCAPE) {
            ev.stopPropagation();
            ev.preventDefault();
            this.props.onFinished();
        }
    };

    onWheel = (ev) => {
        ev.stopPropagation();
        ev.preventDefault();
        const newZoom =this.state.zoom - ev.deltaY;

        if (newZoom <= this.minZoom) {
            this.setState({
                zoom: this.minZoom,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        if (newZoom >= this.maxZoom) {
            this.setState({zoom: this.maxZoom});
            return;
        }

        this.setState({
            zoom: newZoom,
        });
    }

    onRedactClick = () => {
        const ConfirmRedactDialog = sdk.getComponent("dialogs.ConfirmRedactDialog");
        Modal.createTrackedDialog('Confirm Redact Dialog', 'Image View', ConfirmRedactDialog, {
            onFinished: (proceed) => {
                if (!proceed) return;
                this.props.onFinished();
                MatrixClientPeg.get().redactEvent(
                    this.props.mxEvent.getRoomId(), this.props.mxEvent.getId(),
                ).catch(function(e) {
                    const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
                    // display error message stating you couldn't delete this.
                    const code = e.errcode || e.statusCode;
                    Modal.createTrackedDialog('You cannot delete this image.', '', ErrorDialog, {
                        title: _t('Error'),
                        description: _t('You cannot delete this image. (%(code)s)', {code: code}),
                    });
                });
            },
        });
    };

    onRotateCounterClockwiseClick = () => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur - 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onRotateClockwiseClick = () => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur + 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onZoomInClick = () => {
        if (this.state.zoom >= this.maxZoom) {
            this.setState({zoom: this.maxZoom});
            return;
        }

        this.setState({
            zoom: this.state.zoom + 10,
        });
    };

    onZoomOutClick = () => {
        if (this.state.zoom <= this.minZoom) {
            this.setState({
                zoom: this.minZoom,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        this.setState({
            zoom: this.state.zoom - 10,
        });
    }

    onZoomClick = () => {
        if (this.state.zoom <= this.minZoom) {
            this.setState({zoom: this.maxZoom});
        } else {
            this.setState({
                zoom: this.minZoom,
                translationX: 0,
                translationY: 0,
            });
        }
    }

    onStartMoving = ev => {
        ev.stopPropagation();
        ev.preventDefault();

        this.setState({moving: true});
        this.initX = ev.pageX - this.lastX;
        this.initY = ev.pageY - this.lastY;
    }

    onMoving = ev => {
        ev.stopPropagation();
        ev.preventDefault();

        if (!this.state.moving) return false;

        this.lastX = ev.pageX - this.initX;
        this.lastY = ev.pageY - this.initY;
        this.setState({
            translationX: this.lastX,
            translationY: this.lastY,
        });
    }

    onEndMoving = ev => {
        this.setState({moving: false});
    }

    render() {
        let mayRedact = false;
        const showEventMeta = !!this.props.mxEvent;

        let metadata;
        if (showEventMeta) {
            // Figure out the sender, defaulting to mxid
            let sender = this.props.mxEvent.getSender();
            const cli = MatrixClientPeg.get();
            const room = cli.getRoom(this.props.mxEvent.getRoomId());
            if (room) {
                mayRedact = room.currentState.maySendRedactionForEvent(this.props.mxEvent, cli.credentials.userId);
                const member = room.getMember(sender);
                if (member) sender = member.name;
            }

            metadata = (

                { _t('Uploaded on %(date)s by %(user)s', {
                    date: formatDate(new Date(this.props.mxEvent.getTs())),
                    user: sender,
                }) }

);
        }

        let redactButton;
        if (mayRedact) {
            redactButton = (
                <AccessibleButton className="mx_ImageView_button" title={_t("Remove")} onClick={ this.onRedactClick }>

                </AccessibleButton>
            );
        }

        const rotationDegrees = this.state.rotation + "deg";
        const zoomPercentage = this.state.zoom/100;
        const translatePixelsX = this.state.translationX + "px";
        const translatePixelsY = this.state.translationY + "px";
        /* The order of the values is important!
         * First, we translate and only then we rotate, otherwise
         * we would apply the translation to an already rotated
         * image causing it translate in the wrong direction. */
        const style = {
            transform: `translateX(${translatePixelsX})
                        translateY(${translatePixelsY})
                        scale(${zoomPercentage})
                        rotate(${rotationDegrees})`,
        };

        return (
            <FocusLock
                returnFocus={true}
                lockProps={{
                    onKeyDown: this.onKeyDown,
                    role: "dialog",
                }}
                className="mx_ImageView"
                ref={ref => this.focusLock = ref}
            >

                            { metadata }

                            { redactButton }
                            <AccessibleButton className="mx_ImageView_button" title={_t("Rotate Right")} onClick={ this.onRotateClockwiseClick }>

                            </AccessibleButton>
                            <AccessibleButton className="mx_ImageView_button" title={_t("Rotate Left")} onClick={ this.onRotateCounterClockwiseClick }>

                            </AccessibleButton>
                            <AccessibleButton className="mx_ImageView_button" title={_t("Zoom out")} onClick={ this.onZoomOutClick }>

                            </AccessibleButton>
                            <AccessibleButton className="mx_ImageView_button" title={_t("Zoom in")} onClick={ this.onZoomInClick }>

                            </AccessibleButton>

                            <AccessibleButton className="mx_ImageView_button" title={_t("Close")} onClick={ this.props.onFinished }>

                            </AccessibleButton>

            </FocusLock>
        );
    }
}
<|endoftext|>


<commit_before>var map = [
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
];

var size = 10;

canvas = document.getElementById('canvas')
canvas.addEventListener('click', onClick, false);
var g = canvas.getContext('2d');
g.fillStyle='#FF00A5';

function onClick(e) {
  var pp = getPosition(e.currentTarget);
  var xp = e.clientX - pp.x;
  var yp = e.clientY - pp.y;

  console.log(xp + " " + yp);

  for (var i=0; i<map.length; i++) {
    for (var j=0; j<map[i].length; j++) {
      drawHex(map[i][j], i*size*3/2, (i+j*2)*size*Math.sqrt(3)/2);
    }
  }
}

function drawHex(hex, xp, yp) {
  var i;
  for (i=0; i<=6; i++) {
    var angle = 2 * Math.PI / 6 * i;
    x = xp + size * Math.cos(angle);
    y = yp + size * Math.sin(angle);
    if (i == 0)
      g.moveTo(x,y);
    else
      g.lineTo(x,y);
  }
  g.stroke();
}

function getPosition(e) {
    var xp = 0;
    var yp = 0;

    while (e) {
        xp += (e.offsetLeft - e.scrollLeft + e.clientLeft);
        yp += (e.offsetTop - e.scrollTop + e.clientTop);
        e = e.offsetParent;
    }
    return { x: xp, y: yp };
}<commit_msg>Automatically draw, bigger grid.<commit_after>var map = [
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
  [{state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}, {state:0, type:0}],
];

var size = 30;

canvas = document.getElementById('canvas')
canvas.addEventListener('click', onClick, false);
var g = canvas.getContext('2d');
g.fillStyle='#FF00A5';

for (var i=0; i<map.length; i++) {
  for (var j=0; j<map[i].length; j++) {
    drawHex(map[i][j], i*size*3/2, (i+j*2)*size*Math.sqrt(3)/2);
  }
}

function onClick(e) {
  var pp = getPosition(e.currentTarget);
  var xp = e.clientX - pp.x;
  var yp = e.clientY - pp.y;

  console.log(xp + " " + yp);
}

function drawHex(hex, xp, yp) {
  var i;
  for (i=0; i<=6; i++) {
    var angle = 2 * Math.PI / 6 * i;
    x = xp + size * Math.cos(angle);
    y = yp + size * Math.sin(angle);
    if (i == 0)
      g.moveTo(x,y);
    else
      g.lineTo(x,y);
  }
  g.stroke();
}

function getPosition(e) {
    var xp = 0;
    var yp = 0;

    while (e) {
        xp += (e.offsetLeft - e.scrollLeft + e.clientLeft);
        yp += (e.offsetTop - e.scrollTop + e.clientTop);
        e = e.offsetParent;
    }
    return { x: xp, y: yp };
}<|endoftext|>