<commit_before>/**

pcep-grammar

Javascript PCEP grammar library

Supported RFCS:

RFC 5440, RFC 5520, RFC 5521, RFC 5886

Oscar Gonzalez de Dios

*/

jPCEPGrammarDraw = {};

(function (gd,pcep,$,undefined) {

	// Version
	gd.version = "0.6-dev"

	//FIXME: Add list of shown constructs to avoid repeating them

		gd.getHTML = function (element, RFCfilter, optional) {
			var newElem;
			console.log("Entrando en "+element.name+" con type "+element.type);
			//Check if the element's RFC is in the filter, otherwise, don't show it
			var found = $.inArray(element.rfc, RFCfilter) > -1;
			if (found) {
				if (element.type == "object"){
					//Check if the object is in the filter, otherwise, don't show it
						newElem = $('<span />');
						newElem.addClass("object_"+element.rfc);
						if (optional == true){
							newElem.append('[<'+ element.name+'>]');
						}else {
							newElem.append('<'+ element.name+'>');
						}

				} else if (element.type == "header") {
					// The element is the header of a message
					newElem = $('<span />');
					newElem.append('<'+ element.name+'>');
				} else if (element.type == "construct"){
					// The element is a construct
					newElem = $('<span />');
					newElem.addClass("construct_"+element.rfc);
					if (optional == true){
						newElem.append('[<'+ element.name+'>]');
					}else {
						newElem.append('<'+ element.name+'>');
					}
					//FIXME: CHECK IF CONSTRhUCT HAS ALREADY BEEN DRAWN
					if ($.inArray(element.name,gd.shown)!=0) {
						gd.shown.push(element.name);
						//A new element defintion is created to define the construct
						var elem_definition= $('<div />');
						$('#grammar_content').append(elem_definition);
						elem_definition.addClass("elem_definition");
						var defined_element = $('<div />');
						defined_element.addClass("defined_element");
						var displayText = '<'+ element.name+'>'+"::=";
						defined_element.append(displayText);
						elem_definition.append(defined_element);
						var definition = $('<div />');
						definition.addClass("definition");
						definition.append(definition);
						elem_definition.append(definition);
						for (var elem in pcep[element.name].elems) {
							definition.append(gd.getHTML(pcep[element.elems[elem].elem], RFCfilter, pcep[element.name].elems[elem].optional));
						}
					}

				} else if (element.type == "choice") {
					newElem = $('<span />');
					newElem.addClass("choice");
					if (optional == true){
						newElem.append('[');
					}
					for (var elem in element.elems) {
						newElem.append(gd.getHTML(element.elems[elem].pcep_elem, RFCfilter, element.elems[elem].optional));
						if (elem < element.elems.length-1){
							newElem.append('|');
						}
					}
				} else if (element.type == "list"){
					console.log("Lista: Entrando en "+element.name);
					newElem = $('<span />');
					newElem.addClass("list."+element.rfc);
					if (optional == true){
						console.log("OPTIONAL "+element.name);
						newElem.append('[<'+ element.name+'>]');
					}else {
						newElem.append('<'+ element.name+'>');
					}
					//FIXME: CHECK IF LIST HAS ALREADY BEEN DRAWN
					if ($)
					var elem_definition= $('<div />');
					$('#grammar_content').append(elem_definition);
					elem_definition.addClass("elem_definition");
					var defined_element = $('<div />');
					defined_element.addClass("defined_element");
					var displayText = '<'+ element.name+'>'+"::=";
					defined_element.append(displayText);
					elem_definition.append(defined_element);
					var definition = $('<div />');
					definition.addClass("definition");
					definition.append(definition);
					console.log("Lista: vamo a ve... "+element.elems[0].elem);
					definition.append(gd.getHTML(pcep[element.elems[0].elem], RFCfilter,false));
					var definition_text = '[<'+ element.name+'&#62]';
					definition.append(definition_text);
					elem_definition.append(definition);

				}else {
					console.log("Es un mensajito");
					//It is a message
					newElem = $('<div />');
					newElem.addClass("elem_definition");
					//Create a div for the defined element
					var defined_element = $('<div />');
					defined_element.addClass("defined_element");
					var displayText = element.name+"::=";
					defined_element.append(displayText);
					newElem.append(defined_element);
					//Create another div for the defnition itself
					var definition = $('<div />');
					definition.addClass("definition");
					newElem.append(definition);
					for (var elem in element.elems) {
						//definition.append(gd.getHTML(element.elems[elem].elem, RFCfilter, element.elems[elem].optional));
						definition.append(gd.getHTML(pcep[element.elems[elem].elem], RFCfilter, element.elems[elem].optional));

					}

				}
			}
			return newElem;
		}

	gd.draw_message = function (message_name ) {
		console.log("Draw message: "+message_name);
		var newElem = $('<div />');
		newElem.attr('id', 'grammar_content');
		$('#pcep_grammar').html(newElem);
		//Filter of current view
	    //Let's try starting by an Array
	    var RFCfilter = new Array();
		$('#RFCs input:checked').each(function() {
    		RFCfilter.push(this.value);
		});
		gd.shown=[];
		newElem.prepend(gd.getHTML(pcep[message_name], RFCfilter));
	}

}

) (jPCEPGrammarDraw, RFC5440,jQuery);

<commit_msg>choice fixed<commit_after>/**

pcep-grammar

Javascript PCEP grammar library

Supported RFCS:

RFC 5440, RFC 5520, RFC 5521, RFC 5886

Oscar Gonzalez de Dios

*/

jPCEPGrammarDraw = {};

(function (gd,pcep,$,undefined) {

	// Version
	gd.version = "0.6-dev"

	//FIXME: Add list of shown constructs to avoid repeating them

		gd.getHTML = function (element, RFCfilter, optional) {
			var newElem;
			console.log("Entrando en "+element.name+" con type "+element.type);
			//Check if the element's RFC is in the filter, otherwise, don't show it
			var found = $.inArray(element.rfc, RFCfilter) > -1;
			if (found) {
				if (element.type == "object"){
					//Check if the object is in the filter, otherwise, don't show it
						newElem = $('<span />');
						newElem.addClass("object_"+element.rfc);
						if (optional == true){
							newElem.append('[<'+ element.name+'>]');
						}else {
							newElem.append('<'+ element.name+'>');
						}

				} else if (element.type == "header") {
					// The element is the header of a message
					newElem = $('<span />');
					newElem.append('<'+ element.name+'>');
				} else if (element.type == "construct"){
					// The element is a construct
					newElem = $('<span />');
					newElem.addClass("construct_"+element.rfc);
					if (optional == true){
						newElem.append('[<'+ element.name+'>]');
					}else {
						newElem.append('<'+ element.name+'>');
					}
					if ($.inArray(element.name,gd.shown)<0) {
						gd.shown.push(element.name);
						//A new element defintion is created to define the construct
						var elem_definition= $('<div />');
						$('#grammar_content').append(elem_definition);
						elem_definition.addClass("elem_definition");
						var defined_element = $('<div />');
						defined_element.addClass("defined_element");
						var displayText = '<'+ element.name+'>'+"::=";
						defined_element.append(displayText);
						elem_definition.append(defined_element);
						var definition = $('<div />');
						definition.addClass("definition");
						definition.append(definition);
						elem_definition.append(definition);
						for (var elem in pcep[element.name].elems) {
							definition.append(gd.getHTML(pcep[element.elems[elem].elem], RFCfilter, pcep[element.name].elems[elem].optional));
						}
					}

				} else if (element.type == "choice") {
					newElem = $('<span />');
					newElem.addClass("choice");
					if (optional == true){
						newElem.append('[');
					}
					for (var elem in element.elems) {
						newElem.append(gd.getHTML(pcep[element.elems[elem].elem], RFCfilter, false));
						if (elem < element.elems.length-1){
							newElem.append('|');
						}
					}
				} else if (element.type == "list"){
					console.log("Lista: Entrando en "+element.name);
					newElem = $('<span />');
					newElem.addClass("list."+element.rfc);
					if (optional == true){
						console.log("OPTIONAL "+element.name);
						newElem.append('[<'+ element.name+'>]');
					}else {
						newElem.append('<'+ element.name+'>');
					}
					if ($.inArray(element.name,gd.shown)<0) {
						console.log("------------- "+element.name+" no esta defnidio aun da "+$.inArray(element.name,gd.shown));
						gd.shown.push(element.name);
						var elem_definition= $('<div />');
						$('#grammar_content').append(elem_definition);
						elem_definition.addClass("elem_definition");
						var defined_element = $('<div />');
						defined_element.addClass("defined_element");
						var displayText = '<'+ element.name+'>'+"::=";
						defined_element.append(displayText);
						elem_definition.append(defined_element);
						var definition = $('<div />');
						definition.addClass("definition");
						definition.append(definition);
						console.log("Lista: vamo a ve... "+element.elems[0].elem);
						definition.append(gd.getHTML(pcep[element.elems[0].elem], RFCfilter,false));
						var definition_text = '[<'+ element.name+'&#62]';
						definition.append(definition_text);
						elem_definition.append(definition);
					}
				}else {
					console.log("Es un mensajito");
					//It is a message
					newElem = $('<div />');
					newElem.addClass("elem_definition");
					//Create a div for the defined element
					var defined_element = $('<div />');
					defined_element.addClass("defined_element");
					var displayText = element.name+"::=";
					defined_element.append(displayText);
					newElem.append(defined_element);
					//Create another div for the defnition itself
					var definition = $('<div />');
					definition.addClass("definition");
					newElem.append(definition);
					for (var elem in element.elems) {
						//definition.append(gd.getHTML(element.elems[elem].elem, RFCfilter, element.elems[elem].optional));
						definition.append(gd.getHTML(pcep[element.elems[elem].elem], RFCfilter, element.elems[elem].optional));

					}

				}
			}
			return newElem;
		}

	gd.draw_message = function (message_name ) {
		console.log("Draw message: "+message_name);
		var newElem = $('<div />');
		newElem.attr('id', 'grammar_content');
		$('#pcep_grammar').html(newElem);
		//Filter of current view
	    //Let's try starting by an Array
	    var RFCfilter = new Array();
		$('#RFCs input:checked').each(function() {
    		RFCfilter.push(this.value);
		});
		gd.shown=[];
		newElem.prepend(gd.getHTML(pcep[message_name], RFCfilter));
	}

}

) (jPCEPGrammarDraw, RFC5440,jQuery);

<|endoftext|>


<commit_before>// Copyright 2015-2020, University of Colorado Boulder

/**
 * An iOS-style page control. See the 'Navigation' section of the iOS Human Interface Guidelines.
 * A page control indicates the number of pages and which one is currently visible.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import Shape from '../../kite/js/Shape.js';
import inherit from '../../phet-core/js/inherit.js';
import merge from '../../phet-core/js/merge.js';
import DownUpListener from '../../scenery/js/input/DownUpListener.js';
import Circle from '../../scenery/js/nodes/Circle.js';
import Node from '../../scenery/js/nodes/Node.js';
import sun from './sun.js';

/**
 * @param {number} numberOfPages - number of pages
 * @param {Property<number>} pageNumberProperty - which page is currently visible
 * @param {Object} [options]
 * @constructor
 */
function PageControl( numberOfPages, pageNumberProperty, options ) {

  options = merge( {

    //TODO support multiple types of interactivity? see https://github.com/phetsims/sun/issues/199
    interactive: false, // {boolean} whether the control is interactive

    // all dots
    orientation: 'horizontal',
    dotRadius: 3, // {number} radius of the dots
    lineWidth: 1,
    dotSpacing: 10, // {number} spacing between dots
    dotTouchAreaDilation: 0, // {number} how much to dilate the touchArea beyond the radius of a dot
    dotMouseAreaDilation: 0, // {number} how much to dilate the mouseArea beyond the radius of a dot

    // dots representing the current page
    currentPageFill: 'black', // {Color|string} dot color for the page that is visible
    currentPageStroke: null,

    // dots representing all pages except the current page
    pageFill: 'rgb( 200, 200, 200 )', // {Color|string} dot color for pages that are not visible
    pageStroke: null

  }, options );

  // validate options
  assert && assert( _.includes( [ 'horizontal', 'vertical' ], options.orientation ), 'invalid orientation=' + options.orientation );

  // To improve readability
  const isHorizontal = ( options.orientation === 'horizontal' );

  // Clicking on a dot goes to that page
  const dotListener = new DownUpListener( {
    down: function( event ) {
      assert && assert( event.currentTarget.hasOwnProperty( 'pageNumber' ) );
      pageNumberProperty.set( event.currentTarget.pageNumber );
    }
  } );

  // Create a dot for each page.
  // Add them to an intermediate parent node, so that additional children can't be inadvertently added.
  // For horizontal orientation, pages are ordered left-to-right.
  // For vertical orientation, pages are ordered top-to-bottom.
  const dotsParent = new Node();
  for ( let pageNumber = 0; pageNumber < numberOfPages; pageNumber++ ) {

    // dot
    const dotCenter = ( pageNumber * ( 2 * options.dotRadius + options.dotSpacing ) );
    const dotNode = new DotNode( pageNumber, options.dotRadius, {
      fill: options.pageFill,
      stroke: options.pageStroke,
      lineWidth: options.lineWidth,
      x: isHorizontal ? dotCenter : 0,
      y: isHorizontal ? 0 : dotCenter
    } );
    dotsParent.addChild( dotNode );

    // pointer areas
    dotNode.touchArea = ( options.dotTouchAreaDilation === 0 ) ? null : Shape.circle( 0, 0, options.dotRadius + options.dotTouchAreaDilation );
    dotNode.mouseArea = ( options.dotMouseAreaDilation === 0 ) ? null : Shape.circle( 0, 0, options.dotRadius + options.dotMouseAreaDilation );

    // optional interactivity
    if ( options.interactive ) {
      dotNode.cursor = 'pointer';
      dotNode.addInputListener( dotListener );
    }
  }

  // Indicate which page is selected
  const pageNumberObserver = function( pageNumber, oldPageNumber ) {

    // previous dot
    if ( oldPageNumber || oldPageNumber === 0 ) {
      dotsParent.getChildAt( oldPageNumber ).fill = options.pageFill;
      dotsParent.getChildAt( oldPageNumber ).stroke = options.pageStroke;
    }

    // current dot
    dotsParent.getChildAt( pageNumber ).fill = options.currentPageFill;
    dotsParent.getChildAt( pageNumber ).stroke = options.currentPageStroke;
  };
  pageNumberProperty.link( pageNumberObserver );

  // @private
  this.disposePageControl = function() {
    pageNumberProperty.unlink( pageNumberObserver );
  };

  options.children = [ dotsParent ];
  Node.call( this, options );
}

sun.register( 'PageControl', PageControl );

/**
 * @param {number} pageNumber - page number that the dot is associated with
 * @param {number} radius
 * @param {Object} [options]
 * @constructor
 */
function DotNode( pageNumber, radius, options ) {
  this.pageNumber = pageNumber; // @public (read-only)
  Circle.call( this, radius, options );
}

inherit( Circle, DotNode );

inherit( Node, PageControl, {

  // @public
  dispose: function() {
    this.disposePageControl();
    Node.prototype.dispose.call( this );
  }
} );

export default PageControl;<commit_msg>delete vestigial TODO, https://github.com/phetsims/sun/issues/199<commit_after>// Copyright 2015-2020, University of Colorado Boulder

/**
 * An iOS-style page control. See the 'Navigation' section of the iOS Human Interface Guidelines.
 * A page control indicates the number of pages and which one is currently visible.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import Shape from '../../kite/js/Shape.js';
import inherit from '../../phet-core/js/inherit.js';
import merge from '../../phet-core/js/merge.js';
import DownUpListener from '../../scenery/js/input/DownUpListener.js';
import Circle from '../../scenery/js/nodes/Circle.js';
import Node from '../../scenery/js/nodes/Node.js';
import sun from './sun.js';

/**
 * @param {number} numberOfPages - number of pages
 * @param {Property<number>} pageNumberProperty - which page is currently visible
 * @param {Object} [options]
 * @constructor
 */
function PageControl( numberOfPages, pageNumberProperty, options ) {

  options = merge( {

    interactive: false, // {boolean} whether the control is interactive

    // all dots
    orientation: 'horizontal',
    dotRadius: 3, // {number} radius of the dots
    lineWidth: 1,
    dotSpacing: 10, // {number} spacing between dots
    dotTouchAreaDilation: 0, // {number} how much to dilate the touchArea beyond the radius of a dot
    dotMouseAreaDilation: 0, // {number} how much to dilate the mouseArea beyond the radius of a dot

    // dots representing the current page
    currentPageFill: 'black', // {Color|string} dot color for the page that is visible
    currentPageStroke: null,

    // dots representing all pages except the current page
    pageFill: 'rgb( 200, 200, 200 )', // {Color|string} dot color for pages that are not visible
    pageStroke: null

  }, options );

  // validate options
  assert && assert( _.includes( [ 'horizontal', 'vertical' ], options.orientation ), 'invalid orientation=' + options.orientation );

  // To improve readability
  const isHorizontal = ( options.orientation === 'horizontal' );

  // Clicking on a dot goes to that page
  const dotListener = new DownUpListener( {
    down: function( event ) {
      assert && assert( event.currentTarget.hasOwnProperty( 'pageNumber' ) );
      pageNumberProperty.set( event.currentTarget.pageNumber );
    }
  } );

  // Create a dot for each page.
  // Add them to an intermediate parent node, so that additional children can't be inadvertently added.
  // For horizontal orientation, pages are ordered left-to-right.
  // For vertical orientation, pages are ordered top-to-bottom.
  const dotsParent = new Node();
  for ( let pageNumber = 0; pageNumber < numberOfPages; pageNumber++ ) {

    // dot
    const dotCenter = ( pageNumber * ( 2 * options.dotRadius + options.dotSpacing ) );
    const dotNode = new DotNode( pageNumber, options.dotRadius, {
      fill: options.pageFill,
      stroke: options.pageStroke,
      lineWidth: options.lineWidth,
      x: isHorizontal ? dotCenter : 0,
      y: isHorizontal ? 0 : dotCenter
    } );
    dotsParent.addChild( dotNode );

    // pointer areas
    dotNode.touchArea = ( options.dotTouchAreaDilation === 0 ) ? null : Shape.circle( 0, 0, options.dotRadius + options.dotTouchAreaDilation );
    dotNode.mouseArea = ( options.dotMouseAreaDilation === 0 ) ? null : Shape.circle( 0, 0, options.dotRadius + options.dotMouseAreaDilation );

    // optional interactivity
    if ( options.interactive ) {
      dotNode.cursor = 'pointer';
      dotNode.addInputListener( dotListener );
    }
  }

  // Indicate which page is selected
  const pageNumberObserver = function( pageNumber, oldPageNumber ) {

    // previous dot
    if ( oldPageNumber || oldPageNumber === 0 ) {
      dotsParent.getChildAt( oldPageNumber ).fill = options.pageFill;
      dotsParent.getChildAt( oldPageNumber ).stroke = options.pageStroke;
    }

    // current dot
    dotsParent.getChildAt( pageNumber ).fill = options.currentPageFill;
    dotsParent.getChildAt( pageNumber ).stroke = options.currentPageStroke;
  };
  pageNumberProperty.link( pageNumberObserver );

  // @private
  this.disposePageControl = function() {
    pageNumberProperty.unlink( pageNumberObserver );
  };

  options.children = [ dotsParent ];
  Node.call( this, options );
}

sun.register( 'PageControl', PageControl );

/**
 * @param {number} pageNumber - page number that the dot is associated with
 * @param {number} radius
 * @param {Object} [options]
 * @constructor
 */
function DotNode( pageNumber, radius, options ) {
  this.pageNumber = pageNumber; // @public (read-only)
  Circle.call( this, radius, options );
}

inherit( Circle, DotNode );

inherit( Node, PageControl, {

  // @public
  dispose: function() {
    this.disposePageControl();
    Node.prototype.dispose.call( this );
  }
} );

export default PageControl;<|endoftext|>


<commit_before>var pageData = {};

function editRules() {
    setButtonMode(true);

    // API call
    var adminID = getParameterByName('admin');
    var rows = apiRequest(
        '/?admin='
            + adminID
            + '&page=classes'
            + '&cmd=getcommenters'
    );
    if (false === rows) return;
    var commentersList = document.getElementById('commenters-list');
    var commentersListPhantom = document.getElementById('commenters-list-phantom');
    var commenters = [];
    var commenters_phantom = [];
    for (var i=0,ilen=rows.length;i<ilen;i+=1) {
        var row = rows[i];
        commenters.push('' + row.name + '');
        commenters_phantom.push('' + row.name + '');
    }
    commentersList.innerHTML = commenters.join(' ');
    commentersListPhantom.innerHTML = commenters_phantom.join(' ');
    pageData.commenters = document.getElementsByClassName('commenter');;
    buildRulesLists();
    //setCommentersBlockPosition();
};

function buildRulesLists() {
    // API call
    var adminID = getParameterByName('admin');
    var ruleGroupID = getParameterByName('groupid');
    var rows = apiRequest(
        '/?admin='
            + adminID
            + '&page=rules'
            + '&cmd=getrules'
        , {
            groupid:ruleGroupID
        }
    );
    if (false === rows) return;
    var rulesListAdmin = document.getElementById('rules-list-admin');
    var rulesListCommenters = document.getElementById('rules-list-commenters');
    for (var i=0,ilen=rulesListAdmin.childNodes.length;i<ilen;i+=1) {
        rulesListAdmin.removeChild(rulesListAdmin.childNodes[0]);
    }
    for (var i=0,ilen=rulesListCommenters.childNodes.length;i<ilen;i+=1) {
        rulesListCommenters.removeChild(rulesListCommenters.childNodes[0]);
    }
    pageData.adminrules = [];
    for (var i=0,ilen=rows.admin.length;i<ilen;i+=1) {
        var row = rows.admin[i];
        var tr = document.createElement('tr');
        tr.innerHTML = '' + markdown(row.string) + '	';
        rulesListAdmin.appendChild(tr);
        pageData.adminrules.push(tr.childNodes[0]);
    }
    for (var i=0,ilen=rows.commenters.length;i<ilen;i+=1) {
        var row = rows.commenters[i];
        var tr = document.createElement('tr');
        tr.innerHTML = '' + markdown(row.string) + '	';
        rulesListCommenters.appendChild(tr);
    }

};

function promoteRule(node) {
    var okToPromote = confirm("Promote this rule for general use?");
    if (okToPromote) {
        var adminID = getParameterByName('admin');
        var ruleID = node.id;
        var rows = apiRequest(
            '/?admin='
                + adminID
                + '&page=rules'
                + '&cmd=promoteonerule'
            ,{
                ruleid:ruleID
            }
        );
        if (false === rows) return;
        buildRulesLists();
    }
};

function allowDemoteDrop(ev) {
    if (ev.dataTransfer.getData("ruleID").slice(0,7) !== 'demote:') {
        return;
    }
    ev.preventDefault();
    for (var i=0,ilen=pageData.commenters.length;i<ilen;i+=1) {
        if (pageData.commenters[i].hasAttribute('style')) {
            pageData.commenters[i].removeAttribute('style');
        }
    }
    ev.target.setAttribute('style','border:1px dashed black;border-radius:0;background:#00ff00;');
};

function dragDemoteRule(ev) {
    ev.dataTransfer.setData('ruleID','demote:'+ev.target.id);
};

function dragendDemoteRule(ev) {
    for (var i=0,ilen=pageData.commenters.length;i<ilen;i+=1) {
        if (pageData.commenters[i].hasAttribute('style')) {
            pageData.commenters[i].removeAttribute('style');
        }
    }
};

function dropDemoteRule(ev) {
    ev.preventDefault();
    var commenterID = ev.target.id.split('-').slice(-1)[0];
    var commenterName = ev.target.textContent;
    var okToDemote = confirm("Demote this rule for use only by " + commenterName + "?");
    if (okToDemote) {
        // API call
        var ruleID = ev.dataTransfer.getData("ruleID").slice(7);
        var adminID = getParameterByName('admin');
        var rows = apiRequest(
            '/?admin='
                + adminID
                + '&page=rules'
                + '&cmd=demoteonerule'
            ,{
                ruleid:ruleID,
                commenterid:commenterID
            }
        );
        if (false === rows) return;
        buildRulesLists();
    }
    ev.target.removeAttribute('style');
};

function dragleaveDemoteRule(ev) {
    ev.preventDefault();
    if ("function" === typeof ev.target.removeAttribute) {
        ev.target.removeAttribute('style');
    }
};

function allowMergeDrop(ev) {
    if (ev.dataTransfer.getData("ruleID").slice(0,6) !== 'merge:') {
        return;
    }
    ev.preventDefault();
    dragendMergeRule();
    var targ = getParent(ev.target,'td');
    targ.setAttribute('style','border:1px dashed black;border-radius:0;background:#00ff00;');
};

function dragendMergeRule(ev) {
    for (var i=0,ilen=pageData.adminrules.length;i<ilen;i+=1) {
        if (pageData.adminrules[i].hasAttribute('style')) {
            pageData.adminrules[i].removeAttribute('style');
        }
    }
};

function dragMergeRule(ev) {
    ev.dataTransfer.setData('ruleID','merge:'+ev.target.id);
};

function dropMergeRule(ev) {
    ev.preventDefault();
    var targ = getParent(ev.target,'td');
    var senpaiRuleID = targ.id;
    var okToDemote = confirm("Merge this rule with target?");
    if (okToDemote) {
        // API call
        var kohaiRuleID = ev.dataTransfer.getData("ruleID").slice(6);
        var adminID = getParameterByName('admin');
        var result = apiRequest(
            '/?admin='
                + adminID
                + '&page=rules'
                + '&cmd=mergetworules'
            ,{
                kohairuleid:kohaiRuleID,
                senpairuleid:senpaiRuleID
            }
        );
        if (false === result) return;
        buildRulesLists();
    }
    targ.removeAttribute('style');
};

function dragleaveMergeRule(ev) {
    ev.preventDefault();
    if (ev.target.tagName === 'TD') {
        ev.target.removeAttribute('style');
    }
};

/* for scrolling
 * Ahnsirk Dasarp
 * http://stackoverflow.com/questions/5007530/how-do-i-scroll-to-an-element-using-javascript
 */

//Finds y value of given object
function findPos(obj) {
    var curtop = 0;
    var curleft = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
            curleft += obj.offsetLeft;
        } while (obj = obj.offsetParent);
        return [curleft,curtop];
    }
}

function getParent (node,tagname) {
    var targ = node;
    while (targ.tagName !== tagname.toUpperCase()) {
        targ = targ.parentNode;
    }
    return targ;
}

//window.addEventListener('resize', setCommentersBlockPosition);

function setCommentersBlockPosition (event){
    var phantom = document.getElementById('commenters-list-phantom');
    var width = phantom.offsetWidth;
    var xy = findPos(phantom);
    var top = xy[1];
    var left = xy[0];
    var commenters = document.getElementById('commenters-list');
    commenters.setAttribute('style','position:fixed;top:' + 0 + 'px;left:' + left + 'px;width:' + width + 'px');
};

/* StackOverflow to the rescue http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html */

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function trackScroll (ev) {
    var phantom = document.getElementById('commenters-list-phantom');
    var commenters = document.getElementById('commenters-list');
    var xy = findPos(phantom);
    var top = xy[1];
    var vOffset = f_scrollTop();
    console.log("vOffset="+vOffset+", top="+top);
    if (vOffset < top) {
        if (commenters.hasAttribute('style')) {
            commenters.removeAttribute('style');
        }
    } else {
        if (!commenters.hasAttribute('style')) {
            setCommentersBlockPosition();
        }
    }
}

function setButtonMode(rulesMode) {
    return;
    var returnToMainButton = document.getElementById('return-to-main-display-button');
    var editRulesButton = document.getElementById('edit-rules-button');
    var addClassButton = document.getElementById('add-class-button');
    var saveClassButton = document.getElementById('save-class-button');
    var classBoxes = document.getElementById('class-boxes');

    var mainDisplay = document.getElementById('main-display');
    var rulesDisplay = document.getElementById('rules-display');

    var mainDisplayTitle = document.getElementById('main-display-title');
    var rulesDisplayTitle = document.getElementById('rules-display-title');

    if (rulesMode) {
        returnToMainButton.style.display = 'inline';
        editRulesButton.style.display = 'none';
        addClassButton.style.display = 'none';
        saveClassButton.style.display = 'none';
        classBoxes.style.display = 'none';
        mainDisplay.style.display = 'none';
        rulesDisplay.style.display = 'block';
        mainDisplayTitle.style.display = 'none';
        rulesDisplayTitle.style.display = 'block';
    } else {
        returnToMainButton.style.display = 'none';
        editRulesButton.style.display = 'inline';
        addClassButton.style.display = 'inline';
        saveClassButton.style.display = 'none';
        classBoxes.style.display = 'none';
        mainDisplay.style.display = 'block';
        rulesDisplay.style.display = 'none';
        mainDisplayTitle.style.display = 'block';
        rulesDisplayTitle.style.display = 'none';
    }
};

<commit_msg>Call getcommenters on the rules page, not classes<commit_after>var pageData = {};

function editRules() {
    setButtonMode(true);

    // API call
    var adminID = getParameterByName('admin');
    var rows = apiRequest(
        '/?admin='
            + adminID
            + '&page=rules'
            + '&cmd=getcommenters'
    );
    if (false === rows) return;
    var commentersList = document.getElementById('commenters-list');
    var commentersListPhantom = document.getElementById('commenters-list-phantom');
    var commenters = [];
    var commenters_phantom = [];
    for (var i=0,ilen=rows.length;i<ilen;i+=1) {
        var row = rows[i];
        commenters.push('' + row.name + '');
        commenters_phantom.push('' + row.name + '');
    }
    commentersList.innerHTML = commenters.join(' ');
    commentersListPhantom.innerHTML = commenters_phantom.join(' ');
    pageData.commenters = document.getElementsByClassName('commenter');;
    buildRulesLists();
    //setCommentersBlockPosition();
};

function buildRulesLists() {
    // API call
    var adminID = getParameterByName('admin');
    var ruleGroupID = getParameterByName('groupid');
    var rows = apiRequest(
        '/?admin='
            + adminID
            + '&page=rules'
            + '&cmd=getrules'
        , {
            groupid:ruleGroupID
        }
    );
    if (false === rows) return;
    var rulesListAdmin = document.getElementById('rules-list-admin');
    var rulesListCommenters = document.getElementById('rules-list-commenters');
    for (var i=0,ilen=rulesListAdmin.childNodes.length;i<ilen;i+=1) {
        rulesListAdmin.removeChild(rulesListAdmin.childNodes[0]);
    }
    for (var i=0,ilen=rulesListCommenters.childNodes.length;i<ilen;i+=1) {
        rulesListCommenters.removeChild(rulesListCommenters.childNodes[0]);
    }
    pageData.adminrules = [];
    for (var i=0,ilen=rows.admin.length;i<ilen;i+=1) {
        var row = rows.admin[i];
        var tr = document.createElement('tr');
        tr.innerHTML = '' + markdown(row.string) + '	';
        rulesListAdmin.appendChild(tr);
        pageData.adminrules.push(tr.childNodes[0]);
    }
    for (var i=0,ilen=rows.commenters.length;i<ilen;i+=1) {
        var row = rows.commenters[i];
        var tr = document.createElement('tr');
        tr.innerHTML = '' + markdown(row.string) + '	';
        rulesListCommenters.appendChild(tr);
    }

};

function promoteRule(node) {
    var okToPromote = confirm("Promote this rule for general use?");
    if (okToPromote) {
        var adminID = getParameterByName('admin');
        var ruleID = node.id;
        var rows = apiRequest(
            '/?admin='
                + adminID
                + '&page=rules'
                + '&cmd=promoteonerule'
            ,{
                ruleid:ruleID
            }
        );
        if (false === rows) return;
        buildRulesLists();
    }
};

function allowDemoteDrop(ev) {
    if (ev.dataTransfer.getData("ruleID").slice(0,7) !== 'demote:') {
        return;
    }
    ev.preventDefault();
    for (var i=0,ilen=pageData.commenters.length;i<ilen;i+=1) {
        if (pageData.commenters[i].hasAttribute('style')) {
            pageData.commenters[i].removeAttribute('style');
        }
    }
    ev.target.setAttribute('style','border:1px dashed black;border-radius:0;background:#00ff00;');
};

function dragDemoteRule(ev) {
    ev.dataTransfer.setData('ruleID','demote:'+ev.target.id);
};

function dragendDemoteRule(ev) {
    for (var i=0,ilen=pageData.commenters.length;i<ilen;i+=1) {
        if (pageData.commenters[i].hasAttribute('style')) {
            pageData.commenters[i].removeAttribute('style');
        }
    }
};

function dropDemoteRule(ev) {
    ev.preventDefault();
    var commenterID = ev.target.id.split('-').slice(-1)[0];
    var commenterName = ev.target.textContent;
    var okToDemote = confirm("Demote this rule for use only by " + commenterName + "?");
    if (okToDemote) {
        // API call
        var ruleID = ev.dataTransfer.getData("ruleID").slice(7);
        var adminID = getParameterByName('admin');
        var rows = apiRequest(
            '/?admin='
                + adminID
                + '&page=rules'
                + '&cmd=demoteonerule'
            ,{
                ruleid:ruleID,
                commenterid:commenterID
            }
        );
        if (false === rows) return;
        buildRulesLists();
    }
    ev.target.removeAttribute('style');
};

function dragleaveDemoteRule(ev) {
    ev.preventDefault();
    if ("function" === typeof ev.target.removeAttribute) {
        ev.target.removeAttribute('style');
    }
};

function allowMergeDrop(ev) {
    if (ev.dataTransfer.getData("ruleID").slice(0,6) !== 'merge:') {
        return;
    }
    ev.preventDefault();
    dragendMergeRule();
    var targ = getParent(ev.target,'td');
    targ.setAttribute('style','border:1px dashed black;border-radius:0;background:#00ff00;');
};

function dragendMergeRule(ev) {
    for (var i=0,ilen=pageData.adminrules.length;i<ilen;i+=1) {
        if (pageData.adminrules[i].hasAttribute('style')) {
            pageData.adminrules[i].removeAttribute('style');
        }
    }
};

function dragMergeRule(ev) {
    ev.dataTransfer.setData('ruleID','merge:'+ev.target.id);
};

function dropMergeRule(ev) {
    ev.preventDefault();
    var targ = getParent(ev.target,'td');
    var senpaiRuleID = targ.id;
    var okToDemote = confirm("Merge this rule with target?");
    if (okToDemote) {
        // API call
        var kohaiRuleID = ev.dataTransfer.getData("ruleID").slice(6);
        var adminID = getParameterByName('admin');
        var result = apiRequest(
            '/?admin='
                + adminID
                + '&page=rules'
                + '&cmd=mergetworules'
            ,{
                kohairuleid:kohaiRuleID,
                senpairuleid:senpaiRuleID
            }
        );
        if (false === result) return;
        buildRulesLists();
    }
    targ.removeAttribute('style');
};

function dragleaveMergeRule(ev) {
    ev.preventDefault();
    if (ev.target.tagName === 'TD') {
        ev.target.removeAttribute('style');
    }
};

/* for scrolling
 * Ahnsirk Dasarp
 * http://stackoverflow.com/questions/5007530/how-do-i-scroll-to-an-element-using-javascript
 */

//Finds y value of given object
function findPos(obj) {
    var curtop = 0;
    var curleft = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
            curleft += obj.offsetLeft;
        } while (obj = obj.offsetParent);
        return [curleft,curtop];
    }
}

function getParent (node,tagname) {
    var targ = node;
    while (targ.tagName !== tagname.toUpperCase()) {
        targ = targ.parentNode;
    }
    return targ;
}

//window.addEventListener('resize', setCommentersBlockPosition);

function setCommentersBlockPosition (event){
    var phantom = document.getElementById('commenters-list-phantom');
    var width = phantom.offsetWidth;
    var xy = findPos(phantom);
    var top = xy[1];
    var left = xy[0];
    var commenters = document.getElementById('commenters-list');
    commenters.setAttribute('style','position:fixed;top:' + 0 + 'px;left:' + left + 'px;width:' + width + 'px');
};

/* StackOverflow to the rescue http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html */

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function trackScroll (ev) {
    var phantom = document.getElementById('commenters-list-phantom');
    var commenters = document.getElementById('commenters-list');
    var xy = findPos(phantom);
    var top = xy[1];
    var vOffset = f_scrollTop();
    console.log("vOffset="+vOffset+", top="+top);
    if (vOffset < top) {
        if (commenters.hasAttribute('style')) {
            commenters.removeAttribute('style');
        }
    } else {
        if (!commenters.hasAttribute('style')) {
            setCommentersBlockPosition();
        }
    }
}

function setButtonMode(rulesMode) {
    return;
    var returnToMainButton = document.getElementById('return-to-main-display-button');
    var editRulesButton = document.getElementById('edit-rules-button');
    var addClassButton = document.getElementById('add-class-button');
    var saveClassButton = document.getElementById('save-class-button');
    var classBoxes = document.getElementById('class-boxes');

    var mainDisplay = document.getElementById('main-display');
    var rulesDisplay = document.getElementById('rules-display');

    var mainDisplayTitle = document.getElementById('main-display-title');
    var rulesDisplayTitle = document.getElementById('rules-display-title');

    if (rulesMode) {
        returnToMainButton.style.display = 'inline';
        editRulesButton.style.display = 'none';
        addClassButton.style.display = 'none';
        saveClassButton.style.display = 'none';
        classBoxes.style.display = 'none';
        mainDisplay.style.display = 'none';
        rulesDisplay.style.display = 'block';
        mainDisplayTitle.style.display = 'none';
        rulesDisplayTitle.style.display = 'block';
    } else {
        returnToMainButton.style.display = 'none';
        editRulesButton.style.display = 'inline';
        addClassButton.style.display = 'inline';
        saveClassButton.style.display = 'none';
        classBoxes.style.display = 'none';
        mainDisplay.style.display = 'block';
        rulesDisplay.style.display = 'none';
        mainDisplayTitle.style.display = 'block';
        rulesDisplayTitle.style.display = 'none';
    }
};

<|endoftext|>


<commit_before>$(document).ready(function() {
  var Game = function(givenBoard) {

    function getRandomIndex(maxExclusive) {
      return Math.floor(Math.random() * maxExclusive)
    }

    function randomBoard() {
     var board = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
      var index1 = getRandomIndex(16)
      var index2 = index1

      do {
        index2 = getRandomIndex(16)
      } while (index2 === index1)

      var startingNumbers = [2, 4]

      var startingNum1 = startingNumbers[getRandomIndex(2)]
      var startingNum2 = startingNumbers[getRandomIndex(2)]

      board[index1] = startingNum1
      board[index2] = startingNum2
      return board
    }

    function presetBoard(board) {
      var boardArray = board.split("")
      for (i = 0; i < boardArray.length; i++) {
        boardArray[i] = parseInt(boardArray[i])
      }
      return boardArray
    }

    if (givenBoard === undefined) {
      this.board = randomBoard()
    } else {
      this.board = presetBoard(givenBoard)
    }
  }

  function createWorkingBoard(board) {
    return [
      board.slice(0,4),
      board.slice(4,8),
      board.slice(8,12),
      board.slice(12,16)
    ]
  }

  function removeZeros(board) {
    for (i = 0; i < board.length; i++) {
      for (j = 0; j < board[i].length; j++) {
        if (board[i][j] === 0) {
          board[i].splice(j, 1)
          j = j-1
        }
      }
    }
    return board
  }

  function combineTilesRight(board) {
    for (i = 0; i < board.length; i++) {
      for (j = board[i].length-1; j > 0; j--) {
        if (board[i][j] === board[i][j-1]) {
          board[i][j] *=2
          board[i].splice(j-1, 1)
       }
      }
    }
    return board
  }

  function padZeros(board) {
    for (i = 0; i < board.length; i++) {
      if (board[i].length !== 4) {
        do {
          board[i].unshift(0)
        } while (board[i].length < 4)
      }
    }
    return board
  }

  Game.prototype.saveBoard = function(board) {
    this.board = [].concat.apply([], board)
  }

  Game.prototype.moveRight = function() {
    var workingBoard = createWorkingBoard(this.board)
    var noZeros = removeZeros(workingBoard)
    var tilesCombined = combineTilesRight(noZeros)
    var updatedBoard = padZeros(tilesCombined)
    this.saveBoard(updatedBoard)
    return this.board
  }

  function reverseBoard(board) {
    var reverseBoard = []
    for (i = 0; i < board.length; i++) {
      reverseBoard.push(board[i].reverse())
    }
    return reverseBoard
  }

  Game.prototype.moveLeft = function() {
    var workingBoard = createWorkingBoard(this.board)
    var reversedBoard = reverseBoard(workingBoard)
    var noZeros = removeZeros(reversedBoard)
    var tilesCombined = combineTilesRight(noZeros)
    var updatedReversedBoard = padZeros(tilesCombined)
    var updatedBoard = reverseBoard(updatedReversedBoard)
    this.saveBoard(updatedBoard)
    return this.board
  }

  function transposeBoard(board) {
    var workingBoard = createWorkingBoard(board)
    var firstRow = []
    var secondRow = []
    var thirdRow = []
    var fourthRow = []
    for (i = 0; i < workingBoard.length; i++) {
      for (j = 0; j < workingBoard[i].length; j++) {
        if (j === 0) {
          firstRow.push(workingBoard[i][j])
        } else if (j === 1) {
          secondRow.push(workingBoard[i][j])
        } else if (j === 2) {
          thirdRow.push(workingBoard[i][j])
        } else if (j === 3) {
          fourthRow.push(workingBoard[i][j])
        }
      }
    }
    var transposedBoard = [].concat(firstRow).concat(secondRow).concat(thirdRow).concat(fourthRow)
    return transposedBoard
  }

  game = new Game("0024000000222020")
  // console.log(game.moveLeft())
  // console.log(game.moveRight())
  console.log(createWorkingBoard(transposeBoard(game.board)))
  // console.log(transposeBoard(game.board))
})

<commit_msg>Write moveDown function<commit_after>$(document).ready(function() {
  var Game = function(givenBoard) {

    function getRandomIndex(maxExclusive) {
      return Math.floor(Math.random() * maxExclusive)
    }

    function randomBoard() {
     var board = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
      var index1 = getRandomIndex(16)
      var index2 = index1

      do {
        index2 = getRandomIndex(16)
      } while (index2 === index1)

      var startingNumbers = [2, 4]

      var startingNum1 = startingNumbers[getRandomIndex(2)]
      var startingNum2 = startingNumbers[getRandomIndex(2)]

      board[index1] = startingNum1
      board[index2] = startingNum2
      return board
    }

    function presetBoard(board) {
      var boardArray = board.split("")
      for (i = 0; i < boardArray.length; i++) {
        boardArray[i] = parseInt(boardArray[i])
      }
      return boardArray
    }

    if (givenBoard === undefined) {
      this.board = randomBoard()
    } else {
      this.board = presetBoard(givenBoard)
    }
  }

  function createWorkingBoard(board) {
    return [
      board.slice(0,4),
      board.slice(4,8),
      board.slice(8,12),
      board.slice(12,16)
    ]
  }

  function removeZeros(board) {
    for (i = 0; i < board.length; i++) {
      for (j = 0; j < board[i].length; j++) {
        if (board[i][j] === 0) {
          board[i].splice(j, 1)
          j = j-1
        }
      }
    }
    return board
  }

  function combineTilesRight(board) {
    for (i = 0; i < board.length; i++) {
      for (j = board[i].length-1; j > 0; j--) {
        if (board[i][j] === board[i][j-1]) {
          board[i][j] *=2
          board[i].splice(j-1, 1)
       }
      }
    }
    return board
  }

  function padZeros(board) {
    for (i = 0; i < board.length; i++) {
      if (board[i].length !== 4) {
        do {
          board[i].unshift(0)
        } while (board[i].length < 4)
      }
    }
    return board
  }

  Game.prototype.saveBoard = function(board) {
    this.board = [].concat.apply([], board)
  }

  Game.prototype.moveRight = function() {
    var workingBoard = createWorkingBoard(this.board)
    var noZeros = removeZeros(workingBoard)
    var tilesCombined = combineTilesRight(noZeros)
    var updatedBoard = padZeros(tilesCombined)
    this.saveBoard(updatedBoard)
    return this.board
  }

  function reverseBoard(board) {
    var reverseBoard = []
    for (i = 0; i < board.length; i++) {
      reverseBoard.push(board[i].reverse())
    }
    return reverseBoard
  }

  Game.prototype.moveLeft = function() {
    var workingBoard = createWorkingBoard(this.board)
    var reversedBoard = reverseBoard(workingBoard)
    var noZeros = removeZeros(reversedBoard)
    var tilesCombined = combineTilesRight(noZeros)
    var updatedReversedBoard = padZeros(tilesCombined)
    var updatedBoard = reverseBoard(updatedReversedBoard)
    this.saveBoard(updatedBoard)
    return this.board
  }

  function transposeBoard(board) {
    var workingBoard = createWorkingBoard(board)
    var firstRow = []
    var secondRow = []
    var thirdRow = []
    var fourthRow = []
    for (i = 0; i < workingBoard.length; i++) {
      for (j = 0; j < workingBoard[i].length; j++) {
        if (j === 0) {
          firstRow.push(workingBoard[i][j])
        } else if (j === 1) {
          secondRow.push(workingBoard[i][j])
        } else if (j === 2) {
          thirdRow.push(workingBoard[i][j])
        } else if (j === 3) {
          fourthRow.push(workingBoard[i][j])
        }
      }
    }
    var transposedBoard = [].concat(firstRow).concat(secondRow).concat(thirdRow).concat(fourthRow)
    return transposedBoard
  }

  Game.prototype.moveDown = function() {
    var transposedBoard = createWorkingBoard(transposeBoard(this.board))
    var noZeros = removeZeros(transposedBoard)
    var tilesCombined = combineTilesRight(noZeros)
    var paddedBoard = padZeros(tilesCombined)
    var boardArray = [].concat.apply([], paddedBoard)
    this.board = transposeBoard(boardArray)
    return this.board
  }

  game = new Game("0024000000222020")
  game.moveDown()
  console.log(game.board)
  // console.lgame.moveRight()
  // console.log(createWorkingBoard(transposeBoard(game.board)))

})

<|endoftext|>


<commit_before>
$(function(){

  // Models
  var TrackModel = Backbone.Model.extend({
    // Default attributes
    defaults: function() {
      return {
        title: "",
        trackId: 0,
        userId: 0,
        username: ""
      };
    },

    // Set default attributes for tracks if not set previously.
    initialize: function() {
      if (!this.get("title")) {
        this.set({"title": this.defaults.title});
      }
      if (!this.get("trackId")) {
        this.set({"trackId": this.defaults.trackId});
      }
      if (!this.get("userId")) {
        this.set({"userId": this.defaults.userId});
      }
      if (!this.get("username")) {
        this.set({"username": this.defaults.username});
      }
    },

  });

  var PlaylistModel = Backbone.Model.extend({

    // Default attributes
    defaults: function() {
      return {
        title: "Untitled"
      };
    },

    // Ensure that each playlist has a title
    initialize: function(config) {
      if (!this.get("title")) {
        this.set({"title": this.defaults.title});
      }

      this.save();

      //this.set( { "tracks": new TrackCollection } );
      this.tracks = new (Backbone.Collection.extend({
        model: TrackModel,
        localStorage: new Backbone.LocalStorage("sc-playlists-"+this.id+"-tracks") // TODO: Change to cid?
      }))()
      this.tracks.fetch()
    },

    toNestedJSON: function() {
      var json = this.toJSON();
      json.tracks = this.tracks.toJSON();
      return json;
    },

    saveAll: function() {
        _.each(this.tracks.models, function(track) {
          track.save()
        })

    },

  });

  var PlaylistCollection = Backbone.Collection.extend({
    model: PlaylistModel,

    localStorage: new Backbone.LocalStorage("sc-playlists"),

    saveAll: function() {
      _.each(this.models, function(playlist) {
        playlist.save()
        playlist.saveAll()
      })
    }
  });

  // Views
  var PlaylistListView = Backbone.View.extend({

    tagName: "div",

    template: Handlebars.compile($('#tpl-playlist-list').html()),

    events: {
      "keypress #add-playlist": "addPlaylist",
    },

    initialize: function () {
      this.model.bind("reset", this.render, this);
      this.model.bind("add", this.render, this);
      this.model.bind("change", this.render, this);
      this.model.bind("remove", this.render, this);
    },

    render: function () {
      $(this.el).html("");
      this.$el.html( this.template( { playlists: this.model.toJSON() } ) );
      return this;
    },

    addPlaylist: function (e) {
      if (e.keyCode != 13) return;
      var inp = this.$('#add-playlist');
      if (!inp.val()) return;
      this.model.create( { "title": inp.val() } );
      inp.val('');
    }

  });

  var PlaylistView = Backbone.View.extend({

    tagName: "div",

    template: Handlebars.compile($('#tpl-playlist-show').html()),

    events: {
      "dblclick #playlist-title": "edit",
      "click #edit-playlist":  "edit",
      "click #playlist-save": "save",
      "click #delete-playlist":  "delete",
      "click .playpause-track":  "playPauseTrack",
      "click .delete-track":  "deleteTrack",
      "keypress #add-track": "addTrack",
    },

    initialize: function () {
        this.model.bind("reset", this.render, this);
        this.model.bind("change", this.render, this);
        this.model.tracks.bind("add", this.render, this);
        this.model.tracks.bind("change", this.render, this);
        this.model.tracks.bind("remove", this.render, this);
    },

    render: function () {
        $(this.el).html("");
        this.$el.html(this.template(this.model.toNestedJSON()));
        return this;
    },

    edit: function (event) {
      event.preventDefault();
      this.$el.addClass("editing");
      this.$('.edit.focus').focus();
    },

    save: function (event) {
      event.preventDefault();
      var title = $('#playlist-title .edit').val(),
          description = $('#playlist-description .edit').val();
      this.model.save( { title: title, description: description } );
      this.$el.removeClass("editing");
    },

    delete: function (event) {
      event.preventDefault();
      var doRemove = confirm("Are you sure you would like to delete the playlist '"+this.model.get("title")+"'? This cannot be undone.");
      if (doRemove) {
        this.model.destroy();
        app.navigate("/", {trigger: true});
      }
    },

    playPauseTrack: function (event) {
      event.preventDefault();

      var newTrackId = $(event.currentTarget).attr('data-track-id');
      var track = this.model.tracks.get(newTrackId);
      var trackIndex = this.model.tracks.indexOf(track);

      if (this.currentTrackIndex == trackIndex) {
        this.currentTrack.togglePause();
      } else {
        if (this.currentTrackIndex !== null && this.currentTrack !== null) {
          this.currentTrack.pause();
        }

        this.loopTracks(trackIndex);
      }
    },

    deleteTrack: function (event) {
      event.preventDefault();
      var trackId = $(event.currentTarget).attr('data-track-id');
      var track = this.model.tracks.get(trackId);
      var doRemove = confirm("Are you sure you would like to delete the track '"+track.get("title")+"'? This cannot be undone.");
      if (doRemove) {
        track.destroy();
      }
    },

    currentTrackIndex: null,
    currentTrack: null,

    resetPlayPauseIcons: function () {
      $('.playpause-track i.icon-play').show();
      $('.playpause-track i.icon-pause').hide();
    },

    loopTracks: function (startIndex) {
      this.currentTrackIndex = startIndex;

      this.resetPlayPauseIcons();
      var track = this.model.tracks.at(this.currentTrackIndex);
      var trackId = track.get("id");

      var self = this;
      SC.stream("/tracks/"+track.get('trackId'), {
        autoPlay: true,
        onplay: function () {
          self.currentTrack = this;
          $('#playpause-track-'+trackId+' i.icon-play').hide();
          $('#playpause-track-'+trackId+' i.icon-pause').show();
        },
        onpause: function () {
          $('#playpause-track-'+trackId+' i.icon-play').show();
          $('#playpause-track-'+trackId+' i.icon-pause').hide();
        },
        onfinish: function () {
          var newIndex = self.currentTrackIndex+1;
          if (newIndex < self.model.tracks.length) {
            self.loopTracks(newIndex);
          } else {
            currentTrackIndex = null;
            currentTrack = null;
            self.resetPlayPauseIcons();
          }
        }
      });
    },

    addTrack: function (e) {
      if (e.keyCode != 13) return;
      var inp = this.$('#add-track');
      if (!inp.val()) return;
      var self = this;
      var scTrack = SC.get("/resolve", {url: inp.val()}, function (obj, err) {
        if (err === null && typeof(obj.kind) !== 'undefined' && obj.kind == "track") {
          self.model.tracks.create( { title: obj.title,
                                      trackId: obj.id,
                                      userId: obj.user_id,
                                      username: obj.user.username });
        } else {
          alert("The provided url is not a valid soundcloud track.");
        }
      });

      inp.val('');
    }

  });

  // Router
  var AppRouter = Backbone.Router.extend({

      routes: {
          "":"playlists",
          "playlists/:id": "showPlaylist"
      },

      initialize: function () {
        this.playlistList = new PlaylistCollection;
      },

      playlists: function () {
        this.playlistListView = new PlaylistListView({model:this.playlistList});
        this.playlistList.fetch();
        $('#content').html(this.playlistListView.render().el);
      },

      showPlaylist: function (id) {
        this.playlistList.fetch();
        this.playlist = this.playlistList.get(id);
        this.playlistView = new PlaylistView( { model: this.playlist } );
        $('#content').html(this.playlistView.render().el);
      }
  });

  var app = new AppRouter();
  Backbone.history.start();

});
<commit_msg>Cleanup<commit_after>
$(function(){

  // Models
  var TrackModel = Backbone.Model.extend({
    // Default attributes
    defaults: function() {
      return {
        title: "",
        trackId: 0,
        userId: 0,
        username: ""
      };
    },

    // Set default attributes for tracks if not set previously.
    initialize: function() {
      if (!this.get("title")) {
        this.set({"title": this.defaults.title});
      }
      if (!this.get("trackId")) {
        this.set({"trackId": this.defaults.trackId});
      }
      if (!this.get("userId")) {
        this.set({"userId": this.defaults.userId});
      }
      if (!this.get("username")) {
        this.set({"username": this.defaults.username});
      }
    },

  });

  var PlaylistModel = Backbone.Model.extend({

    // Default attributes
    defaults: function() {
      return {
        title: "Untitled"
      };
    },

    // Ensure that each playlist has a title
    initialize: function(config) {
      if (!this.get("title")) {
        this.set({"title": this.defaults.title});
      }

      this.save();

      //this.set( { "tracks": new TrackCollection } );
      this.tracks = new (Backbone.Collection.extend({
        model: TrackModel,

        localStorage: new Backbone.LocalStorage("sc-playlists-"+this.id+"-tracks"),

      }))()
      this.tracks.fetch()
    },

    toNestedJSON: function() {
      var json = this.toJSON();
      json.tracks = this.tracks.toJSON();
      return json;
    },

    saveAll: function() {
        _.each(this.tracks.models, function(track) {
          track.save()
        })

    },

  });

  var PlaylistCollection = Backbone.Collection.extend({
    model: PlaylistModel,

    localStorage: new Backbone.LocalStorage("sc-playlists"),

    saveAll: function() {
      _.each(this.models, function(playlist) {
        playlist.save()
        playlist.saveAll()
      })
    }
  });

  // Views
  var PlaylistListView = Backbone.View.extend({

    tagName: "div",

    template: Handlebars.compile($('#tpl-playlist-list').html()),

    events: {
      "keypress #add-playlist": "addPlaylist",
    },

    initialize: function () {
      this.model.bind("reset", this.render, this);
      this.model.bind("add", this.render, this);
      this.model.bind("change", this.render, this);
      this.model.bind("remove", this.render, this);
    },

    render: function () {
      $(this.el).html("");
      this.$el.html( this.template( { playlists: this.model.toJSON() } ) );
      return this;
    },

    addPlaylist: function (event) {
      if (event.keyCode != 13) return;
      var inp = this.$('#add-playlist');
      if (!inp.val()) return;
      this.model.create( { "title": inp.val() } );
      inp.val('');
    }

  });

  var PlaylistView = Backbone.View.extend({

    tagName: "div",

    template: Handlebars.compile($('#tpl-playlist-show').html()),

    events: {
      "dblclick #playlist-title": "edit",
      "click #edit-playlist":  "edit",
      "click #playlist-save": "save",
      "click #delete-playlist":  "delete",
      "click .playpause-track":  "playPauseTrack",
      "click .delete-track":  "deleteTrack",
      "keypress #add-track": "addTrack",
    },

    initialize: function () {
        this.model.bind("reset", this.render, this);
        this.model.bind("change", this.render, this);
        this.model.tracks.bind("add", this.render, this);
        this.model.tracks.bind("change", this.render, this);
        this.model.tracks.bind("remove", this.render, this);
    },

    render: function () {
        $(this.el).html("");
        this.$el.html(this.template(this.model.toNestedJSON()));
        return this;
    },

    edit: function (event) {
      event.preventDefault();
      this.$el.addClass("editing");
      this.$('.edit.focus').focus();
    },

    save: function (event) {
      event.preventDefault();
      var title = $('#playlist-title .edit').val(),
          description = $('#playlist-description .edit').val();
      this.model.save( { title: title, description: description } );
      this.$el.removeClass("editing");
    },

    delete: function (event) {
      event.preventDefault();
      var doRemove = confirm("Are you sure you would like to delete the playlist '"+this.model.get("title")+"'? This cannot be undone.");
      if (doRemove) {
        this.model.destroy();
        app.navigate("/", {trigger: true});
      }
    },

    playPauseTrack: function (event) {
      event.preventDefault();

      var newTrackId = $(event.currentTarget).attr('data-track-id');
      var track = this.model.tracks.get(newTrackId);
      var trackIndex = this.model.tracks.indexOf(track);

      if (this.currentTrackIndex == trackIndex) {
        this.currentTrack.togglePause();
      } else {
        if (this.currentTrackIndex !== null && this.currentTrack !== null) {
          this.currentTrack.pause();
        }

        this.loopTracks(trackIndex);
      }
    },

    deleteTrack: function (event) {
      event.preventDefault();
      var trackId = $(event.currentTarget).attr('data-track-id');
      var track = this.model.tracks.get(trackId);
      var doRemove = confirm("Are you sure you would like to delete the track '"+track.get("title")+"'? This cannot be undone.");
      if (doRemove) {
        track.destroy();
      }
    },

    currentTrackIndex: null,
    currentTrack: null,

    resetPlayPauseIcons: function () {
      $('.playpause-track i.icon-play').show();
      $('.playpause-track i.icon-pause').hide();
    },

    loopTracks: function (startIndex) {
      this.currentTrackIndex = startIndex;

      this.resetPlayPauseIcons();
      var track = this.model.tracks.at(this.currentTrackIndex);
      var trackId = track.get("id");

      var self = this;
      SC.stream("/tracks/"+track.get('trackId'), {
        autoPlay: true,
        onplay: function () {
          self.currentTrack = this;
          $('#playpause-track-'+trackId+' i.icon-play').hide();
          $('#playpause-track-'+trackId+' i.icon-pause').show();
        },
        onpause: function () {
          $('#playpause-track-'+trackId+' i.icon-play').show();
          $('#playpause-track-'+trackId+' i.icon-pause').hide();
        },
        onfinish: function () {
          var newIndex = self.currentTrackIndex+1;
          if (newIndex < self.model.tracks.length) {
            self.loopTracks(newIndex);
          } else {
            currentTrackIndex = null;
            currentTrack = null;
            self.resetPlayPauseIcons();
          }
        }
      });
    },

    addTrack: function (e) {
      if (e.keyCode != 13) return;
      var inp = this.$('#add-track');
      if (!inp.val()) return;
      var self = this;
      var scTrack = SC.get("/resolve", {url: inp.val()}, function (obj, err) {
        if (err === null && typeof(obj.kind) !== 'undefined' && obj.kind == "track") {
          self.model.tracks.create( { title: obj.title,
                                      trackId: obj.id,
                                      userId: obj.user_id,
                                      username: obj.user.username });
        } else {
          alert("The provided url is not a valid soundcloud track.");
        }
      });

      inp.val('');
    }

  });

  // Router
  var AppRouter = Backbone.Router.extend({

      routes: {
          "":"playlists",
          "playlists/:id": "showPlaylist"
      },

      initialize: function () {
        this.playlistList = new PlaylistCollection;
      },

      playlists: function () {
        this.playlistListView = new PlaylistListView({model:this.playlistList});
        this.playlistList.fetch();
        $('#content').html(this.playlistListView.render().el);
      },

      showPlaylist: function (id) {
        this.playlistList.fetch();
        this.playlist = this.playlistList.get(id);
        this.playlistView = new PlaylistView( { model: this.playlist } );
        $('#content').html(this.playlistView.render().el);
      }
  });

  var app = new AppRouter();
  Backbone.history.start();

});
<|endoftext|>


<commit_before>$(document).ready(function() {
  $('.new_game_button').on('click', function(){
    newGame = new Game();
    newGame.updateBoard();
  })

  // var ways = ['left', 'right', 'up', 'down'];
  // for (var i=0; i< ways.length; i++) {
  //   Mousetrap.bind(ways[i], function(){ newGame.loop(ways[i]); })
  // };
//     Mousetrap.bind('left', function(){ newGame.loop('left')});
//     Mousetrap.bind('right', function(){newGame.loop('right')});
//     Mousetrap.bind('up', function(){newGame.loop('up')});
//     Mousetrap.bind('down', function(){newGame.loop('down')});
// });

  Mousetrap.bind('left', function(){ newGame.moveLeft(); newGame.spawn(); newGame.updateBoard();});
  Mousetrap.bind('right', function(){newGame.moveRight(); newGame.spawn(); newGame.updateBoard();});
  Mousetrap.bind('up', function(){newGame.moveUp(); newGame.spawn(); newGame.updateBoard();});
  Mousetrap.bind('down', function(){newGame.moveDown(); newGame.spawn(); newGame.updateBoard();});
});
<commit_msg>add white space<commit_after>$(document).ready(function() {
  $('.new_game_button').on('click', function(){
    newGame = new Game();
    newGame.updateBoard();
  })

  // var ways = ['left', 'right', 'up', 'down'];
  // for (var i=0; i< ways.length; i++) {
  //   Mousetrap.bind(ways[i], function(){ newGame.loop(ways[i]); })
  // };
//     Mousetrap.bind('left', function(){ newGame.loop('left')});
//     Mousetrap.bind('right', function(){newGame.loop('right')});
//     Mousetrap.bind('up', function(){newGame.loop('up')});
//     Mousetrap.bind('down', function(){newGame.loop('down')});
// });
  Mousetrap.bind('left', function(){ newGame.moveLeft(); newGame.spawn(); newGame.updateBoard();});
  Mousetrap.bind('right', function(){newGame.moveRight(); newGame.spawn(); newGame.updateBoard();});
  Mousetrap.bind('up', function(){newGame.moveUp(); newGame.spawn(); newGame.updateBoard();});
  Mousetrap.bind('down', function(){newGame.moveDown(); newGame.spawn(); newGame.updateBoard();});
});
<|endoftext|>


<commit_before>import { createSelector} from 'reselect';

const getMaterias = state => state.seguidor.materias
const getEstados = state => state.seguidor.estados
const getCorrelativas = state => state.seguidor.correlativas

/*
 *   Estados:
 *   1 - Pendiente
 *   2 - Cursando
 *   3 - Firmada
 *   4 - Aprobada
 *
 *   Los que importan en este caso son firma(3) y aprobación(4).
*/
const ESTADO_FIRMA = 3;
const ESTADO_APROBACION = 4;

/*
 * @name: validarReq
 * @desc: Valida un conjunto de requerimientos contra un conjunto de estados.
 * @param requerimientos: el conjunto de requerimientos a validar.
 * @param estados: estados contra los que se comparan los requerimientos.
 * @param estado: el estado que se quiere que tengan los requerimientos (aprobada/firmada).
*/
function validarReq(requerimientos, estados, estado)
{
    let _valido = true;

	// No hay requisitos, la condición es verdadera.
	if(!requerimientos || requerimientos.length == 0)
		return true;

    for(var req of requerimientos)
	{
	  var result = estados.filter(e => e.id == req && e.status >= estado);

  	  if(result.length == 0)
	  {
	     _valido = false;
		 break;
      }
	}

	return _valido;
}

// TODO: Por ahora solo evalúa si puede cursar la materia _NO_ si puede dar final.
// materia: materia cuyo estado se desea conocer.
// correlativas: correlativas de esa materia.
// aprobadas: materias aprobadas hasta el momento.
function getEstadoMateria(_correlativas, estados){

   if(_correlativas.length == 0)
	  return { cursada: true, final: true};

   const c_cursadas = _correlativas["rCC"];
   const c_finales  = _correlativas["rFC"];

   const f_cursadas = _correlativas["rCF"];
   const f_finales  = _correlativas["rFF"];

   const puedeCursar = validarReq(c_cursadas, estados, ESTADO_FIRMA) &&
                       validarReq(c_finales, estados, ESTADO_APROBACION);

   const puededarFinal = validarReq(f_cursadas, estados, ESTADO_FIRMA) &&
                         validarReq(f_finales, estados, ESTADO_APROBACION);

   return { cursada: puedeCursar, final: puededarFinal };
}

const getMateriasEstado = createSelector(
  [ getMaterias, getEstados, getCorrelativas ],
  (materias, estados, correlativas) => {
	 for(var materia of materias)
	 {
		const _materiaEstado = estados.filter(c => c.id == materia.id);
		let estadoMateria = 1; // Por defecto, la materia esta pendiente.

		if(_materiaEstado.length > 0)
			estadoMateria = _materiaEstado[0].status

		let _correlativas = correlativas.filter(c => c.m == materia.id);

		if(_correlativas.length > 0)
          _correlativas = _correlativas[0].d;

		let estado = getEstadoMateria(_correlativas, estados);

		materia.status = (estado.cursada == false ? 1 : estadoMateria);
		materia.cursada = estado.cursada;
		materia.final = estado.final;
	  }

	  return materias;
   }
);

export default getMateriasEstado;<commit_msg>+ Documentar mejor las funciones. + Remover comentario sobre el calculo del estado que dejo de ser cierto. + Arreglar indentación.<commit_after>import { createSelector} from 'reselect';

const getMaterias = state => state.seguidor.materias
const getEstados = state => state.seguidor.estados
const getCorrelativas = state => state.seguidor.correlativas

/*
 *   Estados:
 *   1 - Pendiente
 *   2 - Cursando
 *   3 - Firmada
 *   4 - Aprobada
 *
 *   Los que importan en este caso son firma(3) y aprobación(4).
*/
const ESTADO_FIRMA = 3;
const ESTADO_APROBACION = 4;

/*
 * @name: validarReq
 * @desc: Valida un conjunto de requerimientos contra un conjunto de estados.
 * @param requerimientos: el conjunto de requerimientos a validar.
 * @param estados: estados contra los que se comparan los requerimientos.
 * @param estado: el estado que se quiere que tengan los requerimientos (aprobada/firmada).
*/
function validarReq(requerimientos, estados, estado)
{
    let _valido = true;

	// No hay requisitos, la condición es verdadera.
	if(!requerimientos || requerimientos.length == 0)
		return true;

    for(var req of requerimientos)
	{
	  var result = estados.filter(e => e.id == req && e.status >= estado);

  	  if(result.length == 0)
	  {
	     _valido = false;
		 break;
      }
	}

	return _valido;
}

/*
 * @name: getEstadoMateria
 * @desc: Obtiene el estado de una materia (si se puede cursar o dar final).
 * @param materia: materia cuyo estado se desea conocer.
 * @param correlativas: correlativas de esa materia.
 * @param aprobadas: materias aprobadas hasta el momento.
*/
function getEstadoMateria(_correlativas, estados)
{

   if(_correlativas.length == 0)
       return { cursada: true, final: true};

   // Requisitos para cursar.
   const c_cursadas = _correlativas["rCC"];
   const c_finales  = _correlativas["rFC"];

   // Requisitos para dar final.
   const f_cursadas = _correlativas["rCF"];
   const f_finales  = _correlativas["rFF"];

   const puedeCursar = validarReq(c_cursadas, estados, ESTADO_FIRMA) &&
                       validarReq(c_finales, estados, ESTADO_APROBACION);

   const puededarFinal = validarReq(f_cursadas, estados, ESTADO_FIRMA) &&
                         validarReq(f_finales, estados, ESTADO_APROBACION);

   return { cursada: puedeCursar, final: puededarFinal };
}

// Obtiene las materias con estado.
const getMateriasEstado = createSelector(
  [ getMaterias, getEstados, getCorrelativas ],
  (materias, estados, correlativas) => {
	 for(var materia of materias)
	 {
		const _materiaEstado = estados.filter(c => c.id == materia.id);
		let estadoMateria = 1; // Por defecto, la materia esta pendiente.

		if(_materiaEstado.length > 0)
          estadoMateria = _materiaEstado[0].status

		let _correlativas = correlativas.filter(c => c.m == materia.id);

		if(_correlativas.length > 0)
          _correlativas = _correlativas[0].d;

		let estado = getEstadoMateria(_correlativas, estados);

		materia.status = (estado.cursada == false ? 1 : estadoMateria);
		materia.cursada = estado.cursada;
		materia.final = estado.final;

	  }

	  return materias;
   }
);

export default getMateriasEstado;<|endoftext|>


<commit_before>//Main game file
"use strict";
var game = game || {};

game.battleBalls = {
  canvas : undefined,
  ctx : undefined,
  arena : undefined,
  playerIDs : [],
  players : {},
  sparks : [],
  booms : [],

  init : function(){
    var me = this;

    // create new instance of socket.io
    var num = Math.floor(Math.random()*10);
    var name ='user'+num;

    //setting client's own properties (MIGHT NOT BE THE BEST PRACTICE);
    var socket = io.connect( window.location.origin, {query: 'user='+name, type: 'desktop'});

    me.canvas = document.querySelector('#area');
    me.ctx = me.canvas.getContext('2d');
    me.ctx.lineWidth = 5;
    me.arena = game.createArena('white', /*230*/me.canvas.height/2-10, me.canvas.width/2, me.canvas.height/2);

    //Set up socket events --Ha Andrew don't look at this --You can't stop me
    socket.on('player join', function(data){
      var x = me.canvas.width/2, y = me.canvas.height/2;
      me.players[data.id] = new game.Player(data.id, data.color, x, y);
      me.playerIDs.push(data.id);
    });

    socket.on('player leave', function(data){
      me.playerIDs.splice(me.playerIDs.indexOf(data.id),1);
      delete me.players[data.id];
    });

    socket.on('charge start', function(data){
      me.players[data.id].beginCharge("boom");
    });

    socket.on('charge end', function(data){
      me.players[data.id].endCharge();
    });

    socket.on('phone tilt', function(data) {
      if(me.players[data.id]) {
        me.players[data.id].updateAcceleration(data.yAcc/300, -data.xAcc/300);
      } //my eyes are everywhere --I will gouge your eyes out
    });
    /*me.playerIDs.push('test');
    me.players['test'] = new game.Player(11, 'red', 200, me.canvas.height/2);
    //me.players[12] = new game.Player(12, 'blue', 400, me.canvas.height/2);
    me.players[11].updateAcceleration(0, 0);
    //me.players[12].updateAcceleration(-1/20, 0);
    */
    me.loop();
  },

  loop : function() {
    requestAnimationFrame(this.loop.bind(this));
    this.update();
    this.render();
  },

  update : function() {
    var dt = 0;
    var me = this;
    me.playerIDs.forEach(function(id) {
      var player = me.players[id];
      //Ugly collisions
      me.playerIDs.forEach(function(id2){
        var player2 = me.players[id2];
        if(player2.id !== player.id){

          if(game.physicsUtils.circleCollision(player, player2) && !player.colliding(player2)) {
            //get impulse
            var impulse = game.physicsUtils.getImpulse(player, player2, 1.5);
            player.applyImpulse(impulse);
            impulse.x = impulse.x * -1;
            impulse.y = impulse.y * -1;
            player2.applyImpulse(impulse);
            player2.collisions.push(player);
            player.collisions.push(player2);
            //me.addSparks(player, player2, impulse);
          }
        }
      });
      //Bad code for resetting player if they leave the arena
      if(!me.arena.inBounds(player)) {
        player.x = me.canvas.width/2;
        player.y = me.canvas.width/2;
      }
      player.update(dt);
    });

    me.booms.forEach(function(boom, index, array){
      boom.update(dt);
      var boomc = {
        x : boom.play.x,
        y : boom.play.y,
        velocity : {x:0, y:0},
        mass : boom.pow * 20,
        radius : boom.radius
      };
      //duplicate, make a helper function
      me.playerIDs.forEach(function(id){
        var player = me.players[id];
        if(boom.id !== player.id){
          if(game.physicsUtils.circleCollision(player, boomc)) {
            //get impulse
            var impulse = {x:0, y:0};
            impulse = game.physicsUtils.normalize(game.physicsUtils.vecDiff(player, boomc));
            impulse.x *= 15;
            impulse.y *= 15;
            player.applyImpulse(impulse);
            //me.addSparks(player, player2, impulse);
          }
        }
      });

      if(boom.remove) {
        array.splice(index, 1);
      }
    });

    this.sparks.forEach(function(spark, index, array){
      spark.update(dt);
      if(spark.remove) {
        array.splice(index, 1);
      }
    });
  },

  addSparks : function(c1, c2, impulse) {
    var line = game.physicsUtils.getPerp(game.physicsUtils.getSlope(c1, c2));
    var x = c1.x - (c1.x - c2.x)/2;
    var y = c1.y - (c1.y - c2.y)/2;

    this.sparks.push(new game.Spark(x, y, line.x/5, line.y/5));
    this.sparks.push(new game.Spark(x, y, -line.x/5, -line.y/5));
  },

  render : function() {
    var me = this;
    me.ctx.save();
    me.ctx.fillStyle = 'black';
    me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
    me.ctx.restore();
    me.arena.render(me.ctx);
    me.playerIDs.forEach(function(id) {
      var player = me.players[id];
      player.render(me.ctx);
    });
    me.booms.forEach(function(boom) {
      boom.render(me.ctx);
    });
    me.sparks.forEach(function(spark) {
      spark.render(me.ctx);
    });
  }
}<commit_msg>Added function to get delta time<commit_after>//Main game file
"use strict";
var game = game || {};

game.battleBalls = {
  canvas : undefined,
  ctx : undefined,
  arena : undefined,
  playerIDs : [],
  players : {},
  sparks : [],
  booms : [],
  dt : 0,
  lastTime : 0,

  init : function(){
    var me = this;
    me.lastTime = Date.now();
    // create new instance of socket.io
    var num = Math.floor(Math.random()*10);
    var name ='user'+num;

    //setting client's own properties (MIGHT NOT BE THE BEST PRACTICE);
    var socket = io.connect( window.location.origin, {query: 'user='+name, type: 'desktop'});

    me.canvas = document.querySelector('#area');
    me.ctx = me.canvas.getContext('2d');
    me.ctx.lineWidth = 5;
    me.arena = game.createArena('white', /*230*/me.canvas.height/2-10, me.canvas.width/2, me.canvas.height/2);

    //Set up socket events --Ha Andrew don't look at this --You can't stop me
    socket.on('player join', function(data){
      var x = me.canvas.width/2, y = me.canvas.height/2;
      me.players[data.id] = new game.Player(data.id, data.color, x, y);
      me.playerIDs.push(data.id);
    });

    socket.on('player leave', function(data){
      me.playerIDs.splice(me.playerIDs.indexOf(data.id),1);
      delete me.players[data.id];
    });

    socket.on('charge start', function(data){
      me.players[data.id].beginCharge("boom");
    });

    socket.on('charge end', function(data){
      me.players[data.id].endCharge();
    });

    socket.on('phone tilt', function(data) {
      if(me.players[data.id]) {
        me.players[data.id].updateAcceleration(data.yAcc/300, -data.xAcc/300);
      } //my eyes are everywhere --I will gouge your eyes out
    });
    /*me.playerIDs.push('test');
    me.players['test'] = new game.Player(11, 'red', 200, me.canvas.height/2);
    //me.players[12] = new game.Player(12, 'blue', 400, me.canvas.height/2);
    me.players[11].updateAcceleration(0, 0);
    //me.players[12].updateAcceleration(-1/20, 0);
    */
    me.loop();
  },

  loop : function() {
    requestAnimationFrame(this.loop.bind(this));
    this.update();
    this.render();
  },

  updateTime : function() {
    var now = Date.now();
    this.dt = now - this.lastTime;
    this.lastTime = now;
  },

  update : function() {
    this.updtateTime();
    var me = this;
    console.log(me.dt);
    me.playerIDs.forEach(function(id) {
      var player = me.players[id];
      //Ugly collisions
      me.playerIDs.forEach(function(id2){
        var player2 = me.players[id2];
        if(player2.id !== player.id){

          if(game.physicsUtils.circleCollision(player, player2) && !player.colliding(player2)) {
            //get impulse
            var impulse = game.physicsUtils.getImpulse(player, player2, 1.5);
            player.applyImpulse(impulse);
            impulse.x = impulse.x * -1;
            impulse.y = impulse.y * -1;
            player2.applyImpulse(impulse);
            player2.collisions.push(player);
            player.collisions.push(player2);
            //me.addSparks(player, player2, impulse);
          }
        }
      });
      //Bad code for resetting player if they leave the arena
      if(!me.arena.inBounds(player)) {
        player.x = me.canvas.width/2;
        player.y = me.canvas.width/2;
      }
      player.update(me.dt);
    });

    me.booms.forEach(function(boom, index, array){
      boom.update(me.dt);
      var boomc = {
        x : boom.play.x,
        y : boom.play.y,
        velocity : {x:0, y:0},
        mass : boom.pow * 20,
        radius : boom.radius
      };
      //duplicate, make a helper function
      me.playerIDs.forEach(function(id){
        var player = me.players[id];
        if(boom.id !== player.id){
          if(game.physicsUtils.circleCollision(player, boomc)) {
            //get impulse
            var impulse = {x:0, y:0};
            impulse = game.physicsUtils.normalize(game.physicsUtils.vecDiff(player, boomc));
            impulse.x *= 15;
            impulse.y *= 15;
            player.applyImpulse(impulse);
            //me.addSparks(player, player2, impulse);
          }
        }
      });

      if(boom.remove) {
        array.splice(index, 1);
      }
    });

    this.sparks.forEach(function(spark, index, array){
      spark.update(me.dt);
      if(spark.remove) {
        array.splice(index, 1);
      }
    });
  },

  addSparks : function(c1, c2, impulse) {
    var line = game.physicsUtils.getPerp(game.physicsUtils.getSlope(c1, c2));
    var x = c1.x - (c1.x - c2.x)/2;
    var y = c1.y - (c1.y - c2.y)/2;

    this.sparks.push(new game.Spark(x, y, line.x/5, line.y/5));
    this.sparks.push(new game.Spark(x, y, -line.x/5, -line.y/5));
  },

  render : function() {
    var me = this;
    me.ctx.save();
    me.ctx.fillStyle = 'black';
    me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
    me.ctx.restore();
    me.arena.render(me.ctx);
    me.playerIDs.forEach(function(id) {
      var player = me.players[id];
      player.render(me.ctx);
    });
    me.booms.forEach(function(boom) {
      boom.render(me.ctx);
    });
    me.sparks.forEach(function(spark) {
      spark.render(me.ctx);
    });
  }
}<|endoftext|>