<commit_before>//     timing.io 0.1
//     http://timing.io
//     (c) 2014 Max Diachenko
//     Timing.io may be freely distributed under the MIT license.

(function () {
  'use strict';

  // Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this;

  var $timing = {};

  // Export the Timing object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `$timing` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = $timing;
    }
    exports.$timing = $timing;
  } else {
    root.$timing = $timing;
  }

  // Current version.
  $timing.VERSION = '0.1';

  $timing.mark = function (markerName) {
    window.performance.mark(markerName);
  };

  $timing.measure = function (resultName, markerFrom, markerTo) {
    window.performance.measure(resultName, markerFrom, markerTo);
  };

  $timing.result = function (name, log) {
    log = log || false;
    if (typeof name === 'string') {
      var result = window.performance.getEntriesByName(name);
      if (log) {
        console.log(result);
      }
      return result;
    } else if (Array.isArray(name)) {
      var result = [];
      name.forEach(function (measureName) {
        result.push($timing.result(measureName));
      });
      if (log) {
        console.log(result);
      }
      return result;
    } else {

    }

  };

  // amdefine
  if (typeof define === 'function' && define.amd) {
    define('$timing', [], function () {
      return $timing;
    });
  }
}).call(this);<commit_msg>feat(navigation): initial commit feat(resources): initial commit refactor(logging): use console log, warn, info, error<commit_after>//     timing.io 0.1
//     http://timing.io
//     (c) 2014 Max Diachenko
//     Timing.io may be freely distributed under the MIT license.

(function () {
  'use strict';

  //addLoadEvent for use multiple functions window.onLoad
  var addLoadEvent = function (func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
      window.onload = func;
    } else {
      window.onload = function () {
        if (oldonload) {
          oldonload();
        }
        func();
      }
    }
  };

  //specific log function
  var log = function (message, type) {
    if ($timing.loging) {
      console[type || 'log'](message);
      console.log('');
    }
  }

  //specific log function
  var getConsoleType = function (duration, linesOfCode) {
    return 'info';
  }

  // Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this;

  var $timing = {};

  // Export the Timing object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `$timing` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = $timing;
    }
    exports.$timing = $timing;
  } else {
    root.$timing = $timing;
  }

  // Current version.
  $timing.VERSION = '0.1';

  $timing.mark = function (markerName, linesOfCode) {
    root.performance.mark(markerName);
  };

  $timing.measure = function (resultName, markerFrom, markerTo) {
    if (resultName && markerFrom && markerTo) {
      root.performance.measure(resultName, markerFrom, markerTo);
      return $timing.measure(resultName);
    } else if (resultName) {
      var output = root.performance.getEntriesByName(resultName);
      output = output[output.length - 1];
      log(output.name + ' = ' + output.duration, getConsoleType());
      return output;
    }
  };

  $timing.resources = function () {
    addLoadEvent(function () {
      var output = root.performance.getEntriesByType('resource');
      output.forEach(function (entry) {
        log(entry.name + ' (' + entry.duration + ')');
      });
      return output;
    });
  };

  $timing.navigation = function () {
    addLoadEvent(function () {
      var output = root.performance.timing;
      log(output);
      return output;
    });
  };

  // amdefine
  if (typeof define === 'function' && define.amd) {
    define('$timing', [], function () {
      return $timing;
    });
  }
}).call(this);<|endoftext|>


<commit_before>/*
  SlideShow

  TODO
   * Get filesuffix better
   * Accept only one file at the time
   * Open asset from url!

*/

engine.ImportExtension("qt.core");
engine.ImportExtension("qt.gui");

// connect to Drag events
ui.GraphicsView().DragEnterEvent.connect(handleEnter);
ui.GraphicsView().DragMoveEvent.connect(handleMove);
ui.GraphicsView().DropEvent.connect(handleDrop);
print ('foo')

var entity;
var canvassource;
var slides;
var slide_index = 0;

function checkSuffix(url) {
    // FIXME
    if (("" + url).split('.txt').length == 2) {
	print("I accept!");

	return true;
    }
    print("No sir, I don't like it");
    return false;
}

function accept(event) {

    var mimedata = event.mimeData();

    if (mimedata.hasUrls()) {
	var urls = mimedata.urls();
	for (u = 0; u < urls.length; u++ ) {
	    if (checkSuffix(urls[u])) {
		event.acceptProposedAction();
	    }
	}
    }
}

function handleEnter(event) {
    print("Enter the event!");
    accept(event);
}

function handleMove(event) {
    print("I like to move it move it!");
    accept(event);
}

function handleDrop(event) {
    print ("DROP!");
    accept(event);

    var mimedata = event.mimeData();
    var urls = mimedata.urls();
    for (u = 0; u < urls.length; u++ ) {
	if (checkSuffix(urls[u])) {
	    //FIXME!!!!!!1!
	    print(urls[u]+"");
	    var filename = ("" + urls[u]).split('///')[1];
	    var file = new QFile(filename);
	    file.open(QIODevice.ReadOnly);
	    var streamer = new QTextStream(file);
	    slides = [];
	    while (true) {
		var line = streamer.readLine();
		if (!line) {
		    break;
		}
		slides.push(line)
	    }
    	    print(slides);
	    createCanvas(filename, slides);
	}
    }
}

function createCanvas(filename, slides) {
    entity = scene.CreateEntityRaw(scene.NextFreeId(), ['EC_Placeable', 'EC_Mesh', 'EC_3DCanvasSource', 'EC_Name', 'EC_DynamicComponent']);

    // set name
    entity.name.name = "Slideshow: " + filename;
    entity.name.description = "Simple slideshow app from " + filename;

    // set mesh
    var mesh_ref = entity.mesh.meshRef;
    mesh_ref.ref = 'local://screen.mesh';
    entity.mesh.meshRef = mesh_ref;

    // set source to first slide
    canvassource = entity.GetComponentRaw('EC_3DCanvasSource')
    canvassource.show2d = false;
    canvassource.source = slides[0];
    canvassource.submesh = 1;

    // start canvas
    var canvas = entity.GetComponentRaw('EC_3DCanvas');
    frame.DelayedExecute(0.1).Triggered.connect(this, function () {
	canvas.Start();
    });

    // Make dynamic component of the slide stuff

    var dyn = entity.dynamiccomponent;

    dyn.Name ="Slidelist";

    for (s = 0; s < slides.length; s++) {
	var slidename = s;
	var attr = dyn.CreateAttribute("string", slidename);
	dyn.SetAttribute(slidename, slides[s] + "");

    }
    dyn.CreateAttribute("int", "Current");
    dyn.SetAttribute("Current", 0);

    // Now we are done
    scene.EmitEntityCreatedRaw(entity);

    entity.Action("MousePress").Triggered.connect(nextSlide);

}

function nextSlide() {
    print("Next slide!");
    changeSlide(1);
}

function prevSlide() {
    print("Previous slide!");
    changeSlide(-1);
}

function changeSlide(dir) {
    print("Changing slide!");
    var dyn = entity.GetComponentRaw("EC_DynamicComponent", "Slidelist");
    var slide_index = dyn.GetAttribute("Current") + dir;

    if (slide_index >= slides.length) {
	slide_index = 0;
    }

    if (slide_index < 0) {
	slide_index = slides.length - 1;
    }

    canvassource.source = dyn.GetAttribute(slide_index);
    dyn.SetAttribute("Current", slide_index);
}

MyPixMap = {};

MyPixMap.prototype = new QWidget();

function makeSlideWidget() {
    var gfxscene = new QGraphicsScene();
    var view = new QGraphicsView(gfxscene);
    var slidethumbs = [];

    for (s = 0; s < 5; s++) {
	slidethumbs.push((new QPixmap("C:\\Users\\playsign\\sand_d.jpg")).scaledToWidth(100));
	slidethumbs.push((new QPixmap("C:\\Users\\playsign\\terrapin_texture.png")).scaledToWidth(100));
    }

    uiservice.AddWidgetToScene(view);

    for (s = 0; s < slidethumbs.length; s++) {
	var item = gfxscene.addPixmap(slidethumbs[s]);
	item.mousePressEvent = function(event) { print("goo"); };
	item.setPos(0,110 * s);
    }

    view.resize(110, 400);
    view.show();

}

makeSlideWidget();<commit_msg>More tinkering wih slideshow. Does not work yet<commit_after>/*
  SlideShow

  TODO
   * Get filesuffix better
   * Open asset from url!

*/

engine.ImportExtension("qt.core");
engine.ImportExtension("qt.gui");

// connect to Drag events
ui.GraphicsView().DragEnterEvent.connect(handleEnter);
ui.GraphicsView().DragMoveEvent.connect(handleMove);
ui.GraphicsView().DropEvent.connect(handleDrop);
print ('foo')

var entity;
var canvassource;
var slides;
var slide_index = 0;

function checkSuffix(url) {
    // FIXME
    if (("" + url).split('.txt').length == 2) {
	print("I accept!");

	return true;
    }
    print("No sir, I don't like it");
    return false;
}

function accept(event) {

    var mimedata = event.mimeData();

    if (mimedata.hasUrls()) {
	var urls = mimedata.urls();
	for (u = 0; u < urls.length; u++ ) {
	    if (checkSuffix(urls[u])) {
		event.acceptProposedAction();
	    }
	}
    }
}

function handleEnter(event) {
    print("Enter the event!");
    accept(event);
}

function handleMove(event) {
    print("I like to move it move it!");
    accept(event);
}

function handleDrop(event) {
    print ("DROP!");
    accept(event);

    var mimedata = event.mimeData();
    var urls = mimedata.urls();
    for (u = 0; u < urls.length; u++ ) {
	if (checkSuffix(urls[u])) {
	    //FIXME!!!!!!1!
	    print(urls[u]+"");
	    var filename = ("" + urls[u]).split('///')[1];
	    var file = new QFile(filename);
	    file.open(QIODevice.ReadOnly);
	    var streamer = new QTextStream(file);
	    slides = [];
	    while (true) {
		var line = streamer.readLine();
		if (!line) {
		    break;
		}
		slides.push(line)
	    }
    	    print(slides);
	    createCanvas(filename, slides);
	}
    }
}

function createCanvas(filename, slides) {
    entity = scene.CreateEntityRaw(scene.NextFreeId(), ['EC_Placeable', 'EC_Mesh', 'EC_3DCanvasSource', 'EC_Name', 'EC_DynamicComponent']);

    // set name
    entity.name.name = "Slideshow: " + filename;
    entity.name.description = "Simple slideshow app from " + filename;

    // set mesh
    var mesh_ref = entity.mesh.meshRef;
    mesh_ref.ref = 'local://screen.mesh';
    entity.mesh.meshRef = mesh_ref;

    // set source to first slide
    canvassource = entity.GetComponentRaw('EC_3DCanvasSource')
    canvassource.show2d = false;
    canvassource.source = slides[0];
    canvassource.submesh = 1;

    // start canvas
    var canvas = entity.GetComponentRaw('EC_3DCanvas');
    frame.DelayedExecute(0.1).Triggered.connect(this, function () {
	canvas.Start();
    });

    // Make dynamic component of the slide stuff

    var dyn = entity.dynamiccomponent;

    dyn.Name ="Slidelist";

    for (s = 0; s < slides.length; s++) {
	var slidename = s;
	var attr = dyn.CreateAttribute("string", slidename);
	dyn.SetAttribute(slidename, slides[s] + "");

    }
    dyn.CreateAttribute("int", "Current");
    dyn.SetAttribute("Current", 0);

    dyn.OnAttributeChanged.connect(onSlideChanged);

    //FIXME not needed in final product :) Just here to make it show
    //right away...

    var transform = entity.placeable.transform
    var pos = new Vector3df();
    pos.y = 20;
    transform.pos = pos;
    var rot = new Vector3df();
    rot.y = 180;
    rot.x = 180;
    transform.rot = rot;
    entity.placeable.transform = transform;

    // Now we are done
    scene.EmitEntityCreatedRaw(entity);

    entity.Action("MousePress").Triggered.connect(nextSlide);

}

function nextSlide() {
    print("Next slide!");
    changeSlide(1);
}

function prevSlide() {
    print("Previous slide!");
    changeSlide(-1);
}

function changeSlide(dir) {
    print("Changing slide!");
    var dyn = entity.GetComponentRaw("EC_DynamicComponent", "Slidelist");
    var slide_index = dyn.GetAttribute("Current") + dir;

    if (slide_index >= slides.length) {
	slide_index = 0;
    }

    if (slide_index < 0) {
	slide_index = slides.length - 1;
    }

    dyn.SetAttribute("Current", slide_index);
}

function onSlideChanged(attribute,type) {
    var dyn = entity.GetComponentRaw("EC_DynamicComponent", "Slidelist");
    var index = dyn.GetAttribute('Current');
    canvassource.source = dyn.GetAttribute(index);
}

function MyLabel(parent) {
    QLabel.call(this, "", parent, 0);
}

MyLabel.prototype = new QLabel();

MyLabel.prototype.mousePressEvent = function (event) {
    event.accept();
    print('AAAAARGH');
}

function makeSlideWidget(slides) {
    var gfxscene = new QGraphicsScene();
    var view = new QGraphicsView(gfxscene);

    view.resize(110, 400);

    var slidethumbs = [];

    for (s = 0; s < slides.length; s++) {
	var label = new MyLabel(gfxscene);
	var pic = new QPixmap("C:\\Users\\playsign\\sand_d.jpg");
	label.setPixmap(pic.scaledToWidth(100));
	gfxscene.addWidget(label)
	label.move(0, 110 * s);

    }
    uiservice.AddWidgetToScene(view);
    view.show();

}

makeSlideWidget([1,2,3,4]);<|endoftext|>


<commit_before>(function($, window, document, undefined) {

    var pluginName = "jqueryVideoLightbox",
        defaults = {
            id: "y-dQw4w9WgXcQ",
            width: "640px",
            height: "390px",
            autoplay: 0,
            autohide: 2,
            controls: 1,
            iv_load_policy: 1,
            loop: 0,
            modestbranding: 0,
            playlist: "",
            related: 0,
            showinfo: 1,
            shart_time: 0,
            theme: "dark",
            color: "",
            byline: 1,
            portrait: 1,
            effectIn: "fadeIn",
            easeIn: 300,
            easeOut: 0
        };

    function JQVideoLightbox ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    JQVideoLightbox.prototype = {
        init: function () {

            $(this.element).on( "click", $.proxy(function(){
                $(this.player ( $(this).element, $(this).settings));
            },this));
        },

        player: function ( element, settings ) {
            var video_autohide, video_autoplay, video_byline, video_color, video_controls, video_height, video_id, video_iv_load_policy, video_loop, video_modestbranding, video_playlist, video_portrait, video_related, video_showinfo, video_start_time, video_theme, video_vendor, video_width, vimeo_player, youtube_player;
            if ($(this.element).find(".video-frame").is(':visible')) {
                $(this.element).find(".video").remove();
                $(this.element).find(".video-frame").hide(((this.settings).easeOut));
                return $(this).destroy;
            } else {
                video_vendor = $(this.element).data("videoId").split("-")[0] || (this.settings).id.split("-")[0];
                video_id = $(this.element).data("videoId").split("-")[1] || (this.settings).id.split("-")[1]; // Youtube: "y-XbTtgr8J8uU" Vimeo: "v-32187194"
                video_width = $(this.element).data("videoWidth") || (this.settings).width; // Y&V: video width in px
                video_height = $(this.element).data("videoHeight") || (this.settings).height; // Y&V: video height in px
                video_autoplay = $(this.element).data("videoAutoplay") || (this.settings).autoplay; // Y&V: start playback immediately (0,1)
                video_autohide = $(this.element).data("videoAutohide") || (this.settings).autohide; // Y: auto hide controls after video load (0,1,2)
                video_controls = $(this.element).data("videoControls") || (this.settings).controls; // Y: display controls (0,1,2)
                video_iv_load_policy = $(this.element).data("videoIvLoadPolicy") || (this.settings).iv_load_policy; // Y: display annotations (1,3)
                video_loop = $(this.element).data("videoLoop") || (this.settings).loop; // Y&V: loop video playback (0,1)
                video_modestbranding = $(this.element).data("videoModestbranding") || (this.settings).modestbranding; // Y: hide large Youtube logo (0,1)
                video_playlist = $(this.element).data("videoPlaylist") || (this.settings).playlist; // Y: comma-separated list of video IDs to play
                video_related = $(this.element).data("videoRelated") || (this.settings).related; // Y: show related videos when playback id finished (0,1)
                video_showinfo = $(this.element).data("videoShowinfo") || (this.settings).showinfo; // Y: display title, uploader (0,1)  V: display title (0,1)
                video_start_time = $(this.element).data("videoStartTime") || (this.settings).start_time; // Y: playback start position in seconds (ex. "132" starts at 2mins, 12secs)
                video_theme = $(this.element).data("videoTheme") || (this.settings).theme; // Y: player theme ("dark","light")
                video_color = $(this.element).data("videoColor") || (this.settings).color; // Y: player controls color ("red","white") V: player controls color (hex code minus the "#", default is "00adef")
                video_byline = $(this.element).data("videoByline") || (this.settings).byline; // V: display byline (0,1)
                video_portrait = $(this.element).data("videoPortrait") || (this.settings).portrait; // V: display user's portrait (0,1)
                youtube_player = $("<embed src=\"https://www.youtube.com/embed/" + video_id + "?autoplay=" + video_autoplay + "&autohide=" + video_autohide + "&controls=" + video_controls + "&iv_load_policy=" + video_iv_load_policy + "&loop=" + video_loop + "&modestbranding=" + video_modestbranding + "&playlist=" + video_playlist + "&rel=" + video_related + "&showinfo=" + video_showinfo + "&start=" + video_start_time + "&theme=" + video_theme + "&color=" + video_color + "\" width=\"" + video_width + "\" height=\"" + video_height + "\" frameborder=\"0\" allowfullscreen></embed>");
                vimeo_player = $("");
                $(this.element).append('
' + '
' + '
' + '
' + '
' + '
');
                $(this.element).find(".video-frame").fadeIn(((this.settings).easeIn));
                if ((video_vendor === "v") || (video_vendor === "V")) {
                    return $(this.element).find(".video").html(vimeo_player);
                } else {
                    return $(this.element).find(".video").html(youtube_player);
                }
            }
        },

        destroy: function () {
            $(this).off();
            $(this).removeData();
        }
    };

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new JQVideoLightbox( this, options ) );
            }
        });
    };

    return this;

})( jQuery, window, document );
<commit_msg>fixed type in option name<commit_after>(function($, window, document, undefined) {

    var pluginName = "jqueryVideoLightbox",
        defaults = {
            id: "y-dQw4w9WgXcQ",
            width: "640px",
            height: "390px",
            autoplay: 0,
            autohide: 2,
            controls: 1,
            iv_load_policy: 1,
            loop: 0,
            modestbranding: 0,
            playlist: "",
            related: 0,
            showinfo: 1,
            start_time: 0,
            theme: "dark",
            color: "",
            byline: 1,
            portrait: 1,
            effectIn: "fadeIn",
            easeIn: 300,
            easeOut: 0
        };

    function JQVideoLightbox ( element, options ) {
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    JQVideoLightbox.prototype = {
        init: function () {

            $(this.element).on( "click", $.proxy(function(){
                $(this.player ( $(this).element, $(this).settings));
            },this));
        },

        player: function ( element, settings ) {
            var video_autohide, video_autoplay, video_byline, video_color, video_controls, video_height, video_id, video_iv_load_policy, video_loop, video_modestbranding, video_playlist, video_portrait, video_related, video_showinfo, video_start_time, video_theme, video_vendor, video_width, vimeo_player, youtube_player;
            if ($(this.element).find(".video-frame").is(':visible')) {
                $(this.element).find(".video").remove();
                $(this.element).find(".video-frame").hide(((this.settings).easeOut));
                return $(this).destroy;
            } else {
                video_vendor = $(this.element).data("videoId").split("-")[0] || (this.settings).id.split("-")[0];
                video_id = $(this.element).data("videoId").split("-")[1] || (this.settings).id.split("-")[1]; // Youtube: "y-XbTtgr8J8uU" Vimeo: "v-32187194"
                video_width = $(this.element).data("videoWidth") || (this.settings).width; // Y&V: video width in px
                video_height = $(this.element).data("videoHeight") || (this.settings).height; // Y&V: video height in px
                video_autoplay = $(this.element).data("videoAutoplay") || (this.settings).autoplay; // Y&V: start playback immediately (0,1)
                video_autohide = $(this.element).data("videoAutohide") || (this.settings).autohide; // Y: auto hide controls after video load (0,1,2)
                video_controls = $(this.element).data("videoControls") || (this.settings).controls; // Y: display controls (0,1,2)
                video_iv_load_policy = $(this.element).data("videoIvLoadPolicy") || (this.settings).iv_load_policy; // Y: display annotations (1,3)
                video_loop = $(this.element).data("videoLoop") || (this.settings).loop; // Y&V: loop video playback (0,1)
                video_modestbranding = $(this.element).data("videoModestbranding") || (this.settings).modestbranding; // Y: hide large Youtube logo (0,1)
                video_playlist = $(this.element).data("videoPlaylist") || (this.settings).playlist; // Y: comma-separated list of video IDs to play
                video_related = $(this.element).data("videoRelated") || (this.settings).related; // Y: show related videos when playback id finished (0,1)
                video_showinfo = $(this.element).data("videoShowinfo") || (this.settings).showinfo; // Y: display title, uploader (0,1)  V: display title (0,1)
                video_start_time = $(this.element).data("videoStartTime") || (this.settings).start_time; // Y: playback start position in seconds (ex. "132" starts at 2mins, 12secs)
                video_theme = $(this.element).data("videoTheme") || (this.settings).theme; // Y: player theme ("dark","light")
                video_color = $(this.element).data("videoColor") || (this.settings).color; // Y: player controls color ("red","white") V: player controls color (hex code minus the "#", default is "00adef")
                video_byline = $(this.element).data("videoByline") || (this.settings).byline; // V: display byline (0,1)
                video_portrait = $(this.element).data("videoPortrait") || (this.settings).portrait; // V: display user's portrait (0,1)
                youtube_player = $("<embed src=\"https://www.youtube.com/embed/" + video_id + "?autoplay=" + video_autoplay + "&autohide=" + video_autohide + "&controls=" + video_controls + "&iv_load_policy=" + video_iv_load_policy + "&loop=" + video_loop + "&modestbranding=" + video_modestbranding + "&playlist=" + video_playlist + "&rel=" + video_related + "&showinfo=" + video_showinfo + "&start=" + video_start_time + "&theme=" + video_theme + "&color=" + video_color + "\" width=\"" + video_width + "\" height=\"" + video_height + "\" frameborder=\"0\" allowfullscreen></embed>");
                vimeo_player = $("");
                $(this.element).append('
' + '
' + '
' + '
' + '
' + '
');
                $(this.element).find(".video-frame").fadeIn(((this.settings).easeIn));
                if ((video_vendor === "v") || (video_vendor === "V")) {
                    return $(this.element).find(".video").html(vimeo_player);
                } else {
                    return $(this.element).find(".video").html(youtube_player);
                }
            }
        },

        destroy: function () {
            $(this).off();
            $(this).removeData();
        }
    };

    $.fn[ pluginName ] = function ( options ) {
        return this.each(function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName, new JQVideoLightbox( this, options ) );
            }
        });
    };

    return this;

})( jQuery, window, document );
<|endoftext|>


<commit_before>(function( $ ){

  $.fn.canvasAreaDraw = function(options) {

    this.each(function(index, element) {
      init.apply(element, [index, element, options]);
    });

  }

  var init = function(index, input, options) {

    var points, activePoint, settings;
    var $reset, $canvas, ctx, image;
    var draw, mousedown, stopdrag, move, resize, reset, rightclick, record;

    settings = $.extend({
      imageUrl: $(this).attr('data-image-url')
    }, options);

    if ( $(this).val().length ) {
      points = $(this).val().split(',').map(function(point) {
        return parseInt(point, 10);
      });
    } else {
      points = [];
    }

    $reset = $('<button type="button" class="btn">Clear</button>');
    $canvas = $('<canvas>');
    ctx = $canvas[0].getContext('2d');

    image = new Image();
    resize = function() {
      $canvas.attr('height', image.height).attr('width', image.width);
      draw();
    };
    $(image).load(resize);
    image.src = settings.imageUrl;
    if (image.loaded) resize();
    $canvas.css({background: 'url('+image.src+')'});

    $(document).ready( function() {
      $(input).after('
', $canvas, '
', $reset);
      $reset.click(reset);
      $canvas.bind('mousedown', mousedown);
      $canvas.bind('contextmenu', rightclick);
      $canvas.bind('mouseup', stopdrag);
    });

    reset = function() {
      points = [];
      draw();
    };

    move = function(e) {
      if(!e.offsetX) {
        e.offsetX = (e.pageX - $(e.target).offset().left);
        e.offsetY = (e.pageY - $(e.target).offset().top);
      }
      points[activePoint] = Math.round(e.offsetX);
      points[activePoint+1] = Math.round(e.offsetY);
      draw();
    };

    stopdrag = function() {
      $(this).unbind('mousemove');
      record();
      activePoint = null;
    };

    rightclick = function(e) {
      e.preventDefault();
      if(!e.offsetX) {
        e.offsetX = (e.pageX - $(e.target).offset().left);
        e.offsetY = (e.pageY - $(e.target).offset().top);
      }
      var x = e.offsetX, y = e.offsetY;
      for (var i = 0; i < points.length; i+=2) {
        dis = Math.sqrt(Math.pow(x - points[i], 2) + Math.pow(y - points[i+1], 2));
        if ( dis < 6 ) {
          points.splice(i, 2);
          draw();
          record();
          return false;
        }
      }
      return false;
    };

    mousedown = function(e) {
      var x, y, dis, lineDis, insertAt = points.length;

      if (e.which === 3) {
        return false;
      }

      e.preventDefault();
      if(!e.offsetX) {
        e.offsetX = (e.pageX - $(e.target).offset().left);
        e.offsetY = (e.pageY - $(e.target).offset().top);
      }
      x = e.offsetX; y = e.offsetY;

      for (var i = 0; i < points.length; i+=2) {
        dis = Math.sqrt(Math.pow(x - points[i], 2) + Math.pow(y - points[i+1], 2));
        if ( dis < 6 ) {
          activePoint = i;
          $(this).bind('mousemove', move);
          return false;
        }
      }

      for (var i = 0; i < points.length; i+=2) {
        if (i > 1) {
          lineDis = dotLineLength(
            x, y,
            points[i], points[i+1],
            points[i-2], points[i-1],
            true
          );
          if (lineDis < 6) {
            insertAt = i;
          }
        }
      }
      console.log(points);

      points.splice(insertAt, 0, Math.round(x), Math.round(y));
      activePoint = insertAt;
      $(this).bind('mousemove', move);

      draw();
      record();

      return false;
    };

    draw = function() {
      ctx.canvas.width = ctx.canvas.width;

      if (points.length < 2) {
        return false;
      }
      ctx.globalCompositeOperation = 'destination-over';
      ctx.fillStyle = 'rgb(255,255,255)'
      ctx.strokeStyle = 'rgb(255,20,20)';
      ctx.lineWidth = 1;

      ctx.beginPath();
      ctx.moveTo(points[0], points[1]);
      for (var i = 0; i < points.length; i+=2) {
        ctx.fillRect(points[i]-2, points[i+1]-2, 4, 4);
        ctx.strokeRect(points[i]-2, points[i+1]-2, 4, 4);
        if (points.length > 2 && i > 1) {
          ctx.lineTo(points[i], points[i+1]);
        }
      }
      ctx.closePath();
      ctx.fillStyle = 'rgba(255,0,0,0.3)';
      ctx.fill();
      ctx.stroke();

      record();
    };

    record = function() {
      $(input).val(points.join(','));
    };

  };

  $(document).ready(function() {
    $('.canvas-area[data-image-url]').canvasAreaDraw();
  });

  var dotLineLength = function(x, y, x0, y0, x1, y1, o) {
    function lineLength(x, y, x0, y0){
      return Math.sqrt((x -= x0) * x + (y -= y0) * y);
    }
    if(o && !(o = function(x, y, x0, y0, x1, y1){
      if(!(x1 - x0)) return {x: x0, y: y};
      else if(!(y1 - y0)) return {x: x, y: y0};
      var left, tg = -1 / ((y1 - y0) / (x1 - x0));
      return {x: left = (x1 * (x * tg - y + y0) + x0 * (x * - tg + y - y1)) / (tg * (x1 - x0) + y0 - y1), y: tg * left - tg * x + y};
    }(x, y, x0, y0, x1, y1), o.x >= Math.min(x0, x1) && o.x <= Math.max(x0, x1) && o.y >= Math.min(y0, y1) && o.y <= Math.max(y0, y1))){
      var l1 = lineLength(x, y, x0, y0), l2 = lineLength(x, y, x1, y1);
      return l1 > l2 ? l2 : l1;
    }
    else {
      var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
      return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
    }
  };
})( jQuery );
<commit_msg>Removed console.log<commit_after>(function( $ ){

  $.fn.canvasAreaDraw = function(options) {

    this.each(function(index, element) {
      init.apply(element, [index, element, options]);
    });

  }

  var init = function(index, input, options) {

    var points, activePoint, settings;
    var $reset, $canvas, ctx, image;
    var draw, mousedown, stopdrag, move, resize, reset, rightclick, record;

    settings = $.extend({
      imageUrl: $(this).attr('data-image-url')
    }, options);

    if ( $(this).val().length ) {
      points = $(this).val().split(',').map(function(point) {
        return parseInt(point, 10);
      });
    } else {
      points = [];
    }

    $reset = $('<button type="button" class="btn">Clear</button>');
    $canvas = $('<canvas>');
    ctx = $canvas[0].getContext('2d');

    image = new Image();
    resize = function() {
      $canvas.attr('height', image.height).attr('width', image.width);
      draw();
    };
    $(image).load(resize);
    image.src = settings.imageUrl;
    if (image.loaded) resize();
    $canvas.css({background: 'url('+image.src+')'});

    $(document).ready( function() {
      $(input).after('
', $canvas, '
', $reset);
      $reset.click(reset);
      $canvas.bind('mousedown', mousedown);
      $canvas.bind('contextmenu', rightclick);
      $canvas.bind('mouseup', stopdrag);
    });

    reset = function() {
      points = [];
      draw();
    };

    move = function(e) {
      if(!e.offsetX) {
        e.offsetX = (e.pageX - $(e.target).offset().left);
        e.offsetY = (e.pageY - $(e.target).offset().top);
      }
      points[activePoint] = Math.round(e.offsetX);
      points[activePoint+1] = Math.round(e.offsetY);
      draw();
    };

    stopdrag = function() {
      $(this).unbind('mousemove');
      record();
      activePoint = null;
    };

    rightclick = function(e) {
      e.preventDefault();
      if(!e.offsetX) {
        e.offsetX = (e.pageX - $(e.target).offset().left);
        e.offsetY = (e.pageY - $(e.target).offset().top);
      }
      var x = e.offsetX, y = e.offsetY;
      for (var i = 0; i < points.length; i+=2) {
        dis = Math.sqrt(Math.pow(x - points[i], 2) + Math.pow(y - points[i+1], 2));
        if ( dis < 6 ) {
          points.splice(i, 2);
          draw();
          record();
          return false;
        }
      }
      return false;
    };

    mousedown = function(e) {
      var x, y, dis, lineDis, insertAt = points.length;

      if (e.which === 3) {
        return false;
      }

      e.preventDefault();
      if(!e.offsetX) {
        e.offsetX = (e.pageX - $(e.target).offset().left);
        e.offsetY = (e.pageY - $(e.target).offset().top);
      }
      x = e.offsetX; y = e.offsetY;

      for (var i = 0; i < points.length; i+=2) {
        dis = Math.sqrt(Math.pow(x - points[i], 2) + Math.pow(y - points[i+1], 2));
        if ( dis < 6 ) {
          activePoint = i;
          $(this).bind('mousemove', move);
          return false;
        }
      }

      for (var i = 0; i < points.length; i+=2) {
        if (i > 1) {
          lineDis = dotLineLength(
            x, y,
            points[i], points[i+1],
            points[i-2], points[i-1],
            true
          );
          if (lineDis < 6) {
            insertAt = i;
          }
        }
      }

      points.splice(insertAt, 0, Math.round(x), Math.round(y));
      activePoint = insertAt;
      $(this).bind('mousemove', move);

      draw();
      record();

      return false;
    };

    draw = function() {
      ctx.canvas.width = ctx.canvas.width;

      if (points.length < 2) {
        return false;
      }
      ctx.globalCompositeOperation = 'destination-over';
      ctx.fillStyle = 'rgb(255,255,255)'
      ctx.strokeStyle = 'rgb(255,20,20)';
      ctx.lineWidth = 1;

      ctx.beginPath();
      ctx.moveTo(points[0], points[1]);
      for (var i = 0; i < points.length; i+=2) {
        ctx.fillRect(points[i]-2, points[i+1]-2, 4, 4);
        ctx.strokeRect(points[i]-2, points[i+1]-2, 4, 4);
        if (points.length > 2 && i > 1) {
          ctx.lineTo(points[i], points[i+1]);
        }
      }
      ctx.closePath();
      ctx.fillStyle = 'rgba(255,0,0,0.3)';
      ctx.fill();
      ctx.stroke();

      record();
    };

    record = function() {
      $(input).val(points.join(','));
    };

  };

  $(document).ready(function() {
    $('.canvas-area[data-image-url]').canvasAreaDraw();
  });

  var dotLineLength = function(x, y, x0, y0, x1, y1, o) {
    function lineLength(x, y, x0, y0){
      return Math.sqrt((x -= x0) * x + (y -= y0) * y);
    }
    if(o && !(o = function(x, y, x0, y0, x1, y1){
      if(!(x1 - x0)) return {x: x0, y: y};
      else if(!(y1 - y0)) return {x: x, y: y0};
      var left, tg = -1 / ((y1 - y0) / (x1 - x0));
      return {x: left = (x1 * (x * tg - y + y0) + x0 * (x * - tg + y - y1)) / (tg * (x1 - x0) + y0 - y1), y: tg * left - tg * x + y};
    }(x, y, x0, y0, x1, y1), o.x >= Math.min(x0, x1) && o.x <= Math.max(x0, x1) && o.y >= Math.min(y0, y1) && o.y <= Math.max(y0, y1))){
      var l1 = lineLength(x, y, x0, y0), l2 = lineLength(x, y, x1, y1);
      return l1 > l2 ? l2 : l1;
    }
    else {
      var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
      return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
    }
  };
})( jQuery );
<|endoftext|>


<commit_before>/**
 * Quick Money Edit - jQuery Input Box Currency Formatting
 *
 * @copyright  Copyright 2013-2014, Website Duck LLC (http://www.websiteduck.com)
 * @link       https://github.com/websiteduck/jquery-quickMoneyEdit
 * @license    MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
(function($) {

    $.fn.quickMoneyEdit = function(options) {

		if (typeof options === 'undefined' || typeof options === 'object') {

			var origGetHook;
			var origSetHook;

			if ($.valHooks.text) {
				if ($.valHooks.text.get) origGetHook = $.valHooks.text.get;
				if ($.valHooks.text.set) origSetHook = $.valHooks.text.set;
			}
			else $.valHooks.text = {};

			$.valHooks.text.get = function(el) {
				if (!$(el).attr('data-quickMoneyEdit')) {
					if (origGetHook) return origGetHook(el);
					else return undefined;
				}
				return $.fn.quickMoneyEdit.unformatCurrency(el.value);
			};

			$.valHooks.text.set = function(el, value) {
				if (!$(el).attr('data-quickMoneyEdit')) {
					if (origGetHook) origSetHook(el);
				}
				el.value = $.fn.quickMoneyEdit.formatCurrency(value);
			};

			return this.filter('input').each(function() {
				$(this).attr('data-quickMoneyEdit', '1');
				this.value = $.fn.quickMoneyEdit.formatCurrency(this.value);
				$(this).focus(function() {
					this.value = $.fn.quickMoneyEdit.unformatCurrency(this.value);
				}).blur(function() {
					this.value = $.fn.quickMoneyEdit.formatCurrency(this.value);
				});
			});

		}
		else if (typeof options === 'string' && options === 'formatted') {
			return $.fn.quickMoneyEdit.formatCurrency(this.get(0).value);
		}

    };

 	$.fn.quickMoneyEdit.unformatCurrency = function(result) {
		return result.replace(/[^-0-9\.]/g, '');
	};

	$.fn.quickMoneyEdit.formatCurrency = function(result) {
		result = result.replace(/[^-0-9\.]/g, '');
		result = parseFloat(result);
		if (isNaN(result)) return '$0.00';
		var sign = result < 0 ? '-' : '';
		result = Math.abs(result);
		var integer = parseInt(result) + '';
		var firstComma = integer.length > 3 ? integer.length % 3 : 0;
		result = result.toFixed(2);
		return sign + '$' + (firstComma ? integer.substr(0, firstComma) + ',' : '') + integer.substr(firstComma).replace(/(\d{3})(?=\d)/g, '$1' + ',') + '.' + result.slice(-2);
	};

}(jQuery));<commit_msg>Fix text set valHook<commit_after>/**
 * Quick Money Edit - jQuery Input Box Currency Formatting
 *
 * @copyright  Copyright 2013-2014, Website Duck LLC (http://www.websiteduck.com)
 * @link       https://github.com/websiteduck/jquery-quickMoneyEdit
 * @license    MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
(function($) {

    $.fn.quickMoneyEdit = function(options) {

		if (typeof options === 'undefined' || typeof options === 'object') {

			var origGetHook;
			var origSetHook;

			if ($.valHooks.text) {
				if ($.valHooks.text.get) origGetHook = $.valHooks.text.get;
				if ($.valHooks.text.set) origSetHook = $.valHooks.text.set;
			}
			else $.valHooks.text = {};

			$.valHooks.text.get = function(el) {
				if (!$(el).attr('data-quickMoneyEdit')) {
					if (origGetHook) return origGetHook(el);
					else return undefined;
				}
				return $.fn.quickMoneyEdit.unformatCurrency(el.value);
			};

			$.valHooks.text.set = function(el, value) {
				if (!$(el).attr('data-quickMoneyEdit')) {
					if (origGetHook) return origSetHook(el);
					else return undefined;
				}
				el.value = $.fn.quickMoneyEdit.formatCurrency(value);
			};

			return this.filter('input').each(function() {
				$(this).attr('data-quickMoneyEdit', '1');
				this.value = $.fn.quickMoneyEdit.formatCurrency(this.value);
				$(this).focus(function() {
					this.value = $.fn.quickMoneyEdit.unformatCurrency(this.value);
				}).blur(function() {
					this.value = $.fn.quickMoneyEdit.formatCurrency(this.value);
				});
			});

		}
		else if (typeof options === 'string' && options === 'formatted') {
			return $.fn.quickMoneyEdit.formatCurrency(this.get(0).value);
		}

    };

 	$.fn.quickMoneyEdit.unformatCurrency = function(result) {
		return result.replace(/[^-0-9\.]/g, '');
	};

	$.fn.quickMoneyEdit.formatCurrency = function(result) {
		result = result.replace(/[^-0-9\.]/g, '');
		result = parseFloat(result);
		if (isNaN(result)) return '$0.00';
		var sign = result < 0 ? '-' : '';
		result = Math.abs(result);
		var integer = parseInt(result) + '';
		var firstComma = integer.length > 3 ? integer.length % 3 : 0;
		result = result.toFixed(2);
		return sign + '$' + (firstComma ? integer.substr(0, firstComma) + ',' : '') + integer.substr(firstComma).replace(/(\d{3})(?=\d)/g, '$1' + ',') + '.' + result.slice(-2);
	};

}(jQuery));<|endoftext|>


<commit_before>(function($){
  $.fn.serializeHash = function() {
    var hash = {};
    /***
     JQuery plugin that returns a hash from serialization of any form or dom element. It supports brakets on input names.
     It is convenient if you want to get values from a form and merge it with an other hash for example.

     ** Added by rilinor on 29/05/2012 : jquery serialize hash now support serialization of any dom elements (before, only form were supported). Thanks !

     Example:
     ---------- HTML ----------
     <form id="form">
       <input type="hidden" name="firstkey" value="val1" />
       <input type="hidden" name="secondkey[0]" value="val2" />
       <input type="hidden" name="secondkey[1]" value="val3" />
       <input type="hidden" name="secondkey[key]" value="val4" />
     </form>
     ---------- JS ----------
     $('#form').serializeHash()
     should return :
     {
       firstkey: 'val1',
       secondkey: {
         0: 'val2',
         1: 'val3',
         key: 'val4'
       }
     }
     ***/
    function stringKey(key, value) {
      var beginBraket = key.lastIndexOf('[');
      if (beginBraket == -1) {
        var hash = {};
        hash[key] = value;
        return hash;
      }
      var newKey = key.substr(0, beginBraket);
      var newValue = {};
      newValue[key.substring(beginBraket + 1, key.length - 1)] = value;
      return stringKey(newKey, newValue);
    }

    var els = $(this).find(':input').get();
    $.each(els, function() {
        if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
            var val = $(this).val();
            $.extend(true, hash, stringKey(this.name, val));
        }
    });
    return hash;
  };
})(jQuery);<commit_msg>Adds support for new to HTML5 form input types.<commit_after>(function($){
  $.fn.serializeHash = function() {
    var hash = {};
    /***
     JQuery plugin that returns a hash from serialization of any form or dom element. It supports brakets on input names.
     It is convenient if you want to get values from a form and merge it with an other hash for example.

     ** Added by rilinor on 29/05/2012 : jquery serialize hash now support serialization of any dom elements (before, only form were supported). Thanks !

     Example:
     ---------- HTML ----------
     <form id="form">
       <input type="hidden" name="firstkey" value="val1" />
       <input type="hidden" name="secondkey[0]" value="val2" />
       <input type="hidden" name="secondkey[1]" value="val3" />
       <input type="hidden" name="secondkey[key]" value="val4" />
     </form>
     ---------- JS ----------
     $('#form').serializeHash()
     should return :
     {
       firstkey: 'val1',
       secondkey: {
         0: 'val2',
         1: 'val3',
         key: 'val4'
       }
     }
     ***/
    function stringKey(key, value) {
      var beginBraket = key.lastIndexOf('[');
      if (beginBraket == -1) {
        var hash = {};
        hash[key] = value;
        return hash;
      }
      var newKey = key.substr(0, beginBraket);
      var newValue = {};
      newValue[key.substring(beginBraket + 1, key.length - 1)] = value;
      return stringKey(newKey, newValue);
    }

    var els = $(this).find(':input').get();
    $.each(els, function() {
        if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /hidden|text|search|tel|url|email|password|datetime|date|month|week|time|datetime-local|number|range|color/i.test(this.type))) {
            var val = $(this).val();
            $.extend(true, hash, stringKey(this.name, val));
        }
    });
    return hash;
  };
})(jQuery);
<|endoftext|>


<commit_before>import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';

/**
 * Converts an itk.js image to a vtk.js image.
 *
 * Requires an itk.js image as input.
 */
function convertItkToVtkImage(itkImage) {
  // create VTK image data
  const imageData = vtkImageData.newInstance({
    origin: itkImage.origin.slice(),
    spacing: itkImage.spacing.slice(),
  });
  const scalars = vtkDataArray.newInstance({
    name: 'Scalars',
    values: itkImage.data,
    numberOfComponents: itkImage.imageType.components,
  });

  imageData.setDirection(itkImage.direction.data);
  imageData.setDimensions(...itkImage.size);
  imageData.getPointData().setScalars(scalars);

  return imageData;
}

export default {
  convertItkToVtkImage,
};
<commit_msg>fix(ITKHelper): Optionally give a name for image scalars<commit_after>import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';

/**
 * Converts an itk.js image to a vtk.js image.
 *
 * Requires an itk.js image as input.
 */
function convertItkToVtkImage(itkImage, options) {
  // create VTK image data
  const imageData = vtkImageData.newInstance({
    origin: itkImage.origin.slice(),
    spacing: itkImage.spacing.slice(),
  });
  const scalars = vtkDataArray.newInstance({
    name: options.scalarArrayName || 'Scalars',
    values: itkImage.data,
    numberOfComponents: itkImage.imageType.components,
  });

  imageData.setDirection(itkImage.direction.data);
  imageData.setDimensions(...itkImage.size);
  imageData.getPointData().setScalars(scalars);

  return imageData;
}

export default {
  convertItkToVtkImage,
};
<|endoftext|>


<commit_before>var imagemin = require("imagemin"),    // The imagemin module.
    webp = require("imagemin-webp");   // imagemin's WebP plugin.

(async () => {
  await imagemin(['./public/content/themes/gj-boilerplate/img/*.{jpg,png}'], {
    destination: './public/content/themes/gj-boilerplate/img/webp',
    plugins: [
      webp({
        quality: [80]
      })
    ]
  });
  console.log("Images converted!");
})();<commit_msg>code cleanup<commit_after>var imagemin = require("imagemin"),    // The imagemin module.
    webp = require("imagemin-webp");   // imagemin's WebP plugin.

(async () => {
  await imagemin(['./public/content/themes/gj-boilerplate/img/*.{jpg,png}'], {
    destination: './public/content/themes/gj-boilerplate/img/webp',
    plugins: [
      webp({
        quality: [80]
      })
    ]
  });
  console.log("Images converted!");
})();<|endoftext|>


<commit_before>/*!
 * Copyright 2017 Joji Doi, Greg Mendez-Weeks

 * Licensed under the MIT license
 */
var jsonResult;

var mq = window.matchMedia( "(min-width: 40em)" );
 var barContainer = document.getElementById("myScrollspy");
    var bar = document.getElementById("navBar");

function resizeContent(){

    if (mq.matches) {

        bar.className ="nav nav-pills nav-stacked ";
        barContainer.className = "col-sm-1 bg-faded sidebar";
      // window width is at least 40em

    } else {

       bar.className ="breadcrumb";
        barContainer.className = "col-sm-1 bg-faded breadcrumb-item";
      // window width is less than 40em
    }
}

function getMediaFilePath(mediaItem, dirName) {
  return "ext-content" + dirName + "/" + mediaItem.name;
}

function getExt(mediaItem) {
  var end = mediaItem.name.toString().toLowerCase();
  var ind = end.lastIndexOf(".");
  end = end.substring(ind);
  return end;
}

function renderPdf(mediaItem, dir) {
  // Note embed nor iframe works great to render pdf. So, this is workaround until better alternative is found.
  //window.location = getMediaFilePath(mediaItem, dir);
  $(".bubble-audio-title").text(mediaItem.name);
  $("#pdf_elm").empty(); // clear previous source element
  var pdf_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "application/pdf",
    "class": "txt",
  }).appendTo("#pdf_elm");
  $("#pdf_elm").load();
}

function renderText(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#pdf_elm").empty(); // clear previous source element
  var pdf_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "txt",
    "height": "50em",
    "width": "100%"
  }).appendTo("#pdf_elm");
  $("#pdf_elm").load();
}

function renderDoc(mediaItem) {
  var mediaType = getExt(mediaItem);
  switch (mediaType) {
    case ".pdf":
      renderPdf(mediaItem);
      break;
    case ".txt":
      renderText(mediaItem);
      break;
    default:
      console.log("Unsupported media type " + mediaType);
  }
}

function renderAudio(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#audio_elm").empty(); // clear previous source element
  var type = getExt(mediaItem).substring(1);
  var video_src = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "audio/" + type
  }).appendTo("#audio_elm");
  $("#audio_elm").load();
}

function renderVideo(mediaItem, dir) {
  var type = getExt(mediaItem).substring(1);
  $("#video_elm").empty(); // clear previous source element
  var sour = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "video/" + type,
  }).appendTo("#video_elm");
  $("#video_elm").load();
}

function renderPhoto(mediaItem, dir) {
  $("#img_elm").empty(); // clear previous source element
  var video_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "modal-content"
  }).appendTo("#img_elm");
  $("#img_elm").load();
}
//
// Photo viewer is still under construction.
//
function renderPhotoOld(mediaItem) {
  webix.ui({
    view: "window",
    id: "image_window",
    fullscreen: true,
    head: {
      view: "toolbar",
      margin: -10,
      cols: [{
        view: "label",
        label: "~~ Images Beta ~~"
      }, {
        view: "icon",
        icon: "times-circle",
        click: function() {
          $$('image_window').close();
        }
      }]
    },
    body: {
      view: "carousel",
      id: "bubble_carousel",
      fullscreen: true,
      cols: getImageFilePathsFromCache()
    }
  });
  $$("bubble_carousel").setActive(mediaItem.id);
  $$("image_window").show();
}
/*
 * Retrieve cached image file path data.
 * See cacheImageFilePaths(media_file_list) function for cache creation.
 */
function getImageFilePathsFromCache() {
  return $("body").data("image file list");
}
/*
 * Save image file paths data in cache for later reuse via getImageFilePathsFromCache() function.
 */
function cacheImageFilePaths(media_file_list) {
  function img(obj) {
    return '
' + obj.name + '
';
  }
  console.log("This should be called only once.");
  var imageFilePaths = [];
  media_file_list.forEach(function(media_file) {
    if (media_file.type.toString().toLowerCase() == "photos") {
      imageFilePaths.push({
        id: media_file.id,
        css: "image",
        template: img,
        data: webix.copy({
          src: getMediaFilePath(media_file),
          title: media_file.name
        })
      });
    }
  });
  $("body").data("image file list", imageFilePaths);
}
var folderStack = [];

function renderMediaDynamic(mediaItem, title) {
  if (mediaItem.type == "directory") {
    var opened = false;
    var pos;
    var elementIcon;
    var element;
    var len = folderStack.length;
    elementIcon = document.getElementById(mediaItem.name + "Icon");
    for (var i = 0; i < folderStack.length; i++) {
      if (elementIcon.parentElement.parentElement.id + "/" + mediaItem.name == folderStack[i]) {
        opened = true;
        pos = i;
      }
    }
    if (opened) {
      for (var i = pos; i < len; i++) {
        element = document.getElementById(folderStack[i]);
        element.outerHTML = "";
        delete element;
        var elephant = document.getElementById(folderStack[i] + "bar");
        elephant.outerHTML = "";
        delete elephant;
        elementIcon.src = "img/folder.png";
      }
      for (var i = pos; i < len; i++) {
        folderStack.pop();
      }
    } else {
      elementIcon.src = "img/openFolder.png";
      folderStack.push(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      addNavBar(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      getFilesInDir(mediaItem.contents, elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
    }
  } else {
    switch (getExt(mediaItem)) {
      case ".ogg":
      case ".mp3":
        renderAudio(mediaItem, title);
        break;
      case ".pdf":
        renderPdf(mediaItem, title);
        break;
      case ".webm":
      case ".mp4":
        renderVideo(mediaItem, title);
        break;
      case ".png":
      case ".jpg":
        renderPhoto(mediaItem, title);
        break;
      case ".txt":
        renderText(mediaItem, title);
        mediaSrc = "img/textFile.png";
        break;
        //case "tv":
        // break;
      default:
        mediaSrc = "img/unreadable.png";
        break;
    }
  }
}

function getCurrentDir(title) {
  return title.substring(title.lastIndexOf("/") + 1);
}

function addNavBar(name) {
  var nam = name + "bar";
  var nav = $("

", {
    "class": "",
    "id": nam
  });
  var txt = $("", {
    "href": "#" + name
  });
  txt.html(getCurrentDir(name));
  nav.append(txt);
  nav.appendTo("#navBar");
}

function getFilesInDir(dir, title) {
  var mediaDirs = jsonResult;
  var currentDir = getCurrentDir(title);
  var directory = $("

", {
    "id": title,
  });
  directory.appendTo("#files_list");
  var name = $("
" + currentDir + "
", {});
  name.appendTo(directory);
  $.each(dir, function(i, mediaItem) {
    var mediaSrc = getMediaFilePath(mediaItem, title);
    var divType = "img";
    var modalType = "";
    if (mediaItem.type == "directory") {
      mediaSrc = "img/folder.png";
    } else {
      switch (getExt(mediaItem)) {
        //   case "document":
        //  mediaSrc = mediaItem;
        //break;
        case ".ogg":
        case ".mp3":
          mediaSrc = "img/musicFile.png";
          modalType = "audio";
          break;
        case ".pdf":
          mediaSrc = "img/pdfFile.png";
          modalType = "pdf";
          break;
        case ".webm":
        case ".mp4":
          modalType = "video";
          divType = "video";
          break;
        case ".png":
        case ".jpg":
          modalType = "img";
          break;
        case ".txt":
          mediaSrc = "img/textFile.png";
          modalType = "pdf";
          break;
          //case "tv":
          // break;
        default:
          mediaSrc = "img/unreadable.png";
          break;
      }
    }
    var img = $("

", {
      "class": "thumbContainer"
    });
    var image = $("<" + divType + "></" + divType + ">", {
      "id": mediaItem.name + "Icon",
      "class": "bubble_thumb",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem,
      "src": mediaSrc
    });
    var lnk = $("", {
      "class": "fileName",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem
    });
    lnk.html(mediaItem.name);
    lnk.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    image.html(mediaItem.name);
    image.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    img.append(image);
    img.append(lnk);
    img.appendTo(directory);
  });
}
$.getJSON("data/media_files_list_v3.json", function(result) {
  jsonResult = result;
  addNavBar("")
  getFilesInDir(result, "");
}); // end of getJSON()
$("#audio_modal").on("hide.bs.modal", function(e) {
  $("#audio_elm")[0].pause();
});
$("#video_modal").on("hide.bs.modal", function(e) {
  $("#video_elm")[0].pause();
});
<commit_msg>Formated js and added format instruction<commit_after>/*!
 * Copyright 2017 Joji Doi, Greg Mendez-Weeks
 * Licensed under the MIT license
 *
 * Format: http://jsbeautifier.org/
 * - with Indent with 2 spaces
 * - Remove all extra newlines
 * - Wrap lines near 110 characters
 * - Braces with control statement
 * - Add one indent level
 */
var jsonResult;
var mq = window.matchMedia("(min-width: 40em)");
var barContainer = document.getElementById("myScrollspy");
var bar = document.getElementById("navBar");

function resizeContent() {
  if (mq.matches) {
    bar.className = "nav nav-pills nav-stacked ";
    barContainer.className = "col-sm-1 bg-faded sidebar";
    // window width is at least 40em
  } else {
    bar.className = "breadcrumb";
    barContainer.className = "col-sm-1 bg-faded breadcrumb-item";
    // window width is less than 40em
  }
}

function getMediaFilePath(mediaItem, dirName) {
  return "ext-content" + dirName + "/" + mediaItem.name;
}

function getExt(mediaItem) {
  var end = mediaItem.name.toString().toLowerCase();
  var ind = end.lastIndexOf(".");
  end = end.substring(ind);
  return end;
}

function renderPdf(mediaItem, dir) {
  // Note embed nor iframe works great to render pdf. So, this is workaround until better alternative is found.
  //window.location = getMediaFilePath(mediaItem, dir);
  $(".bubble-audio-title").text(mediaItem.name);
  $("#pdf_elm").empty(); // clear previous source element
  var pdf_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "application/pdf",
    "class": "txt",
  }).appendTo("#pdf_elm");
  $("#pdf_elm").load();
}

function renderText(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#pdf_elm").empty(); // clear previous source element
  var pdf_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "txt",
    "height": "50em",
    "width": "100%"
  }).appendTo("#pdf_elm");
  $("#pdf_elm").load();
}

function renderDoc(mediaItem) {
  var mediaType = getExt(mediaItem);
  switch (mediaType) {
    case ".pdf":
      renderPdf(mediaItem);
      break;
    case ".txt":
      renderText(mediaItem);
      break;
    default:
      console.log("Unsupported media type " + mediaType);
  }
}

function renderAudio(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#audio_elm").empty(); // clear previous source element
  var type = getExt(mediaItem).substring(1);
  var video_src = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "audio/" + type
  }).appendTo("#audio_elm");
  $("#audio_elm").load();
}

function renderVideo(mediaItem, dir) {
  var type = getExt(mediaItem).substring(1);
  $("#video_elm").empty(); // clear previous source element
  var sour = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "video/" + type,
  }).appendTo("#video_elm");
  $("#video_elm").load();
}

function renderPhoto(mediaItem, dir) {
  $("#img_elm").empty(); // clear previous source element
  var video_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "modal-content"
  }).appendTo("#img_elm");
  $("#img_elm").load();
}
//
// Photo viewer is still under construction.
//
function renderPhotoOld(mediaItem) {
  webix.ui({
    view: "window",
    id: "image_window",
    fullscreen: true,
    head: {
      view: "toolbar",
      margin: -10,
      cols: [{
        view: "label",
        label: "~~ Images Beta ~~"
      }, {
        view: "icon",
        icon: "times-circle",
        click: function() {
          $$('image_window').close();
        }
      }]
    },
    body: {
      view: "carousel",
      id: "bubble_carousel",
      fullscreen: true,
      cols: getImageFilePathsFromCache()
    }
  });
  $$("bubble_carousel").setActive(mediaItem.id);
  $$("image_window").show();
}
/*
 * Retrieve cached image file path data.
 * See cacheImageFilePaths(media_file_list) function for cache creation.
 */
function getImageFilePathsFromCache() {
  return $("body").data("image file list");
}
/*
 * Save image file paths data in cache for later reuse via getImageFilePathsFromCache() function.
 */
function cacheImageFilePaths(media_file_list) {
  function img(obj) {
    return '
' + obj
      .name + '
';
  }
  console.log("This should be called only once.");
  var imageFilePaths = [];
  media_file_list.forEach(function(media_file) {
    if (media_file.type.toString().toLowerCase() == "photos") {
      imageFilePaths.push({
        id: media_file.id,
        css: "image",
        template: img,
        data: webix.copy({
          src: getMediaFilePath(media_file),
          title: media_file.name
        })
      });
    }
  });
  $("body").data("image file list", imageFilePaths);
}
var folderStack = [];

function renderMediaDynamic(mediaItem, title) {
  if (mediaItem.type == "directory") {
    var opened = false;
    var pos;
    var elementIcon;
    var element;
    var len = folderStack.length;
    elementIcon = document.getElementById(mediaItem.name + "Icon");
    for (var i = 0; i < folderStack.length; i++) {
      if (elementIcon.parentElement.parentElement.id + "/" + mediaItem.name == folderStack[i]) {
        opened = true;
        pos = i;
      }
    }
    if (opened) {
      for (var i = pos; i < len; i++) {
        element = document.getElementById(folderStack[i]);
        element.outerHTML = "";
        delete element;
        var elephant = document.getElementById(folderStack[i] + "bar");
        elephant.outerHTML = "";
        delete elephant;
        elementIcon.src = "img/folder.png";
      }
      for (var i = pos; i < len; i++) {
        folderStack.pop();
      }
    } else {
      elementIcon.src = "img/openFolder.png";
      folderStack.push(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      addNavBar(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      getFilesInDir(mediaItem.contents, elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
    }
  } else {
    switch (getExt(mediaItem)) {
      case ".ogg":
      case ".mp3":
        renderAudio(mediaItem, title);
        break;
      case ".pdf":
        renderPdf(mediaItem, title);
        break;
      case ".webm":
      case ".mp4":
        renderVideo(mediaItem, title);
        break;
      case ".png":
      case ".jpg":
        renderPhoto(mediaItem, title);
        break;
      case ".txt":
        renderText(mediaItem, title);
        mediaSrc = "img/textFile.png";
        break;
        //case "tv":
        // break;
      default:
        mediaSrc = "img/unreadable.png";
        break;
    }
  }
}

function getCurrentDir(title) {
  return title.substring(title.lastIndexOf("/") + 1);
}

function addNavBar(name) {
  var nam = name + "bar";
  var nav = $("

", {
    "class": "",
    "id": nam
  });
  var txt = $("", {
    "href": "#" + name
  });
  txt.html(getCurrentDir(name));
  nav.append(txt);
  nav.appendTo("#navBar");
}

function getFilesInDir(dir, title) {
  var mediaDirs = jsonResult;
  var currentDir = getCurrentDir(title);
  var directory = $("

", {
    "id": title,
  });
  directory.appendTo("#files_list");
  var name = $("
" + currentDir + "
", {});
  name.appendTo(directory);
  $.each(dir, function(i, mediaItem) {
    var mediaSrc = getMediaFilePath(mediaItem, title);
    var divType = "img";
    var modalType = "";
    if (mediaItem.type == "directory") {
      mediaSrc = "img/folder.png";
    } else {
      switch (getExt(mediaItem)) {
        //   case "document":
        //  mediaSrc = mediaItem;
        //break;
        case ".ogg":
        case ".mp3":
          mediaSrc = "img/musicFile.png";
          modalType = "audio";
          break;
        case ".pdf":
          mediaSrc = "img/pdfFile.png";
          modalType = "pdf";
          break;
        case ".webm":
        case ".mp4":
          modalType = "video";
          divType = "video";
          break;
        case ".png":
        case ".jpg":
          modalType = "img";
          break;
        case ".txt":
          mediaSrc = "img/textFile.png";
          modalType = "pdf";
          break;
          //case "tv":
          // break;
        default:
          mediaSrc = "img/unreadable.png";
          break;
      }
    }
    var img = $("

", {
      "class": "thumbContainer"
    });
    var image = $("<" + divType + "></" + divType + ">", {
      "id": mediaItem.name + "Icon",
      "class": "bubble_thumb",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem,
      "src": mediaSrc
    });
    var lnk = $("", {
      "class": "fileName",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem
    });
    lnk.html(mediaItem.name);
    lnk.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    image.html(mediaItem.name);
    image.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    img.append(image);
    img.append(lnk);
    img.appendTo(directory);
  });
}
$.getJSON("data/media_files_list_v3.json", function(result) {
  jsonResult = result;
  addNavBar("")
  getFilesInDir(result, "");
}); // end of getJSON()
$("#audio_modal").on("hide.bs.modal", function(e) {
  $("#audio_elm")[0].pause();
});
$("#video_modal").on("hide.bs.modal", function(e) {
  $("#video_elm")[0].pause();
});
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * When a level is completed, this node shows how you did.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Imports
  var Color = require( 'SCENERY/util/Color' );
  var Dimension2 = require( 'DOT/Dimension2' );
  var ProgressIndicator = require( 'VEGAS/ProgressIndicator' );
  var GameTimer = require( 'VEGAS/GameTimer' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Line = require( 'SCENERY/nodes/Line' );
  var MultiLineText = require( 'SCENERY_PHET/MultiLineText' );
  var Node = require( 'SCENERY/nodes/Node' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var StringUtils = require( 'PHETCOMMON/util/StringUtils' );
  var Text = require( 'SCENERY/nodes/Text' );
  var TextPushButton = require( 'SUN/TextPushButton' );

  // Strings
  var keepTryingString = require( 'string!VEGAS/keepTrying' );
  var goodString = require( 'string!VEGAS/good' );
  var greatString = require( 'string!VEGAS/great' );
  var excellentString = require( 'string!VEGAS/excellent' );
  var scoreOutOfString = require( 'string!VEGAS/label.score.max' );
  var timeString = require( 'string!VEGAS/label.time' );
  var yourNewBestString = require( 'string!VEGAS/yourNewBest' );
  var pattern0YourBestString = require( 'string!VEGAS/pattern.0yourBest' );
  var continueString = require( 'string!VEGAS/continue' );

  // Constants
  var BACKGROUND_COLOR = new Color( 180, 205, 255 );
  var INFO_TEXT_FONT = new PhetFont( { size: 22, weight: 'bold' } );

  /**
   * @param {number} score
   * @param {number} maxPossibleScore
   * @param {number} numStars
   * @param {boolean} timerEnabled
   * @param {number} elapsedTime In seconds
   * @param {number} bestTimeAtThisLevel In seconds, should be Number.POSITIVE_INFINITY if no best time exists yet.
   * @param {Bounds2} layoutBounds
   * @param {function} continueFunction Function to call when the user presses the 'Continue' button.
   * @constructor
   */
  function LevelCompletedNode( score, maxPossibleScore, numStars, timerEnabled, elapsedTime, bestTimeAtThisLevel, layoutBounds, continueFunction ) {

    Node.call( this ); // Call super constructor.

    var size = new Dimension2( layoutBounds.width * 0.5, layoutBounds.height * 0.7 );

    var rounding = size.width * 0.1;
    var background = new Rectangle( 0, 0, size.width, size.height, rounding, rounding,
      {
        fill: BACKGROUND_COLOR,
        stroke: 'black',
        lineWidth: 2
      } );

    this.addChild( background );

    var proportionCorrect = score / maxPossibleScore;
    var titleText = keepTryingString;
    if ( proportionCorrect > 0.95 ) {
      titleText = excellentString;
    }
    else if ( proportionCorrect > 0.75 ) {
      titleText = greatString;
    }
    else if ( proportionCorrect >= 0.5 ) {
      titleText = goodString;
    }
    var title = new Text( titleText, {font: new PhetFont( { size: 28, weight: 'bold' } )} ); // TODO: i18n
    title.scale( Math.min( 1, (size.width * 0.9 ) / title.width ) );
    background.addChild( title );

    var starDiameter = Math.min( size.width / numStars * 0.8, size.width * 0.2 );
    var gameProgressIndicator = new ProgressIndicator( numStars, starDiameter, new Property( score ), maxPossibleScore );
    background.addChild( gameProgressIndicator );

    // TODO: i18n of everything below
    var scoreText = new Text( StringUtils.format( scoreOutOfString, score, maxPossibleScore ), { font: INFO_TEXT_FONT } );
    background.addChild( scoreText );

    var time = new MultiLineText( StringUtils.format( timeString, GameTimer.formatTime( elapsedTime ) ), { font: INFO_TEXT_FONT, align: 'center' } );
    if ( elapsedTime === bestTimeAtThisLevel ) {
      time.text += '\n' + yourNewBestString;
    }
    else if ( bestTimeAtThisLevel !== Number.POSITIVE_INFINITY ) {
      time.text += '\n' + StringUtils.format( pattern0YourBestString, GameTimer.formatTime( bestTimeAtThisLevel ) );
    }
    background.addChild( time );

    var continueButton = new TextPushButton( continueString, { listener: continueFunction, font: new PhetFont( 28 ), rectangleFillUp: new Color( 255, 255, 0 ) } );
    background.addChild( continueButton );

    // Layout
    var inset = size.width * 0.05;
    var centerX = size.width / 2;
    title.centerX = centerX;
    title.top = inset;
    gameProgressIndicator.centerX = centerX;
    gameProgressIndicator.top = title.bottom + inset / 2;
    continueButton.centerX = centerX;
    continueButton.bottom = size.height - inset;
    var verticalSpaceForInfoText = continueButton.top - gameProgressIndicator.bottom;
    scoreText.centerX = centerX;
    time.centerX = centerX;
    if ( timerEnabled ) {
      scoreText.centerY = gameProgressIndicator.bottom + verticalSpaceForInfoText * 0.3;
      time.centerY = gameProgressIndicator.bottom + verticalSpaceForInfoText * 0.7;
    }
    else {
      time.visible = false;
      scoreText.centerY = gameProgressIndicator.bottom + verticalSpaceForInfoText * 0.5;
    }
  }

  // Inherit from Node.
  return inherit( Node, LevelCompletedNode );
} );
<commit_msg>add things to LevelCompletedNode that are needed by graphing-lines, provide these things in an adhoc manner in BAAGameView.<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * When a level is completed, this node shows how you did.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Imports
  var Color = require( 'SCENERY/util/Color' );
  var Dimension2 = require( 'DOT/Dimension2' );
  var ProgressIndicator = require( 'VEGAS/ProgressIndicator' );
  var GameTimer = require( 'VEGAS/GameTimer' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Line = require( 'SCENERY/nodes/Line' );
  var MultiLineText = require( 'SCENERY_PHET/MultiLineText' );
  var Node = require( 'SCENERY/nodes/Node' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var StringUtils = require( 'PHETCOMMON/util/StringUtils' );
  var Text = require( 'SCENERY/nodes/Text' );
  var TextPushButton = require( 'SUN/TextPushButton' );

  // Strings
  var keepTryingString = require( 'string!VEGAS/keepTrying' );
  var goodString = require( 'string!VEGAS/good' );
  var greatString = require( 'string!VEGAS/great' );
  var excellentString = require( 'string!VEGAS/excellent' );
  var scoreOutOfString = require( 'string!VEGAS/label.score.max' );
  var timeString = require( 'string!VEGAS/label.time' );
  var yourNewBestString = require( 'string!VEGAS/yourNewBest' );
  var pattern0YourBestString = require( 'string!VEGAS/pattern.0yourBest' );
  var continueString = require( 'string!VEGAS/continue' );

  // Constants
  var BACKGROUND_COLOR = new Color( 180, 205, 255 );
  var INFO_TEXT_FONT = new PhetFont( { size: 22, weight: 'bold' } );

  /**
   * @param {number} level
   * @param {number} score
   * @param {number} maxPossibleScore
   * @param {number} numStars
   * @param {boolean} timerEnabled
   * @param {number} elapsedTime In seconds
   * @param {number} bestTimeAtThisLevel In seconds, null if no best time exists yet.
   * @param {boolean} isNewBestTime
   * @param {Bounds2} layoutBounds
   * @param {function} continueFunction Function to call when the user presses the 'Continue' button.
   * @param {*} options
   * @constructor
   */
  function LevelCompletedNode( level, score, maxPossibleScore, numStars, timerEnabled, elapsedTime, bestTimeAtThisLevel, isNewBestTime, layoutBounds, continueFunction, options ) {

    options = _.extend( {
      levelVisible: false // display the level number?
    }, options );

    //TODO display the level number based on options.levelVisible

    Node.call( this ); // Call super constructor.

    var size = new Dimension2( layoutBounds.width * 0.5, layoutBounds.height * 0.7 );

    var rounding = size.width * 0.1;
    var background = new Rectangle( 0, 0, size.width, size.height, rounding, rounding,
      {
        fill: BACKGROUND_COLOR,
        stroke: 'black',
        lineWidth: 2
      } );

    this.addChild( background );

    var proportionCorrect = score / maxPossibleScore;
    var titleText = keepTryingString;
    if ( proportionCorrect > 0.95 ) {
      titleText = excellentString;
    }
    else if ( proportionCorrect > 0.75 ) {
      titleText = greatString;
    }
    else if ( proportionCorrect >= 0.5 ) {
      titleText = goodString;
    }
    var title = new Text( titleText, {font: new PhetFont( { size: 28, weight: 'bold' } )} );
    title.scale( Math.min( 1, (size.width * 0.9 ) / title.width ) );
    background.addChild( title );

    var starDiameter = Math.min( size.width / numStars * 0.8, size.width * 0.2 );
    var gameProgressIndicator = new ProgressIndicator( numStars, starDiameter, new Property( score ), maxPossibleScore );
    background.addChild( gameProgressIndicator );

    // TODO: i18n of everything below
    var scoreText = new Text( StringUtils.format( scoreOutOfString, score, maxPossibleScore ), { font: INFO_TEXT_FONT } );
    background.addChild( scoreText );

    var time = new MultiLineText( StringUtils.format( timeString, GameTimer.formatTime( elapsedTime ) ), { font: INFO_TEXT_FONT, align: 'center' } );
    if ( isNewBestTime ) {
      time.text += '\n' + yourNewBestString;
    }
    else if ( bestTimeAtThisLevel !== null ) {
      time.text += '\n' + StringUtils.format( pattern0YourBestString, GameTimer.formatTime( bestTimeAtThisLevel ) );
    }
    background.addChild( time );

    var continueButton = new TextPushButton( continueString, { listener: continueFunction, font: new PhetFont( 28 ), rectangleFillUp: new Color( 255, 255, 0 ) } );
    background.addChild( continueButton );

    // Layout
    var inset = size.width * 0.05;
    var centerX = size.width / 2;
    title.centerX = centerX;
    title.top = inset;
    gameProgressIndicator.centerX = centerX;
    gameProgressIndicator.top = title.bottom + inset / 2;
    continueButton.centerX = centerX;
    continueButton.bottom = size.height - inset;
    var verticalSpaceForInfoText = continueButton.top - gameProgressIndicator.bottom;
    scoreText.centerX = centerX;
    time.centerX = centerX;
    if ( timerEnabled ) {
      scoreText.centerY = gameProgressIndicator.bottom + verticalSpaceForInfoText * 0.3;
      time.centerY = gameProgressIndicator.bottom + verticalSpaceForInfoText * 0.7;
    }
    else {
      time.visible = false;
      scoreText.centerY = gameProgressIndicator.bottom + verticalSpaceForInfoText * 0.5;
    }
  }

  // Inherit from Node.
  return inherit( Node, LevelCompletedNode );
} );
<|endoftext|>