<commit_before>VISH.Editor.AvatarPicker = (function(V,$,undefined){
    var avatars = null;

   /**
    * function to create the carrousel with the avatars in the div with id "avatars_carrousel"
    */
   var init = function(){

   };

	 var onLoadExcursionDetails = function(){
	 	 $("#thumbnails_in_excursion_details").hide();
	 	 VISH.Editor.API.requestThumbnails(_onThumbnailsReceived,_onThumbnailsError);
	 }

  /**
   * Callback function to select an avatar
   */
  var _selectAvatar = function(event){
  	$(".carrousel_element_single_row_thumbnails").removeClass("selectedThumbnail");
  	$(event.target).addClass("selectedThumbnail");
  	$('#excursion_avatar').val($(event.target).attr("src"));
  };

  /**
   * function to select a random avatar, it will be chosen between the first and the max (to be in the first carrousel page)
   */
  var selectRandom = function(max){
  	var randomnumber=Math.ceil(Math.random()*max);
  	$("#avatars_carrousel .carrousel_element_single_row_thumbnails:nth-child("+randomnumber+") img").addClass("carrousel_element_selected");
  	$('#excursion_avatar').val($("#avatars_carrousel .carrousel_element_single_row_thumbnails:nth-child("+randomnumber+") img").attr("src"));
  };

	var _onThumbnailsReceived = function(data){
		    avatars = data;

        //Clean previous carrousel
        VISH.Editor.Carrousel.cleanCarrousel("avatars_carrousel");

        //Build new carrousel
        var content = "";
        var carrouselImages = [];
        $.each(avatars.pictures, function(i, item) {
          var myImg = $("")
          carrouselImages.push(myImg)
        });

        VISH.Utils.loader.loadImagesOnCarrousel(carrouselImages,_onImagesLoaded,"avatars_carrousel");
	}

	var _onThumbnailsError = function(xhr, ajaxOptions, thrownError){
		VISH.Debugging.log("_onThumbnailsError")
		VISH.Debugging.log("status returned by server:" + xhr.status);
    VISH.Debugging.log("Error in client: " + thrownError);
    VISH.Debugging.log("ERROR!" + thrownError)
	}

	var _onImagesLoaded = function(){
    $("#thumbnails_in_excursion_details").show();

		var options = new Array();
    options['rows'] = 1;
    options['callback'] = _selectAvatar;
    options['rowItems'] = 5;
		options['styleClass'] = "thumbnails";

    VISH.Editor.Carrousel.createCarrousel("avatars_carrousel", options);

    $(".buttonintro").addClass("buttonintro_extramargin");
    VISH.Editor.AvatarPicker.selectRandom(5);  //randomly select one between first page
	}

	return {
		init	       : init,
		selectAvatar   : selectAvatar,
		selectRandom   : selectRandom,
		onLoadExcursionDetails : onLoadExcursionDetails

	};

}) (VISH, jQuery);<commit_msg>Minor bug fixed<commit_after>VISH.Editor.AvatarPicker = (function(V,$,undefined){
    var avatars = null;

   /**
    * function to create the carrousel with the avatars in the div with id "avatars_carrousel"
    */
   var init = function(){

   };

	 var onLoadExcursionDetails = function(){
	 	 $("#thumbnails_in_excursion_details").hide();
	 	 VISH.Editor.API.requestThumbnails(_onThumbnailsReceived,_onThumbnailsError);
	 }

  /**
   * Callback function to select an avatar
   */
  var _selectAvatar = function(event){
  	$(".carrousel_element_single_row_thumbnails").removeClass("selectedThumbnail");
  	$(event.target).addClass("selectedThumbnail");
  	$('#excursion_avatar').val($(event.target).attr("src"));
  };

  /**
   * function to select a random avatar, it will be chosen between the first and the max (to be in the first carrousel page)
   */
  var selectRandom = function(max){
  	var randomnumber=Math.ceil(Math.random()*max);
  	$("#avatars_carrousel .carrousel_element_single_row_thumbnails:nth-child("+randomnumber+") img").addClass("carrousel_element_selected");
  	$('#excursion_avatar').val($("#avatars_carrousel .carrousel_element_single_row_thumbnails:nth-child("+randomnumber+") img").attr("src"));
  };

	var _onThumbnailsReceived = function(data){
		    avatars = data;

        //Clean previous carrousel
        VISH.Editor.Carrousel.cleanCarrousel("avatars_carrousel");

        //Build new carrousel
        var content = "";
        var carrouselImages = [];
        $.each(avatars.pictures, function(i, item) {
          var myImg = $("")
          carrouselImages.push(myImg)
        });

        VISH.Utils.loader.loadImagesOnCarrousel(carrouselImages,_onImagesLoaded,"avatars_carrousel");
	}

	var _onThumbnailsError = function(xhr, ajaxOptions, thrownError){
		VISH.Debugging.log("_onThumbnailsError")
		VISH.Debugging.log("status returned by server:" + xhr.status);
    VISH.Debugging.log("Error in client: " + thrownError);
    VISH.Debugging.log("ERROR!" + thrownError)
	}

	var _onImagesLoaded = function(){
    $("#thumbnails_in_excursion_details").show();

		var options = new Array();
    options['rows'] = 1;
    options['callback'] = _selectAvatar;
    options['rowItems'] = 5;
		options['styleClass'] = "thumbnails";

    VISH.Editor.Carrousel.createCarrousel("avatars_carrousel", options);

    $(".buttonintro").addClass("buttonintro_extramargin");
    VISH.Editor.AvatarPicker.selectRandom(5);  //randomly select one between first page
	}

	return {
		init	       : init,
		selectRandom   : selectRandom,
		onLoadExcursionDetails : onLoadExcursionDetails

	};

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


<commit_before>angular.module('foundation.panel', ['foundation.common.services']);

angular.module('foundation.panel')
  .directive('faPanel', ['FoundationApi', function(foundationApi) {
  return {
    restrict: 'EA',
    templateUrl: '/partials/panel.html',
    transclude: true,
    scope: {
      position: '@'
    },
    replace: true,
    compile: function compile(tElement, tAttrs, transclude) {
      var type = 'panel';

      return {
        pre: function preLink(scope, iElement, iAttrs, controller) {
          iAttrs.$set('fa-closable', type);
        },
        post: function postLink(scope, element, attrs) {
          var currentStatus = 'hide';
          scope.active = false;

          //setup
          foundationApi.subscribe(attrs.id, function(msg) {
            if(msg == 'show' || msg == 'open') {
              scope.show();
            } else if (msg == 'close' || msg == 'hide') {
              scope.hide();
            } else if (msg == 'toggle') {
              scope.toggle();
            }

            scope.$apply();

            return;
          });

          scope.hide = function() {
            scope.active = false;
            return;
          };

          scope.show = function() {
            scope.active = false;
            return;
          };

          scope.toggle = function() {
            scope.active = !scope.active;
            return;
          };
        }
      };
    },
  };
}]);
<commit_msg>Open panels properly, fixing #106<commit_after>angular.module('foundation.panel', ['foundation.common.services']);

angular.module('foundation.panel')
  .directive('faPanel', ['FoundationApi', function(foundationApi) {
  return {
    restrict: 'EA',
    templateUrl: '/partials/panel.html',
    transclude: true,
    scope: {
      position: '@'
    },
    replace: true,
    compile: function compile(tElement, tAttrs, transclude) {
      var type = 'panel';

      return {
        pre: function preLink(scope, iElement, iAttrs, controller) {
          iAttrs.$set('fa-closable', type);
        },
        post: function postLink(scope, element, attrs) {
          var currentStatus = 'hide';
          scope.active = false;

          //setup
          foundationApi.subscribe(attrs.id, function(msg) {
            if(msg == 'show' || msg == 'open') {
              scope.show();
            } else if (msg == 'close' || msg == 'hide') {
              scope.hide();
            } else if (msg == 'toggle') {
              scope.toggle();
            }

            scope.$apply();

            return;
          });

          scope.hide = function() {
            scope.active = false;
            return;
          };

          scope.show = function() {
            scope.active = true;
            return;
          };

          scope.toggle = function() {
            scope.active = !scope.active;
            return;
          };
        }
      };
    },
  };
}]);
<|endoftext|>


<commit_before>/*jslint indent: 2,
         nomen: true,
         maxlen: 80 */
/*global require,
    db,
    assertEqual, assertTrue,
    print,
    PRINT_OBJECT,
    console,
    AvocadoCollection, AvocadoEdgesCollection */
(function () {
  "use strict";

////////////////////////////////////////////////////////////////////////////////
/// @brief test the graph class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler, Lucas Dohmen
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

  var jsunity = require("jsunity");

// -----------------------------------------------------------------------------
// --SECTION--                                                collection methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Creation
////////////////////////////////////////////////////////////////////////////////

  function graphCreationSuite() {

    return {

////////////////////////////////////////////////////////////////////////////////
/// @brief test: Graph Creation
////////////////////////////////////////////////////////////////////////////////

      testCreation: function () {
        var Graph = require("graph").Graph,
          graph_name = "UnitTestsCollectionGraph",
          vertex = "UnitTestsCollectionVertex",
          edge = "UnitTestsCollectionEdge",
          graph = null;

        graph = new Graph(graph_name, vertex, edge);

        assertEqual(graph_name, graph._properties.name);
        assertTrue(graph._vertices instanceof AvocadoCollection);
        assertTrue(graph._edges instanceof AvocadoEdgesCollection);

        graph.drop();
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: Find Graph
////////////////////////////////////////////////////////////////////////////////

      testFindGraph: function () {
        var Graph = require("graph").Graph,
          graph_name = "UnitTestsCollectionGraph",
          vertex = "UnitTestsCollectionVertex",
          edge = "UnitTestsCollectionEdge",
          graph1 = null,
          graph2 = null;

        graph1 = new Graph(graph_name, vertex, edge);
        graph2 = new Graph(graph_name);

        assertEqual(graph1._properties.name, graph2._properties.name);
        assertEqual(graph1._vertices, graph2._vertices);
        assertEqual(graph1._edges, graph2._edges);

        graph1.drop();
      }
    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Basics
////////////////////////////////////////////////////////////////////////////////

  function graphBasicsSuite() {
    //var ERRORS = require("internal").errors;
    var Graph = require("graph").Graph,
      graph_name = "UnitTestsCollectionGraph",
      vertex = "UnitTestsCollectionVertex",
      edge = "UnitTestsCollectionEdge",
      graph = null;

    return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

      setUp : function () {
        try {
          try {
            graph = new Graph(graph_name);
            print("FOUND: ");
            PRINT_OBJECT(graph);
            graph.drop();
          } catch (err1) {
          }

          graph = new Graph(graph_name, vertex, edge);
        } catch (err2) {
          console.error("[FAILED] setup failed:" + err2);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

      tearDown : function () {
        try {
          if (graph !== null) {
            graph.drop();
          }
        } catch (err) {
          console.error("[FAILED] tear-down failed:" + err);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex without data
////////////////////////////////////////////////////////////////////////////////

      testCreateVertexWithoutData : function () {
        var v = graph.addVertex("name1");

        assertEqual("name1", v.getId());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex
////////////////////////////////////////////////////////////////////////////////

      testCreateVertex : function () {
        var v = graph.addVertex("name1", { age : 23 });

        assertEqual("name1", v.getId());
        assertEqual(23, v.getProperty("age"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief get a vertex
////////////////////////////////////////////////////////////////////////////////

      testGetVertex : function () {
        var v1 = graph.addVertex("find_me", { age : 23 }),
          vid,
          v2;

        vid = v1.getId();
        v2 = graph.getVertex(vid);
        assertEqual(23, v2.getProperty("age"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testChangeProperty : function () {
        var v = graph.addVertex("name2", { age : 32 });

        assertEqual("name2", v.getId());
        assertEqual(32, v.getProperty("age"));

        v.setProperty("age", 23);

        assertEqual("name2", v.getId());
        assertEqual(23, v.getProperty("age"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testAddEdgeWithoutInfo : function () {
        var v1,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2);

        assertEqual(null, edge.getId());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testAddEdge : function () {
        var v1,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        assertEqual("edge1", edge.getId());
        assertEqual("label", edge.getLabel());
        assertEqual("testValue", edge.getProperty("testProperty"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testGetEdges : function () {
        var v1,
          v2,
          edge1,
          edge2;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge1 = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        edge2 = graph.getEdges().next();
        assertEqual(true, graph.getEdges().hasNext());
        assertEqual(edge1.getId(), edge2.getId());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief remove an edge
////////////////////////////////////////////////////////////////////////////////

      testRemoveEdges : function () {
        var v1,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        graph.removeEdge(edge);
        assertEqual(false, graph.getEdges().hasNext());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief remove a vertex
////////////////////////////////////////////////////////////////////////////////

      testRemoveVertex : function () {
        var v1,
          v1_id,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v1_id = v1.getId();
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        graph.removeVertex(v1);

        assertEqual(null, graph.getVertex(v1_id));
        assertEqual(false, graph.getEdges().hasNext());
      }

    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Vertex
////////////////////////////////////////////////////////////////////////////////

  function vertexSuite() {
    var Graph = require("graph").Graph,
      graph_name = "UnitTestsCollectionGraph",
      vertex = "UnitTestsCollectionVertex",
      edge = "UnitTestsCollectionEdge",
      graph = null;

    return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

      setUp : function () {
        try {
          try {
            graph = new Graph(graph_name);
            print("FOUND: ");
            PRINT_OBJECT(graph);
            graph.drop();
          } catch (err1) {
          }

          graph = new Graph(graph_name, vertex, edge);
        } catch (err2) {
          console.error("[FAILED] setup failed:" + err2);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

      tearDown : function () {
        try {
          if (graph !== null) {
            graph.drop();
          }
        } catch (err) {
          console.error("[FAILED] tear-down failed:" + err);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief add edges
////////////////////////////////////////////////////////////////////////////////

      testAddEdges : function () {
        var v1,
          v2,
          v3,
          edge1,
          edge2;

        v1 = graph.addVertex(graph);
        v2 = graph.addVertex(graph);
        v3 = graph.addVertex(graph);

		edge1 = v1.addInEdge(v2);
		edge2 = v1.addOutEdge(v3);

		assertEqual(v1.getId(), edge1.getInVertex().getId());
		assertEqual(v2.getId(), edge1.getOutVertex().getId());
		assertEqual(v3.getId(), edge2.getInVertex().getId());
		assertEqual(v1.getId(), edge2.getOutVertex().getId());
      }

    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

  //jsunity.run(graphCreationSuite);
  //jsunity.run(graphBasicsSuite);
  jsunity.run(vertexSuite);
  jsunity.done();

}());
<commit_msg>Added Tests to get Edges for Vertices<commit_after>/*jslint indent: 2,
         nomen: true,
         maxlen: 80 */
/*global require,
    db,
    assertEqual, assertTrue,
    print,
    PRINT_OBJECT,
    console,
    AvocadoCollection, AvocadoEdgesCollection */
(function () {
  "use strict";

////////////////////////////////////////////////////////////////////////////////
/// @brief test the graph class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler, Lucas Dohmen
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

  var jsunity = require("jsunity");

// -----------------------------------------------------------------------------
// --SECTION--                                                collection methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Creation
////////////////////////////////////////////////////////////////////////////////

  function graphCreationSuite() {

    return {

////////////////////////////////////////////////////////////////////////////////
/// @brief test: Graph Creation
////////////////////////////////////////////////////////////////////////////////

      testCreation: function () {
        var Graph = require("graph").Graph,
          graph_name = "UnitTestsCollectionGraph",
          vertex = "UnitTestsCollectionVertex",
          edge = "UnitTestsCollectionEdge",
          graph = null;

        graph = new Graph(graph_name, vertex, edge);

        assertEqual(graph_name, graph._properties.name);
        assertTrue(graph._vertices instanceof AvocadoCollection);
        assertTrue(graph._edges instanceof AvocadoEdgesCollection);

        graph.drop();
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: Find Graph
////////////////////////////////////////////////////////////////////////////////

      testFindGraph: function () {
        var Graph = require("graph").Graph,
          graph_name = "UnitTestsCollectionGraph",
          vertex = "UnitTestsCollectionVertex",
          edge = "UnitTestsCollectionEdge",
          graph1 = null,
          graph2 = null;

        graph1 = new Graph(graph_name, vertex, edge);
        graph2 = new Graph(graph_name);

        assertEqual(graph1._properties.name, graph2._properties.name);
        assertEqual(graph1._vertices, graph2._vertices);
        assertEqual(graph1._edges, graph2._edges);

        graph1.drop();
      }
    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Basics
////////////////////////////////////////////////////////////////////////////////

  function graphBasicsSuite() {
    //var ERRORS = require("internal").errors;
    var Graph = require("graph").Graph,
      graph_name = "UnitTestsCollectionGraph",
      vertex = "UnitTestsCollectionVertex",
      edge = "UnitTestsCollectionEdge",
      graph = null;

    return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

      setUp : function () {
        try {
          try {
            graph = new Graph(graph_name);
            print("FOUND: ");
            PRINT_OBJECT(graph);
            graph.drop();
          } catch (err1) {
          }

          graph = new Graph(graph_name, vertex, edge);
        } catch (err2) {
          console.error("[FAILED] setup failed:" + err2);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

      tearDown : function () {
        try {
          if (graph !== null) {
            graph.drop();
          }
        } catch (err) {
          console.error("[FAILED] tear-down failed:" + err);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex without data
////////////////////////////////////////////////////////////////////////////////

      testCreateVertexWithoutData : function () {
        var v = graph.addVertex("name1");

        assertEqual("name1", v.getId());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex
////////////////////////////////////////////////////////////////////////////////

      testCreateVertex : function () {
        var v = graph.addVertex("name1", { age : 23 });

        assertEqual("name1", v.getId());
        assertEqual(23, v.getProperty("age"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief get a vertex
////////////////////////////////////////////////////////////////////////////////

      testGetVertex : function () {
        var v1 = graph.addVertex("find_me", { age : 23 }),
          vid,
          v2;

        vid = v1.getId();
        v2 = graph.getVertex(vid);
        assertEqual(23, v2.getProperty("age"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testChangeProperty : function () {
        var v = graph.addVertex("name2", { age : 32 });

        assertEqual("name2", v.getId());
        assertEqual(32, v.getProperty("age"));

        v.setProperty("age", 23);

        assertEqual("name2", v.getId());
        assertEqual(23, v.getProperty("age"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testAddEdgeWithoutInfo : function () {
        var v1,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2);

        assertEqual(null, edge.getId());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testAddEdge : function () {
        var v1,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        assertEqual("edge1", edge.getId());
        assertEqual("label", edge.getLabel());
        assertEqual("testValue", edge.getProperty("testProperty"));
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////

      testGetEdges : function () {
        var v1,
          v2,
          edge1,
          edge2;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge1 = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        edge2 = graph.getEdges().next();
        assertEqual(true, graph.getEdges().hasNext());
        assertEqual(edge1.getId(), edge2.getId());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief remove an edge
////////////////////////////////////////////////////////////////////////////////

      testRemoveEdges : function () {
        var v1,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        graph.removeEdge(edge);
        assertEqual(false, graph.getEdges().hasNext());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief remove a vertex
////////////////////////////////////////////////////////////////////////////////

      testRemoveVertex : function () {
        var v1,
          v1_id,
          v2,
          edge;

        v1 = graph.addVertex("vertex1");
        v1_id = v1.getId();
        v2 = graph.addVertex("vertex2");

        edge = graph.addEdge(v1,
          v2,
          "edge1",
          "label",
          { testProperty: "testValue" });

        graph.removeVertex(v1);

        assertEqual(null, graph.getVertex(v1_id));
        assertEqual(false, graph.getEdges().hasNext());
      }

    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Vertex
////////////////////////////////////////////////////////////////////////////////

  function vertexSuite() {
    var Graph = require("graph").Graph,
      graph_name = "UnitTestsCollectionGraph",
      vertex = "UnitTestsCollectionVertex",
      edge = "UnitTestsCollectionEdge",
      graph = null;

    return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

      setUp : function () {
        try {
          try {
            graph = new Graph(graph_name);
            print("FOUND: ");
            PRINT_OBJECT(graph);
            graph.drop();
          } catch (err1) {
          }

          graph = new Graph(graph_name, vertex, edge);
        } catch (err2) {
          console.error("[FAILED] setup failed:" + err2);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

      tearDown : function () {
        try {
          if (graph !== null) {
            graph.drop();
          }
        } catch (err) {
          console.error("[FAILED] tear-down failed:" + err);
        }
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief add edges
////////////////////////////////////////////////////////////////////////////////

      testAddEdges : function () {
        var v1,
          v2,
          v3,
          edge1,
          edge2;

        v1 = graph.addVertex(graph);
        v2 = graph.addVertex(graph);
        v3 = graph.addVertex(graph);

        edge1 = v1.addInEdge(v2);
        edge2 = v1.addOutEdge(v3);

        assertEqual(v1.getId(), edge1.getInVertex().getId());
        assertEqual(v2.getId(), edge1.getOutVertex().getId());
        assertEqual(v3.getId(), edge2.getInVertex().getId());
        assertEqual(v1.getId(), edge2.getOutVertex().getId());
      },

////////////////////////////////////////////////////////////////////////////////
/// @brief get edges
////////////////////////////////////////////////////////////////////////////////

      testGetEdges : function () {
        var v1,
          v2,
          edge;

        v1 = graph.addVertex(graph);
        v2 = graph.addVertex(graph);

        edge = graph.addEdge(v1, v2);

        assertEqual(edge.getId(), v1.getOutEdges()[0].getId());
        assertEqual(edge.getId(), v2.getInEdges()[0].getId());
        assertEqual([], v1.getInEdges());
        assertEqual([], v2.getOutEdges());
      }
    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

  //jsunity.run(graphCreationSuite);
  //jsunity.run(graphBasicsSuite);
  jsunity.run(vertexSuite);
  jsunity.done();

}());
<|endoftext|>


<commit_before>define('editor', [
  'constants',
  'config',
  'eventsWithPromises',
  'scribe-wrapper',
  'source-converter'
], function (
    constants,
    config,
    events,
    scribe,
    converter
) {
    'use strict';

    /**
     * Creates an editor instance
     * @class
     * @param {Object} htmlEditorNode       HTML editor node
     * @param {Object} markdownEditorNode   Markdown editor node
     * @param {Object} toolbarNode          HTML editor toolbar node
     * @param {Object} options              Options
     */
    var Editor = function(htmlEditorNode, markdownEditorNode, toolbarNode, options) {
      this.constants = constants;
      this.config = config;
      this.toolbarNode = toolbarNode;
      this.htmlEditorNode = htmlEditorNode;
      this.markdownEditorNode = markdownEditorNode;
      this.options = options || {};
      this.converter = converter;
      this.editor = scribe(this.htmlEditorNode, this.toolbarNode , {
        allowBlockElements : true
      });
      this.mode = this.options.mode || config.defaultEditingMode;
      this._init();
    };

    /**
     * Starts up the class
     * @return {Object} this
     */
    Editor.prototype._init = function() {
      this.changeEditingMode(this.mode);
      return this;
    };

    /**
     * Converts HTML to Markdown
     * @private
     * @param {string} html    HTML to be converted to Markdown
     * @return {string}
     */
    Editor.prototype._convertHTMLToMarkdown = function(html) {
      return this.converter.toMarkdown(html);
    };

    /**
     * Converts Markdown to HTML
     * @private
     * @param {string} markdown     Markdown to be converted to HTML
     * @return {string}
     */
    Editor.prototype._convertMarkdownToHTML = function(markdown) {
      return this.converter.toHTML(markdown);
    };

    /**
     * Sets mode property
     * @private
     * @param {string} mode  HTML to be converted to Markdown
     * @return {string}
     */
    Editor.prototype._setEditingMode = function(mode) {
      this.mode = mode;
      return this;
    };

    /**
     * Changes the editing mode
     * @param  {string} mode Editing mode
     * @return {Object}      this
     */
    Editor.prototype.changeEditingMode = function(mode) {
      var dispatch,
          dispatchDefault,
          that = this;

      dispatch = {
        'markdown': function() {
          that.setMarkdownContent(
            that._convertHTMLToMarkdown(that.getHTMLContent())
          );
        },
        'html': function() {
          that.setHTMLContent(
            that._convertMarkdownToHTML(that.getMarkdownContent())
          );
        }
      };

      dispatchDefault = function() {
        throw new Error('That conversion isn\'t supported');
      };

      (dispatch[mode] || dispatchDefault())();
      this._setEditingMode(mode);
      return this;
    };

    /**
     * Gets the contents of the HTML editor
     * @return {string} HTML
     */
    Editor.prototype.getHTMLContent = function() {
      return this.editor.getContent();
    };

    /**
     * Sets the HTML editor's content
     * @param {string} html    HTML content
     * @return {Object} this
     */
    Editor.prototype.setHTMLContent = function(html) {
      this.editor.setContent(html);
      return this;
    };

    /**
     * Gets the content of the Markdown `textarea` box
     * @return {string} Markdown
     */
    Editor.prototype.getMarkdownContent = function() {
      return this.markdownEditorNode.value;
    };

    /**
     * Sets the Markdown editor's content
     * @param {string} markdown    Markdown content
     * @return {Object} this
     */
    Editor.prototype.setMarkdownContent = function(markdown) {
      this.markdownEditorNode.value = markdown;
      return this;
    };

    /**
     * Boots up the display of the content
     * @param {string} mode Mode
     * @param {string} src Source to convert
     * @return {Object} this
     */
    Editor.prototype.render = function(mode, src) {
      this.changeEditingMode(mode);
      return this;
    };

    /**
     * Activates plugin
     * An instance of the editor is passed to the activated plugin
     * @param  {Object} activatePlugin Plugin to activate
     * @return {Object} this
     */
    Editor.prototype.use = function(activatePlugin) {
      activatePlugin(this);
      return this;
    };

    return Editor;
});
<commit_msg>Publish some basic events<commit_after>define('editor', [
  'constants',
  'config',
  'eventsWithPromises',
  'scribe-wrapper',
  'source-converter'
], function (
    constants,
    config,
    events,
    scribe,
    converter
) {
    'use strict';

    /**
     * Creates an editor instance
     * @class
     * @param {Object} htmlEditorNode       HTML editor node
     * @param {Object} markdownEditorNode   Markdown editor node
     * @param {Object} toolbarNode          HTML editor toolbar node
     * @param {Object} options              Options
     */
    var Editor = function(htmlEditorNode, markdownEditorNode, toolbarNode, options) {
      this.constants = constants;
      this.config = config;
      this.events = events;
      this.toolbarNode = toolbarNode;
      this.htmlEditorNode = htmlEditorNode;
      this.markdownEditorNode = markdownEditorNode;
      this.options = options || {};
      this.converter = converter;
      this.editor = scribe(this.htmlEditorNode, this.toolbarNode , {
        allowBlockElements : true
      });
      this.mode = this.options.mode || config.defaultEditingMode;
      this._init();
    };

    /**
     * Starts up the class
     * @return {Object} this
     */
    Editor.prototype._init = function() {
      this.changeEditingMode(this.mode);
      this.events.publish('editor:initialised');
      return this;
    };

    /**
     * Converts HTML to Markdown
     * @private
     * @param {string} html    HTML to be converted to Markdown
     * @return {string}
     */
    Editor.prototype._convertHTMLToMarkdown = function(html) {
      return this.converter.toMarkdown(html);
    };

    /**
     * Converts Markdown to HTML
     * @private
     * @param {string} markdown     Markdown to be converted to HTML
     * @return {string}
     */
    Editor.prototype._convertMarkdownToHTML = function(markdown) {
      return this.converter.toHTML(markdown);
    };

    /**
     * Sets mode property
     * @private
     * @param {string} mode  HTML to be converted to Markdown
     * @return {string}
     */
    Editor.prototype._setEditingMode = function(mode) {
      this.mode = mode;
      return this;
    };

    /**
     * Changes the editing mode
     * @param  {string} mode Editing mode
     * @return {Object}      this
     */
    Editor.prototype.changeEditingMode = function(mode) {
      var dispatch,
          dispatchDefault,
          that = this;

      dispatch = {
        'markdown': function() {
          that.setMarkdownContent(
            that._convertHTMLToMarkdown(that.getHTMLContent())
          );
        },
        'html': function() {
          that.setHTMLContent(
            that._convertMarkdownToHTML(that.getMarkdownContent())
          );
        }
      };

      dispatchDefault = function() {
        throw new Error('That conversion isn\'t supported');
      };

      (dispatch[mode] || dispatchDefault())();
      this._setEditingMode(mode);
      this.events.publish('mode:changed', mode);

      return this;
    };

    /**
     * Gets the contents of the HTML editor
     * @return {string} HTML
     */
    Editor.prototype.getHTMLContent = function() {
      return this.editor.getContent();
    };

    /**
     * Sets the HTML editor's content
     * @param {string} html    HTML content
     * @return {Object} this
     */
    Editor.prototype.setHTMLContent = function(html) {
      this.editor.setContent(html);
      return this;
    };

    /**
     * Gets the content of the Markdown `textarea` box
     * @return {string} Markdown
     */
    Editor.prototype.getMarkdownContent = function() {
      return this.markdownEditorNode.value;
    };

    /**
     * Sets the Markdown editor's content
     * @param {string} markdown    Markdown content
     * @return {Object} this
     */
    Editor.prototype.setMarkdownContent = function(markdown) {
      this.markdownEditorNode.value = markdown;
      return this;
    };

    /**
     * Boots up the display of the content
     * @param {string} mode Mode
     * @param {string} src Source to convert
     * @return {Object} this
     */
    Editor.prototype.render = function(mode, src) {
      this.changeEditingMode(mode);
      return this;
    };

    /**
     * Activates plugin
     * An instance of the editor is passed to the activated plugin
     * @param  {Object} activatePlugin Plugin to activate
     * @return {Object} this
     */
    Editor.prototype.use = function(activatePlugin) {
      activatePlugin(this);
      return this;
    };

    return Editor;
});
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * Base class for ScreenViews in this sim.
 * Responsible for creating Nodes that are common to all screens, and for common layout.
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' );
  const GraphContentsToggleButton = require( 'GRAPHING_LINES/common/view/GraphContentsToggleButton' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const Node = require( 'SCENERY/nodes/Node' );
  const PointToolNode = require( 'GRAPHING_QUADRATICS/common/view/PointToolNode' );
  const ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  const ScreenView = require( 'JOIST/ScreenView' );
  const Tandem = require( 'TANDEM/Tandem' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  // constants
  const X_SPACING = 15; // between graph and control panels

  class GQScreenView extends ScreenView {

    /**
     * @param {GQModel} model
     * @param {GQViewProperties} viewProperties
     * @param {Node} graphNode
     * @param {Node} equationAccordionBox
     * @param {Node} graphControlPanel
     * @param {Object} [options]
     */
    constructor( model, viewProperties, graphNode, equationAccordionBox, graphControlPanel, options ) {

      options = _.extend( {

        // ScreenView options
        layoutBounds: GQConstants.SCREEN_VIEW_LAYOUT_BOUNDS,

        // phet-io
        tandem: Tandem.required
      }, options );

      super( options );

      // Point tools moveToFront when dragged, so give them a common parent to preserve rendering order.
      const pointToolsParent = new Node();
      pointToolsParent.addChild( new PointToolNode(
        model.leftPointTool,
        model.modelViewTransform,
        model.graph,
        viewProperties.graphContentsVisibleProperty, {
          tandem: options.tandem.createTandem( 'leftPointToolNode' ),
          phetioDocumentation: 'the point tool that is initially on the left'
        } ) );
      pointToolsParent.addChild( new PointToolNode(
        model.rightPointTool,
        model.modelViewTransform,
        model.graph,
        viewProperties.graphContentsVisibleProperty, {
          tandem: options.tandem.createTandem( 'rightPointToolNode' ),
          phetioDocumentation: 'the point tool that is initially on the right'
        } ) );

      // Toggle button for showing/hiding contents of graph
      const graphContentsToggleButton = new GraphContentsToggleButton( viewProperties.graphContentsVisibleProperty, {
        scale: 0.75,
        left: model.modelViewTransform.modelToViewX( model.graph.xRange.max ) + 21,
        bottom: model.modelViewTransform.modelToViewY( model.graph.yRange.min ),
        tandem: options.tandem.createTandem( 'graphContentsToggleButton' ),
        phetioDocumentation: 'button that shows/hides the contents of the graph',
        phetioComponentOptions: { visibleProperty: { phetioFeatured: true } }
      } );

      // Set maxWidth for each control panel individually
      const controlPanelMaxWidth = this.layoutBounds.width - graphNode.width - ( 2 * GQConstants.SCREEN_VIEW_X_MARGIN ) - X_SPACING;
      assert && assert( controlPanelMaxWidth > 0, 'unexpected controlPanelMaxWidth: ' + controlPanelMaxWidth );
      equationAccordionBox.maxWidth = controlPanelMaxWidth;
      graphControlPanel.maxWidth = controlPanelMaxWidth;

      // Parent for all control panels, to simplify layout
      const controlsParent = new VBox( {

        // set maxHeight to guard against font size differences across supported browsers
        maxHeight: this.layoutBounds.height - ( 2 * GQConstants.SCREEN_VIEW_Y_MARGIN ),
        resize: false,
        align: 'center',
        spacing: 10,
        children: [
          equationAccordionBox,
          graphControlPanel
        ]
      } );

      // rendering order
      this.addChild( controlsParent );
      this.addChild( graphContentsToggleButton );
      this.addChild( graphNode );
      this.addChild( pointToolsParent );

      // Horizontally center controls in the space to the right of the graph.
      controlsParent.centerX = graphNode.right + X_SPACING + ( controlPanelMaxWidth / 2 );
      controlsParent.top = GQConstants.SCREEN_VIEW_Y_MARGIN;

      // Reset All Button
      const resetAllButton = new ResetAllButton( {
        listener: () => {
          this.interruptSubtreeInput(); // interrupt all listeners for this screen
          model.reset();
          viewProperties.reset();
        },
        right: this.layoutBounds.maxX - GQConstants.SCREEN_VIEW_X_MARGIN,
        bottom: this.layoutBounds.maxY - GQConstants.SCREEN_VIEW_Y_MARGIN,
        tandem: options.tandem.createTandem( 'resetAllButton' ),
        phetioDocumentation: 'button that resets the screen to its initial state',
        phetioComponentOptions: { visibleProperty: { phetioFeatured: true } }
      } );
      this.addChild( resetAllButton );
    }
  }

  return graphingQuadratics.register( 'GQScreenView', GQScreenView );
} );
<commit_msg>remove phetioFeatured:true from graph content toggle button, because it's the default, #112<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * Base class for ScreenViews in this sim.
 * Responsible for creating Nodes that are common to all screens, and for common layout.
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' );
  const GraphContentsToggleButton = require( 'GRAPHING_LINES/common/view/GraphContentsToggleButton' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const Node = require( 'SCENERY/nodes/Node' );
  const PointToolNode = require( 'GRAPHING_QUADRATICS/common/view/PointToolNode' );
  const ResetAllButton = require( 'SCENERY_PHET/buttons/ResetAllButton' );
  const ScreenView = require( 'JOIST/ScreenView' );
  const Tandem = require( 'TANDEM/Tandem' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  // constants
  const X_SPACING = 15; // between graph and control panels

  class GQScreenView extends ScreenView {

    /**
     * @param {GQModel} model
     * @param {GQViewProperties} viewProperties
     * @param {Node} graphNode
     * @param {Node} equationAccordionBox
     * @param {Node} graphControlPanel
     * @param {Object} [options]
     */
    constructor( model, viewProperties, graphNode, equationAccordionBox, graphControlPanel, options ) {

      options = _.extend( {

        // ScreenView options
        layoutBounds: GQConstants.SCREEN_VIEW_LAYOUT_BOUNDS,

        // phet-io
        tandem: Tandem.required
      }, options );

      super( options );

      // Point tools moveToFront when dragged, so give them a common parent to preserve rendering order.
      const pointToolsParent = new Node();
      pointToolsParent.addChild( new PointToolNode(
        model.leftPointTool,
        model.modelViewTransform,
        model.graph,
        viewProperties.graphContentsVisibleProperty, {
          tandem: options.tandem.createTandem( 'leftPointToolNode' ),
          phetioDocumentation: 'the point tool that is initially on the left'
        } ) );
      pointToolsParent.addChild( new PointToolNode(
        model.rightPointTool,
        model.modelViewTransform,
        model.graph,
        viewProperties.graphContentsVisibleProperty, {
          tandem: options.tandem.createTandem( 'rightPointToolNode' ),
          phetioDocumentation: 'the point tool that is initially on the right'
        } ) );

      // Toggle button for showing/hiding contents of graph
      const graphContentsToggleButton = new GraphContentsToggleButton( viewProperties.graphContentsVisibleProperty, {
        scale: 0.75,
        left: model.modelViewTransform.modelToViewX( model.graph.xRange.max ) + 21,
        bottom: model.modelViewTransform.modelToViewY( model.graph.yRange.min ),
        tandem: options.tandem.createTandem( 'graphContentsToggleButton' ),
        phetioDocumentation: 'button that shows/hides the contents of the graph'
      } );

      // Set maxWidth for each control panel individually
      const controlPanelMaxWidth = this.layoutBounds.width - graphNode.width - ( 2 * GQConstants.SCREEN_VIEW_X_MARGIN ) - X_SPACING;
      assert && assert( controlPanelMaxWidth > 0, 'unexpected controlPanelMaxWidth: ' + controlPanelMaxWidth );
      equationAccordionBox.maxWidth = controlPanelMaxWidth;
      graphControlPanel.maxWidth = controlPanelMaxWidth;

      // Parent for all control panels, to simplify layout
      const controlsParent = new VBox( {

        // set maxHeight to guard against font size differences across supported browsers
        maxHeight: this.layoutBounds.height - ( 2 * GQConstants.SCREEN_VIEW_Y_MARGIN ),
        resize: false,
        align: 'center',
        spacing: 10,
        children: [
          equationAccordionBox,
          graphControlPanel
        ]
      } );

      // rendering order
      this.addChild( controlsParent );
      this.addChild( graphContentsToggleButton );
      this.addChild( graphNode );
      this.addChild( pointToolsParent );

      // Horizontally center controls in the space to the right of the graph.
      controlsParent.centerX = graphNode.right + X_SPACING + ( controlPanelMaxWidth / 2 );
      controlsParent.top = GQConstants.SCREEN_VIEW_Y_MARGIN;

      // Reset All Button
      const resetAllButton = new ResetAllButton( {
        listener: () => {
          this.interruptSubtreeInput(); // interrupt all listeners for this screen
          model.reset();
          viewProperties.reset();
        },
        right: this.layoutBounds.maxX - GQConstants.SCREEN_VIEW_X_MARGIN,
        bottom: this.layoutBounds.maxY - GQConstants.SCREEN_VIEW_Y_MARGIN,
        tandem: options.tandem.createTandem( 'resetAllButton' ),
        phetioDocumentation: 'button that resets the screen to its initial state',
        phetioComponentOptions: { visibleProperty: { phetioFeatured: true } }
      } );
      this.addChild( resetAllButton );
    }
  }

  return graphingQuadratics.register( 'GQScreenView', GQScreenView );
} );
<|endoftext|>


<commit_before>import ThreeSixtyViewer from './three-sixty-viewer';
import THREE from 'threejs360';

export default class Audio extends ThreeSixtyViewer {
  constructor(options) {
    super(options);
  }

  play() {
    this.driver.play();
  }

  pause() {
    this.driver.pause();
  }

  getElement() {
    if (this.source && this.source.tagName) {
      this.driver = this.source;
    } else {
      this.driver = document.createElement('audio');
      this.driver.src = this.source;
      this.driver.loop = this.loop || false;
      this.driver.muted = this.muted || false;
      this.driver.setAttribute('crossorigin', 'anonymous');
      this.driver.autoplay = this.autoplay || true;
    }
    let video = document.createElement('video');
    video.src = this.driver.src;
    video.setAttribute('crossorigin', 'anonymous');
    video.addEventListener('error', this.onError);
    video.load();
    return video;
  }

  createTexture() {
    let texture = new THREE.VideoTexture(this.element);
    //TODO: we can pass all this info through the constructor
    texture.minFilter = THREE.LinearFilter;
    texture.magFilter = THREE.LinearFilter;
    texture.format = THREE.RGBFormat;
    texture.generateMipmaps = false;
    texture.needsUpdate = true;
    return texture;
  }

  destroy() {
    this.driver.style.display = '';
    super.destroy();
  }

  render() {
    this.target.appendChild(this.renderer.el);
    this.element.style.display = 'none';
    this.driver.style.display = 'none';
    let loop = () => {
      let cameraUpdated = this.controls.update();
      this.renderer.render(this.scene, this.camera, this.needsUpdate || cameraUpdated);
      if (this.element.readyState === 4) {
        this.element.currentTime = this.driver.currentTime;
      }
      this.animationFrameId = requestAnimationFrame(loop);
    };
    this.startVideoLoop();
    loop();
  }
}
<commit_msg>set needsToUpdate to false after rendering video frame on the audio driver<commit_after>import ThreeSixtyViewer from './three-sixty-viewer';
import THREE from 'threejs360';

export default class Audio extends ThreeSixtyViewer {
  constructor(options) {
    super(options);
  }

  play() {
    this.driver.play();
  }

  pause() {
    this.driver.pause();
  }

  getElement() {
    if (this.source && this.source.tagName) {
      this.driver = this.source;
    } else {
      this.driver = document.createElement('audio');
      this.driver.src = this.source;
      this.driver.loop = this.loop || false;
      this.driver.muted = this.muted || false;
      this.driver.setAttribute('crossorigin', 'anonymous');
      this.driver.autoplay = this.autoplay || true;
    }
    let video = document.createElement('video');
    video.src = this.driver.src;
    video.setAttribute('crossorigin', 'anonymous');
    video.addEventListener('error', this.onError);
    video.load();
    return video;
  }

  createTexture() {
    let texture = new THREE.VideoTexture(this.element);
    //TODO: we can pass all this info through the constructor
    texture.minFilter = THREE.LinearFilter;
    texture.magFilter = THREE.LinearFilter;
    texture.format = THREE.RGBFormat;
    texture.generateMipmaps = false;
    texture.needsUpdate = true;
    return texture;
  }

  destroy() {
    this.driver.style.display = '';
    super.destroy();
  }

  render() {
    this.target.appendChild(this.renderer.el);
    this.element.style.display = 'none';
    this.driver.style.display = 'none';
    let loop = () => {
      let cameraUpdated = this.controls.update();
      this.renderer.render(this.scene, this.camera, this.needsUpdate || cameraUpdated);
      this.needsUpdate = false;
      if (this.element.readyState === 4) {
        this.element.currentTime = this.driver.currentTime;
      }
      this.animationFrameId = requestAnimationFrame(loop);
    };
    this.startVideoLoop();
    loop();
  }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const Immutable = require('immutable')
const ImmutableComponent = require('./immutableComponent')

const cx = require('../lib/classSet')
const Button = require('./button')
const UrlBar = require('./urlBar')
const windowActions = require('../actions/windowActions')
const siteTags = require('../constants/siteTags')
const messages = require('../constants/messages')
const settings = require('../constants/settings')
const ipc = global.require('electron').ipcRenderer
const {isSourceAboutUrl} = require('../lib/appUrlUtil')
const siteUtil = require('../state/siteUtil')
const eventUtil = require('../lib/eventUtil')
const getSetting = require('../settings').getSetting
const windowStore = require('../stores/windowStore')

class NavigationBar extends ImmutableComponent {
  constructor () {
    super()
    this.onToggleBookmark = this.onToggleBookmark.bind(this)
    this.onStop = this.onStop.bind(this)
    this.onReload = this.onReload.bind(this)
    this.onNoScript = this.onNoScript.bind(this)
  }

  get activeFrame () {
    return windowStore.getFrame(this.props.activeFrameKey)
  }

  get loading () {
    return this.props.activeFrameKey !== undefined && this.props.loading
  }

  onToggleBookmark () {
    // trigger the AddEditBookmark modal; saving/deleting takes place there
    const siteDetail = siteUtil.getDetailFromFrame(this.activeFrame, siteTags.BOOKMARK)
    windowActions.setBookmarkDetail(siteDetail, siteDetail)
  }

  onReload (e) {
    if (eventUtil.isForSecondaryAction(e)) {
      ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_CLONE, {}, { openInForeground: !!e.shiftKey })
    } else {
      ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_RELOAD)
    }
  }

  onHome () {
    getSetting(settings.HOMEPAGE).split('|')
      .forEach((homepage, i) => {
        ipc.emit(i === 0 ? messages.SHORTCUT_ACTIVE_FRAME_LOAD_URL : messages.SHORTCUT_NEW_FRAME, {}, homepage)
      })
  }

  onStop () {
    ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_STOP)
  }

  get bookmarked () {
    return this.props.activeFrameKey !== undefined &&
      siteUtil.isSiteBookmarked(this.props.sites, Immutable.fromJS({
        location: this.props.location,
        partitionNumber: this.props.partitionNumber,
        title: this.props.title
      }))
  }

  get titleMode () {
    return this.props.mouseInTitlebar === false &&
      this.props.title &&
      !['about:blank', 'about:newtab'].includes(this.props.location) &&
      !this.loading &&
      !this.props.navbar.getIn(['urlbar', 'focused']) &&
      !this.props.navbar.getIn(['urlbar', 'active']) &&
      getSetting(settings.DISABLE_TITLE_MODE) === false
  }

  componentDidMount () {
    ipc.on(messages.SHORTCUT_ACTIVE_FRAME_BOOKMARK, () => this.onToggleBookmark())
    ipc.on(messages.SHORTCUT_ACTIVE_FRAME_REMOVE_BOOKMARK, () => this.onToggleBookmark())
  }

  get showNoScriptInfo () {
    return this.props.enableNoScript && this.props.scriptsBlocked && this.props.scriptsBlocked.size
  }

  onNoScript () {
    windowActions.setNoScriptVisible(!this.props.noScriptIsVisible)
  }

  componentDidUpdate (prevProps) {
    if (this.props.noScriptIsVisible && !this.showNoScriptInfo) {
      // There are no blocked scripts, so hide the noscript dialog.
      windowActions.setNoScriptVisible(false)
    }
  }

  render () {
    if (this.props.activeFrameKey === undefined) {
      return null
    }

    return

        {
          isSourceAboutUrl(this.props.location) || this.titleMode
          ?
          : this.loading
            ? <Button iconClass='fa-times'
              l10nId='reloadButton'
              className='navbutton stop-button'
              onClick={this.onStop} />
            : <Button iconClass='fa-repeat'
              l10nId='reloadButton'
              className='navbutton reload-button'
              onClick={this.onReload} />
        }
        {
          !this.titleMode && getSetting(settings.SHOW_HOME_BUTTON)
          ? <Button iconClass='fa-home'
            l10nId='homeButton'
            className='navbutton homeButton'
            onClick={this.onHome} />
          : null
        }

      <UrlBar ref='urlBar'
        sites={this.props.sites}
        activeFrameKey={this.props.activeFrameKey}
        searchDetail={this.props.searchDetail}
        loading={this.loading}
        location={this.props.location}
        suggestionIndex={this.props.suggestionIndex}
        title={this.props.title}
        history={this.props.history}
        isSecure={this.props.isSecure}
        locationValueSuffix={this.props.locationValueSuffix}
        startLoadTime={this.props.startLoadTime}
        endLoadTime={this.props.endLoadTime}
        titleMode={this.titleMode}
        urlbar={this.props.navbar.get('urlbar')}
        />
      {
        isSourceAboutUrl(this.props.location)
        ?

        :

          {
            !this.showNoScriptInfo
            ? null
            : <Button iconClass='fa-ban'
              l10nId='noScriptButton'
              className={cx({
                'noScript': true
              })}
              onClick={this.onNoScript} />
          }
          <Button iconClass={this.bookmarked ? 'fa-star' : 'fa-star-o'}
            className={cx({
              navbutton: true,
              bookmarkButton: true,
              removeBookmarkButton: this.bookmarked
            })}
            l10nId={this.bookmarked ? 'removeBookmarkButton' : 'addBookmarkButton'}
            onClick={this.onToggleBookmark} />

      }

  }
}

module.exports = NavigationBar
<commit_msg>fix l10n of stopButton<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const Immutable = require('immutable')
const ImmutableComponent = require('./immutableComponent')

const cx = require('../lib/classSet')
const Button = require('./button')
const UrlBar = require('./urlBar')
const windowActions = require('../actions/windowActions')
const siteTags = require('../constants/siteTags')
const messages = require('../constants/messages')
const settings = require('../constants/settings')
const ipc = global.require('electron').ipcRenderer
const {isSourceAboutUrl} = require('../lib/appUrlUtil')
const siteUtil = require('../state/siteUtil')
const eventUtil = require('../lib/eventUtil')
const getSetting = require('../settings').getSetting
const windowStore = require('../stores/windowStore')

class NavigationBar extends ImmutableComponent {
  constructor () {
    super()
    this.onToggleBookmark = this.onToggleBookmark.bind(this)
    this.onStop = this.onStop.bind(this)
    this.onReload = this.onReload.bind(this)
    this.onNoScript = this.onNoScript.bind(this)
  }

  get activeFrame () {
    return windowStore.getFrame(this.props.activeFrameKey)
  }

  get loading () {
    return this.props.activeFrameKey !== undefined && this.props.loading
  }

  onToggleBookmark () {
    // trigger the AddEditBookmark modal; saving/deleting takes place there
    const siteDetail = siteUtil.getDetailFromFrame(this.activeFrame, siteTags.BOOKMARK)
    windowActions.setBookmarkDetail(siteDetail, siteDetail)
  }

  onReload (e) {
    if (eventUtil.isForSecondaryAction(e)) {
      ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_CLONE, {}, { openInForeground: !!e.shiftKey })
    } else {
      ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_RELOAD)
    }
  }

  onHome () {
    getSetting(settings.HOMEPAGE).split('|')
      .forEach((homepage, i) => {
        ipc.emit(i === 0 ? messages.SHORTCUT_ACTIVE_FRAME_LOAD_URL : messages.SHORTCUT_NEW_FRAME, {}, homepage)
      })
  }

  onStop () {
    ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_STOP)
  }

  get bookmarked () {
    return this.props.activeFrameKey !== undefined &&
      siteUtil.isSiteBookmarked(this.props.sites, Immutable.fromJS({
        location: this.props.location,
        partitionNumber: this.props.partitionNumber,
        title: this.props.title
      }))
  }

  get titleMode () {
    return this.props.mouseInTitlebar === false &&
      this.props.title &&
      !['about:blank', 'about:newtab'].includes(this.props.location) &&
      !this.loading &&
      !this.props.navbar.getIn(['urlbar', 'focused']) &&
      !this.props.navbar.getIn(['urlbar', 'active']) &&
      getSetting(settings.DISABLE_TITLE_MODE) === false
  }

  componentDidMount () {
    ipc.on(messages.SHORTCUT_ACTIVE_FRAME_BOOKMARK, () => this.onToggleBookmark())
    ipc.on(messages.SHORTCUT_ACTIVE_FRAME_REMOVE_BOOKMARK, () => this.onToggleBookmark())
  }

  get showNoScriptInfo () {
    return this.props.enableNoScript && this.props.scriptsBlocked && this.props.scriptsBlocked.size
  }

  onNoScript () {
    windowActions.setNoScriptVisible(!this.props.noScriptIsVisible)
  }

  componentDidUpdate (prevProps) {
    if (this.props.noScriptIsVisible && !this.showNoScriptInfo) {
      // There are no blocked scripts, so hide the noscript dialog.
      windowActions.setNoScriptVisible(false)
    }
  }

  render () {
    if (this.props.activeFrameKey === undefined) {
      return null
    }

    return

        {
          isSourceAboutUrl(this.props.location) || this.titleMode
          ?
          : this.loading
            ? <Button iconClass='fa-times'
              l10nId='stopButton'
              className='navbutton stop-button'
              onClick={this.onStop} />
            : <Button iconClass='fa-repeat'
              l10nId='reloadButton'
              className='navbutton reload-button'
              onClick={this.onReload} />
        }
        {
          !this.titleMode && getSetting(settings.SHOW_HOME_BUTTON)
          ? <Button iconClass='fa-home'
            l10nId='homeButton'
            className='navbutton homeButton'
            onClick={this.onHome} />
          : null
        }

      <UrlBar ref='urlBar'
        sites={this.props.sites}
        activeFrameKey={this.props.activeFrameKey}
        searchDetail={this.props.searchDetail}
        loading={this.loading}
        location={this.props.location}
        suggestionIndex={this.props.suggestionIndex}
        title={this.props.title}
        history={this.props.history}
        isSecure={this.props.isSecure}
        locationValueSuffix={this.props.locationValueSuffix}
        startLoadTime={this.props.startLoadTime}
        endLoadTime={this.props.endLoadTime}
        titleMode={this.titleMode}
        urlbar={this.props.navbar.get('urlbar')}
        />
      {
        isSourceAboutUrl(this.props.location)
        ?

        :

          {
            !this.showNoScriptInfo
            ? null
            : <Button iconClass='fa-ban'
              l10nId='noScriptButton'
              className={cx({
                'noScript': true
              })}
              onClick={this.onNoScript} />
          }
          <Button iconClass={this.bookmarked ? 'fa-star' : 'fa-star-o'}
            className={cx({
              navbutton: true,
              bookmarkButton: true,
              removeBookmarkButton: this.bookmarked
            })}
            l10nId={this.bookmarked ? 'removeBookmarkButton' : 'addBookmarkButton'}
            onClick={this.onToggleBookmark} />

      }

  }
}

module.exports = NavigationBar
<|endoftext|>


<commit_before>
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Page change transition core
//>>label: Transition Core
//>>group: Transitions
//>>css: ../css/themes/default/jquery.mobile.theme.css, ../css/structure/jquery.mobile.transitions.css

define( [ "jquery", "./jquery.mobile.core" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {

var createHandler = function( sequential ){

	// Default to sequential
	if( sequential === undefined ){
		sequential = true;
	}

	return function( name, reverse, $to, $from ) {

		var deferred = new $.Deferred(),
			reverseClass = reverse ? " reverse" : "",
			active	= $.mobile.urlHistory.getActive(),
			toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
			screenHeight = $.mobile.getScreenHeight(),
			maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $( window ).width() > $.mobile.maxTransitionWidth,
			none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none",
			toggleViewportClass = function(){
				$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
			},
			cleanFrom = function(){
				$from
					.removeClass( $.mobile.activePageClass + " out in reverse " + name )
					.height( "" );
			},
			doneOut = function() {

				if ( $from && sequential ) {
					cleanFrom();
				}

				$to.addClass( $.mobile.activePageClass );

				if( !none ){
					$to.animationComplete( doneIn );
				}

				// Send focus to page as it is now display: block
				$.mobile.focusPage( $to );

				// Jump to top or prev scroll, sometimes on iOS the page has not rendered yet.
				$to.height( screenHeight + toScroll );

				$.mobile.silentScroll( toScroll );

				$to.addClass( name + " in" + reverseClass );

				if( none ){
					doneIn();
				}

			},

			doneIn = function() {

				if ( !sequential ) {

					$.mobile.silentScroll( toScroll );

					if( $from ){
						cleanFrom();
					}
				}

				$to
					.removeClass( "out in reverse " + name )
					.height( "" );

				toggleViewportClass();

				deferred.resolve( name, reverse, $to, $from, true );
			};

		toggleViewportClass();

		if ( $from && !none ) {

			// if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
			if( !sequential ){
				doneOut();
			}
			else {
				$from.animationComplete( doneOut );
			}

			$from
				.height( screenHeight + $(window ).scrollTop() )
				.addClass( name + " out" + reverseClass );
		}
		else {
			doneOut();
		}

		return deferred.promise();
	};
}

// generate the handlers from the above
var sequentialHandler = createHandler(),
	simultaneousHandler = createHandler( false );

// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;

//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
	"default": $.mobile.defaultTransitionHandler,
	"sequential": sequentialHandler,
	"simultaneous": simultaneousHandler
};

$.mobile.transitionFallbacks = {};

})( jQuery, this );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");<commit_msg>This works around an issue where iOS5 and maybe others fail to scroll to the desired location during a transition that uses 3D transforms.<commit_after>
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Page change transition core
//>>label: Transition Core
//>>group: Transitions
//>>css: ../css/themes/default/jquery.mobile.theme.css, ../css/structure/jquery.mobile.transitions.css

define( [ "jquery", "./jquery.mobile.core" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {

var createHandler = function( sequential ){

	// Default to sequential
	if( sequential === undefined ){
		sequential = true;
	}

	return function( name, reverse, $to, $from ) {

		var deferred = new $.Deferred(),
			reverseClass = reverse ? " reverse" : "",
			active	= $.mobile.urlHistory.getActive(),
			toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
			screenHeight = $.mobile.getScreenHeight(),
			maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $( window ).width() > $.mobile.maxTransitionWidth,
			none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none",
			toggleViewportClass = function(){
				$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
			},
			cleanFrom = function(){
				$from
					.removeClass( $.mobile.activePageClass + " out in reverse " + name )
					.height( "" );
			},
			doneOut = function() {

				if ( $from && sequential ) {
					cleanFrom();
				}

				$to.addClass( $.mobile.activePageClass );

				if( !none ){
					$to.animationComplete( doneIn );
				}

				// Send focus to page as it is now display: block
				$.mobile.focusPage( $to );

				// Jump to top or prev scroll, sometimes on iOS the page has not rendered yet.
				$to.height( screenHeight + toScroll );

				$.mobile.silentScroll( toScroll );

				$to.addClass( name + " in" + reverseClass );

				if( none ){
					doneIn();
				}

			},

			doneIn = function() {

				if ( !sequential ) {

					$.mobile.silentScroll( toScroll );

					if( $from ){
						cleanFrom();
					}
				}

				$to
					.removeClass( "out in reverse " + name )
					.height( "" );

				toggleViewportClass();

				// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
				// This ensures we jump to that spot after the fact, if we aren't there already.
				if( $( window ).scrollTop() !== toScroll ){
					$.mobile.silentScroll( toScroll );
				}

				deferred.resolve( name, reverse, $to, $from, true );
			};

		toggleViewportClass();

		if ( $from && !none ) {

			// if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
			if( !sequential ){
				doneOut();
			}
			else {
				$from.animationComplete( doneOut );
			}

			$from
				.height( screenHeight + $(window ).scrollTop() )
				.addClass( name + " out" + reverseClass );
		}
		else {
			doneOut();
		}

		return deferred.promise();
	};
}

// generate the handlers from the above
var sequentialHandler = createHandler(),
	simultaneousHandler = createHandler( false );

// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;

//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
	"default": $.mobile.defaultTransitionHandler,
	"sequential": sequentialHandler,
	"simultaneous": simultaneousHandler
};

$.mobile.transitionFallbacks = {};

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


<commit_before>/**
  * @desc Kendo Custom Plugin Selectable Grid
  * @author Triet Nguyen petertriet@gmail.com
  * @required jquery.min.js, kendo.web.min.js, kendo.custom.selectable.js
*/
(function (kendo, $) {
    var ExtGridSelectable = kendo.ui.Widget.extend({
        _grid: null,
        _gridID: null,
        _chkClass: null,
        _chkAllID: null,
        _selectedRow: null,

        init: function (element, options) {
            var that = this;

            kendo.ui.Widget.fn.init.call(that, element, options);
            that._gridID = "#" + $(element).attr('id');
            that._chkClass = "." + $(options.chkTemplate).attr('class');
            that._chkAllID = "#" + (options.chkAllID !== "" && options.chkAllID !== undefined ? options.chkAllID : $(options.chkAllTemplate).attr('id'));

            options.grid.columns.unshift({
                title: "",
                template: options.chkTemplate,
                headerTemplate: options.chkAllTemplate,
                attributes: {"class": "align-center"},
                width: "30px",
                sortable: false
            });

            options.grid.dataBound = that.databound;

            that._grid = $(element).kendoGrid(options.grid).data("kendoGrid");
            that._grid.thead.append(options.filterHeader);
            that._grid.bind("change", function (e) {
                $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", true);
            });

            $(that._gridID + " table tbody tr").on({click: function(e) {
                that._handleSingleClick(e);
            }});

            $(that._chkAllID).on({change:function(e){
                that._handleSelectAll();
            }});

			var pager = that._grid.pager.bind("change", function(){
				that._pageChange();
			});
        },
        _handleSingleClick: function (e) {
            var checkBox = e.target;
            var row = $(checkBox).parent().parent();
            var checkedAll = $(this._chkAllID).prop("checked");

            if($(checkBox).is("input[type=checkbox]")) {
                if($(checkBox).prop("checked")) {
                    $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", false);
                    var selected = this._grid.select();
					console.log(selected);
					$(selected).find(this._chkClass).prop("checked", true);
					this._grid.select(selected);
                } else {
					var count = $(this._selectedRow).size();
					console.log(count);
					if(count > 1){
						$(this._gridID + " table " + this._chkClass + ":checked").prop("checked", false);
						var selected = this._grid.select();
						$(selected).find(this._chkClass).prop("checked", true);
						this._grid.select(selected);
					} else {
						$(row).removeClass("k-state-selected").removeAttr("aria-selected");
					}
                }
            } else {
                var selected = this._grid.select();
                this._grid.clearSelection();
                if (checkedAll) {
                    $(this._chkAllID).prop("checked", false);
                    this._deselectRow(this._gridID + " tbody tr");
                    $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", true);
                } else {
                    $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", false);
                }

                this._grid.select(selected);
                selected.find(this._chkClass).prop("checked", true);
            }
			this._selectedRow = this._grid.select();
        },
        _handleSelectAll: function () {
			var checked = $(this._chkAllID).prop("checked");
			var row = $(this._gridID + " table tbody tr");
				if(checked){
					this._selectRow(row);
				} else {
					this._deselectRow(row);
				}
        },
        _handleSelectMultiRow: function (rowSelector) {
            if($(rowSelector).hasClass("selectedRow")) {
                this._deselectRow(rowSelector);
            } else {
                this._selectRow(rowSelector);
            }
        },
        _selectRow: function (rowSelector) {
            $(rowSelector).removeClass("k-state-selected");
            $(rowSelector).addClass("selectedRow");
            $(rowSelector).attr("aria-selected", true);
            if(this._chkClass !== "") {
                $(rowSelector).find(this._chkClass).prop("checked", true);
            }
        },
        _deselectRow: function (rowSelector) {
            $(rowSelector).removeClass("k-state-selected");
            $(rowSelector).removeClass("selectedRow");
            $(rowSelector).attr("aria-selected", false);
            if(this._chkClass !== "") {
                $(rowSelector).find(this._chkClass).prop("checked", false);
            }
        },
		_pageChange: function () {
			var that = this;
			$(that._chkAllID).prop("checked", false);
			$(that._gridID + " table tr").on({click: function(e) {
                that._handleSingleClick(e);
            }});
		},
        grid: function () {
            return this._grid;
        },
        options: {
            name: "ExtGridSelectable",
            filterHeader: "",
            chkTemplate: "",
            chkAllTemplate: "",
            chkAllID: "",
            selKendoClass: "",
            selRowClass: ""
        }
    });
    kendo.ui.plugin(ExtGridSelectable);
})(window.kendo, window.kendo.jQuery);<commit_msg>Update ext<commit_after>/**
  * @desc Kendo Custom Plugin Selectable Grid
  * @author Triet Nguyen petertriet@gmail.com
  * @required jquery.min.js, kendo.web.min.js, kendo.custom.selectable.js
*/
(function (kendo, $) {
    var ExtGridSelectable = kendo.ui.Widget.extend({
        _grid: null,
        _gridID: null,
        _chkClass: null,
        _chkAllID: null,
        _selectedRow: null,

        init: function (element, options) {
            var that = this;

            kendo.ui.Widget.fn.init.call(that, element, options);
            that._gridID = "#" + $(element).attr('id');
            that._chkClass = "." + $(options.chkTemplate).attr('class');
            that._chkAllID = "#" + (options.chkAllID !== "" && options.chkAllID !== undefined ? options.chkAllID : $(options.chkAllTemplate).attr('id'));

            options.grid.columns.unshift({
                title: "",
                template: options.chkTemplate,
                headerTemplate: options.chkAllTemplate,
                attributes: {"class": "align-center"},
                width: "30px",
                sortable: false
            });

            options.grid.dataBound = that.databound;

            that._grid = $(element).kendoGrid(options.grid).data("kendoGrid");
            that._grid.thead.append(options.filterHeader);
            that._grid.bind("change", function (e) {
                $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", true);
            });

            $(that._gridID + " table tbody tr").on({click: function(e) {
                that._handleSingleClick(e);
            }});

            $(that._chkAllID).on({change:function(e){
                that._handleSelectAll();
            }});

			that._grid.pager.bind("change", function(){
				that._pageChange();
			});
        },
        _handleSingleClick: function (e) {
            var checkBox = e.target;
            var row = $(checkBox).parent().parent();
            var checkedAll = $(this._chkAllID).prop("checked");

            if($(checkBox).is("input[type=checkbox]")) {
                if($(checkBox).prop("checked")) {
                    $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", false);
                    var selected = this._grid.select();
					console.log(selected);
					$(selected).find(this._chkClass).prop("checked", true);
					this._grid.select(selected);
                } else {
					var count = $(this._selectedRow).size();
					console.log(count);
					if(count > 1){
						$(this._gridID + " table " + this._chkClass + ":checked").prop("checked", false);
						var selected = this._grid.select();
						$(selected).find(this._chkClass).prop("checked", true);
						this._grid.select(selected);
					} else {
						$(row).removeClass("k-state-selected").removeAttr("aria-selected");
					}
                }
            } else {
                var selected = this._grid.select();
                this._grid.clearSelection();
                if (checkedAll) {
                    $(this._chkAllID).prop("checked", false);
                    this._deselectRow(this._gridID + " tbody tr");
                    $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", true);
                } else {
                    $(this._gridID + " table " + this._chkClass + ":checked").prop("checked", false);
                }

                this._grid.select(selected);
                selected.find(this._chkClass).prop("checked", true);
            }
			this._selectedRow = this._grid.select();
        },
        _handleSelectAll: function () {
			var checked = $(this._chkAllID).prop("checked");
			var row = $(this._gridID + " table tbody tr");
			if(checked){
				this._selectRow(row);
			} else {
				this._deselectRow(row);
			}
        },
        _handleSelectMultiRow: function (rowSelector) {
            if($(rowSelector).hasClass("selectedRow")) {
                this._deselectRow(rowSelector);
            } else {
                this._selectRow(rowSelector);
            }
        },
        _selectRow: function (rowSelector) {
            $(rowSelector).removeClass("k-state-selected");
            $(rowSelector).addClass("selectedRow");
            $(rowSelector).attr("aria-selected", true);
            if(this._chkClass !== "") {
                $(rowSelector).find(this._chkClass).prop("checked", true);
            }
        },
        _deselectRow: function (rowSelector) {
            $(rowSelector).removeClass("k-state-selected");
            $(rowSelector).removeClass("selectedRow");
            $(rowSelector).attr("aria-selected", false);
            if(this._chkClass !== "") {
                $(rowSelector).find(this._chkClass).prop("checked", false);
            }
        },
		_pageChange: function () {
			var that = this;
			$(that._chkAllID).prop("checked", false);
			$(that._gridID + " table tr").on({click: function(e) {
                that._handleSingleClick(e);
            }});
		},
        grid: function () {
            return this._grid;
        },
        options: {
            name: "ExtGridSelectable",
            filterHeader: "",
            chkTemplate: "",
            chkAllTemplate: "",
            chkAllID: "",
            selKendoClass: "",
            selRowClass: ""
        }
    });
    kendo.ui.plugin(ExtGridSelectable);
})(window.kendo, window.kendo.jQuery);<|endoftext|>


<commit_before>"use strict";

(function(){

	// Copy the next n bytes, unmodified
	var VERBATIM = 'v';
	// Repeat the next byte n times
	var REPEAT = 'r';
	// Skip the next n bytes
	var SKIP = 's';
	// End this frame
	var END = 'e';

	var MAX_RLE_LENGTH = 64;

	function DeltaRleTileEncoder() {
	}

	DeltaRleTileEncoder.prototype = _.extend(new TileSetEncoders.BaseEncoder(), {
		getName: function() {
			return "Tile bank plus tile streaming plus map delta";
		},

		doEncoding: function(converted, originalVideo) {
			converted.format = 'TILEBANK_DELTAMAPVH';

			var firstStepEncoding = new TileSetEncoders.TileBankTileEncoder().encode(originalVideo);
			converted.tileBank = firstStepEncoding.tileBank.slice();

			function flattenMap(map) {
				var flattened = _.flatten(map);
				return {
					tiles: flattened.map(function(cell){
						// The tiles array will only contain the bottom 8 bits of the tile number
						return {
							n: cell.n & 0xFF
						};
					}),

					attrs: flattened.map(function(cell){
						var attrs = _.pick(cell, 'v', 'h', 'i');
						// Tells if the 9th bit of the tile number is on
						if (cell.n & 0x100) {
							attrs.s = 1;
						}
						return attrs;
					})
				}
			}

			var prevMapState = flattenMap(_.times(originalVideo.tileCountX * originalVideo.tileCountY, _.constant({n: 0})));

			function encodeDeltaRle(previous, current) {
				var commands = [];

				var pos = 0;
				while (pos < current.length) {
					// Checks how many tiles haven't changed since last frame

					var unchangedPos = pos;
					while (unchangedPos < current.length &&
							_.isEqual(previous[unchangedPos], current[unchangedPos])) {
						unchangedPos++;
					}

					if (unchangedPos >= current.length) {
						commands.push({
							c: END
						});
						pos = unchangedPos;

						continue;
					} else if (unchangedPos > pos) {
						var len = Math.min(unchangedPos - pos, MAX_RLE_LENGTH);
						commands.push({
							c: SKIP,
							l: len
						});
						pos += len;

						continue;
					}

					// Checks for repeated tiles

					var repeatedPos = pos;
					while (repeatedPos < current.length && repeatedPos - pos < MAX_RLE_LENGTH &&
							_.isEqual(current[pos], current[repeatedPos])) {
						repeatedPos++;
					}

					var len = repeatedPos - pos;
					if (len > 1) {
						commands.push({
							c: REPEAT,
							l: len
						});
						pos += len;

						continue;
					}

					// Checks for non-repeated tiles

					var verbatimPos = pos + 1;
					while (verbatimPos < current.length && verbatimPos - pos < MAX_RLE_LENGTH &&
							!_.isEqual(previous[verbatimPos], current[verbatimPos]) &&
							!_.isEqual(current[verbatimPos - 1], current[verbatimPos])) {
						verbatimPos++;
					}

					var len = verbatimPos - pos;
					commands.push({
						c: VERBATIM,
						l: len
					});

					while (pos != verbatimPos) {
						commands.push(current[pos]);
						pos++;
					}
				}

				// Always add a 'end' command, if it isn't there already.
				if (_.last(commands).c !== END) {
					commands.push({
						c: END
					});
				}

				return commands;
			}

			converted.frames = firstStepEncoding.frames.map(function(origFrame){
				var destFrame = _.omit(origFrame, 'map');

				var mapState = flattenMap(origFrame.map);
				destFrame.map = {
					tiles: encodeDeltaRle(prevMapState.tiles, mapState.tiles),
					attrs: encodeDeltaRle(prevMapState.attrs, mapState.attrs)
				};
				prevMapState = mapState;

				return destFrame;
			});
		},

		stats: function(converted) {
			function add(a, b) {
				return a + b;
			}

			function sumLengths(array, attrName) {
				return _.chain(array).pluck(attrName).compact().pluck('length').reduce(add, 0).value();
			}

			var tileCounts = _.chain(converted.frames).map(function(f){ return (f.tilesFromBank || []).length + (f.tilesToStream || []).length }).value();

			var stats = {
				frameCount: converted.frames.length,
				maxTilesToLoadPerFrame: _.max(tileCounts),
				avgTilesToLoadPerFrame: Math.round(tileCounts.reduce(add, 0) / converted.frames.length),
				totalTileLoadsFromBank: sumLengths(converted.frames, 'tilesFromBank'),
				totalTilesToStream: sumLengths(converted.frames, 'tilesToStream'),
				encodedMapBytes: _.chain(converted.frames).map(function(f){ return f.map.tiles.length + f.map.attrs.length }).reduce(add, 0).value()
			};

			stats.estimatedMaximumSize = converted.tileBank.length * 8 + // Supposes there's no compression
					stats.totalTileLoadsFromBank * (2 + 2) + // Tile # from bank + VRAM tile #
					stats.totalTilesToStream * (8 + 2) + // Tile data (8 bytes) + VRAM tile #
					stats.encodedMapBytes; // Delta RLE encoded maps

			return stats;
		}
	});

	window.TileSetEncoders.register('DeltaRleTileEncoder', DeltaRleTileEncoder);

})();<commit_msg>Fixed RLE bug and added support for length > 64<commit_after>"use strict";

(function(){

	// Copy the next n bytes, unmodified
	var VERBATIM = 'v';
	// Repeat the next byte n times
	var REPEAT = 'r';
	// Skip the next n bytes
	var SKIP = 's';
	// Sets the top bits of the length of the next command
	var BOOST_LENGTH = 'b';
	// End this frame
	var END = 'e';

	var MAX_RLE_LENGTH = 64;

	function DeltaRleTileEncoder() {
	}

	DeltaRleTileEncoder.prototype = _.extend(new TileSetEncoders.BaseEncoder(), {
		getName: function() {
			return "Tile bank plus tile streaming plus map delta";
		},

		doEncoding: function(converted, originalVideo) {
			converted.format = 'TILEBANK_DELTAMAPVH';

			var firstStepEncoding = new TileSetEncoders.TileBankTileEncoder().encode(originalVideo);
			converted.tileBank = firstStepEncoding.tileBank.slice();

			function flattenMap(map) {
				var flattened = _.flatten(map);
				return {
					tiles: flattened.map(function(cell){
						// The tiles array will only contain the bottom 8 bits of the tile number
						return {
							n: cell.n & 0xFF
						};
					}),

					attrs: flattened.map(function(cell){
						var attrs = _.pick(cell, 'v', 'h', 'i');
						// Tells if the 9th bit of the tile number is on
						if (cell.n & 0x100) {
							attrs.t = 1;
						}
						return attrs;
					})
				}
			}

			var prevMapState = flattenMap(_.times(originalVideo.tileCountX * originalVideo.tileCountY, _.constant({n: 0})));

			function encodeDeltaRle(previous, current) {
				var commands = [];

				function addCommand(command, len) {
					if (len > MAX_RLE_LENGTH) {
						commands.push({
							c: BOOST_LENGTH,
							l: Math.floor(len / MAX_RLE_LENGTH)
						});
					}
					commands.push({
						c: command,
						l: len % MAX_RLE_LENGTH
					});
				}

				var pos = 0;
				while (pos < current.length) {
					// Checks how many tiles haven't changed since last frame

					var unchangedPos = pos;
					while (unchangedPos < current.length &&
							_.isEqual(previous[unchangedPos], current[unchangedPos])) {
						unchangedPos++;
					}

					if (unchangedPos >= current.length) {
						commands.push({
							c: END
						});
						pos = unchangedPos;

						continue;
					} else if (unchangedPos > pos) {
						var len = unchangedPos - pos;
						addCommand(SKIP, len);
						pos += len;

						continue;
					}

					// Checks for repeated tiles

					var repeatedPos = pos;
					while (repeatedPos < current.length &&
							_.isEqual(current[pos], current[repeatedPos])) {
						repeatedPos++;
					}

					var len = repeatedPos - pos;
					if (len > 1) {
						addCommand(REPEAT, len);
						commands.push(current[pos]);
						pos += len;

						continue;
					}

					// Checks for non-repeated tiles

					var verbatimPos = pos + 1;
					while (verbatimPos < current.length &&
							!_.isEqual(previous[verbatimPos], current[verbatimPos]) &&
							!_.isEqual(current[verbatimPos - 1], current[verbatimPos])) {
						verbatimPos++;
					}

					var len = verbatimPos - pos;
					addCommand(VERBATIM, len);
					while (pos != verbatimPos) {
						commands.push(current[pos]);
						pos++;
					}
				}

				// Always add a 'end' command, if it isn't there already.
				if (_.last(commands).c !== END) {
					commands.push({
						c: END
					});
				}

				return commands;
			}

			converted.frames = firstStepEncoding.frames.map(function(origFrame){
				var destFrame = _.omit(origFrame, 'map');

				var mapState = flattenMap(origFrame.map);
				destFrame.map = {
					tiles: encodeDeltaRle(prevMapState.tiles, mapState.tiles),
					attrs: encodeDeltaRle(prevMapState.attrs, mapState.attrs)
				};
				prevMapState = mapState;

				return destFrame;
			});
		},

		stats: function(converted) {
			function add(a, b) {
				return a + b;
			}

			function sumLengths(array, attrName) {
				return _.chain(array).pluck(attrName).compact().pluck('length').reduce(add, 0).value();
			}

			var tileCounts = _.chain(converted.frames).map(function(f){ return (f.tilesFromBank || []).length + (f.tilesToStream || []).length }).value();

			var stats = {
				frameCount: converted.frames.length,
				maxTilesToLoadPerFrame: _.max(tileCounts),
				avgTilesToLoadPerFrame: Math.round(tileCounts.reduce(add, 0) / converted.frames.length),
				totalTileLoadsFromBank: sumLengths(converted.frames, 'tilesFromBank'),
				totalTilesToStream: sumLengths(converted.frames, 'tilesToStream'),
				encodedMapBytes: _.chain(converted.frames).map(function(f){ return f.map.tiles.length + f.map.attrs.length }).reduce(add, 0).value()
			};

			stats.estimatedMaximumSize = converted.tileBank.length * 8 + // Supposes there's no compression
					stats.totalTileLoadsFromBank * (2 + 2) + // Tile # from bank + VRAM tile #
					stats.totalTilesToStream * (8 + 2) + // Tile data (8 bytes) + VRAM tile #
					stats.encodedMapBytes; // Delta RLE encoded maps

			return stats;
		}
	});

	window.TileSetEncoders.register('DeltaRleTileEncoder', DeltaRleTileEncoder);

})();<|endoftext|>


<commit_before>/**
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 *
 * Mail
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

define(function() {
	'use strict';

	var smileys = [
		':-(',
		':-/',
		':-\\',
		':-|',
		':\'-(',
		':\'-/',
		':\'-\\',
		':\'-|'
	];

	function getRandomSmiley() {
		return smileys[Math.floor(Math.random() * smileys.length)]
	}

	/**
	 * @param {Folder} folder
	 * @returns {string}
	 */
	function getRandomFolderErrorMessage(folder) {
		var folderName = folder.get('name');
		var rawTexts = [
			t('mail', 'Could not load {tag}{name}{endtag}', {
				name: folderName
			}),
			t('mail', 'Couldn\x27t load {tag}{name}{endtag}', {
				name: folderName
			}),
			t('mail', 'There was a problem loading {tag}{name}{endtag}', {
				name: folderName
			})
		];
		var texts = _.map(rawTexts, function(text) {
			return text.replace('{tag}', '').replace('{endtag}', '');
		});
		var text = texts[Math.floor(Math.random() * texts.length)]
		return text + ' ' + getRandomSmiley();
	}

	/**
	 * @returns {string}
	 */
	function getRandomMessageErrorMessage() {
		var texts = [
			t('mail', 'Couldn\x27t load your message'),
			t('mail', 'Could not load the desired message'),
			t('mail', 'Could not load the message')
		];
		var text = texts[Math.floor(Math.random() * texts.length)]
		return text + ' ' + getRandomSmiley();
	}

	return {
		getRandomFolderErrorMessage: getRandomFolderErrorMessage,
		getRandomMessageErrorMessage: getRandomMessageErrorMessage
	};
});
<commit_msg>Actual consistent use of "could not", no escapes<commit_after>/**
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 *
 * Mail
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

define(function() {
	'use strict';

	var smileys = [
		':-(',
		':-/',
		':-\\',
		':-|',
		':\'-(',
		':\'-/',
		':\'-\\',
		':\'-|'
	];

	function getRandomSmiley() {
		return smileys[Math.floor(Math.random() * smileys.length)]
	}

	/**
	 * @param {Folder} folder
	 * @returns {string}
	 */
	function getRandomFolderErrorMessage(folder) {
		var folderName = folder.get('name');
		var rawTexts = [
			t('mail', 'Could not load {tag}{name}{endtag}', {
				name: folderName
			}),
			t('mail', 'Could not load {tag}{name}{endtag}', {
				name: folderName
			}),
			t('mail', 'There was a problem loading {tag}{name}{endtag}', {
				name: folderName
			})
		];
		var texts = _.map(rawTexts, function(text) {
			return text.replace('{tag}', '').replace('{endtag}', '');
		});
		var text = texts[Math.floor(Math.random() * texts.length)]
		return text + ' ' + getRandomSmiley();
	}

	/**
	 * @returns {string}
	 */
	function getRandomMessageErrorMessage() {
		var texts = [
			t('mail', 'Could not load your message'),
			t('mail', 'Could not load the desired message'),
			t('mail', 'Could not load the message')
		];
		var text = texts[Math.floor(Math.random() * texts.length)]
		return text + ' ' + getRandomSmiley();
	}

	return {
		getRandomFolderErrorMessage: getRandomFolderErrorMessage,
		getRandomMessageErrorMessage: getRandomMessageErrorMessage
	};
});
<|endoftext|>