<commit_before>/*
 * Limb PHP Framework
 *
 * @link http://limb-project.com
 * @copyright  Copyright © 2004-2007 BIT(http://bit-creative.com)
 * @license    LGPL http://www.gnu.org/copyleft/lesser.html
 */

Limb.Class('Limb.DynamicList',
{
  __construct: function(button_id, answer_sample_id, container_id, init_arr, init_func)
  {
    this.create_button = document.getElementById(button_id);
    this.answer_sample = document.getElementById(answer_sample_id);
    this.container = document.getElementById(container_id);
    this.create_button.controller = this;
    this.init_arr = init_arr;
    this.init_func = init_func;
    this.index = 0;
    this.init();
  },

  init: function()
  {
    for(i=0; i<this.init_arr.length; i++)
      this.addItem();

    this.create_button.onclick = function()
    {
      this.controller.addItem();
      Limb.DynamicList.setModifiedFlag();
      return false;
    }
    this.answer_sample.style.display = 'none';
  },

  addItem: function(top_obj)
  {
    var div = document.createElement('div');
    if(top_obj)
    {
      var next = top_obj.nextSibling;
      if(next)
        div = this.container.insertBefore(div, next);
      else
        this.container.appendChild(div);
    }
    else
    {
      this.container.appendChild(div);
    }
    div.innerHTML = this.answer_sample.innerHTML;

    this.init_func(div, this.index, this.init_arr);

    this.initBehavior(div);
    this.index++;
  },

  initBehavior: function(div)
  {
    div.name = 'dynamic_list_row';

    var del = Limb.DynamicList.get_obj_by_id(div, 'del');
    del.id = del.id + this.index;
    var add = Limb.DynamicList.get_obj_by_id(div, 'add')
    add.id = add.id + this.index;
    var up = Limb.DynamicList.get_obj_by_id(div, 'up')
    up.id = up.id + this.index;
    var down = Limb.DynamicList.get_obj_by_id(div, 'down')
    down.id = down.id + this.index;

    del.controller = add.controller = up.controller = down.controller = this;
    up.div = down.div = add.div = div;

    del.onclick =  function()
    {
      var node = this;
      while((node = node.parentNode) != null)
      {
        if(node && node.name == 'dynamic_list_row')
        {
          node.parentNode.removeChild(node);
          Limb.DynamicList.setModifiedFlag();
        }
      }
    }

    add.onclick =  function()
    {
      this.controller.addItem(this.div);
      Limb.DynamicList.setModifiedFlag();
    }

    up.onclick =  function()
    {
      if(!this.div.previousSibling) return;
      var tmp = this.div.parentNode.removeChild(this.div.previousSibling);

      if(this.div.nextSibling)
        this.controller.container.insertBefore(tmp, this.div.nextSibling);
      else
        this.controller.container.appendChild(tmp);

      Limb.DynamicList.setModifiedFlag();
    }

    down.onclick =  function()
    {
      if(!this.div.nextSibling) return;
      var tmp = this.div.parentNode.removeChild(this.div.nextSibling);

      this.controller.container.insertBefore(tmp, this.div);

      Limb.DynamicList.setModifiedFlag();
    }
  },

  fixSelectValues: function(original, clone)
  {
    var selects = original.getElementsByTagName('select');
    var clone_selects = clone.getElementsByTagName('select');

    for(var i=0; (i < clone_selects.length); i++)
      clone_selects[i].selectedIndex = selects[i].selectedIndex;
  },

  static:
  {
    is_modified: 0,
    setModifiedFlag: function()
    {
      Limb.DynamicList.is_modified = 1;
    },

    get_obj_by_id: function(node, id)
    {
      if(node.id == id)
        return node;

      if(!node.hasChildNodes())
        return null;

      result = null;

      for(var i = 0; (i < node.childNodes.length && !result); i++)
        result = Limb.DynamicList.get_obj_by_id(node.childNodes[i], id);

      return result;
    }
  }
});

Limb.Class('Limb.DoubleSelect',
{
  __construct: function(instanceName)
  {
    // Properties
    this.instanceName	= instanceName;
    this.select = null;
    this.srcSelect = null;
    this.dstSelect = null;
    this.replaceSelect();
  },

  replaceSelect: function()
  {
    this.select = document.getElementById(this.instanceName);
    this.drawControl();
    this.drawOptions();
  },

  drawOptions: function()
  {
    this.dstSelect.options.length = 0;
    this.srcSelect.options.length = 0;

    for(i = 0; i < this.select.options.length; i++)
    {
      if(this.select.options[i].selected)
        option = this.addElement('option', this.dstSelect);
      else
        option = this.addElement('option', this.srcSelect);

      option.value = this.select.options[i].value;
      option.text = this.select.options[i].text;
      option.selected = false;
    }
  },

  drawControl: function()
  {
    this.select.style.display = 'none';
    var parent = this.select.parentNode;
    var div = this.addElement('div', parent);
    div.className = 'DoubleSelect';

    div.innerHTML = "

";
    container = div.childNodes[0].childNodes[0].childNodes[0];
    this.srcSelect = this.addSelector(container.childNodes[0]);
    this.makeupSelector(this.srcSelect, this.select)
    this.addButtons(container.childNodes[1]);
    this.dstSelect = this.addSelector(container.childNodes[2])
    this.makeupSelector(this.dstSelect, this.select)

  },

  makeupSelector: function(src, example)
  {
    if(example.style.width)
      src.style.width = example.style.width;
    else
      src.style.width = '200px';
    if(example.size)
      src.size = example.size;
    else if(example.style.height)
      src.style.height = example.style.height;
    else
      src.style.height = '200px';
  },

  addSelector: function(parent)
  {
    parent.innerHTML = "<select multiple></select>"
    return parent.childNodes[0];
  },

  addButtons: function(parent)
  {
    button  = this.addButton(parent);
    button.value = '>>';
    button.onclick = this.selectAll;
    button.className = 'button';

    this.addElement('br', parent);
    this.addElement('br', parent);

    button  = this.addButton(parent);
    button.value = ' > ';
    button.className = 'button';
    button.onclick = this.selectItems;

    this.addElement('br', parent);
    this.addElement('br', parent);

    button  = this.addButton(parent);
    button.value = ' < ';
    button.className = 'button';
    button.onclick = this.deselectItems;

    this.addElement('br', parent);
    this.addElement('br', parent);

    button  = this.addButton(parent);
    button.value = '<<';
    button.className = 'button';
    button.onclick = this.deselectAll;
  },

  addElement: function(type, parent)
  {
    element = document.createElement(type);
    parent.appendChild(element);
    return element;
  },

  addButton: function(parent)
  {
    element = document.createElement('input');
    element.type = 'button';
    element.style.display = 'inline';
    element.selector_obj = this;
    parent.appendChild(element);
    return element;
  },

  selectAll: function()
  {
    var selector = this.selector_obj;
    for(i = 0; i < selector.select.options.length; i++)
      selector.select.options[i].selected = true;
    selector.drawOptions();
    return false;
  },

  deselectAll: function()
  {
    var selector = this.selector_obj;
    for(i = 0; i < selector.select.options.length; i++)
      selector.select.options[i].selected = false;
    selector.drawOptions();
    return false;
  },

  selectItems: function()
  {
    this.selector_obj.setSelection(this.selector_obj.srcSelect, this.selector_obj.select, true);
    this.selector_obj.drawOptions();
    return false;
  },

  deselectItems: function()
  {
    this.selector_obj.setSelection(this.selector_obj.dstSelect, this.selector_obj.select, false);
    this.selector_obj.drawOptions();
    return false;
  },

  setSelection: function(source, main, selected)
  {
    for(i = 0; i < source.options.length; i++)
    {
      if(!source.options[i].selected)
        continue;
      for(j = 0; j < main.options.length; j++)
      {
        if(main.options[j].value == source.options[i].value &&
           main.options[j].text == source.options[i].text)
        {
          main.options[j].selected = selected;
          continue;
        }
      }
    }
  }
}
);
<commit_msg>[svn r6521] -- improve bug in ie<commit_after>/*
 * Limb PHP Framework
 *
 * @link http://limb-project.com
 * @copyright  Copyright © 2004-2007 BIT(http://bit-creative.com)
 * @license    LGPL http://www.gnu.org/copyleft/lesser.html
 */

Limb.Class('Limb.DynamicList',
{
  __construct: function(button_id, answer_sample_id, container_id, init_arr, init_func)
  {
    this.create_button = document.getElementById(button_id);
    this.answer_sample = document.getElementById(answer_sample_id);
    this.container = document.getElementById(container_id);
    this.create_button.controller = this;
    this.init_arr = init_arr;
    this.init_func = init_func;
    this.index = 0;
    this.init();
  },

  init: function()
  {
    for(i=0; i<this.init_arr.length; i++)
      this.addItem();

    this.create_button.onclick = function()
    {
      this.controller.addItem();
      Limb.DynamicList.setModifiedFlag();
      return false;
    }
    this.answer_sample.style.display = 'none';
  },

  addItem: function(top_obj)
  {
    var div = document.createElement('div');
    if(top_obj)
    {
      var next = top_obj.nextSibling;
      if(next)
        div = this.container.insertBefore(div, next);
      else
        this.container.appendChild(div);
    }
    else
    {
      this.container.appendChild(div);
    }
    div.innerHTML = this.answer_sample.innerHTML;

    this.init_func(div, this.index, this.init_arr);

    this.initBehavior(div);
    this.index++;
  },

  initBehavior: function(div)
  {
    div.name = 'dynamic_list_row';

    var del = Limb.DynamicList.get_obj_by_id(div, 'del');
    del.id = del.id + this.index;
    var add = Limb.DynamicList.get_obj_by_id(div, 'add')
    add.id = add.id + this.index;
    var up = Limb.DynamicList.get_obj_by_id(div, 'up')
    up.id = up.id + this.index;
    var down = Limb.DynamicList.get_obj_by_id(div, 'down')
    down.id = down.id + this.index;

    del.controller = add.controller = up.controller = down.controller = this;
    up.div = down.div = add.div = div;

    del.onclick =  function()
    {
      var node = this;
      while((node = node.parentNode) != null)
      {
        if(node && node.name == 'dynamic_list_row')
        {
          node.parentNode.removeChild(node);
          Limb.DynamicList.setModifiedFlag();
        }
      }
    }

    add.onclick =  function()
    {
      this.controller.addItem(this.div);
      Limb.DynamicList.setModifiedFlag();
    }

    up.onclick =  function()
    {
      if(!this.div.previousSibling) return;
      var tmp = this.div.parentNode.removeChild(this.div.previousSibling);

      if(this.div.nextSibling)
        this.controller.container.insertBefore(tmp, this.div.nextSibling);
      else
        this.controller.container.appendChild(tmp);

      Limb.DynamicList.setModifiedFlag();
    }

    down.onclick =  function()
    {
      if(!this.div.nextSibling) return;
      var tmp = this.div.parentNode.removeChild(this.div.nextSibling);

      this.controller.container.insertBefore(tmp, this.div);

      Limb.DynamicList.setModifiedFlag();
    }
  },

  fixSelectValues: function(original, clone)
  {
    var selects = original.getElementsByTagName('select');
    var clone_selects = clone.getElementsByTagName('select');

    for(var i=0; (i < clone_selects.length); i++)
      clone_selects[i].selectedIndex = selects[i].selectedIndex;
  },

  static:
  {
    is_modified: 0,
    setModifiedFlag: function()
    {
      Limb.DynamicList.is_modified = 1;
    },

    get_obj_by_id: function(node, id)
    {
      if(node.id == id)
        return node;

      if(!node.hasChildNodes())
        return null;

      result = null;

      for(var i = 0; (i < node.childNodes.length && !result); i++)
        result = Limb.DynamicList.get_obj_by_id(node.childNodes[i], id);

      return result;
    }
  }
});

Limb.Class('Limb.DoubleSelect',
{
  __construct: function(instanceName)
  {
    // Properties

    this.instanceName	= instanceName;

    this.select = null;
    this.srcSelect = null;
    this.dstSelect = null;
    this.replaceSelect();

  },

  replaceSelect: function()
  {
    this.select = document.getElementById(this.instanceName);
    this.drawControl();
    this.drawOptions();
  },

  drawOptions: function()
  {
    this.dstSelect.options.length = 0;
    this.srcSelect.options.length = 0;

    for(i = 0; i < this.select.options.length; i++)
    {
      if(this.select.options[i].selected)
        option = this.addElement('option', this.dstSelect);
      else
        option = this.addElement('option', this.srcSelect);

      option.value = this.select.options[i].value;
      option.text = this.select.options[i].text;
      option.selected = false;
    }
  },

  drawControl: function()
  {
    this.select.style.display = 'none';
    var parent = this.select.parentNode;
    var div = this.addElement('div', parent);
    div.className = 'DoubleSelect';

    div.innerHTML = "

";

    var container = div.childNodes[0].childNodes[0].childNodes[0];

    this.srcSelect = this.addSelector(container.childNodes[0]);
    this.makeupSelector(this.srcSelect, this.select)
    this.addButtons(container.childNodes[1]);
    this.dstSelect = this.addSelector(container.childNodes[2])
    this.makeupSelector(this.dstSelect, this.select)

  },

  makeupSelector: function(src, example)
  {
    if(example.style.width)
      src.style.width = example.style.width;
    else
      src.style.width = '200px';
    if(example.size)
      src.size = example.size;
    else if(example.style.height)
      src.style.height = example.style.height;
    else
      src.style.height = '200px';
  },

  addSelector: function(parent)
  {
    parent.innerHTML = "<select multiple></select>"
    return parent.childNodes[0];
  },

  addButtons: function(parent)
  {
    button  = this.addButton(parent);
    button.value = '>>';
    button.onclick = this.selectAll;
    button.className = 'button';

    this.addElement('br', parent);
    this.addElement('br', parent);

    button  = this.addButton(parent);
    button.value = ' > ';
    button.className = 'button';
    button.onclick = this.selectItems;

    this.addElement('br', parent);
    this.addElement('br', parent);

    button  = this.addButton(parent);
    button.value = ' < ';
    button.className = 'button';
    button.onclick = this.deselectItems;

    this.addElement('br', parent);
    this.addElement('br', parent);

    button  = this.addButton(parent);
    button.value = '<<';
    button.className = 'button';
    button.onclick = this.deselectAll;
  },

  addElement: function(type, parent)
  {
    element = document.createElement(type);
    parent.appendChild(element);
    return element;
  },

  addButton: function(parent)
  {
    element = document.createElement('input');
    element.type = 'button';
    element.style.display = 'inline';
    element.selector_obj = this;
    parent.appendChild(element);
    return element;
  },

  selectAll: function()
  {
    var selector = this.selector_obj;
    for(i = 0; i < selector.select.options.length; i++)
      selector.select.options[i].selected = true;
    selector.drawOptions();
    return false;
  },

  deselectAll: function()
  {
    var selector = this.selector_obj;
    for(i = 0; i < selector.select.options.length; i++)
      selector.select.options[i].selected = false;
    selector.drawOptions();
    return false;
  },

  selectItems: function()
  {
    this.selector_obj.setSelection(this.selector_obj.srcSelect, this.selector_obj.select, true);
    this.selector_obj.drawOptions();
    return false;
  },

  deselectItems: function()
  {
    this.selector_obj.setSelection(this.selector_obj.dstSelect, this.selector_obj.select, false);
    this.selector_obj.drawOptions();
    return false;
  },

  setSelection: function(source, main, selected)
  {
    for(i = 0; i < source.options.length; i++)
    {
      if(!source.options[i].selected)
        continue;
      for(j = 0; j < main.options.length; j++)
      {
        if(main.options[j].value == source.options[i].value &&
           main.options[j].text == source.options[i].text)
        {
          main.options[j].selected = selected;
          continue;
        }
      }
    }
  }
}
);
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import TransitionGroup from 'react-addons-transition-group';
import { TweenMax } from 'gsap';
import Add from './Add.react';
import Message from '../components/Message.react';
import { fetchPostEdge } from '../actions/edge';
import { fetchHeart } from '../actions/heart';

const startIndex = 0;
const endIndex = 3;

const mapStateToProps = (state) => {
  const {
    user: {
      isLoggedIn,
    },
    edge,
    connectEntity,
    currentPage: {
      id,
      entityCount,
      isFetching,
      title,
      superEdges,
      queryLink,
      canonicalLink,
      heartCount,
      heartValue,
    },
  } = state;

  const connectEntityId = connectEntity.id;
  const isFetchingEdge = edge.isFetching;
  const messages = edge.messages;

  return {
    isFetching,
    isLoggedIn,
    edge,
    id,
    connectEntityId,
    entityCount,
    title,
    isFetchingEdge,
    superEdges,
    queryLink,
    canonicalLink,
    messages,
    heartCount,
    heartValue,
  };
};

class Connections extends Component {
  state = {
    connectionDisplayIndex: 0,
    isAddConnectionToggledOn: false,
    heartClickAttempted: false,
    rotateConnectionBox: false,
  };

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    superEdges: PropTypes.array.isRequired,
    entityCount: PropTypes.number.isRequired,
    id: PropTypes.string,
  }

  componentDidMount() {
    //no opp
  }

  render() {
    const {
      isFetching,
      isLoggedIn,
      superEdges,
      entityCount,
      id,
      title,
      isFetchingEdge,
      messages,
      heartValue,
      heartCount,
    } = this.props;

    const {
      connectionDisplayIndex,
      isAddConnectionToggledOn,
      heartClickAttempted,
      rotateConnectionBox,
    } = this.state;

    /* increment/decrement styling */
    let incrementButtonStyle;
    let decrementButtonStyle;
    if (entityCount > 0) {
      incrementButtonStyle = { color: 'rgba(0,0,0,.6)' };
      decrementButtonStyle = { color: 'rgba(0,0,0,.6)' };
      if (connectionDisplayIndex === entityCount - 1) {
        decrementButtonStyle = { color: 'rgba(0,0,0,.33)' };
      } else if (connectionDisplayIndex === 0) {
        incrementButtonStyle = { color: 'rgba(0,0,0,.33)' };
      }
    } else {
      incrementButtonStyle = { display: 'none' };
      decrementButtonStyle = { display: 'none' };
    }

    /* TODO: make this login link dynamic */
    const showLoginInfo = (isAddConnectionToggledOn && !isLoggedIn) || (heartClickAttempted && !isLoggedIn) ? 'flex' : 'none';
    const loginButton = (

        Log in

)

    const loginText = heartClickAttempted ?
      (

        You must be logged in to recommend a web page

) :
      (

        You must be logged in to make a connection

)

    const showRecommenderInfo = !isAddConnectionToggledOn && isLoggedIn ? 'flex' : 'none';
    const recommenderInfo =  entityCount > 0 ?
      (

            Contributor

              @{superEdges[connectionDisplayIndex].edges[0].user.username}

) : null

    const showAddRecommendationButton = !isAddConnectionToggledOn && isLoggedIn ? 'flex' : 'none';
    const addRecommendationButton = entityCount === 0 ?
      (

        Add Recommendation

) : null

    const inputBox = isLoggedIn && isAddConnectionToggledOn ? (

        <Add onSave={this.onSave} />

) : null;

    const showRecommendationBox = isAddConnectionToggledOn ? 'none' : 'flex';
    const recommendationBox = entityCount > 0 ?
      (

                Read next

                {superEdges[connectionDisplayIndex].entity.domain} - {superEdges[connectionDisplayIndex].entity.title}

) : null

    const noRecommendationBox = entityCount === 0 && !heartClickAttempted ?
      (

              There are no recommendations for this page

) : null

    const inputSuccessErrorMessages = isAddConnectionToggledOn ?
      (

        {isFetchingEdge?'isFetchingEdge':''}
        <Message messages={messages} />

) : null

    const heartIconType = heartValue ? 'fa-heart' : 'fa-heart-o';
    const showHeartCount = heartCount > 0 ? 'flex' : 'none';
    const connectionBoxRotationClass = rotateConnectionBox ? 'rotateIn' : 'rotateOut';

    return (

                {heartCount}

            {recommendationBox}
            {noRecommendationBox}
            {loginText}
            {inputBox}

            {loginButton}
            {recommenderInfo}
            {addRecommendationButton}
            {inputSuccessErrorMessages}

    );
  }

  incrementConnectionsIndex = (e) => {
    if (this.state.connectionDisplayIndex < this.props.entityCount - 1) {
      this.setState({
        connectionDisplayIndex: this.state.connectionDisplayIndex + 1
      })
    }
  }

  decrementConnectionsIndex = (e) => {
    if (this.state.connectionDisplayIndex > 0) {
      this.setState({
        connectionDisplayIndex: this.state.connectionDisplayIndex - 1
      })
    }
  }

  onSave = (e) => {
    const { dispatch, id, connectEntityId } = this.props;

    //const { description, tags } = this.state;
    dispatch(fetchPostEdge(
      id,
      connectEntityId,
      '',
      []
    ));
    this.setState({
      isAddConnectionToggledOn: !this.state.isAddConnectionToggledOn,
      rotateConnectionBox: false
    });
    e.preventDefault();
  }

  onHeart = (e) => {
    if (this.props.isLoggedIn) {
      const { dispatch, id, heartValue } = this.props;
      dispatch(fetchHeart(
        id,
        !heartValue,
      ));
    } else {
      this.setState({
        heartClickAttempted: !this.state.heartClickAttempted
      })
    }
    e.preventDefault();
  }
}

export default connect(mapStateToProps)(Connections);

// Functons and constants
const styles = {
  /* currently blank... styles moved to stylesheet */
}

function enterConnectionBox(e) {
  this.setState({
    rotateConnectionBox: true,
  });
  e.preventDefault();
}

function leaveConnectionBox(e) {
  if (!this.state.isAddConnectionToggledOn) {
    this.setState({
      rotateConnectionBox: false,
    });
  }
  e.preventDefault();
}

function toggleMiddleSection(e) {
  this.setState({
    heartClickAttempted: false,
    isAddConnectionToggledOn: !this.state.isAddConnectionToggledOn
  });
  e.preventDefault();
}

window.onkeyup = function(e) {
  if (e.keyCode == 27) { /* escape key */
    /* Yo Jeff - I'm too tired to think this one through, but how do I pass state through to a function on keypress? */
    /* thoughts are to attach this to body and pass state "this" through on all keystrokes, ... seems excessive */
  }
}
<commit_msg>removing a blank line (?) so I can commit & merge.<commit_after>import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import TransitionGroup from 'react-addons-transition-group';
import { TweenMax } from 'gsap';
import Add from './Add.react';
import Message from '../components/Message.react';
import { fetchPostEdge } from '../actions/edge';
import { fetchHeart } from '../actions/heart';

const startIndex = 0;
const endIndex = 3;

const mapStateToProps = (state) => {
  const {
    user: {
      isLoggedIn,
    },
    edge,
    connectEntity,
    currentPage: {
      id,
      entityCount,
      isFetching,
      title,
      superEdges,
      queryLink,
      canonicalLink,
      heartCount,
      heartValue,
    },
  } = state;

  const connectEntityId = connectEntity.id;
  const isFetchingEdge = edge.isFetching;
  const messages = edge.messages;

  return {
    isFetching,
    isLoggedIn,
    edge,
    id,
    connectEntityId,
    entityCount,
    title,
    isFetchingEdge,
    superEdges,
    queryLink,
    canonicalLink,
    messages,
    heartCount,
    heartValue,
  };
};

class Connections extends Component {
  state = {
    connectionDisplayIndex: 0,
    isAddConnectionToggledOn: false,
    heartClickAttempted: false,
    rotateConnectionBox: false,
  };

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    superEdges: PropTypes.array.isRequired,
    entityCount: PropTypes.number.isRequired,
    id: PropTypes.string,
  }

  componentDidMount() {
    //no opp
  }

  render() {
    const {
      isFetching,
      isLoggedIn,
      superEdges,
      entityCount,
      id,
      title,
      isFetchingEdge,
      messages,
      heartValue,
      heartCount,
    } = this.props;

    const {
      connectionDisplayIndex,
      isAddConnectionToggledOn,
      heartClickAttempted,
      rotateConnectionBox,
    } = this.state;

    /* increment/decrement styling */
    let incrementButtonStyle;
    let decrementButtonStyle;
    if (entityCount > 0) {
      incrementButtonStyle = { color: 'rgba(0,0,0,.6)' };
      decrementButtonStyle = { color: 'rgba(0,0,0,.6)' };
      if (connectionDisplayIndex === entityCount - 1) {
        decrementButtonStyle = { color: 'rgba(0,0,0,.33)' };
      } else if (connectionDisplayIndex === 0) {
        incrementButtonStyle = { color: 'rgba(0,0,0,.33)' };
      }
    } else {
      incrementButtonStyle = { display: 'none' };
      decrementButtonStyle = { display: 'none' };
    }

    /* TODO: make this login link dynamic */
    const showLoginInfo = (isAddConnectionToggledOn && !isLoggedIn) || (heartClickAttempted && !isLoggedIn) ? 'flex' : 'none';
    const loginButton = (

        Log in

)

    const loginText = heartClickAttempted ?
      (

        You must be logged in to recommend a web page

) :
      (

        You must be logged in to make a connection

)

    const showRecommenderInfo = !isAddConnectionToggledOn && isLoggedIn ? 'flex' : 'none';
    const recommenderInfo =  entityCount > 0 ?
      (

            Contributor

              @{superEdges[connectionDisplayIndex].edges[0].user.username}

) : null

    const showAddRecommendationButton = !isAddConnectionToggledOn && isLoggedIn ? 'flex' : 'none';
    const addRecommendationButton = entityCount === 0 ?
      (

        Add Recommendation

) : null

    const inputBox = isLoggedIn && isAddConnectionToggledOn ? (

        <Add onSave={this.onSave} />

) : null;

    const showRecommendationBox = isAddConnectionToggledOn ? 'none' : 'flex';
    const recommendationBox = entityCount > 0 ?
      (

                Read next

                {superEdges[connectionDisplayIndex].entity.domain} - {superEdges[connectionDisplayIndex].entity.title}

) : null

    const noRecommendationBox = entityCount === 0 && !heartClickAttempted ?
      (

              There are no recommendations for this page

) : null

    const inputSuccessErrorMessages = isAddConnectionToggledOn ?
      (

        {isFetchingEdge?'isFetchingEdge':''}
        <Message messages={messages} />

) : null

    const heartIconType = heartValue ? 'fa-heart' : 'fa-heart-o';
    const showHeartCount = heartCount > 0 ? 'flex' : 'none';
    const connectionBoxRotationClass = rotateConnectionBox ? 'rotateIn' : 'rotateOut';

    return (

                {heartCount}

            {recommendationBox}
            {noRecommendationBox}
            {loginText}
            {inputBox}

            {loginButton}
            {recommenderInfo}
            {addRecommendationButton}
            {inputSuccessErrorMessages}

    );
  }

  incrementConnectionsIndex = (e) => {
    if (this.state.connectionDisplayIndex < this.props.entityCount - 1) {
      this.setState({
        connectionDisplayIndex: this.state.connectionDisplayIndex + 1
      })
    }
  }

  decrementConnectionsIndex = (e) => {
    if (this.state.connectionDisplayIndex > 0) {
      this.setState({
        connectionDisplayIndex: this.state.connectionDisplayIndex - 1
      })
    }
  }

  onSave = (e) => {
    const { dispatch, id, connectEntityId } = this.props;

    //const { description, tags } = this.state;
    dispatch(fetchPostEdge(
      id,
      connectEntityId,
      '',
      []
    ));
    this.setState({
      isAddConnectionToggledOn: !this.state.isAddConnectionToggledOn,
      rotateConnectionBox: false
    });
    e.preventDefault();
  }

  onHeart = (e) => {
    if (this.props.isLoggedIn) {
      const { dispatch, id, heartValue } = this.props;
      dispatch(fetchHeart(
        id,
        !heartValue,
      ));
    } else {
      this.setState({
        heartClickAttempted: !this.state.heartClickAttempted
      })
    }
    e.preventDefault();
  }
}

export default connect(mapStateToProps)(Connections);

// Functons and constants
const styles = {
  /* currently blank... styles moved to stylesheet */
}

function enterConnectionBox(e) {
  this.setState({
    rotateConnectionBox: true,
  });
  e.preventDefault();
}

function leaveConnectionBox(e) {
  if (!this.state.isAddConnectionToggledOn) {
    this.setState({
      rotateConnectionBox: false,
    });
  }
  e.preventDefault();
}

function toggleMiddleSection(e) {
  this.setState({
    heartClickAttempted: false,
    isAddConnectionToggledOn: !this.state.isAddConnectionToggledOn
  });
  e.preventDefault();
}

window.onkeyup = function(e) {
  if (e.keyCode == 27) { /* escape key */
    /* Yo Jeff - I'm too tired to think this one through, but how do I pass state through to a function on keypress? */
    /* thoughts are to attach this to body and pass state "this" through on all keystrokes, ... seems excessive */
  }
}
<|endoftext|>


<commit_before>// Gimme a Github object! Please.
function github() {
  return new Github({
    token: $.cookie('oauth-token'),
    auth: "oauth"
  });
}

// Authentication
// -------

function authenticate() {
  if ($.cookie("oauth-token")) return window.authenticated = true;
  var match = window.location.href.match(/\?code=(.*)/);

  // Handle Code
  if (match) {
    var code = match[1];
    $.getJSON('{{site.gatekeeper_url}}/authenticate/'+match[1], function(data) {
      $.cookie('oauth-token', data.token);
      window.authenticated = true;
      window.location.href = window.location.href.replace(/\?code=(.*)/, '');
    });
  }
}

function logout() {
  window.authenticated = false;
  $.cookie("oauth-token", null);
}

// Load Application
// -------
//
// Load everything that's needed for the app + header

function loadApplication(cb) {

  if (window.authenticated) {
    $.ajax({
      type: "GET",
      url: 'https://api.github.com/user',
      dataType: 'json',
      contentType: 'application/x-www-form-urlencoded',
      success: function(res) {
        $.cookie("avatar", res.avatar_url);
        app.username = res.login;
        var user = github().getUser(app.username);
        var owners = {};

        user.repos(function(err, repos) {
          _.each(repos, function(r) {
            owners[r.owner.login] = owners[r.owner.login] ? owners[r.owner.login].concat([r])
                                                          : [r];
          });
          cb(null, { "available_repos": repos, "owners": owners });
        });
      },
      error: function(err) {
        logout();
        cb(null, { "available_repos": [], "owners": {} });
      },
      headers : { Authorization : 'token ' + $.cookie('oauth-token') }
    });

  } else {
    cb(null, { "available_repos": [], "owners": {} });
  }
}

// Load Branches
// -------
//
// List all available Jekyll branches

function loadBranches(user, repo, cb) {
  var repo = github().getRepo(user, repo);

  repo.listBranches(function(err, branches) {
    var jekyllBranches = [],
        processed = 0;

    _.each(branches, function(branch) {
      repo.read(branch, "_config.yml", function(err, data) {
        if (!err) jekyllBranches.push(branch);
        processed += 1;
        if (processed === branches.length) cb(null, jekyllBranches);
      });
    });
  });
}

// Load Site
// -------
//
// List all postings for a given site plus load _config.yml

function loadSite(user, repo, branch, path, cb) {

  var repo = github().getRepo(user, repo, branch);
  function loadConfig(cb) {
    repo.read(branch, "_config.yml", function(err, data) {
      if (err) return cb(err);
      cb(null, jsyaml.load(data));
    });
  }

  if (!path) path = "_posts";
  repo.getSha(branch, path, function(err, sha) {

    repo.getTree(sha, function(err, tree) {
      if (err) cb("Not a valid Jekyll repository.");

      var paths = _.compact(_.map(tree, function(file) {
        return file.type === "tree" ? path + "/"+ file.path : null
      }));

      paths = [path].concat(paths);

      // Load Jekyll config file (_config.yml)
      loadConfig(function(err, config) {
        if (err) return cb(err);
        app.state.config = config;
        app.state.paths = paths;
        app.state.path = path ? path : paths[0];

        var posts = _.map(tree, function(file) {
          var regex = new RegExp("^(\\w|-)*.md$");

          // Make sense of the file path
          function semantify(p) {
            return {
              path: path + "/"+p,
              date: "",
              title: p
            };
          }
          return regex.test(file.path) ? semantify(file.path) : null;
        });
        cb(null, {"posts": _.compact(posts)});
      });
    });
  });
}

// Save Post
// -------
//
// List all postings for a given repository
// Looks into _posts/blog

function savePost(user, repo, branch, path, file, metadata, content, message, cb) {
  var repo = github().getRepo(user, repo);
  function serialize(data) {
    return ["---", data, "---"].join('\n')+'\n\n'+content;
  }
  repo.write(branch, path + "/" + file, serialize(metadata), message, cb);
}

// Delete Post
// -------

function deletePost(user, repo, branch, path, file, cb) {
  var repo = github().getRepo(user, repo);
  repo.remove(branch, path+ "/" + file, cb);
}

// Move Post
// -------

function movePost(user, repo, branch, path, newPath, cb) {
  var repo = github().getRepo(user, repo);
  repo.move(branch, path, newPath, cb);
}

// New Post
// -------
//
// Prepare new empty post

function emptyPost(user, repo, branch, path, cb) {
  var repo = github().getRepo(user, repo);
  cb(null, {
    "metadata": {
      "layout": "default",
      "published": false,
    },
    "raw_metadata": "published: false",
    "content": "How does it work?\n=================\n\nEnter Text in Markdown format.",
    "repo": repo,
    "path": "_posts",
    "persisted": false,
    "file": new Date().format("Y-m-d")+"-your-filename.md"
  });
}

// Save Post
// -------
//
// List all postings for a given repository
// Looks into _posts/blog

function loadPost(user, repo, branch, path, file, cb) {
  var repo = github().getRepo(user, repo);

  repo.read(branch, path + "/" + file, function(err, data) {
    function parse(content) {
      var res = {};
      var chunked = (content+'\n').split('---\n');
      if (chunked[0] === '' && chunked.length > 2) {
        res.metadata = jsyaml.load(chunked[1]);
        res.raw_metadata = chunked[1].trim();
        res.content = chunked.slice(2).join('---\n');
      } else {
        res.metadata = {};
        res.content = content;
      }
      return res;
    }

    // Extract metadata
    var post = parse(data);

    // We're done. Can you hear me?!
    cb(err, _.extend(post, {"repo": repo, "path": path, "file": file, "persisted": true}));
  });
}
<commit_msg>Deal with CR/LF line endings.<commit_after>// Gimme a Github object! Please.
function github() {
  return new Github({
    token: $.cookie('oauth-token'),
    auth: "oauth"
  });
}

// Authentication
// -------

function authenticate() {
  if ($.cookie("oauth-token")) return window.authenticated = true;
  var match = window.location.href.match(/\?code=(.*)/);

  // Handle Code
  if (match) {
    var code = match[1];
    $.getJSON('{{site.gatekeeper_url}}/authenticate/'+match[1], function(data) {
      $.cookie('oauth-token', data.token);
      window.authenticated = true;
      window.location.href = window.location.href.replace(/\?code=(.*)/, '');
    });
  }
}

function logout() {
  window.authenticated = false;
  $.cookie("oauth-token", null);
}

// Load Application
// -------
//
// Load everything that's needed for the app + header

function loadApplication(cb) {

  if (window.authenticated) {
    $.ajax({
      type: "GET",
      url: 'https://api.github.com/user',
      dataType: 'json',
      contentType: 'application/x-www-form-urlencoded',
      success: function(res) {
        $.cookie("avatar", res.avatar_url);
        app.username = res.login;
        var user = github().getUser(app.username);
        var owners = {};

        user.repos(function(err, repos) {
          _.each(repos, function(r) {
            owners[r.owner.login] = owners[r.owner.login] ? owners[r.owner.login].concat([r])
                                                          : [r];
          });
          cb(null, { "available_repos": repos, "owners": owners });
        });
      },
      error: function(err) {
        logout();
        cb(null, { "available_repos": [], "owners": {} });
      },
      headers : { Authorization : 'token ' + $.cookie('oauth-token') }
    });

  } else {
    cb(null, { "available_repos": [], "owners": {} });
  }
}

// Load Branches
// -------
//
// List all available Jekyll branches

function loadBranches(user, repo, cb) {
  var repo = github().getRepo(user, repo);

  repo.listBranches(function(err, branches) {
    var jekyllBranches = [],
        processed = 0;

    _.each(branches, function(branch) {
      repo.read(branch, "_config.yml", function(err, data) {
        if (!err) jekyllBranches.push(branch);
        processed += 1;
        if (processed === branches.length) cb(null, jekyllBranches);
      });
    });
  });
}

// Load Site
// -------
//
// List all postings for a given site plus load _config.yml

function loadSite(user, repo, branch, path, cb) {

  var repo = github().getRepo(user, repo, branch);
  function loadConfig(cb) {
    repo.read(branch, "_config.yml", function(err, data) {
      if (err) return cb(err);
      cb(null, jsyaml.load(data));
    });
  }

  if (!path) path = "_posts";
  repo.getSha(branch, path, function(err, sha) {

    repo.getTree(sha, function(err, tree) {
      if (err) cb("Not a valid Jekyll repository.");

      var paths = _.compact(_.map(tree, function(file) {
        return file.type === "tree" ? path + "/"+ file.path : null
      }));

      paths = [path].concat(paths);

      // Load Jekyll config file (_config.yml)
      loadConfig(function(err, config) {
        if (err) return cb(err);
        app.state.config = config;
        app.state.paths = paths;
        app.state.path = path ? path : paths[0];

        var posts = _.map(tree, function(file) {
          var regex = new RegExp("^(\\w|-)*.md$");

          // Make sense of the file path
          function semantify(p) {
            return {
              path: path + "/"+p,
              date: "",
              title: p
            };
          }
          return regex.test(file.path) ? semantify(file.path) : null;
        });
        cb(null, {"posts": _.compact(posts)});
      });
    });
  });
}

// Save Post
// -------
//
// List all postings for a given repository
// Looks into _posts/blog

function savePost(user, repo, branch, path, file, metadata, content, message, cb) {
  var repo = github().getRepo(user, repo);
  function serialize(data) {
    return ["---", data, "---"].join('\n')+'\n\n'+content;
  }
  repo.write(branch, path + "/" + file, serialize(metadata), message, cb);
}

// Delete Post
// -------

function deletePost(user, repo, branch, path, file, cb) {
  var repo = github().getRepo(user, repo);
  repo.remove(branch, path+ "/" + file, cb);
}

// Move Post
// -------

function movePost(user, repo, branch, path, newPath, cb) {
  var repo = github().getRepo(user, repo);
  repo.move(branch, path, newPath, cb);
}

// New Post
// -------
//
// Prepare new empty post

function emptyPost(user, repo, branch, path, cb) {
  var repo = github().getRepo(user, repo);
  cb(null, {
    "metadata": {
      "layout": "default",
      "published": false,
    },
    "raw_metadata": "published: false",
    "content": "How does it work?\n=================\n\nEnter Text in Markdown format.",
    "repo": repo,
    "path": "_posts",
    "persisted": false,
    "file": new Date().format("Y-m-d")+"-your-filename.md"
  });
}

// Save Post
// -------
//
// List all postings for a given repository
// Looks into _posts/blog

function loadPost(user, repo, branch, path, file, cb) {
  var repo = github().getRepo(user, repo);
  repo.read(branch, path + "/" + file, function(err, data) {

    function parse(content) {
      var res = {};
      var chunked = (content+'\n').replace(/\r\n/g, "\n").split('---\n');
      if (chunked[0] === '' && chunked.length > 2) {
        res.metadata = jsyaml.load(chunked[1]);
        res.raw_metadata = chunked[1].trim();
        res.content = chunked.slice(2).join('---\n');
      } else {
        res.metadata = {};
        res.raw_metadata = "";
        res.content = content;
      }
      return res;
    }
    // Extract metadata
    var post = parse(data);

    // We're done. Can you hear me?!
    cb(err, _.extend(post, {"repo": repo, "path": path, "file": file, "persisted": true}));
  });
}
<|endoftext|>


<commit_before>var Board = function(turn){
  this.turn = turn;
  this.turnNumber = turn.turnNumber;
  this.player = turn.player;
  this.getBoardState();
  Board.all.push(this);
}

Board.all = [];

Board.current = function(){
  return Board.all[Board.all.length - 1]
}

// [0 = empty, 1= p1, 2= p2, 3= p1King, 4= p2King, -1= off-square]

Board.prototype.getBoardState = function(){
  var segmentedBoard = [];
  var unsegmentedBoard = this.getUnsegmentedBoard();
  for(var i=0; i<8; i++){
    segmentedBoard.push(unsegmentedBoard.splice(0,8));
  }
  this.boardState = segmentedBoard;
};

// Board.prototype.imagineFutureBoards

Board.prototype.getUnsegmentedBoard = function(){
  return Square.all.map(function(square){
    if(square.color === "off"){
      return -1;
    } else if(square.piece === null){
      return 0;
    } else if(square.piece.isKing && square.piece.player.name === 'p1'){
      return 3;
    } else if(square.piece.isKing && square.piece.player.name === 'p2'){
      return 4;
    } else if(square.piece.player.name === 'p1'){
      return 1;
    } else if(square.piece.player.name === 'p2'){
      return 2;
    }
  });
};

Board.displayBoardState = function(boardState){
  Piece.all = [];
  var newBoard = boardState.map(function(row, y){
    row.map(function(square, x){
      var squareToUpdate = Square.findByPosition(x, y);
      if(square == 3 || square == 1){
        var p1Piece = new Piece(Player.all[0])
        if(square == 3){
          p1Piece.kingMe()
        }
        p1Piece.goToSquare(squareToUpdate);
      } else if(square == 4 || square == 2){
        var p2Piece = new Piece(Player.all[1])
        if(square == 4){
          p2Piece.kingMe()
        }
        p2Piece.goToSquare(squareToUpdate);
      } else if(square == 0){
        if(squareToUpdate.piece){
          squareToUpdate.piece.leaveSquare();
        }
      }
    })
  })
}

Board.prototype.sendToDatabase = function(){
  var consider = function(dur) {
    var d = new Date().getTime() + dur;
    while(new Date().getTime() <= d ) {
    //Do nothing
    }
  }

  var _that = this
  $.ajax({
    method: "POST",
    url: "/boards",
    data: {
      state: this.boardState,
      turn: this.turnNumber,
      player: Player.all.indexOf(this.player)
    }
  }).done(function(message){
    // debugger
    var msg = JSON.parse(message)
    // debugger
    var msgCount = msg.length;

    (function theLoop(i) {
      setTimeout(function () {
        // alert('hello')
        Board.displayBoardState(msg[msgCount - i]);
        if (--i) {          // If i > 0, keep going
          theLoop(i);       // Call the loop again, and pass it the current value of i
        }
      }, 500);
    })(msgCount);

    // msg.forEach(function(move){
    //   Board.displayBoardState(move)
    //   consider(3000)
    //   msgCount -= 1
    //   if (msgCount == 0) { _that.turn.end(); }
    // })

  })
}

// var interval = setInterval(function(){
  // Board.displayBoardState(msg.shift());
  // if (!msg.length) {
  //   clearInterval(interval);
  //   _that.turn.end();
  // }
// }, 3000)
<commit_msg>fix end turn after ajax<commit_after>var Board = function(turn){
  this.turn = turn;
  this.turnNumber = turn.turnNumber;
  this.player = turn.player;
  this.getBoardState();
  Board.all.push(this);
}

Board.all = [];

Board.current = function(){
  return Board.all[Board.all.length - 1]
}

// [0 = empty, 1= p1, 2= p2, 3= p1King, 4= p2King, -1= off-square]

Board.prototype.getBoardState = function(){
  var segmentedBoard = [];
  var unsegmentedBoard = this.getUnsegmentedBoard();
  for(var i=0; i<8; i++){
    segmentedBoard.push(unsegmentedBoard.splice(0,8));
  }
  this.boardState = segmentedBoard;
};

// Board.prototype.imagineFutureBoards

Board.prototype.getUnsegmentedBoard = function(){
  return Square.all.map(function(square){
    if(square.color === "off"){
      return -1;
    } else if(square.piece === null){
      return 0;
    } else if(square.piece.isKing && square.piece.player.name === 'p1'){
      return 3;
    } else if(square.piece.isKing && square.piece.player.name === 'p2'){
      return 4;
    } else if(square.piece.player.name === 'p1'){
      return 1;
    } else if(square.piece.player.name === 'p2'){
      return 2;
    }
  });
};

Board.displayBoardState = function(boardState){
  Piece.all = [];
  var newBoard = boardState.map(function(row, y){
    row.map(function(square, x){
      var squareToUpdate = Square.findByPosition(x, y);
      if(square == 3 || square == 1){
        var p1Piece = new Piece(Player.all[0])
        if(square == 3){
          p1Piece.kingMe()
        }
        p1Piece.goToSquare(squareToUpdate);
      } else if(square == 4 || square == 2){
        var p2Piece = new Piece(Player.all[1])
        if(square == 4){
          p2Piece.kingMe()
        }
        p2Piece.goToSquare(squareToUpdate);
      } else if(square == 0){
        if(squareToUpdate.piece){
          squareToUpdate.piece.leaveSquare();
        }
      }
    })
  })
}

Board.prototype.sendToDatabase = function(){
  var consider = function(dur) {
    var d = new Date().getTime() + dur;
    while(new Date().getTime() <= d ) {
    //Do nothing
    }
  }

  var _that = this
  $.ajax({
    method: "POST",
    url: "/boards",
    data: {
      state: this.boardState,
      turn: this.turnNumber,
      player: Player.all.indexOf(this.player)
    }
  }).done(function(message){
    // debugger
    var msg = JSON.parse(message)
    // debugger
    var msgCount = msg.length;

    (function theLoop(i) {
      setTimeout(function () {
        // alert('hello')
        Board.displayBoardState(msg[msgCount - i]);
        if (--i) {          // If i > 0, keep going
          theLoop(i);       // Call the loop again, and pass it the current value of i
        }
        _that.turn.end()
      }, 500);
    })(msgCount);
  })
}

// var interval = setInterval(function(){
  // Board.displayBoardState(msg.shift());
  // if (!msg.length) {
  //   clearInterval(interval);
  //   _that.turn.end();
  // }
// }, 3000)
<|endoftext|>


<commit_before>$(document).ready(function(){
  $('#graph').load(loadGraph);
});

var loadGraph = function() {
    //Add vertical line to denote where the user is.
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: '/bills/comparison.json',
        dataType: 'json',
        success: function(data) {
            var arr = [];
            data.comparison_bills.forEach(function(d) {
                d.amount = +d.amount;
                arr.push({ amount: d.amount, user: d.user_id, id: d.id });
            });
            draw(arr, data.current_user_id, data.most_recent_bill_id);
        },
        error: function(result) {
            error();
        }
    });
};

function draw(data, current_user_id, last_bill) {
    var color = d3.scale.category20b();
    var margin = {top: 20, right: 30, bottom: 30, left: 40},
        width = parseInt(d3.select(".small-centered").style("width")) - margin.left - margin.right,
        height = parseInt(d3.select(".small-centered").style("height")) - margin.top - margin.bottom;

    var barWidth = width / data.length;

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0])
        .domain([0, d3.max(data, function(d) { return d.amount; })]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var chart = d3.select("#graph")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var bar = chart.selectAll("g")
        .data(data)
        .enter().append("g")
        .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; })
        .style("fill", "blue");

    bar.append("rect")
        .attr("y", function(d) { return y(d.amount) })
        .attr("width", barWidth - 1)
      	.attr("height", function(d) { return height-y(d.amount); })
        .style("fill", function (d) { if(d.id == last_bill) { return "red"; } });

    chart.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 0)
        .attr("dy", "-2.6em")
        .style("text-anchor", "end")
        .text("Amount in Dollars");
}

function error() {
    console.log("error")
}
<commit_msg>Fixed graph on Firefox<commit_after>$(document).ready(function(){
  $('#graph').append(loadGraph);
});

var loadGraph = function() {
    //Add vertical line to denote where the user is.
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: '/bills/comparison.json',
        dataType: 'json',
        success: function(data) {
            var arr = [];
            data.comparison_bills.forEach(function(d) {
                d.amount = +d.amount;
                arr.push({ amount: d.amount, user: d.user_id, id: d.id });
            });
            draw(arr, data.current_user_id, data.most_recent_bill_id);
        },
        error: function(result) {
            error();
        }
    });
};

function draw(data, current_user_id, last_bill) {
    var color = d3.scale.category20b();
    var margin = {top: 20, right: 30, bottom: 30, left: 40},
        width = parseInt(d3.select(".small-centered").style("width")) - margin.left - margin.right,
        height = parseInt(d3.select(".small-centered").style("height")) - margin.top - margin.bottom;

    var barWidth = width / data.length;

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0])
        .domain([0, d3.max(data, function(d) { return d.amount; })]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var chart = d3.select("#graph")
        .attr("width", width + margin.left + margin.right+'px')
        .attr("height", height + margin.top + margin.bottom+'px')
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var bar = chart.selectAll("g")
        .data(data)
        .enter().append("g")
        .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; })
        .style("fill", "blue");

    bar.append("rect")
        .attr("y", function(d) { return y(d.amount) })
        .attr("width", barWidth - 1)
      	.attr("height", function(d) { return height-y(d.amount); })
        .style("fill", function (d) { if(d.id == last_bill) { return "red"; } });

    chart.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 0)
        .attr("dy", "-2.6em")
        .style("text-anchor", "end")
        .text("Amount in Dollars");
}

function error() {
    console.log("error")
}
<|endoftext|>


<commit_before>$(document).on("page:change", function(){
  var isPlaying = false;
  var queue = [];
  var deleteFromQueueMode = false;
  var currentTrack = "";

  $(document).on("click", "#mute_button", function() {
    currentTrack.toggleMute();
  });

  $(document).on("click", "#skip_button", function() {
    currentTrack.setPosition(currentTrack.duration - 1);
  });

  $(document).on("click", "#delete_button", function() {
    if (deleteFromQueueMode === false) {
      deleteFromQueueMode = true;
      $("#delete_mode_toggle").text("ON");
    } else {
      deleteFromQueueMode = false;
      $("#delete_mode_toggle").text("OFF");
    };
  });

  var addSongsToQueue = function(){
    var id = $("#queue_container ul button").last().attr("id")
    var type = $("#queue_container ul button").last().attr("data-type")
    var audio = $("#queue_container ul button").last().attr("data-track-link");
    var duration = $("#queue_container ul button").last().attr("data-track-duration");
    var trackTitle = $("#queue_container ul button").last().attr("data-track-title");

    queue.push({
      id: id,
      type: type,
      audio: audio,
      duration: parseInt(duration),
      trackTitle: trackTitle
    })
  }

  var playSong = function(id) {
    // prevents two songs from playing at the same time
     if(typeof(soundManager) !== "undefined"){
        soundManager.stopAll();
    }

      $("#soundcloud").empty();
      var currentItem = queue[0].id
      SC.get("/tracks/" + currentItem, function(track){
      var waveform = new Waveform({
      container: document.getElementById("soundcloud"),
      innerColor: "#333",
      width: ($('#player_container').width()) * 0.9,
      height: ($('#player_container').height()) * 0.2,
      interpolate: false
    });

    var data = [];
    var ctx = waveform.context;

    var gradient = ctx.createLinearGradient(0, 0, 0, waveform.height);
    gradient.addColorStop(0.0, "#f60");
    gradient.addColorStop(1.0, "#ff1b00");
    waveform.innerColor = gradient;

    var i = 0;

    waveform.dataFromSoundCloudTrack(track);
    SC.stream(track.uri, {onplay:function(){
        $("#currently_playing").text(queue[0].trackTitle);
        isPlaying = true;
        setInterval(function(){
          data.push(Math.cos(i++/25) - 0.2 + Math.random()*0.3);
          waveform.update({
            data: data
          });
        }, 50);
      }, onfinish: function(){
        isPlaying = false;
        $("#soundcloud").empty();
        $("#queue_container ul button:first-child").remove();
        queue.shift();
        playSong();
      }
    }, function(stream){
      currentTrack = stream;
    window.exampleStream = stream.play();
    });
  });
  }

  $("#queue_container ul").on("click", ".track_title", function(){
    if (deleteFromQueueMode === true) {
      $(this).remove();
    }
  })

  $("#query_song_list").on("click", ".track_title", function() {
    var $deleteListTag = $(this).parent();
    $("#queue_container ul").append($(this))
    $deleteListTag.remove()
    addSongsToQueue();

    if ((queue.length === 1) || (isPlaying === false)) {
      playSong();
    }
  })

  var colours=[ '#333333','#ffffff'];  // List of colors
  var tempID=0;
  var changeInterval=1000;    // Change interval in miliseconds
  var objectID='#dance_floor';

  setInterval(function(){
        $(objectID).animate({backgroundColor: colours[tempID]},500);
        tempID=tempID+1;
        if (tempID>colours.length-1) tempID=0;
    },changeInterval);

  setInterval(function(){
    $(".avatar").each(function(){
      var num = getRandomInt(1,15);
      $(this).attr("src", "/assets/crazy_dancing_girl_"+num+".png")
    });
  }, 1000)

  function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }
});
//'#ff0000','#00ff00','#0000ff','#ffff00','#acacac',<commit_msg>fixed bug with audio play<commit_after>$(document).on("page:change", function(){
  var isPlaying = false;
  var queue = [];
  var deleteFromQueueMode = false;
  var currentTrack = "";

  $(document).on("click", "#mute_button", function() {
    currentTrack.toggleMute();
  });

  $(document).on("click", "#skip_button", function() {
    currentTrack.setPosition(currentTrack.duration - 1);
  });

  $(document).on("click", "#delete_button", function() {
    if (deleteFromQueueMode === false) {
      deleteFromQueueMode = true;
      $("#delete_mode_toggle").text("ON");
    } else {
      deleteFromQueueMode = false;
      $("#delete_mode_toggle").text("OFF");
    };
  });

  var addSongsToQueue = function(){
    var id = $("#queue_container ul button").last().attr("id")
    var type = $("#queue_container ul button").last().attr("data-type")
    var audio = $("#queue_container ul button").last().attr("data-track-link");
    var duration = $("#queue_container ul button").last().attr("data-track-duration");
    var trackTitle = $("#queue_container ul button").last().attr("data-track-title");

    queue.push({
      id: id,
      type: type,
      audio: audio,
      duration: parseInt(duration),
      trackTitle: trackTitle
    })
  }

  var playSong = function(id) {
    // prevents two songs from playing at the same time
     if(typeof(soundManager) !== "undefined"){
        soundManager.stopAll();
    }

      $("#soundcloud").empty();
      var currentItem = queue[0].id
      SC.get("/tracks/" + currentItem, function(track){
      var waveform = new Waveform({
      container: document.getElementById("soundcloud"),
      innerColor: "#333",
      width: ($('#player_container').width()) * 0.9,
      height: ($('#player_container').height()) * 0.2,
      interpolate: false
    });

    var data = [];
    var ctx = waveform.context;

    var gradient = ctx.createLinearGradient(0, 0, 0, waveform.height);
    gradient.addColorStop(0.0, "#f60");
    gradient.addColorStop(1.0, "#ff1b00");
    waveform.innerColor = gradient;

    var i = 0;
    setInterval(function(){
      data.push(Math.cos(i++/25) - 0.2 + Math.random()*0.3);
      waveform.update({
        data: data
      });
    }, 50);

    waveform.dataFromSoundCloudTrack(track);
    SC.stream(track.uri, {onplay:function(){
        $("#currently_playing").text(queue[0].trackTitle);
        isPlaying = true;
      }, onfinish: function(){
        isPlaying = false;
        $("#soundcloud").empty();
        $("#queue_container ul button:first-child").remove();
        queue.shift();
        playSong();
      }
    }, function(stream){
      currentTrack = stream;
    window.exampleStream = stream.play();
    });
  });
  }

  $("#queue_container ul").on("click", ".track_title", function(){
    if (deleteFromQueueMode === true) {
      $(this).remove();
    }
  })

  $("#query_song_list").on("click", ".track_title", function() {
    var $deleteListTag = $(this).parent();
    $("#queue_container ul").append($(this))
    $deleteListTag.remove()
    addSongsToQueue();

    if ((queue.length === 1) || (isPlaying === false)) {
      playSong();
    }
  })

  var colours=[ '#333333','#ffffff'];  // List of colors
  var tempID=0;
  var changeInterval=1000;    // Change interval in miliseconds
  var objectID='#dance_floor';

  setInterval(function(){
        $(objectID).animate({backgroundColor: colours[tempID]},500);
        tempID=tempID+1;
        if (tempID>colours.length-1) tempID=0;
    },changeInterval);

  setInterval(function(){
    $(".avatar").each(function(){
      var num = getRandomInt(1,15);
      $(this).attr("src", "/assets/crazy_dancing_girl_"+num+".png")
    });
  }, 1000)

  function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }
});
//'#ff0000','#00ff00','#0000ff','#ffff00','#acacac',<|endoftext|>


<commit_before>///////////////////////////////////////////////
// Find a message list element by message id
///////////////////////////////////////////////

findMessage = function(message_id) {
  var message = 0;
  $("#message_list li.message").each(function(index) {
    if ($(this).data("message_id") == message_id) {
      message = $(this);
    }
  });
  return message;
}

////////////////////////////////////////
// Get the user's id
////////////////////////////////////////

$(function() {
  user_name = $("#main_menu").attr("class");

});

////////////////////////////////////////
// heartbeat
////////////////////////////////////////

//$(function() {
//  if ($('#content').length > 0) {
//    setTimeout(heartbeat, 20000);
//  }
//});

var heartbeat = function() {
  // store the current user's name
  user_id = $("#content").attr("class");

    $.ajax( {
      type: "PUT",
      url: "/users/" + user_id + ".js",
      success: function(response) {
        response;
      }
    });

    setTimeout(heartbeat, 20000);
};

////////////////////////////////////////
// Calculate Height
////////////////////////////////////////

// calculate_message_section_height
// resize the '#messages_section' to be 68% of the window
var calculate_message_section_height = function() {
  height = $(window).outerHeight(true);
  outer_height = (height * 80) / 100;
  inner_height = (outer_height * 75) / 100;
  $('#content').height(outer_height);
  $('#messages_section').height(inner_height);
  //$('#messages_section').scrollTo("max");
};

// resize on page load
$(function() {
  calculate_message_section_height();
});

// resize on each browser resize by the user
$(function() {
  $(window).resize(calculate_message_section_height);
});

////////////////////////////////////////
// hide_available_users()
////////////////////////////////////////

var hide_available_users = function() {
  $("#recipient_selection_section").html("Add Available Users");
};

////////////////////////////////////////
// auto select jobs on signin page
////////////////////////////////////////

$(function() {
  // if on the sign on page
  if ($("#signin").length > 0) {
    // user name field loses focus
    $("input#user_name").focusout(function(event) {
      name = event.target.value;
      if (name) {
        // GET - sessions#new
        $.ajax( {
          type: "GET",
          url: "/session/new.json",
          data: { "user": name },
          success: function(response) {
            if (response.normal_workstations) {
              $("input:checkbox").removeAttr("checked");
              var normal_workstations = response.normal_workstations.split(",");
              var i;
              for (i = 0; i < normal_workstations.length; i++) {
                $("input#" + normal_workstations[i]).prop("checked", true);
              }
            }
          }
        });
      }
    });
  }
});

/////////////////////////////////////////
// create the workstation html elements
/////////////////////////////////////////

// get the workstation data
var build_workstation_buttons = function() {
  var workstation_section = $('#recipient_workstation_selection');
  var html = "";
  if (workstation_section.length > 0) {
    $.ajax( {
      type: "GET",
      url: "/workstations.json",
      success: function(response) {
        for (var i = 0; i < response.length; i++) {
          var class_name = "recipient_workstation";
          if (i == 0) {
            class_name += " first";
          }
          var html = "
";
          html += "
" + response[i].long_name + "
";
          if (response[i].user_name && response[i].user_name.length > 0) {
            html += "
(" + response[i].user_name + ")
";
          } else {
            html += "
(vacant)
"
          }
          html += "
";
          var workstation = $(html).data("workstation_id", response[i].id).turnOff().click(toggle_recipient);
          workstation_section.append(workstation);
        }
        html = "

Message
all

";
        var toggle_all_button = $(html).click(toggle_all_workstations);
        workstation_section.append(toggle_all_button);
      }
    });
  }
};

// get the user data
var build_user_workstation_info = function() {
  var workstation_section = $('#recipient_workstation_selection');
  var user_name = $("#main_menu").attr("class");
  if (workstation_section.length > 0) {
    $.ajax( {
      type: "GET",
      url: "/users/" + user_name + ".json",
      success: function(response) {
        for (var i = 0; i < response.workstations.length; i++) {
          $("#" + response.workstations[i].name).addClass("mine").removeClass("off");
        }
        for (var i = 0; i < response.recipient_workstations.length; i++) {
          $("#" + response.recipient_workstations[i].name).turnOn().data("recipient_id", response.recipient_workstations[i].recipient_id);
        }
      }
    });
  }
};

$(build_workstation_buttons);
$(build_user_workstation_info);

///////////////////////////////////
// add recipient
///////////////////////////////////

var toggle_recipient = function() {
  var state = $(this).onOrOff();

  if (state && state == "off") {
    var workstation_id = $(this).data("workstation_id");

    if (workstation_id) {
      // POST - recipients#create
      $.ajax( {
        type: "POST",
        url: "/recipients",
        data: { "workstation_id": workstation_id },
        success: function(response) {
          response;
        }
      });
    }

  } else if (state && state == "on") {
    var recipient_id = $(this).data("recipient_id");

    if (recipient_id) {
      // DELETE - recipients#destroy
      $.ajax( {
        type: "POST",
        url: "/recipients/" + recipient_id,
        data: { _method: 'delete' },
        success: function(response) {
          response;
        }
      });
    }
  }
};

///////////////////////////////////
// Toggle all (workstations)
//////////////////////////////////

var toggle_all_workstations = function() {
  $(this).toggleClass("all");
  $(this).toggleClass("none");

  if ($(this).hasClass("none")) {
    $(this).html("
Message
none
");

    // POST - recipients#create all
    $.ajax( {
      type: "POST",
      url: "/recipients",
      data: { "workstation_id": "all" },
      success: function(response) {
        response;
      }
    });
  } else {
    $(this).html("
Message
all
");

    // DELETE - workstations#destroy all
    $.ajax( {
      type: "POST",
      url: "/recipients/all",
      data: { _method: 'delete' },
      success: function(response) {
        response;
      }
    });
  }
}

///////////////////////////////////
// acknowledge (read) message
///////////////////////////////////

var read_message = function(message_id) {
  if ($(this).hasClass("recieved") && $(this).hasClass("unread")) {
    var message_id = $(this).data("message_id");

    if (message_id) {
      $.ajax( {
        type: "PUT",
        url: "/messages/" + message_id,
        success: function(response) {
          response;
        }
      });
    }
  }
};

$(function() {
  $("li.message.recieved.unread").click(read_message);
});

////////////////////////////////////
// create a user_name
////////////////////////////////////

var name_user = function() {
  var user_name_input = $('input#user_user_name');
  if (!user_name_input.val()) {
    var first_name = $('input#user_first_name').val();
    var middle_initial = $('input#user_middle_initial').val();
    var last_name = $('input#user_last_name').val();
    var user_name = "";
    if (first_name && first_name.length >= 1) {
      user_name += first_name[0];
    }
    if (middle_initial && middle_initial.length >= 1) {
      user_name += middle_initial[0];
    }
    if (last_name && last_name.length >= 1) {
      user_name += last_name;
    }
    if (user_name) {
      user_name_input.val(user_name.toLowerCase());
    }
  }
};

$(function() {
  $('input#user_user_name').click(name_user).focusin(name_user);
  $('label[for=user_user_name]').click(name_user);
});

////////////////////////////////////
// Workstation radio buttons
////////////////////////////////////
$(function() {
  $("#td_workstations input").click(function() {
    $("#ops_workstations input").removeAttr("checked");
  });
  $("input#YDCTL").click(function() {
    $("#td_workstations input").removeAttr("checked");
    $("input#YDMSTR").removeAttr("checked");
    $("input#GLHSE").removeAttr("checked");
  });
  $("input#YDMSTR").click(function() {
    $("#td_workstations input").removeAttr("checked");
    $("input#YDCTL").removeAttr("checked");
    $("input#GLHSE").removeAttr("checked");
  });
  $("input#GLHSE").click(function() {
    $("#td_workstations input").removeAttr("checked");
    $("input#YDCTL").removeAttr("checked");
    $("input#YDMSTR").removeAttr("checked");
  });
});

///////////////////////////////////
// show the most recent message
///////////////////////////////////

//$(function() {
//  if ($("#messages_section").length > 0) {
//    $('#messages_section').scrollTo("max");
//  }
//});

///////////////////////////////////
// Upload Section
///////////////////////////////////

$(function() {
  $('a#attach_button').click(function() {
    upload_section = $('#upload_section');
    height = upload_section.outerHeight(true);
    messages_section = $('#messages_section');
    upload_section.toggle();
    upload_button = $('a#attach_button');

    if (upload_section.is(":hidden")) {
      messages_section.css("height", "+=" + height);
      $('input[type="file"]').val("");
      upload_button.text("Show File Uploader");
    } else {
      messages_section.css("height", "-=" + height);
      upload_button.text("Hide File Uploader");
    }
  });
});

//////////////////////////////////////////////
// message upload
//////////////////////////////////////////////

//$(function() {
//  if ($("#messages_section").length > 0) {
//    var uploader = new qq.FileUploader({
//        // pass the dom node (ex. $(selector)[0] for jQuery users)
//        element: document.getElementById('file-uploader'),
//        // path to server-side upload script
//        action: '/attachments.js'
//    });
//  }
//});

///////////////////////////////////////////////
// message recieve handler
///////////////////////////////////////////////

$(function() {
  // store the current user's name
  user_name = $("#main_menu").attr("class");

  // register callback
  PrivatePub.subscribe("/messages/" + user_name, function(data, channel) {
    // play tone
    $('#tone')[0].innerHTML = "<embed src=/assets/soft_chime_beep.mp3 hidden=true autostart=true loop=false>";

    // clear message text field
    $("input#message_content").val("");

    // create the new message html
    var html ="
" +
            "
" +
              "
" +
                "
" +
                  "
" + data.sender + "
" +
                "
" +
                "
" +
                  "
" + data.timestamp + "
" +
                "
" +
              "
" +
              "
" +
                "
";

    if (data.attachment_url) {
      html += "" + data.chat_message + "";
    } else {
      html += "
" + data.chat_message + "
";
    }

    html += "
" +
           "
" +
         "
" +
       "
";

    // display the new message
    display_new_message(html, data.message_id);

    // add click handler to new message element
    $("li.message.recieved.unread").click(read_message);

    // show the sending workstation(s) as recipient(s)
    for (var i = 0; i < data.recipient_ids.length; i++) {
      if (data.recipient_ids[i] > 0) {
        selector = "#" + data.from_workstations[i] + ".recipient_workstation.off";
        $(selector).turnOn().data("recipient_id", data.recipient_ids[i]);
      }
    }

    // scroll to last message
    //if (data.chat_message) {
    //  $('#messages_section').scrollTo("max");
    //}
  });
});

var display_new_message = function(message_html, message_id) {
  message_list_item = $("li.message:first-child");
  var message = $(message_html).data("message_id", message_id);
  if (message_list_item[0]) {
    message_list_item.before(message);
  } else {
    $("ul#message_list").html(message);
  }
};

///////////////////////////////////////////////
// user signin/signout handler
///////////////////////////////////////////////

$(function() {
  // store the current user's name
  user_name = $("#main_menu").attr("class");

  // register callback
  PrivatePub.subscribe("/workstations/" + user_name, function(data, channel) {
    var workstations = data.workstations.split(",");
    for (var i = 0; i < workstations.length; i++) {
      var selector = "#user_at_" + workstations[i];
      $(selector).html("(" + data.name + ")");
    }
  });
});

///////////////////////////////////////////////
// message read handler
///////////////////////////////////////////////

$(function() {
  // store the current user's name
  user_name = $("#main_menu").attr("class");

  // register callback
  PrivatePub.subscribe("/readers/" + user_name, function(data, channel) {
    console.log("message: " + data.message);
    selector = "li.message.owner." + data.message + " ul.inner_message li .read_by";
    console.log(selector);
    $(selector).html(data.readers);
  });
});
<commit_msg>add some javascript debug statements<commit_after>///////////////////////////////////////////////
// Find a message list element by message id
///////////////////////////////////////////////

findMessage = function(message_id) {
  var message = 0;
  $("#message_list li.message").each(function(index) {
    if ($(this).data("message_id") == message_id) {
      message = $(this);
    }
  });
  return message;
}

////////////////////////////////////////
// Get the user's id
////////////////////////////////////////

$(function() {
  user_name = $("#main_menu").attr("class");

});

////////////////////////////////////////
// heartbeat
////////////////////////////////////////

//$(function() {
//  if ($('#content').length > 0) {
//    setTimeout(heartbeat, 20000);
//  }
//});

var heartbeat = function() {
  // store the current user's name
  user_id = $("#content").attr("class");

    $.ajax( {
      type: "PUT",
      url: "/users/" + user_id + ".js",
      success: function(response) {
        response;
      }
    });

    setTimeout(heartbeat, 20000);
};

////////////////////////////////////////
// Calculate Height
////////////////////////////////////////

// calculate_message_section_height
// resize the '#messages_section' to be 68% of the window
var calculate_message_section_height = function() {
  height = $(window).outerHeight(true);
  outer_height = (height * 80) / 100;
  inner_height = (outer_height * 75) / 100;
  $('#content').height(outer_height);
  $('#messages_section').height(inner_height);
  //$('#messages_section').scrollTo("max");
};

// resize on page load
$(function() {
  calculate_message_section_height();
});

// resize on each browser resize by the user
$(function() {
  $(window).resize(calculate_message_section_height);
});

////////////////////////////////////////
// hide_available_users()
////////////////////////////////////////

var hide_available_users = function() {
  $("#recipient_selection_section").html("Add Available Users");
};

////////////////////////////////////////
// auto select jobs on signin page
////////////////////////////////////////

$(function() {
  // if on the sign on page
  if ($("#signin").length > 0) {
    // user name field loses focus
    $("input#user_name").focusout(function(event) {
      name = event.target.value;
      if (name) {
        // GET - sessions#new
        $.ajax( {
          type: "GET",
          url: "/session/new.json",
          data: { "user": name },
          success: function(response) {
            if (response.normal_workstations) {
              $("input:checkbox").removeAttr("checked");
              var normal_workstations = response.normal_workstations.split(",");
              var i;
              for (i = 0; i < normal_workstations.length; i++) {
                $("input#" + normal_workstations[i]).prop("checked", true);
              }
            }
          }
        });
      }
    });
  }
});

/////////////////////////////////////////
// create the workstation html elements
/////////////////////////////////////////

// get the workstation data
var build_workstation_buttons = function() {
  var workstation_section = $('#recipient_workstation_selection');
  var html = "";
  if (workstation_section.length > 0) {
    $.ajax( {
      type: "GET",
      url: "/workstations.json",
      success: function(response) {
        console.log("in build_workstation_buttons ajax callback");
        for (var i = 0; i < response.length; i++) {
          var class_name = "recipient_workstation";
          if (i == 0) {
            class_name += " first";
          }
          var html = "
";
          html += "
" + response[i].long_name + "
";
          if (response[i].user_name && response[i].user_name.length > 0) {
            html += "
(" + response[i].user_name + ")
";
          } else {
            html += "
(vacant)
"
          }
          html += "
";
          var workstation = $(html).data("workstation_id", response[i].id).turnOff().click(toggle_recipient);
          workstation_section.append(workstation);
        }
        html = "

Message
all

";
        var toggle_all_button = $(html).click(toggle_all_workstations);
        workstation_section.append(toggle_all_button);
      }
    });
  }
};

// get the user data
var build_user_workstation_info = function() {
  var workstation_section = $('#recipient_workstation_selection');
  var user_name = $("#main_menu").attr("class");
  if (workstation_section.length > 0) {
    $.ajax( {
      type: "GET",
      url: "/users/" + user_name + ".json",
      success: function(response) {
        console.log("in build_user_workstation_info ajax callback");
        for (var i = 0; i < response.workstations.length; i++) {
          $("#" + response.workstations[i].name).addClass("mine").removeClass("off");
        }
        for (var i = 0; i < response.recipient_workstations.length; i++) {
          $("#" + response.recipient_workstations[i].name).turnOn().data("recipient_id", response.recipient_workstations[i].recipient_id);
        }
      }
    });
  }
};

$(build_workstation_buttons);
$(build_user_workstation_info);

///////////////////////////////////
// add recipient
///////////////////////////////////

var toggle_recipient = function() {
  var state = $(this).onOrOff();

  if (state && state == "off") {
    var workstation_id = $(this).data("workstation_id");

    if (workstation_id) {
      // POST - recipients#create
      $.ajax( {
        type: "POST",
        url: "/recipients",
        data: { "workstation_id": workstation_id },
        success: function(response) {
          response;
        }
      });
    }

  } else if (state && state == "on") {
    var recipient_id = $(this).data("recipient_id");

    if (recipient_id) {
      // DELETE - recipients#destroy
      $.ajax( {
        type: "POST",
        url: "/recipients/" + recipient_id,
        data: { _method: 'delete' },
        success: function(response) {
          response;
        }
      });
    }
  }
};

///////////////////////////////////
// Toggle all (workstations)
//////////////////////////////////

var toggle_all_workstations = function() {
  $(this).toggleClass("all");
  $(this).toggleClass("none");

  if ($(this).hasClass("none")) {
    $(this).html("
Message
none
");

    // POST - recipients#create all
    $.ajax( {
      type: "POST",
      url: "/recipients",
      data: { "workstation_id": "all" },
      success: function(response) {
        response;
      }
    });
  } else {
    $(this).html("
Message
all
");

    // DELETE - workstations#destroy all
    $.ajax( {
      type: "POST",
      url: "/recipients/all",
      data: { _method: 'delete' },
      success: function(response) {
        response;
      }
    });
  }
}

///////////////////////////////////
// acknowledge (read) message
///////////////////////////////////

var read_message = function(message_id) {
  if ($(this).hasClass("recieved") && $(this).hasClass("unread")) {
    var message_id = $(this).data("message_id");

    if (message_id) {
      $.ajax( {
        type: "PUT",
        url: "/messages/" + message_id,
        success: function(response) {
          response;
        }
      });
    }
  }
};

$(function() {
  $("li.message.recieved.unread").click(read_message);
});

////////////////////////////////////
// create a user_name
////////////////////////////////////

var name_user = function() {
  var user_name_input = $('input#user_user_name');
  if (!user_name_input.val()) {
    var first_name = $('input#user_first_name').val();
    var middle_initial = $('input#user_middle_initial').val();
    var last_name = $('input#user_last_name').val();
    var user_name = "";
    if (first_name && first_name.length >= 1) {
      user_name += first_name[0];
    }
    if (middle_initial && middle_initial.length >= 1) {
      user_name += middle_initial[0];
    }
    if (last_name && last_name.length >= 1) {
      user_name += last_name;
    }
    if (user_name) {
      user_name_input.val(user_name.toLowerCase());
    }
  }
};

$(function() {
  $('input#user_user_name').click(name_user).focusin(name_user);
  $('label[for=user_user_name]').click(name_user);
});

////////////////////////////////////
// Workstation radio buttons
////////////////////////////////////
$(function() {
  $("#td_workstations input").click(function() {
    $("#ops_workstations input").removeAttr("checked");
  });
  $("input#YDCTL").click(function() {
    $("#td_workstations input").removeAttr("checked");
    $("input#YDMSTR").removeAttr("checked");
    $("input#GLHSE").removeAttr("checked");
  });
  $("input#YDMSTR").click(function() {
    $("#td_workstations input").removeAttr("checked");
    $("input#YDCTL").removeAttr("checked");
    $("input#GLHSE").removeAttr("checked");
  });
  $("input#GLHSE").click(function() {
    $("#td_workstations input").removeAttr("checked");
    $("input#YDCTL").removeAttr("checked");
    $("input#YDMSTR").removeAttr("checked");
  });
});

///////////////////////////////////
// show the most recent message
///////////////////////////////////

//$(function() {
//  if ($("#messages_section").length > 0) {
//    $('#messages_section').scrollTo("max");
//  }
//});

///////////////////////////////////
// Upload Section
///////////////////////////////////

$(function() {
  $('a#attach_button').click(function() {
    upload_section = $('#upload_section');
    height = upload_section.outerHeight(true);
    messages_section = $('#messages_section');
    upload_section.toggle();
    upload_button = $('a#attach_button');

    if (upload_section.is(":hidden")) {
      messages_section.css("height", "+=" + height);
      $('input[type="file"]').val("");
      upload_button.text("Show File Uploader");
    } else {
      messages_section.css("height", "-=" + height);
      upload_button.text("Hide File Uploader");
    }
  });
});

//////////////////////////////////////////////
// message upload
//////////////////////////////////////////////

//$(function() {
//  if ($("#messages_section").length > 0) {
//    var uploader = new qq.FileUploader({
//        // pass the dom node (ex. $(selector)[0] for jQuery users)
//        element: document.getElementById('file-uploader'),
//        // path to server-side upload script
//        action: '/attachments.js'
//    });
//  }
//});

///////////////////////////////////////////////
// message recieve handler
///////////////////////////////////////////////

$(function() {
  // store the current user's name
  user_name = $("#main_menu").attr("class");

  // register callback
  PrivatePub.subscribe("/messages/" + user_name, function(data, channel) {
    // play tone
    $('#tone')[0].innerHTML = "<embed src=/assets/soft_chime_beep.mp3 hidden=true autostart=true loop=false>";

    // clear message text field
    $("input#message_content").val("");

    // create the new message html
    var html ="
" +
            "
" +
              "
" +
                "
" +
                  "
" + data.sender + "
" +
                "
" +
                "
" +
                  "
" + data.timestamp + "
" +
                "
" +
              "
" +
              "
" +
                "
";

    if (data.attachment_url) {
      html += "" + data.chat_message + "";
    } else {
      html += "
" + data.chat_message + "
";
    }

    html += "
" +
           "
" +
         "
" +
       "
";

    // display the new message
    display_new_message(html, data.message_id);

    // add click handler to new message element
    $("li.message.recieved.unread").click(read_message);

    // show the sending workstation(s) as recipient(s)
    for (var i = 0; i < data.recipient_ids.length; i++) {
      if (data.recipient_ids[i] > 0) {
        selector = "#" + data.from_workstations[i] + ".recipient_workstation.off";
        $(selector).turnOn().data("recipient_id", data.recipient_ids[i]);
      }
    }

    // scroll to last message
    //if (data.chat_message) {
    //  $('#messages_section').scrollTo("max");
    //}
  });
});

var display_new_message = function(message_html, message_id) {
  message_list_item = $("li.message:first-child");
  var message = $(message_html).data("message_id", message_id);
  if (message_list_item[0]) {
    message_list_item.before(message);
  } else {
    $("ul#message_list").html(message);
  }
};

///////////////////////////////////////////////
// user signin/signout handler
///////////////////////////////////////////////

$(function() {
  // store the current user's name
  user_name = $("#main_menu").attr("class");

  // register callback
  PrivatePub.subscribe("/workstations/" + user_name, function(data, channel) {
    var workstations = data.workstations.split(",");
    for (var i = 0; i < workstations.length; i++) {
      var selector = "#user_at_" + workstations[i];
      $(selector).html("(" + data.name + ")");
    }
  });
});

///////////////////////////////////////////////
// message read handler
///////////////////////////////////////////////

$(function() {
  // store the current user's name
  user_name = $("#main_menu").attr("class");

  // register callback
  PrivatePub.subscribe("/readers/" + user_name, function(data, channel) {
    console.log("message: " + data.message);
    selector = "li.message.owner." + data.message + " ul.inner_message li .read_by";
    console.log(selector);
    $(selector).html(data.readers);
  });
});
<|endoftext|>


<commit_before>// # Place all the behaviors and hooks related to the matching controller here.
// # All this logic will automatically be available in application.js.
// # You can use CoffeeScript in this file: http://coffeescript.org/

$(document).ready(function() {

  var overlays = [];
  SKIOverlay.prototype = new google.maps.OverlayView();

  function initialize() {
    var mapCanvas = document.getElementById('map-canvas');
    var lat = $('#map-canvas').data('lat');
    var lng = $('#map-canvas').data('lng');
    var zoom_level = $('#map-canvas').data('zoom');
    var visuals = $('#map-canvas').data('visuals');

    var mapOptions = {
      center: new google.maps.LatLng(lat, lng),
      zoom: zoom_level,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    var map = new google.maps.Map(mapCanvas, mapOptions); //global

    for (var i = 0, visual; visual = visuals[i]; i++) {
      // debugger
      var swBound = new google.maps.LatLng(visual.lat, visual.lng);
      var neBound = new google.maps.LatLng(visual.lat, visual.lng);
      var bounds = new google.maps.LatLngBounds(swBound, neBound);
      // bounds = bounds + "i";
      var srcImage = visual.thumbnail_url;
      // srcImage = srcImage + "i";
      overlays.push(new SKIOverlay(bounds, srcImage, map));
    };

  }

  /** @constructor */
  function SKIOverlay(bounds, image, map) {

    // Initialize all properties.
    this.bounds_ = bounds;
    this.image_ = image;
    this.map_ = map;

    // Define a property to hold the image's div. We'll
    // actually create this div upon receipt of the onAdd()
    // method so we'll leave it null for now.
    this.div_ = null;

    // Explicitly call setMap on this overlay.
    this.setMap(map);
  }

  SKIOverlay.prototype.onAdd = function() {
    var div = document.createElement('div');
    div.style.border = 'solid green';
    div.style.borderWidth = '10px';
    div.style.position = 'absolute';
    div.style.cursor = 'pointer';
    div.className = "fancybox-thumb";
    div.setAttribute("rel", "fancybox-thumb");
    div.setAttribute("href", "http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10817636_759659604113358_950808159_n.jpg");

    // Create the img element and attach it to the div.
    var img = document.createElement('img');
    img.src = this.image_;
    img.style.width = '100px';
    img.style.height = '100px';
    img.style.borderRadius = '50%';
    div.appendChild(img);

    this.div_ = div;

    // Add the element to the "overlayImage" pane.
    var panes = this.getPanes();
    panes.overlayImage.appendChild(this.div_);
  };

  SKIOverlay.prototype.draw = function() {

    // We use the south-west and north-east
    // coordinates of the overlay to peg it to the correct position and size.
    // To do this, we need to retrieve the projection from the overlay.
    var overlayProjection = this.getProjection();

    // Retrieve the south-west and north-east coordinates of this overlay
    // in LatLngs and convert them to pixel coordinates.
    // We'll use these coordinates to resize the div.
    var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
    var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

    // Resize the image's div to fit the indicated dimensions.
    var div = this.div_;
    debugger
    div.style.left = sw.x + 'px';
    div.style.top = ne.y + 'px';
    div.style.width = (ne.x - sw.x) + 'px';
    div.style.height = (sw.y - ne.y) + 'px';
  };

  if( typeof google !== 'undefined' ) {
    google.maps.event.addDomListener(window, 'load', initialize);
  }

  //CODE REQUIRED FOR FANCYBOX TEST
  $(".fancybox-thumb").fancybox({
    prevEffect  : 'none',
    nextEffect  : 'none',
    helpers : {
      title : {
        type: 'outside'
      },
      thumbs  : {
        width : 50,
        height  : 50
      }
    }
  });

});

  //ADD MARKER CODE BEGIN
  // function addMarker(visual) {
  //   var image = {
  //     url: visual.thumbnail_url,
  //     // This marker is 20 pixels wide by 32 pixels tall.
  //     size: new google.maps.Size(200, 200),
  //     // The origin for this image is 0,0.
  //     origin: new google.maps.Point(0,0),
  //     // The anchor for this image is the base of the flagpole at 0,32.
  //     anchor: new google.maps.Point(0, 80)
  //     // radius: new google.maps.Radius(100)
  //   };

  //   var shape = {
  //     coords: [1, 1, 1, 20, 18, 20, 18 , 1],
  //     type: 'poly'
  //   };

  //   var marker = new google.maps.Marker({
  //     position: new google.maps.LatLng(visual.lat, visual.lng),
  //     icon: image,
  //     map: map,
  //     shape: shape,
  //     zIndex: visual.id,
  //     animation: google.maps.Animation.DROP
  //   });
  // };
  //ADD MAKER CODE END

    //CREATE MARKER FOR TESTING ALERT MESSAGE
    // var image = {
    //   url: 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSBbU1XiZj_pRw5gUrUuReEvcz_QVKs3jtuvZn5FTU3LMM9wakP'
    // };

    // var marker = new google.maps.Marker({
    //   position: new google.maps.LatLng(39.470746, -106.083668),
    //   icon: image,
    //   map: map,
    //   animation: google.maps.Animation.DROP
    // });

    // for (var i = 0, visual; visual = visuals[i]; i++) {
    //   var marky = marker;
    // };

    //ALERT WHEN YOU CLICK ON MARKER
    // google.maps.event.addListener(marker, 'click', function() {
    //   alert( "Thanks for visiting!" );
    // });

    // COPIED MARKERLIGHT CODE
    // var map;

    // function initialize() {
    //   if (GBrowserIsCompatible()) {
    //     map = new GMap2(document.getElementById("map_canvas"));
    //     map.setCenter(new GLatLng(37.4419, -122.1419), 4);
    //     map.addControl(new GLargeMapControl());
    //   }
    // }

    // for (var i = 0, visual; visual = visuals[i]; i++) {
    //   addMarker(visual);
    // };

<commit_msg>fb works<commit_after>// # Place all the behaviors and hooks related to the matching controller here.
// # All this logic will automatically be available in application.js.
// # You can use CoffeeScript in this file: http://coffeescript.org/

$(document).ready(function() {

  overlays = [];
  SKIOverlay.prototype = new google.maps.OverlayView();

  function initialize() {
    var mapCanvas = document.getElementById('map-canvas');
    var lat = $('#map-canvas').data('lat');
    var lng = $('#map-canvas').data('lng');
    var zoom_level = $('#map-canvas').data('zoom');
    var visuals = $('#map-canvas').data('visuals');

    var mapOptions = {
      center: new google.maps.LatLng(lat, lng),
      zoom: zoom_level,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    var map = new google.maps.Map(mapCanvas, mapOptions); //global

    for (var i = 0; i < visuals.length; i++) {
      // debugger
      var swBound = new google.maps.LatLng(visuals[i].lat, visuals[i].lng);
      var neBound = new google.maps.LatLng(visuals[i].lat, visuals[i].lng);
      var bounds = new google.maps.LatLngBounds(swBound, neBound);
      var srcImage = visuals[i].thumbnail_url;

      overlays.push(new SKIOverlay(bounds, srcImage, map));
    };

    console.log(overlays);
  }

  /** @constructor */
  function SKIOverlay(bounds, image, map) {

    // Initialize all properties.
    this.bounds_ = bounds;
    this.image_ = image;
    this.map_ = map;

    // Define a property to hold the image's div. We'll
    // actually create this div upon receipt of the onAdd()
    // method so we'll leave it null for now.
    this.div_ = null;

    // Explicitly call setMap on this overlay.
    this.setMap(map);
  }

  SKIOverlay.prototype.onAdd = function() {
    var div = document.createElement('div');
    div.style.border = 'solid green';
    div.style.borderWidth = '3px';
    div.style.position = 'absolute';
    div.style.cursor = 'pointer';
    div.className = "fancybox-media";
    // div.setAttribute("rel", "fancybox-media");
    // console.log(srcImage);
    div.setAttribute("href", this.image_);

    // Create the img element and attach it to the div.
    var img = document.createElement('img');
    img.src = this.image_;
    img.style.width = '100px';
    img.style.height = '100px';
    img.style.left = '-50px';
    img.style.top = '-50px';
    img.style.position = 'relative';
    img.style.borderRadius = '50%';
    div.appendChild(img);

    this.div_ = div;

    // Add the element to the "overlayImage" pane.
    var panes = this.getPanes();
    panes.overlayImage.appendChild(this.div_);
  };

  SKIOverlay.prototype.draw = function() {

    // We use the south-west and north-east
    // coordinates of the overlay to peg it to the correct position and size.
    // To do this, we need to retrieve the projection from the overlay.
    var overlayProjection = this.getProjection();

    // Retrieve the south-west and north-east coordinates of this overlay
    // in LatLngs and convert them to pixel coordinates.
    // We'll use these coordinates to resize the div.
    var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
    var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

    // Resize the image's div to fit the indicated dimensions.
    var div = this.div_;
    div.style.left = sw.x + 'px';
    div.style.top = ne.y + 'px';
    div.style.width = '1px';
    div.style.height ='1px';
  };

  if( typeof google !== 'undefined' ) {
    google.maps.event.addDomListener(window, 'load', initialize);
  }

  //CODE REQUIRED FOR FANCYBOX TEST
  $(".fancybox-media").fancybox({
    prevEffect  : 'none',
    nextEffect  : 'none',
    helpers : {
      media : {}
      // title : {
      //   type: 'outside'
      // },
      // thumbs  : {
      //   width : 50,
      //   height  : 50
      // }
    }
  });

});//end of document ready

<|endoftext|>