<commit_before>// Ugis Germanis
// My javascript

var music = {
    selected: "byartist",
    sort: new Event('sort'),
};

document.addEventListener("sort", function(e){
    console.log("sort event: ", music.selected);
}, false)

window.addEventListener('WebComponentsReady', function(e) {
    console.log('webcomponents are ready!!!');
    //Init the default
    document.getElementById(music.selected).active=true;
    document.dispatchEvent(music.sort);
    //Nifty button stuff
    var sorter = document.getElementsByClassName("sorter");
    for (i=0; i< sorter.length; i++) {
        sorter[i].addEventListener("change", function(e){
            music.selected = e.path[0].id
            for(j=0; j<sorter.length; j++){
                sorter[j].active=false;
            }
            document.getElementById(music.selected).active=true;
            document.dispatchEvent(music.sort);
        }, false);
    }
});<commit_msg>fix firefox<commit_after>// Ugis Germanis
// My javascript

var music = {
    selected: "byartist",
    sort: new Event('sort'),
};

document.addEventListener("sort", function(e){
    console.log("sort event: ", music.selected);
}, false)

window.addEventListener('WebComponentsReady', function(e) {
    console.log('webcomponents are ready!!!');
    //Init the default
    document.getElementById(music.selected).active=true;
    document.dispatchEvent(music.sort);
    //Nifty button stuff
    var sorter = document.getElementsByClassName("sorter");
    for (i=0; i< sorter.length; i++) {
        sorter[i].addEventListener("change", function(e){
            music.selected = e.target.id
            for(j=0; j<sorter.length; j++){
                sorter[j].active=false;
            }
            document.getElementById(music.selected).active=true;
            document.dispatchEvent(music.sort);
        }, false);
    }
});<|endoftext|>


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

/**
 * base class for model elements that can be moved around by the user
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanProperty = require( 'AXON/BooleanProperty' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var inherit = require( 'PHET_CORE/inherit' );
  var ModelElement = require( 'ENERGY_FORMS_AND_CHANGES/common/model/ModelElement' );
  var Property = require( 'AXON/Property' );

  /**
   * {Vector2} initialPosition
   * @constructor
   */
  function UserMovableModelElement( initialPosition ) {

    var self = this;

    ModelElement.call( this, initialPosition );

    // @public {BooleanProperty}
    this.userControlledProperty = new BooleanProperty( false );

    // @protected {HorizontalSurface|null} - The surface upon which this model element is resting.  This is null if the
    // element is not resting on a movable surface.  This should only be set through the getter/setter methods below.
    this.supportingSurface = null;

    // @public {Property.<number>}
    this.verticalVelocityProperty = new Property( 0 );

    // update internal state when the user picks up this model element
    this.userControlledProperty.link( function( userControlled ) {
      if ( userControlled ) {

        // the user has picked up this model element, so it is no longer sitting on any surface
        self.clearSupportingSurface();
      }
    } );

    // @private - observer that moves this model element if and when the surface that is supporting it moves
    this.surfaceMotionObserver = function( position ) {
      self.positionProperty.value = position;
    };
  }

  energyFormsAndChanges.register( 'UserMovableModelElement', UserMovableModelElement );

  return inherit( ModelElement, UserMovableModelElement, {

    /**
     * restore initial state
     * @public
     */
    reset: function() {
      this.clearSupportingSurface();
      this.userControlledProperty.reset();
      this.verticalVelocityProperty.reset();
      ModelElement.prototype.reset.call( this );
    },

    /**
     * Set the supporting surface of this model element
     * @param {HorizontalSurface} supportingSurface
     * @override
     * @public
     */
    setSupportingSurface: function( supportingSurface ) {

      // state and parameter checking
      assert && assert(
        supportingSurface !== null,
        'this method should not be used to clear the supporting surface'
      );
      assert && assert(
        this.supportingSurface === null,
        'a supporting surface was already set'
      );

      supportingSurface.positionProperty.link( this.surfaceMotionObserver );
      this.supportingSurface = supportingSurface;
    },

    /**
     * clear the supporting surface so that this model element is no longer sitting on a surface
     * @public TODO: Check this visibility when sim dev is closer to completion
     */
    clearSupportingSurface: function() {

      // only do something if the supporting surface was set
      if ( this.supportingSurface !== null ) {
        this.supportingSurface.positionProperty.unlink( this.surfaceMotionObserver );
        this.supportingSurface.elementOnSurfaceProperty.set( null );
        this.supportingSurface = null;
      }
    },

    /**
     * get a value that indicates whether this element is stacked upon the given model element
     * @param {ModelElement} element - model element to be checked
     * @returns {boolean} - true if this model element is stacked anywhere on top of the provided element, which
     * includes cases where one or more elements are in between.
     * @public
     * @override
     */
    isStackedUpon: function( element ) {
      var surface = this.supportingSurface ? this.supportingSurface : null;
      return ( surface !== null ) && ( surface.owner === element || surface.owner.isStackedUpon( element ) );
    }

  } );
} );

<commit_msg>Convert to ES6, see https://github.com/phetsims/energy-forms-and-changes/issues/211<commit_after>// Copyright 2014-2018, University of Colorado Boulder

/**
 * base class for model elements that can be moved around by the user
 *
 * @author John Blanco
 */
define( require => {
  'use strict';

  // modules
  const BooleanProperty = require( 'AXON/BooleanProperty' );
  const energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  const ModelElement = require( 'ENERGY_FORMS_AND_CHANGES/common/model/ModelElement' );
  const Property = require( 'AXON/Property' );

  class UserMovableModelElement extends ModelElement {

    /**
     * {Vector2} initialPosition
     */
    constructor( initialPosition ) {
      super( initialPosition );

      // @public {BooleanProperty}
      this.userControlledProperty = new BooleanProperty( false );

      // @protected {HorizontalSurface|null} - The surface upon which this model element is resting.  This is null if the
      // element is not resting on a movable surface.  This should only be set through the getter/setter methods below.
      this.supportingSurface = null;

      // @public {Property.<number>}
      this.verticalVelocityProperty = new Property( 0 );

      // update internal state when the user picks up this model element
      this.userControlledProperty.link( userControlled => {
        if ( userControlled ) {

          // the user has picked up this model element, so it is no longer sitting on any surface
          this.clearSupportingSurface();
        }
      } );

      // @private - observer that moves this model element if and when the surface that is supporting it moves
      this.surfaceMotionObserver = position => {
        this.positionProperty.value = position;
      };
    }

    /**
     * restore initial state
     * @public
     */
    reset() {
      this.clearSupportingSurface();
      this.userControlledProperty.reset();
      this.verticalVelocityProperty.reset();
      super.reset();
    }

    /**
     * Set the supporting surface of this model element
     * @param {HorizontalSurface} supportingSurface
     * @override
     * @public
     */
    setSupportingSurface( supportingSurface ) {

      // state and parameter checking
      assert && assert(
        supportingSurface !== null,
        'this method should not be used to clear the supporting surface'
      );
      assert && assert(
        this.supportingSurface === null,
        'a supporting surface was already set'
      );

      supportingSurface.positionProperty.link( this.surfaceMotionObserver );
      this.supportingSurface = supportingSurface;
    }

    /**
     * clear the supporting surface so that this model element is no longer sitting on a surface
     * @private
     */
    clearSupportingSurface() {

      // only do something if the supporting surface was set
      if ( this.supportingSurface !== null ) {
        this.supportingSurface.positionProperty.unlink( this.surfaceMotionObserver );
        this.supportingSurface.elementOnSurfaceProperty.set( null );
        this.supportingSurface = null;
      }
    }

    /**
     * get a value that indicates whether this element is stacked upon the given model element
     * @param {ModelElement} element - model element to be checked
     * @returns {boolean} - true if this model element is stacked anywhere on top of the provided element, which
     * includes cases where one or more elements are in between.
     * @public
     * @override
     */
    isStackedUpon( element ) {
      const surface = this.supportingSurface ? this.supportingSurface : null;
      return ( surface !== null ) && ( surface.owner === element || surface.owner.isStackedUpon( element ) );
    }
  }

  return energyFormsAndChanges.register( 'UserMovableModelElement', UserMovableModelElement );
} );

<|endoftext|>


<commit_before>(function (c) {
  if (!c) {
    throw 'Oops, Crafty not found';
  }

  c.init(187, 374);
  c.canvas.init();

  c.background('/img/bg.png');

}(Crafty));
<commit_msg>added scene and sprites<commit_after>(function (c) {
  if (!c) {
    throw 'Oops, Crafty not found';
  }

  c.init(197, 384);
  c.canvas.init();

  c.background('url(/img/objects/board_bg.png)');

  c.sprite(40, "/img/tiles_spritesheet.png", {
      tile_blue: [0,0],
      tile_red: [1,0],
      tile_orange: [2,0],
      tile_green: [3,0],
      monster_blue: [4,0],
      monster_red: [5,0],
      monster_orange: [6,0],
      monster_green: [7,0],
    });

  c.scene("game", function() {

  });

  c.scene("game");

}(Crafty));
<|endoftext|>


<commit_before>$("#menu-toggle").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
});

// Click handler for the "Post" button to create new comments
(function ($) {
    $('#btn-chat').on('click', function (e) {
        e.preventDefault();
        $('#comment-form').submit();

        /*var clickTime = Math.floor(Date.now() / 1000);
        ckEditor.updateElement();
        $.ajax({
            url:      commentForm.prop('action'),
            type:     commentForm.prop('method'),
            dataType: 'json',
            data:     'comment=' + $('#comment-txt'),
            beforeSend: function () {
                ckEditor.showNotification('Posting...', 'info').show();
            }
        }).then(
            function (comment) {
                console.log(comment);
                if (comment.error) {
                    ckEditor.showNotification('There was a problem posting your comment.').show();
                    return;
                }

                var newComment = $('ul.chat > li:first-child').clone();
                newComment.find('strong.primary-font').html(comment.user.name);

                var timeAgo = Math.floor(Date.now() / 1000) - clickTime;
                if (timeAgo === 0) {
                    timeAgo = 1;
                }
                newComment.find('.time-since').html(timeAgo + ' seconds ago');
                newComment.find('.chat-body > p').html(comment.content);

                newComment.prependTo('ul.chat');
            },
            function () {
                ckEditor.showNotification('There was a problem posting your comment.').show();
            }
        );*/
    });
})(jQuery);

// Check for new comments every 30 seconds
(function ($) {
    if ($('.chat-card').length < 1) {
        return;
    }

    var chatInterval = setInterval(function () {
        // Get the time since the newest chat and the vulnerability ID
        var timeSince       = $('ul.chat > li:first-child').find('.time-since'),
            newerThan       = timeSince.data('created-at') || '0000-00-00 00:00:00',
            vulnerabilityId = timeSince.data('vulnerability-id');

        // Make sure we have both otherwise we can't send the request
        if (!newerThan || !vulnerabilityId) {
            return;
        }

        $.ajax({
            url:      '/comments/updated/' + vulnerabilityId,
            type:     'POST',
            dataType: 'HTML',
            data:     'newer-than=' + newerThan
        }).done(function (comments) {
            // If there are no new comments, there's nothing to do
            if (!comments || comments.length < 1) {
                return;
            }

            // Prepend the new comments to the comments list and reset the comment count value
            $(comments).prependTo('ul.chat');
            $('#comment-count').text($('ul.chat > li').length);
            // TODO: update all the dates of all the other comments
        }).fail(function (jqXHR) {
            // Check which error was encountered
            var firstDigit = (''+jqXHR.status)[0],
                body       = $('body');

            if ((firstDigit != '5' && firstDigit != '4') || !body.data('comment-poll')) {
                return;
            }

            // If a 5xx for 4xx error was encountered then stop polling for comments until the next page request
            clearInterval(body.data('comment-poll'));
        });
    }, 20000);

    // Store the chat interval in a data attribute on the body element
    $('body').data('comment-poll', chatInterval);
})(jQuery);

// Enable existing comment editing
(function ($) {
    // Make sure the there are comment edit buttons on the page
    var commentEditBtns = $('.edit-comment');
    if (commentEditBtns.length < 1) {
        return;
    }

    // Bind a click handler to the edit comment button
    commentEditBtns.on('click', function (e) {
        // Make sure we can get the comment ID
        var commentId = $(this).data('comment-id');
        if (!commentId) {
            return;
        }

        // Prevent the default action and fade out the comment text and fade in the comment editor
        e.preventDefault();
        $('#comment-text-' + commentId).fadeOut(300, function() {
            $('#comment-editor-' + commentId).fadeIn(300);
        });
    });

    // Cancel comment editing button
    $('.edit-comment-cancel').on('click', function(e) {
        // Make sure we can get the comment ID
        var commentId = $(this).data('comment-id');
        if (!commentId) {
            return;
        }

        // Prevent the default action and fade out the comment editor fade in the comment text
        e.preventDefault();
        $('#comment-editor-' + commentId).fadeOut(300, function() {
            $('#comment-text-' + commentId).fadeIn(300);
        });
    });
})(jQuery);

// Enable existing comment edit form post when the "Save Changes" button is clicked
(function ($) {
    // Make sure we have a save comment button
    var saveCommentBtn = $('.btn-edit-chat');
    if (saveCommentBtn.length < 1) {
        return;
    }

    // When the save comment button is clicked, submit the form to save the comment
    saveCommentBtn.on('click', function (e) {
        var commentId = $(this).data('comment-id');
        if (!commentId) {
            return;
        }

        e.preventDefault();
        $('#comment-editor-' + commentId).find('form').submit();
    });
})(jQuery);

// Send to Jira with Ajax
(function ($) {
    var jiraContainer = $('#jira');
    if (jiraContainer.length < 1) {
        return;
    }

    var jiraForm       = jiraContainer.find('form'),
        modalContent   = jiraContainer.find('.modal-content'),
        overlayAndIcon = jiraContainer.find('.waiting-icon-container, .waiting-overlay'),
        defaultError   = '
'
        + '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
        + 'Jira Issue creation failed this time. Please try again.
',
        // Hide the error alert after 5 seconds
        hideAlert    = function() {
            var alert = modalContent.find('.alert');
            if (alert.length <  1) {
                return;
            }

            setTimeout(function () {
                alert.slideUp(800);
                alert.remove();
            }, 5000);
        };

    // When the Send to Jira form is submitted
    jiraForm.on('submit', function (e) {
        // Prevent the default form submission
        e.preventDefault();

        // Send an ajax request with all the form data
        $.ajax({
            url: $(this).prop('action'),
            type: $(this).prop('method'),
            dataType: 'JSON',
            data: $(this).serialize(),
            // Overlay the form with a light-grey overlay and a loading icon
            beforeSend: function () {
                overlayAndIcon.fadeIn(300);
            }
        }).done(function(data) {
            // Successful ajax request, but invalid response. Show the default error.
            if (!data.html) {
                modalContent.prepend(defaultError);
                return;
            }

            // Prepend the form with the response message
            modalContent.prepend(data.html);
            if (data.isError) {
                // If the response is an error, hide it after 5s.
                hideAlert();
                return;
            }

            // Success: don't hide the success message because it contains the issue URL, but reset the form.
            jiraForm.find('input').val("");
        }).fail(function () {
            // Show the default error.
            modalContent.prepend(defaultError);
            hideAlert();
        }).always(function () {
            // Always hide the overlay and loading icon when the ajax request is done
            overlayAndIcon.fadeOut(300);
        });
    })
})(jQuery);<commit_msg>Make the code that submits the modal form reusable.<commit_after>$("#menu-toggle").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
});

// Click handler for the "Post" button to create new comments
(function ($) {
    $('#btn-chat').on('click', function (e) {
        e.preventDefault();
        $('#comment-form').submit();

        /*var clickTime = Math.floor(Date.now() / 1000);
        ckEditor.updateElement();
        $.ajax({
            url:      commentForm.prop('action'),
            type:     commentForm.prop('method'),
            dataType: 'json',
            data:     'comment=' + $('#comment-txt'),
            beforeSend: function () {
                ckEditor.showNotification('Posting...', 'info').show();
            }
        }).then(
            function (comment) {
                console.log(comment);
                if (comment.error) {
                    ckEditor.showNotification('There was a problem posting your comment.').show();
                    return;
                }

                var newComment = $('ul.chat > li:first-child').clone();
                newComment.find('strong.primary-font').html(comment.user.name);

                var timeAgo = Math.floor(Date.now() / 1000) - clickTime;
                if (timeAgo === 0) {
                    timeAgo = 1;
                }
                newComment.find('.time-since').html(timeAgo + ' seconds ago');
                newComment.find('.chat-body > p').html(comment.content);

                newComment.prependTo('ul.chat');
            },
            function () {
                ckEditor.showNotification('There was a problem posting your comment.').show();
            }
        );*/
    });
})(jQuery);

// Check for new comments every 30 seconds
(function ($) {
    if ($('.chat-card').length < 1) {
        return;
    }

    var chatInterval = setInterval(function () {
        // Get the time since the newest chat and the vulnerability ID
        var timeSince       = $('ul.chat > li:first-child').find('.time-since'),
            newerThan       = timeSince.data('created-at') || '0000-00-00 00:00:00',
            vulnerabilityId = timeSince.data('vulnerability-id');

        // Make sure we have both otherwise we can't send the request
        if (!newerThan || !vulnerabilityId) {
            return;
        }

        $.ajax({
            url:      '/comments/updated/' + vulnerabilityId,
            type:     'POST',
            dataType: 'HTML',
            data:     'newer-than=' + newerThan
        }).done(function (comments) {
            // If there are no new comments, there's nothing to do
            if (!comments || comments.length < 1) {
                return;
            }

            // Prepend the new comments to the comments list and reset the comment count value
            $(comments).prependTo('ul.chat');
            $('#comment-count').text($('ul.chat > li').length);
            // TODO: update all the dates of all the other comments
        }).fail(function (jqXHR) {
            // Check which error was encountered
            var firstDigit = (''+jqXHR.status)[0],
                body       = $('body');

            if ((firstDigit != '5' && firstDigit != '4') || !body.data('comment-poll')) {
                return;
            }

            // If a 5xx for 4xx error was encountered then stop polling for comments until the next page request
            clearInterval(body.data('comment-poll'));
        });
    }, 20000);

    // Store the chat interval in a data attribute on the body element
    $('body').data('comment-poll', chatInterval);
})(jQuery);

// Enable existing comment editing
(function ($) {
    // Make sure the there are comment edit buttons on the page
    var commentEditBtns = $('.edit-comment');
    if (commentEditBtns.length < 1) {
        return;
    }

    // Bind a click handler to the edit comment button
    commentEditBtns.on('click', function (e) {
        // Make sure we can get the comment ID
        var commentId = $(this).data('comment-id');
        if (!commentId) {
            return;
        }

        // Prevent the default action and fade out the comment text and fade in the comment editor
        e.preventDefault();
        $('#comment-text-' + commentId).fadeOut(300, function() {
            $('#comment-editor-' + commentId).fadeIn(300);
        });
    });

    // Cancel comment editing button
    $('.edit-comment-cancel').on('click', function(e) {
        // Make sure we can get the comment ID
        var commentId = $(this).data('comment-id');
        if (!commentId) {
            return;
        }

        // Prevent the default action and fade out the comment editor fade in the comment text
        e.preventDefault();
        $('#comment-editor-' + commentId).fadeOut(300, function() {
            $('#comment-text-' + commentId).fadeIn(300);
        });
    });
})(jQuery);

// Enable existing comment edit form post when the "Save Changes" button is clicked
(function ($) {
    // Make sure we have a save comment button
    var saveCommentBtn = $('.btn-edit-chat');
    if (saveCommentBtn.length < 1) {
        return;
    }

    // When the save comment button is clicked, submit the form to save the comment
    saveCommentBtn.on('click', function (e) {
        var commentId = $(this).data('comment-id');
        if (!commentId) {
            return;
        }

        e.preventDefault();
        $('#comment-editor-' + commentId).find('form').submit();
    });
})(jQuery);

// Send to Jira with Ajax
(function ($) {
    var submitAjaxForm = function (formContainer, defaultErrorTxt, done) {
        if (formContainer.length < 1) {
            return;
        }

        var form = formContainer.find('form'),
            modalContent = formContainer.find('.modal-content'),
            overlayAndIcon = formContainer.find('.waiting-icon-container, .waiting-overlay'),
            defaultErrorTxt = defaultErrorTxt
                || "Something went wrong and we could not complete your request this time. Please try again.",
            defaultError = '
'
                + '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
                + defaultErrorTxt + '
',
            // Hide the error alert after 5 seconds
            hideAlert = function () {
                var alert = modalContent.find('.alert');
                if (alert.length < 1) {
                    return;
                }

                setTimeout(function () {
                    alert.slideUp(800);
                    alert.remove();
                }, 5000);
            };

            done = done || function (data) {
                // Successful ajax request, but invalid response. Show the default error.
                if (!data.html) {
                    modalContent.prepend(defaultError);
                    return;
                }

                // Prepend the form with the response message
                modalContent.prepend(data.html);
                if (data.isError) {
                    // If the response is an error, hide it after 5s.
                    hideAlert();
                    return;
                }

                // Success: don't hide the success message because it contains the issue URL, but reset the form.
                form.find('input').val("");
            };

        // When the Send to Jira form is submitted
        form.on('submit', function (e) {
            // Prevent the default form submission
            e.preventDefault();

            // Send an ajax request with all the form data
            $.ajax({
                url: $(this).prop('action'),
                type: $(this).prop('method'),
                dataType: 'JSON',
                data: $(this).serialize(),
                // Overlay the form with a light-grey overlay and a loading icon
                beforeSend: function () {
                    overlayAndIcon.fadeIn(300);
                }
            }).done(done).fail(function () {
                // Show the default error.
                modalContent.prepend(defaultError);
                hideAlert();
            }).always(function () {
                // Always hide the overlay and loading icon when the ajax request is done
                overlayAndIcon.fadeOut(300);
            });
        });
    };

    // Jira issue creation
    submitAjaxForm(
        $('#jira'),
        'Something went wrong and we were not able to create an new Jira Issue for you, but please try again.'
    );

    // New asset creation for the Ruggedy app
    submitAjaxForm(
        $('#add-asset-form'),
        "Something went wrong and we were not able to create a new Asset for you, but please try again."
    );

})(jQuery);

(function ($) {
    var newAssetForm = $('form#new-asset');
    if (newAssetForm.length < 1) {
        return;
    }

    newAssetForm.on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            url: $(this).prop('action'),
            type: $(this).prop('method'),
            dataType: 'JSON',
            data: $(this).serialize(),
            beforeSend: function () {

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


<commit_before>function getCounterstream() {
  $.get("/counterstream", renderCounterstream);
}

function renderCounterstream(data) {
  renderSection('#counterstream', data);
}

function getEarwaves() {
  $.get("/earwaves", renderEarwaves);
}

function renderEarwaves(data) {
  renderSection('#earwaves', data);
}

function getQ2() {
  $.get("/q2", renderQ2);
}

function renderQ2(data) {
  renderSection('#q2', data);
}

function getYLE() {
  $.get("/yle", renderYLE);
}

function renderYLE(data) {
  renderSection('#yle', data);
}

function getSecondInversion() {
  $.get("/second-inversion", renderSecondInversion);
}

function renderSecondInversion(data) {
  renderSection('#second-inversion', data);
}

function renderSection(id, data) {
  $(id.concat(' .title')).text(data.title);
  $(id.concat(' .composer')).text(data.composer);
}

function renderPieces() {
  getCounterstream();
  getEarwaves();
  getQ2();
  getSecondInversion();
  getYLE();
}

function start() {
  renderPieces();
  setInterval(renderPieces, 60 * 1000);
}

$(start());
<commit_msg>remove unused jquery version<commit_after><|endoftext|>


<commit_before><<<<<<< HEAD
/*
  These are utility functions that are going to be used to filter frontend data.
*/

/*
  This function takes a collection of objects then filters those based on location.
  @param programs --> the colleciton of objects to be filtered
  @param location --> the location to filter the objects by
  @return a collection of objects that are located at the specified location
*/
function filterByLocation(programs,location){
  var programsByLocation = _.filter(programs, function(program){
      return program.location === location;
  });

  return programsByLocation;
}

/*
  @param cost --> the cost to filter objects by
*/
function filterByCost(programs, cost){
  var programsByCost = _.filter(programs, function(program) {
    return program.cost === cost;
  });
  return programsByCost;
}

//@params timeline --> filter by length of time of the program
function filterByTimeLength(programs, timeline){
  var programsByTimeLength = _.filter(programs, function(program) {
    return program.timeline === timeline;
  });
  return programsByTimeLength;
}

//filter by time of day
function filterByTimeOfDay(programs, timeOfDay){
  var programsByTimeOfDay = _.filter(programs, function(program) {
    return program.timeOfDay === timeOfDay;
  });
  return programsByTimeOfDay;
}

//@params age --> filter by age
// function filterByAge(programs, age){
//   var programsByAge - _.filter(programs, function(program) {
//     return program.age === age;
//   });
//   return programsByAge;
// }
=======
>>>>>>> bce7bdbf3db4a9ae6d6995f0f36c0111f3288202
<commit_msg>modifying filter functions<commit_after>/*
  These are utility functions that are going to be used to filter frontend data.
*/

/*
  This function takes a collection of objects then filters those based on location.
  @param programs --> the colleciton of objects to be filtered
  @param location --> the location to filter the objects by
  @return a collection of objects that are located at the specified location
*/
function filterByLocation(programs,location){
  var programsByLocation = _.filter(programs, function(program){
      return program.location === location;
  });

  return programsByLocation;
}

//@param cost --> the cost to filter objects by
function filterByCost(programs, cost){
  var programsByCost = _.filter(programs, function(program) {
    return program.cost === cost;
  });
  return programsByCost;
}

//@params timeline --> filter by length of time of the program
function filterByTimeLength(programs, timeline){
  var programsByTimeLength = _.filter(programs, function(program) {
    return program.timeline === timeline;
  });
  return programsByTimeLength;
}

//@marams timeOfDay --> filter by time of day
function filterByTimeOfDay(programs, timeOfDay){
  var programsByTimeOfDay = _.filter(programs, function(program) {
    return program.timeOfDay === timeOfDay;
  });
  return programsByTimeOfDay;
}

//@params age --> filter by age lower and upper
function filterByAgeMin(programs, ageMin){
  var programsByAgeMin = _.filter(programs, function(program) {
    return program.ageMin >= ageMin;
  });
  return programsByAgeMin;
}

function filterByAgeMax(programs, ageMax){
  var programsByAgeMax = _.filter(programs, function(program) {
    return program.ageMax <= ageMax;
  });
  return programsByAgeMax;
}

/*
  This is the overall filter function
*/
function filterPrograms(programs, location, cost, duration, age){
    var filteredPrograms = programs;
    if (location && cost && duration && age){ //each field has constraints on l c d and a
        filteredPrograms = filterByLocation(programs, location);
        filteredPrograms = filterByCost(filteredPrograms, cost);
        filteredPrograms = filterByTimeLength(filteredPrograms, duration);
        filteredPrograms = filterByAgeMin(filteredPrograms, age);
    } else if (location && cost && duration && !age){  //dont filter age (allow all age object properties)
        filteredPrograms = filterByLocation(programs, location);
        filteredPrograms = filterByCost(filteredPrograms, cost);
        filteredPrograms = filterByTimeLength(filteredPrograms, duration);
    } else if (location && cost && !duration && age) {  //dont filter duration
        filteredPrograms = filterByLocation(programs, location);
        filteredPrograms = filterByCost(filteredPrograms, cost);
        filteredPrograms = filterByAgeMin (filteredPrograms, age);
    } else if (location && !cost && duration && age) { //dont filter cost
        filteredPrograms = filterByLocation(programs, location);
        filteredPrograms = filterByTimeLength(filteredPrograms, duration);
        filteredPrograms = filterByAgeMin(filteredPrograms, age);
    } else if (!location && cost && duration && age) { //dont filter location
        filteredPrograms = filterByCost(filteredPrograms, cost);
        filteredPrograms = filterByTimeLength(filteredPrograms, duration);
        filteredPrograms = filterByAgeMin(filteredPrograms, age);
    }

     else if (!location && !cost && !duration && !age) { //returns errything
        filteredPrograms = programs;
    } else if (location && !cost && !duration && !age)

    return filteredPrograms;
}
<|endoftext|>


<commit_before>/*jshint globalstrict: true */
/*global require, describe, beforeEach, it, expect*/

////////////////////////////////////////////////////////////////////////////////
/// @brief Spec for foxx manager
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB 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 ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

"use strict";

var FoxxManager = require("org/arangodb/foxx/manager");
var arangodb = require("org/arangodb");
var errors = arangodb.errors;

describe("Foxx Manager", function() {

  beforeEach(function() {
    FoxxManager.update();
  });

  it("should fetch apps from the appstore", function() {
    var list = FoxxManager.availableJson();
    var i, app, l = list.length;
    expect(l).toBeGreaterThan(0);
    for (i = 0; i < l; ++i) {
      app = list[i];
      expect(app.name).toBeDefined("App has no name");
      expect(app.latestVersion).toBeDefined("App " + app.name + " has no latestVersion.");
      expect(app.author).toBeDefined("App " + app.name + " has no author.");
      expect(app.description).toBeDefined("App " + app.name + " has no description");
    }
  });

  it("should be able to install all apps from appstore", function() {
    var mount = "/unittest/testApps";
    try {
      FoxxManager.uninstall(mount, { force: true });
    } catch(e) {
    }
    var list = FoxxManager.availableJson();
    var i, app, l = list.length;
    for (i = 0; i < l; ++i) {
      app = list[i];
      if (app.name === "sessions-example-app") {
        // Requires oauth2 to be installed
        try {
          FoxxManager.uninstall("/oauth2", { force: true });
        } catch(err) {
        }
        try {
          FoxxManager.install(app.name, mount);
          expect(true).toBeFalsy("Installing sessions-example-app should require oauth2");
        } catch(e) {
          expect(e.errorNum).toEqual(errors.ERROR_FAILED_TO_EXECUTE_SCRIPT.code);
          try {
            FoxxManager.install("oauth2", "/oauth2");
          } catch(err) {
            expect(e).toBeUndefined("Could not install oauth2");
            continue;
          }
          try {
            FoxxManager.install(app.name, mount);
            FoxxManager.uninstall(mount);
          } catch(err2) {
            expect(err2).toBeUndefined("Could not install " + app.name);
            try {
              FoxxManager.uninstall(mount, { force: true });
            } catch(err) {
            }
          }
          try {
            FoxxManager.uninstall("/oauth2", {force: true});
          } catch(err) {
          }
        }
      } else {
        try {
          FoxxManager.install(app.name, mount);
          FoxxManager.uninstall(mount);
        } catch(e) {
          expect(e).toBeUndefined("Could not install " + app.name);
          try {
            FoxxManager.uninstall(mount, { force: true });
          } catch(err) {
          }
        }
      }
    }
  });

});

<commit_msg>Add stacktrace from the exception to the output; the jasmine provided stacktrace is pretty useless here.<commit_after>/*jshint globalstrict: true */
/*global require, describe, beforeEach, it, expect*/

////////////////////////////////////////////////////////////////////////////////
/// @brief Spec for foxx manager
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB 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 ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

"use strict";

var FoxxManager = require("org/arangodb/foxx/manager");
var arangodb = require("org/arangodb");
var errors = arangodb.errors;

describe("Foxx Manager", function() {

  beforeEach(function() {
    FoxxManager.update();
  });

  it("should fetch apps from the appstore", function() {
    var list = FoxxManager.availableJson();
    var i, app, l = list.length;
    expect(l).toBeGreaterThan(0);
    for (i = 0; i < l; ++i) {
      app = list[i];
      expect(app.name).toBeDefined("App has no name");
      expect(app.latestVersion).toBeDefined("App " + app.name + " has no latestVersion.");
      expect(app.author).toBeDefined("App " + app.name + " has no author.");
      expect(app.description).toBeDefined("App " + app.name + " has no description");
    }
  });

  it("should be able to install all apps from appstore", function() {
    var mount = "/unittest/testApps";
    try {
      FoxxManager.uninstall(mount, { force: true });
    } catch(e) {
    }
    var list = FoxxManager.availableJson();
    var i, app, l = list.length;
    for (i = 0; i < l; ++i) {
      app = list[i];
      if (app.name === "sessions-example-app") {
        // Requires oauth2 to be installed
        try {
          FoxxManager.uninstall("/oauth2", { force: true });
        } catch(err) {
        }
        try {
          FoxxManager.install(app.name, mount);
          expect(true).toBeFalsy("Installing sessions-example-app should require oauth2");
        } catch(e) {
          expect(e.errorNum).toEqual(errors.ERROR_FAILED_TO_EXECUTE_SCRIPT.code);
          try {
            FoxxManager.install("oauth2", "/oauth2");
          } catch(err) {
            expect(e).toBeUndefined("Could not install oauth2");
            continue;
          }
          try {
            FoxxManager.install(app.name, mount);
            FoxxManager.uninstall(mount);
          } catch(err2) {
            expect(err2).toBeUndefined("Could not install " + app.name);
            try {
              FoxxManager.uninstall(mount, { force: true });
            } catch(err) {
            }
          }
          try {
            FoxxManager.uninstall("/oauth2", {force: true});
          } catch(err) {
          }
        }
      } else {
        try {
          FoxxManager.install(app.name, mount);
          FoxxManager.uninstall(mount);
        } catch(e) {
          expect(e).toBeUndefined("Could not install " + app.name + " - \n" + e.stack);
          try {
            FoxxManager.uninstall(mount, { force: true });
          } catch(err) {
          }
        }
      }
    }
  });

});

<|endoftext|>


<commit_before>!function(){

  var map;

  var centerChanged = function(){
    clearTimeout(centerChanged.timeout);
    centerChanged.timeout = setTimeout(refreshMarkers, 300);
  }

  var refreshMarkers = function(){
    var bounds = map.getBounds();
    var northEast = bounds.getNorthEast();
    var southWest = bounds.getSouthWest();

    var data = {
      sw_latitude:  southWest.lat(),
      sw_longitude: southWest.lng(),
      ne_latitude:  northEast.lat(),
      ne_longitude: northEast.lng(),
    };
    console.log(data)
    var request = $.getJSON('/yelp_search', data);
    request.done(function(response){
      drawBusinesses(response.businesses);
    });
  }

  var drawBusinesses = function(businesses){
    businesses.forEach(function(business){
      var coordinate = business.location.coordinate;
      var marker = new google.maps.Marker({
         position: {
           lat: coordinate.latitude,
           lng: coordinate.longitude,
         },
         map: map,
         title: business.name,
      });

      var infowindow = new google.maps.InfoWindow({
        content: marker['title']
        });

      google.maps.event.addListener(marker, 'click', function() {
        console.log('CLICKED ON', business);
        infowindow.open(map, marker)
      });

    });
  }

  $(function(){

    navigator.geolocation.getCurrentPosition(function(position){

      map = new google.maps.Map($('#map-canvas')[0], {
        center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      setTimeout(refreshMarkers, 1000);

      google.maps.event.addListener(map, 'center_changed', function() {
        centerChanged();
      });
    });

  });

}();<commit_msg>show some info about place when marker is click. also linked to 'create event' page.<commit_after>!function(){

  var map;

  var centerChanged = function(){
    clearTimeout(centerChanged.timeout);
    centerChanged.timeout = setTimeout(refreshMarkers, 300);
  }

  var refreshMarkers = function(){
    var bounds = map.getBounds();
    var northEast = bounds.getNorthEast();
    var southWest = bounds.getSouthWest();

    var data = {
      sw_latitude:  southWest.lat(),
      sw_longitude: southWest.lng(),
      ne_latitude:  northEast.lat(),
      ne_longitude: northEast.lng(),
    };
    console.log(data)
    var request = $.getJSON('/yelp_search', data);
    request.done(function(response){
      drawBusinesses(response.businesses);
    });
  }

  var drawBusinesses = function(businesses){
    businesses.forEach(function(business){
      var coordinate = business.location.coordinate;
      var marker = new google.maps.Marker({
         position: {
           lat: coordinate.latitude,
           lng: coordinate.longitude,
         },
         map: map,
         title: '
' + business.name + '

Rating: ' + business.rating + '
Address: ' + business.location.address + '

Review Snippet: ' + business.snippet_text + '

Create Event
',
      });

      var infowindow = new google.maps.InfoWindow({
        content: marker['title']
        });

      google.maps.event.addListener(marker, 'click', function() {
        console.log('CLICKED ON', business);
        infowindow.open(map, marker)
      });

    });
  }

  $(function(){

    navigator.geolocation.getCurrentPosition(function(position){

      map = new google.maps.Map($('#map-canvas')[0], {
        center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      setTimeout(refreshMarkers, 1000);

      google.maps.event.addListener(map, 'center_changed', function() {
        centerChanged();
      });
    });

  });

}();<|endoftext|>


<commit_before>/**
 * ControlSelection.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class handles control selection of elements. Controls are elements
 * that can be resized and needs to be selected as a whole. It adds custom resize handles
 * to all browser engines that support properly disabling the built in resize logic.
 *
 * @class tinymce.dom.ControlSelection
 */
define("tinymce/dom/ControlSelection", [
	"tinymce/util/VK",
	"tinymce/util/Tools",
	"tinymce/Env"
], function(VK, Tools, Env) {
	return function(selection, editor) {
		var dom = editor.dom, each = Tools.each;
		var selectedElm, selectedElmGhost, resizeHandles, selectedHandle;
		var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
		var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie;

		// Details about each resize handle how to scale etc
		resizeHandles = {
			// Name: x multiplier, y multiplier, delta size x, delta size y
			n:  [0.5,   0,     0,   -1],
			e:  [1,    0.5,    1,    0],
			s:  [0.5,   1,     0,    1],
			w:  [0,    0.5,   -1,    0],
			nw: [0,     0,    -1,   -1],
			ne: [1,     0,     1,   -1],
			se: [1,     1,     1,    1],
			sw: [0,     1,    -1,    1]
		};

		// Add CSS for resize handles, cloned element and selected
		var rootClass = '.mce-content-body';
		editor.contentStyles.push(
			rootClass + ' div.mce-resizehandle {' +
				'position: absolute;' +
				'border: 1px solid black;' +
				'background: #FFF;' +
				'width: 5px;' +
				'height: 5px;' +
				'z-index: 10000' +
			'}' +
			rootClass + ' .mce-resizehandle:hover {' +
				'background: #000' +
			'}' +
			rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' +
				'outline: 1px solid black;' +
				'resize: none' + // Have been talks about implementing this in browsers
			'}' +
			rootClass + ' .mce-clonedresizable {' +
				'position: absolute;' +
				(Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing
				'opacity: .5;' +
				'filter: alpha(opacity=50);' +
				'z-index: 10000' +
			'}'
		);

		function isResizable(elm) {
			if (editor.settings.object_resizing === false) {
				return false;
			}

			if (!/TABLE|IMG|DIV/.test(elm.nodeName)) {
				return false;
			}

			if (elm.getAttribute('data-mce-resize') === 'false') {
				return false;
			}

			return true;
		}

		function resizeGhostElement(e) {
			var deltaX, deltaY;

			// Calc new width/height
			deltaX = e.screenX - startX;
			deltaY = e.screenY - startY;

			// Calc new size
			width = deltaX * selectedHandle[2] + startW;
			height = deltaY * selectedHandle[3] + startH;

			// Never scale down lower than 5 pixels
			width = width < 5 ? 5 : width;
			height = height < 5 ? 5 : height;

			// Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image
			if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) {
				width = Math.round(height / ratio);
				height = Math.round(width * ratio);
			}

			// Update ghost size
			dom.setStyles(selectedElmGhost, {
				width: width,
				height: height
			});

			// Update ghost X position if needed
			if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
				dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
			}

			// Update ghost Y position if needed
			if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
				dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
			}

			if (!resizeStarted) {
				editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH});
				resizeStarted = true;
			}
		}

		function endGhostResize() {
			resizeStarted = false;

			function setSizeProp(name, value) {
				if (value) {
					// Resize by using style or attribute
					if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) {
						dom.setStyle(selectedElm, name, value);
					} else {
						dom.setAttrib(selectedElm, name, value);
					}
				}
			}

			// Set width/height properties
			setSizeProp('width', width);
			setSizeProp('height', height);

			dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
			dom.unbind(editableDoc, 'mouseup', endGhostResize);

			if (rootDocument != editableDoc) {
				dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
				dom.unbind(rootDocument, 'mouseup', endGhostResize);
			}

			// Remove ghost and update resize handle positions
			dom.remove(selectedElmGhost);

			if (!isIE || selectedElm.nodeName == "TABLE") {
				showResizeRect(selectedElm);
			}

			editor.fire('ObjectResized', {target: selectedElm, width: width, height: height});
			editor.nodeChanged();
		}

		function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) {
			var position, targetWidth, targetHeight, e, rect;

			// Get position and size of target
			position = dom.getPos(targetElm, editor.getBody());
			selectedElmX = position.x;
			selectedElmY = position.y;
			rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption
			targetWidth = rect.width || (rect.right - rect.left);
			targetHeight = rect.height || (rect.bottom - rect.top);

			// Reset width/height if user selects a new image/table
			if (selectedElm != targetElm) {
				detachResizeStartListener();
				selectedElm = targetElm;
				width = height = 0;
			}

			// Makes it possible to disable resizing
			e = editor.fire('ObjectSelected', {target: targetElm});

			if (isResizable(targetElm) && !e.isDefaultPrevented()) {
				each(resizeHandles, function(handle, name) {
					var handleElm, handlerContainerElm;

					function startDrag(e) {
						resizeStarted = true;

						startX = e.screenX;
						startY = e.screenY;
						startW = selectedElm.clientWidth;
						startH = selectedElm.clientHeight;
						ratio = startH / startW;
						selectedHandle = handle;

						selectedElmGhost = selectedElm.cloneNode(true);
						dom.addClass(selectedElmGhost, 'mce-clonedresizable');
						selectedElmGhost.contentEditable = false; // Hides IE move layer cursor
						selectedElmGhost.unSelectabe = true;
						dom.setStyles(selectedElmGhost, {
							left: selectedElmX,
							top: selectedElmY,
							margin: 0
						});

						selectedElmGhost.removeAttribute('data-mce-selected');
						editor.getBody().appendChild(selectedElmGhost);

						dom.bind(editableDoc, 'mousemove', resizeGhostElement);
						dom.bind(editableDoc, 'mouseup', endGhostResize);

						if (rootDocument != editableDoc) {
							dom.bind(rootDocument, 'mousemove', resizeGhostElement);
							dom.bind(rootDocument, 'mouseup', endGhostResize);
						}
					}

					if (mouseDownHandleName) {
						// Drag started by IE native resizestart
						if (name == mouseDownHandleName) {
							startDrag(mouseDownEvent);
						}

						return;
					}

					// Get existing or render resize handle
					handleElm = dom.get('mceResizeHandle' + name);
					if (!handleElm) {
						handlerContainerElm = editor.getBody();

						handleElm = dom.add(handlerContainerElm, 'div', {
							id: 'mceResizeHandle' + name,
							'data-mce-bogus': true,
							'class': 'mce-resizehandle',
							contentEditable: false, // Hides IE move layer cursor
							unSelectabe: true,
							style: 'cursor:' + name + '-resize; margin:0; padding:0'
						});

						dom.bind(handleElm, 'mousedown', function(e) {
							e.preventDefault();
							startDrag(e);
						});
					} else {
						dom.show(handleElm);
					}

					/*
					var halfHandleW = handleElm.offsetWidth / 2;
					var halfHandleH = handleElm.offsetHeight / 2;

					// Position element
					dom.setStyles(handleElm, {
						left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)),
						top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH))
					});
					*/

					// Position element
					dom.setStyles(handleElm, {
						left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2),
						top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2)
					});
				});
			} else {
				hideResizeRect();
			}

			selectedElm.setAttribute('data-mce-selected', '1');
		}

		function hideResizeRect() {
			var name, handleElm;

			if (selectedElm) {
				selectedElm.removeAttribute('data-mce-selected');
			}

			for (name in resizeHandles) {
				handleElm = dom.get('mceResizeHandle' + name);
				if (handleElm) {
					dom.unbind(handleElm);
					dom.remove(handleElm);
				}
			}
		}

		function updateResizeRect(e) {
			var controlElm;

			function isChildOrEqual(node, parent) {
				do {
					if (node === parent) {
						return true;
					}
				} while ((node = node.parentNode));
			}

			// Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v
			each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) {
				img.removeAttribute('data-mce-selected');
			});

			controlElm = e.type == 'mousedown' ? e.target : selection.getNode();
			controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr');

			if (controlElm) {
				if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) {
					if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) {
						showResizeRect(controlElm);
						return;
					}
				}
			}

			hideResizeRect();
		}

		function attachEvent(elm, name, func) {
			if (elm && elm.attachEvent) {
				elm.attachEvent('on' + name, func);
			}
		}

		function detachEvent(elm, name, func) {
			if (elm && elm.detachEvent) {
				elm.detachEvent('on' + name, func);
			}
		}

		function resizeNativeStart(e) {
			var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY;

			pos = target.getBoundingClientRect();
			relativeX = e.clientX - pos.left;
			relativeY = e.clientY - pos.top;

			// Figure out what corner we are draging on
			for (name in resizeHandles) {
				corner = resizeHandles[name];

				cornerX = target.offsetWidth * corner[0];
				cornerY = target.offsetHeight * corner[1];

				if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) {
					selectedHandle = corner;
					break;
				}
			}

			// Remove native selection and let the magic begin
			resizeStarted = true;
			editor.getDoc().selection.empty();
			showResizeRect(target, name, e);
		}

		function nativeControlSelect(e) {
			var target = e.srcElement;

			if (target != selectedElm) {
				detachResizeStartListener();

				if (target.id.indexOf('mceResizeHandle') === 0) {
					e.returnValue = false;
					return;
				}

				if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') {
					hideResizeRect();
					selectedElm = target;
					attachEvent(target, 'resizestart', resizeNativeStart);
				}
			}
		}

		function detachResizeStartListener() {
			detachEvent(selectedElm, 'resizestart', resizeNativeStart);
		}

		function controlSelect(elm) {
			var ctrlRng;

			if (!isIE) {
				return;
			}

			ctrlRng = editableDoc.body.createControlRange();

			try {
				ctrlRng.addElement(elm);
				ctrlRng.select();
				return true;
			} catch (ex) {
				// Ignore since the element can't be control selected for example a P tag
			}
		}

		editor.on('init', function() {
			if (isIE) {
				// Hide the resize rect on resize and reselect the image
				editor.on('ObjectResized', function(e) {
					if (e.target.nodeName != 'TABLE') {
						hideResizeRect();
						controlSelect(e.target);
					}
				});

				attachEvent(editor.getBody(), 'controlselect', nativeControlSelect);
			} else {
				try {
					// Disable object resizing on Gecko
					editor.getDoc().execCommand('enableObjectResizing', false, false);
				} catch (ex) {
					// Ignore
				}
			}

			editor.on('nodechange mousedown ResizeEditor', updateResizeRect);

			// Update resize rect while typing in a table
			editor.on('keydown keyup', function(e) {
				if (selectedElm && selectedElm.nodeName == "TABLE") {
					updateResizeRect(e);
				}
			});

			// Hide rect on focusout since it would float on top of windows otherwise
			//editor.on('focusout', hideResizeRect);
		});

		function destroy() {
			selectedElm = selectedElmGhost = null;

			if (isIE) {
				detachResizeStartListener();
				detachEvent(editor.getBody(), 'controlselect', nativeControlSelect);
			}
		}

		return {
			controlSelect: controlSelect,
			destroy: destroy
		};
	};
});
<commit_msg>Fixed issue with drag/drop of tables restoring gecko resizing.<commit_after>/**
 * ControlSelection.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class handles control selection of elements. Controls are elements
 * that can be resized and needs to be selected as a whole. It adds custom resize handles
 * to all browser engines that support properly disabling the built in resize logic.
 *
 * @class tinymce.dom.ControlSelection
 */
define("tinymce/dom/ControlSelection", [
	"tinymce/util/VK",
	"tinymce/util/Tools",
	"tinymce/Env"
], function(VK, Tools, Env) {
	return function(selection, editor) {
		var dom = editor.dom, each = Tools.each;
		var selectedElm, selectedElmGhost, resizeHandles, selectedHandle;
		var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
		var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie;

		// Details about each resize handle how to scale etc
		resizeHandles = {
			// Name: x multiplier, y multiplier, delta size x, delta size y
			n:  [0.5,   0,     0,   -1],
			e:  [1,    0.5,    1,    0],
			s:  [0.5,   1,     0,    1],
			w:  [0,    0.5,   -1,    0],
			nw: [0,     0,    -1,   -1],
			ne: [1,     0,     1,   -1],
			se: [1,     1,     1,    1],
			sw: [0,     1,    -1,    1]
		};

		// Add CSS for resize handles, cloned element and selected
		var rootClass = '.mce-content-body';
		editor.contentStyles.push(
			rootClass + ' div.mce-resizehandle {' +
				'position: absolute;' +
				'border: 1px solid black;' +
				'background: #FFF;' +
				'width: 5px;' +
				'height: 5px;' +
				'z-index: 10000' +
			'}' +
			rootClass + ' .mce-resizehandle:hover {' +
				'background: #000' +
			'}' +
			rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' +
				'outline: 1px solid black;' +
				'resize: none' + // Have been talks about implementing this in browsers
			'}' +
			rootClass + ' .mce-clonedresizable {' +
				'position: absolute;' +
				(Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing
				'opacity: .5;' +
				'filter: alpha(opacity=50);' +
				'z-index: 10000' +
			'}'
		);

		function isResizable(elm) {
			if (editor.settings.object_resizing === false) {
				return false;
			}

			if (!/TABLE|IMG|DIV/.test(elm.nodeName)) {
				return false;
			}

			if (elm.getAttribute('data-mce-resize') === 'false') {
				return false;
			}

			return true;
		}

		function resizeGhostElement(e) {
			var deltaX, deltaY;

			// Calc new width/height
			deltaX = e.screenX - startX;
			deltaY = e.screenY - startY;

			// Calc new size
			width = deltaX * selectedHandle[2] + startW;
			height = deltaY * selectedHandle[3] + startH;

			// Never scale down lower than 5 pixels
			width = width < 5 ? 5 : width;
			height = height < 5 ? 5 : height;

			// Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image
			if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) {
				width = Math.round(height / ratio);
				height = Math.round(width * ratio);
			}

			// Update ghost size
			dom.setStyles(selectedElmGhost, {
				width: width,
				height: height
			});

			// Update ghost X position if needed
			if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
				dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
			}

			// Update ghost Y position if needed
			if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
				dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
			}

			if (!resizeStarted) {
				editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH});
				resizeStarted = true;
			}
		}

		function endGhostResize() {
			resizeStarted = false;

			function setSizeProp(name, value) {
				if (value) {
					// Resize by using style or attribute
					if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) {
						dom.setStyle(selectedElm, name, value);
					} else {
						dom.setAttrib(selectedElm, name, value);
					}
				}
			}

			// Set width/height properties
			setSizeProp('width', width);
			setSizeProp('height', height);

			dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
			dom.unbind(editableDoc, 'mouseup', endGhostResize);

			if (rootDocument != editableDoc) {
				dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
				dom.unbind(rootDocument, 'mouseup', endGhostResize);
			}

			// Remove ghost and update resize handle positions
			dom.remove(selectedElmGhost);

			if (!isIE || selectedElm.nodeName == "TABLE") {
				showResizeRect(selectedElm);
			}

			editor.fire('ObjectResized', {target: selectedElm, width: width, height: height});
			editor.nodeChanged();
		}

		function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) {
			var position, targetWidth, targetHeight, e, rect;

			// Get position and size of target
			position = dom.getPos(targetElm, editor.getBody());
			selectedElmX = position.x;
			selectedElmY = position.y;
			rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption
			targetWidth = rect.width || (rect.right - rect.left);
			targetHeight = rect.height || (rect.bottom - rect.top);

			// Reset width/height if user selects a new image/table
			if (selectedElm != targetElm) {
				detachResizeStartListener();
				selectedElm = targetElm;
				width = height = 0;
			}

			// Makes it possible to disable resizing
			e = editor.fire('ObjectSelected', {target: targetElm});

			if (isResizable(targetElm) && !e.isDefaultPrevented()) {
				each(resizeHandles, function(handle, name) {
					var handleElm, handlerContainerElm;

					function startDrag(e) {
						resizeStarted = true;

						startX = e.screenX;
						startY = e.screenY;
						startW = selectedElm.clientWidth;
						startH = selectedElm.clientHeight;
						ratio = startH / startW;
						selectedHandle = handle;

						selectedElmGhost = selectedElm.cloneNode(true);
						dom.addClass(selectedElmGhost, 'mce-clonedresizable');
						selectedElmGhost.contentEditable = false; // Hides IE move layer cursor
						selectedElmGhost.unSelectabe = true;
						dom.setStyles(selectedElmGhost, {
							left: selectedElmX,
							top: selectedElmY,
							margin: 0
						});

						selectedElmGhost.removeAttribute('data-mce-selected');
						editor.getBody().appendChild(selectedElmGhost);

						dom.bind(editableDoc, 'mousemove', resizeGhostElement);
						dom.bind(editableDoc, 'mouseup', endGhostResize);

						if (rootDocument != editableDoc) {
							dom.bind(rootDocument, 'mousemove', resizeGhostElement);
							dom.bind(rootDocument, 'mouseup', endGhostResize);
						}
					}

					if (mouseDownHandleName) {
						// Drag started by IE native resizestart
						if (name == mouseDownHandleName) {
							startDrag(mouseDownEvent);
						}

						return;
					}

					// Get existing or render resize handle
					handleElm = dom.get('mceResizeHandle' + name);
					if (!handleElm) {
						handlerContainerElm = editor.getBody();

						handleElm = dom.add(handlerContainerElm, 'div', {
							id: 'mceResizeHandle' + name,
							'data-mce-bogus': true,
							'class': 'mce-resizehandle',
							contentEditable: false, // Hides IE move layer cursor
							unSelectabe: true,
							style: 'cursor:' + name + '-resize; margin:0; padding:0'
						});

						dom.bind(handleElm, 'mousedown', function(e) {
							e.preventDefault();
							startDrag(e);
						});
					} else {
						dom.show(handleElm);
					}

					/*
					var halfHandleW = handleElm.offsetWidth / 2;
					var halfHandleH = handleElm.offsetHeight / 2;

					// Position element
					dom.setStyles(handleElm, {
						left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)),
						top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH))
					});
					*/

					// Position element
					dom.setStyles(handleElm, {
						left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2),
						top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2)
					});
				});
			} else {
				hideResizeRect();
			}

			selectedElm.setAttribute('data-mce-selected', '1');
		}

		function hideResizeRect() {
			var name, handleElm;

			if (selectedElm) {
				selectedElm.removeAttribute('data-mce-selected');
			}

			for (name in resizeHandles) {
				handleElm = dom.get('mceResizeHandle' + name);
				if (handleElm) {
					dom.unbind(handleElm);
					dom.remove(handleElm);
				}
			}
		}

		function updateResizeRect(e) {
			var controlElm;

			function isChildOrEqual(node, parent) {
				do {
					if (node === parent) {
						return true;
					}
				} while ((node = node.parentNode));
			}

			// Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v
			each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) {
				img.removeAttribute('data-mce-selected');
			});

			controlElm = e.type == 'mousedown' ? e.target : selection.getNode();
			controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr');

			if (controlElm) {
				disableGeckoResize();

				if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) {
					if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) {
						showResizeRect(controlElm);
						return;
					}
				}
			}

			hideResizeRect();
		}

		function attachEvent(elm, name, func) {
			if (elm && elm.attachEvent) {
				elm.attachEvent('on' + name, func);
			}
		}

		function detachEvent(elm, name, func) {
			if (elm && elm.detachEvent) {
				elm.detachEvent('on' + name, func);
			}
		}

		function resizeNativeStart(e) {
			var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY;

			pos = target.getBoundingClientRect();
			relativeX = e.clientX - pos.left;
			relativeY = e.clientY - pos.top;

			// Figure out what corner we are draging on
			for (name in resizeHandles) {
				corner = resizeHandles[name];

				cornerX = target.offsetWidth * corner[0];
				cornerY = target.offsetHeight * corner[1];

				if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) {
					selectedHandle = corner;
					break;
				}
			}

			// Remove native selection and let the magic begin
			resizeStarted = true;
			editor.getDoc().selection.empty();
			showResizeRect(target, name, e);
		}

		function nativeControlSelect(e) {
			var target = e.srcElement;

			if (target != selectedElm) {
				detachResizeStartListener();

				if (target.id.indexOf('mceResizeHandle') === 0) {
					e.returnValue = false;
					return;
				}

				if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') {
					hideResizeRect();
					selectedElm = target;
					attachEvent(target, 'resizestart', resizeNativeStart);
				}
			}
		}

		function detachResizeStartListener() {
			detachEvent(selectedElm, 'resizestart', resizeNativeStart);
		}

		function disableGeckoResize() {
			try {
				// Disable object resizing on Gecko
				editor.getDoc().execCommand('enableObjectResizing', false, false);
			} catch (ex) {
				// Ignore
			}
		}

		function controlSelect(elm) {
			var ctrlRng;

			if (!isIE) {
				return;
			}

			ctrlRng = editableDoc.body.createControlRange();

			try {
				ctrlRng.addElement(elm);
				ctrlRng.select();
				return true;
			} catch (ex) {
				// Ignore since the element can't be control selected for example a P tag
			}
		}

		editor.on('init', function() {
			if (isIE) {
				// Hide the resize rect on resize and reselect the image
				editor.on('ObjectResized', function(e) {
					if (e.target.nodeName != 'TABLE') {
						hideResizeRect();
						controlSelect(e.target);
					}
				});

				attachEvent(editor.getBody(), 'controlselect', nativeControlSelect);
			} else {
				disableGeckoResize();
			}

			editor.on('nodechange mousedown ResizeEditor', updateResizeRect);

			// Update resize rect while typing in a table
			editor.on('keydown keyup', function(e) {
				if (selectedElm && selectedElm.nodeName == "TABLE") {
					updateResizeRect(e);
				}
			});

			// Hide rect on focusout since it would float on top of windows otherwise
			//editor.on('focusout', hideResizeRect);
		});

		function destroy() {
			selectedElm = selectedElmGhost = null;

			if (isIE) {
				detachResizeStartListener();
				detachEvent(editor.getBody(), 'controlselect', nativeControlSelect);
			}
		}

		return {
			controlSelect: controlSelect,
			destroy: destroy
		};
	};
});
<|endoftext|>


<commit_before>var input = [60, 30, 90, 20, 80, 70];

//Array size
var arrElementWidth = 50;
var arrElementHeight = 50;

var width = $('#graphics').width(),
    height = $('#graphics').height();

var barChart = d3.select(".drawingArea")
    .append("svg:svg")
    .attr("width", width + 200)
    .attr("height", height + 200)
    .append('g')
        .attr("id", "barChart");

barChart.attr("transform", "translate(" + (width/2 - input.length/2 * (arrElementWidth + 5)) + ",10)");

var rectPositions = [];
var textPositions = [];
var elementPositions = [];

resetPosition();
createArray(input);

//Panning
var pan = d3.zoom()
    .on("zoom", panning);

barChart.call(pan);

var codeDisplayManager = new CodeDisplayManager('javascript', 'mergeSort');

function createArray(data) {
    barChart.selectAll("*").remove();
    input = data;
    createRects(data.length, 0);
    createTexts(data);
}

function resetPosition() {
    textPositions = [];
    rectPositions[0] = [];
    elementPositions = [];
    for(var i = 0; i < input.length; i++) {
        rectPositions[0][i] = [i * (arrElementWidth + 5) + (arrElementWidth+5)/2, 30];
        elementPositions[i] = 0;
        textPositions.push([i * (arrElementWidth + 5) + arrElementWidth / 2 + 5, 30]);
    }
}

function createRects(length, y) {
    for(var i = 0; i < length; i++) {
        createRect(i * (arrElementWidth + 5), y, 1);
    }
}

function createRect(x, y, opacity) {
    barChart.insert("rect", ":first-child")
        .attr("x", x)
        .attr("y", y)
        .attr("height", arrElementHeight)
        .attr("width", arrElementWidth)
        .attr("fill", "#F44336")
        .style("opacity", opacity)
        .attr("class", "level" + y/100)
        .attr("transform", "translate(0,0)");
}

function createTexts(data) {
    barChart.selectAll("text")
        .data(data)
        .enter()
        .append("text")
        .text(function (d) { return d; })
        .attr("x", function (d, index) { return index * (arrElementWidth+5) + (arrElementWidth+5) / 2; })
        .attr("y", 30)
        .attr("text-anchor", "middle")
        .attr("width", arrElementWidth)
        .attr("transform", "translate(0,0)")
		.attr("class", function (d, i) { return "element" + i; });
}

function panning() {
    barChart.attr("transform", d3.event.transform);
}

function sort() {
    $('#barChart').empty();
    resetPosition();
    createArray(input);
    codeDisplayManager.loadFunctions('mergeSort', 'merge');
    codeDisplayManager.changeFunction('mergeSort');
    var ms = new MergeSort(input.slice());
    ms.sort();
}

function split(from, to, direction, line) {
    var animations = [];

    for(var i = from; i <= to; i++) {
        var element = d3.select(".element" + i);
        var y = textPositions[i][1];
        y = y + 2*50;
        var delta;

        if(direction == "left") {
            delta = -50 / (y / 50);

        } else if(direction == "right") {
            delta = 50 / (y / 50);
        }

        textPositions[i][0] += delta;
        textPositions[i][1] += 2*50;

        elementPositions[i] += 1;

        if(rectPositions[elementPositions[i]] == undefined) rectPositions[elementPositions[i]] = [];
        rectPositions[elementPositions[i]][i] = [textPositions[i][0], textPositions[i][1]];

        createRect(textPositions[i][0] - arrElementWidth / 2, textPositions[i][1] - 30, 0);
        var movingElement = $("#barChart .element" + i);
        animations.push({ e: movingElement, p: { attr: {x: textPositions[i][0], y: textPositions[i][1]} }, o: { duration: 1, position: '-=1' } });

        movingElement.attr("class", ""); //Remove old classes
        movingElement.addClass("element" + i + " " + "level" + elementPositions[i]);

        animations.push({ e: $("#barChart .level" + (textPositions[i][1]-30)/100), p: { opacity: "1" }, o: { duration: 1, position: '-=1' } });
    }
    animations[0].o.position = '+=0';
    appendAnimation(line, animations, codeDisplayManager);
}

function merge(dest, from) {
    elementPositions[from] -= 1;
    var level = elementPositions[from];
    var position = rectPositions[level][dest];

    var movingElement = $(".element" + from + ".level" + (level+1));
    appendAnimation(null, [{ e: movingElement, p: { attr: {x:position[0], y: position[1] } }, o: { duration: 1 } }], null);

    movingElement.attr("class", ""); //Remove old classes
    movingElement.addClass("element" + dest + " " + "level" + level);
}

function highlightCode(lines, functionName) {
    if (functionName)
        codeDisplayManager.changeFunction(functionName);
    appendCodeLines(lines, codeDisplayManager);
}
<commit_msg>Now fading out the empty arrays in Merge Sort<commit_after>var input = [60, 30, 90, 20, 80, 70];

//Array size
var arrElementWidth = 50;
var arrElementHeight = 50;

var width = $('#graphics').width(),
    height = $('#graphics').height();

var barChart = d3.select(".drawingArea")
    .append("svg:svg")
    .attr("width", width + 200)
    .attr("height", height + 200)
    .append('g')
        .attr("id", "barChart");

barChart.attr("transform", "translate(" + (width/2 - input.length/2 * (arrElementWidth + 5)) + ",10)");

var rectPositions = [];
var textPositions = [];
var elementPositions = [];

resetPosition();
createArray(input);

//Panning
var pan = d3.zoom()
    .on("zoom", panning);

barChart.call(pan);

var codeDisplayManager = new CodeDisplayManager('javascript', 'mergeSort');

function createArray(data) {
    barChart.selectAll("*").remove();
    input = data;
    createRects(data.length, 0);
    createTexts(data);
}

function resetPosition() {
    textPositions = [];
    rectPositions[0] = [];
    elementPositions = [];
    for(var i = 0; i < input.length; i++) {
        rectPositions[0][i] = [i * (arrElementWidth + 5) + (arrElementWidth+5)/2, 30];
        elementPositions[i] = 0;
        textPositions.push([i * (arrElementWidth + 5) + arrElementWidth / 2 + 5, 30]);
    }
}

function createRects(length, y) {
    for(var i = 0; i < length; i++) {
        createRect(i * (arrElementWidth + 5), y, 1);
    }
}

function createRect(x, y, opacity, index) {
    barChart.insert("rect", ":first-child")
        .attr("x", x)
        .attr("y", y)
        .attr("height", arrElementHeight)
        .attr("width", arrElementWidth)
        .attr("fill", "#F44336")
        .style("opacity", opacity)
        .attr("class", "rectElem" + index + " level" + y/100)
        .attr("transform", "translate(0,0)");
}

function createTexts(data) {
    barChart.selectAll("text")
        .data(data)
        .enter()
        .append("text")
        .text(function (d) { return d; })
        .attr("x", function (d, index) { return index * (arrElementWidth+5) + (arrElementWidth+5) / 2; })
        .attr("y", 30)
        .attr("text-anchor", "middle")
        .attr("width", arrElementWidth)
        .attr("transform", "translate(0,0)")
		.attr("class", function (d, i) { return "element" + i; });
}

function panning() {
    barChart.attr("transform", d3.event.transform);
}

function sort() {
    $('#barChart').empty();
    resetPosition();
    createArray(input);
    codeDisplayManager.loadFunctions('mergeSort', 'merge');
    codeDisplayManager.changeFunction('mergeSort');
    var ms = new MergeSort(input.slice());
    ms.sort();
}

function split(from, to, direction, line) {
    var animations = [];

    for(var i = from; i <= to; i++) {
        var element = d3.select(".element" + i);
        var y = textPositions[i][1];
        y = y + 2*50;
        var delta;

        if(direction == "left") {
            delta = -50 / (y / 50);

        } else if(direction == "right") {
            delta = 50 / (y / 50);
        }

        textPositions[i][0] += delta;
        textPositions[i][1] += 2*50;

        elementPositions[i] += 1;

        if(rectPositions[elementPositions[i]] == undefined) rectPositions[elementPositions[i]] = [];
        rectPositions[elementPositions[i]][i] = [textPositions[i][0], textPositions[i][1]];

        createRect(textPositions[i][0] - arrElementWidth / 2, textPositions[i][1] - 30, 0, i);
        var movingElement = $("#barChart .element" + i);
        animations.push({ e: movingElement, p: { attr: {x: textPositions[i][0], y: textPositions[i][1]} }, o: { duration: 1, position: "-=1" } });

        movingElement.attr("class", ""); //Remove old classes
        movingElement.addClass("element" + i + " " + "level" + elementPositions[i]);

        animations.push({ e: $("#barChart " + ".rectElem" + i + ".level" + (textPositions[i][1]-30)/100), p: { opacity: "1" }, o: { duration: 1, position: "-=1" } });
    }
    animations[0].o.position = "+=0";
    appendAnimation(line, animations, codeDisplayManager);
}

function merge(dest, from) {
    elementPositions[from] -= 1;
    var level = elementPositions[from];
	var position = rectPositions[level][dest];

    var movingElement = $(".element" + from + ".level" + (level+1));
	appendAnimation(null, [{ e: movingElement, p: { attr: { x: position[0], y: position[1] } }, o: { duration: 1 } }], null);
	console.log($(".rectElem" + from + ".level" + (level + 1)));
	appendAnimation(null, [{ e: $(".rectElem" + from + ".level" + (level + 1)), p: { opacity: "0" }, o: {position: "-=1"}}]);

    movingElement.attr("class", ""); //Remove old classes
    movingElement.addClass("element" + dest + " " + "level" + level);
}

function highlightCode(lines, functionName) {
    if (functionName)
        codeDisplayManager.changeFunction(functionName);
    appendCodeLines(lines, codeDisplayManager);
}
<|endoftext|>


<commit_before>var Hotel;

$(document).ready(function() {
    Hotel = function(data) {
        var self = this;
        eachKeyValue(data, function(key, val) {
            self[key] = val;
        });
        // if there's a hotel, just delete previous and add this one
        if (currentDay.hotel) {
            currentDay.hotel.delete();
        }
        // building marker
        this.buildMarker()
            .drawMarker()
            .buildItineraryItem()
            .drawItineraryItem();
        currentDay.hotel = this;
    };

    // Hotel.prototype = generateAttraction({
    //     icon: '/images/lodging_0star.png',
    //     $listGroup: $('#my-hotel .list-group'),
    //     $all: $('#all-hotels'),
    //     all: all_hotels,
    //     constructor: Hotel
    // });

    // Hotel.prototype.delete = function() {
    //     currentDay.hotel
    //         .eraseMarker()
    //         .eraseItineraryItem();
    //     currentDay.hotel = null;
    // };

    // now using AJAX to make a get request for the data
    $.get('/hotels', function(data) {
        Hotel.prototype = generateAttraction({
            icon: '/images/lodging_0star.png',
            $listGroup: $('#my-hotel .list-group'),
            $all: $('#all-hotels'),
            // all: all_hotels,
            all: data,
            constructor: Hotel,
            addToDay: function(attraction) {
                $.post('/days/' + currentDay.number + '/hotel', attraction);
            }
        });

        // delete hotel
        Hotel.prototype.delete = function() {
            currentDay.hotel
                .eraseMarker()
                .eraseItineraryItem();
            currentDay.hotel = null;
            // adding AJAX
            $.ajax({
                url: '/days/' + currentDay.number + '/hotel',
                type: 'DELETE'
            });
        };
    });
});

// console.log("Change made.");<commit_msg>back to normal<commit_after>var Hotel;

$(document).ready(function() {
    Hotel = function(data) {
        var self = this;
        eachKeyValue(data, function(key, val) {
            self[key] = val;
        });
        // if there's a hotel, just delete previous and add this one
        if (currentDay.hotel) {
            currentDay.hotel.delete();
        }
        // building marker
        this.buildMarker()
            .drawMarker()
            .buildItineraryItem()
            .drawItineraryItem();
        currentDay.hotel = this;
    };

    // Hotel.prototype = generateAttraction({
    //     icon: '/images/lodging_0star.png',
    //     $listGroup: $('#my-hotel .list-group'),
    //     $all: $('#all-hotels'),
    //     all: all_hotels,
    //     constructor: Hotel
    // });

    // Hotel.prototype.delete = function() {
    //     currentDay.hotel
    //         .eraseMarker()
    //         .eraseItineraryItem();
    //     currentDay.hotel = null;
    // };

    // now using AJAX to make a get request for the data
    $.get('/hotels', function(data) {
        Hotel.prototype = generateAttraction({
            icon: '/images/lodging_0star.png',
            $listGroup: $('#my-hotel .list-group'),
            $all: $('#all-hotels'),
            // all: all_hotels,
            all: data,
            constructor: Hotel,
            addToDay: function(attraction) {
                $.post('/days/' + currentDay.number + '/hotel', attraction);
            }
        });

        // delete hotel
        Hotel.prototype.delete = function() {
            currentDay.hotel
                .eraseMarker()
                .eraseItineraryItem();
            currentDay.hotel = null;
            // adding AJAX
            $.ajax({
                url: '/days/' + currentDay.number + '/hotel',
                type: 'DELETE'
            });
        };
    });
});
<|endoftext|>