<commit_before>window.admin = {};

$(document).ready(function() {
	$("#admin-feedback").on("tabOpened", function() {
		window.api.get("admin/feedback/getList", function(resp) {
			$("#admin-feedback-list").text("");
			for (var feedbackIndex in resp.feedback) {
				var feedbackItem = resp.feedback[feedbackIndex];
				var $feedbackLi = $('

');
					var $feedbackDesc = $('

');
						$feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg);
						var $icon = $('');
							if (feedbackItem.type == "smile") {
								$icon.addClass("fa-smile-o");
							} else if (feedbackItem.type == "frown") {
								$icon.addClass("fa-frown-o");
							} else if (feedbackItem.type == "idea") {
								$icon.addClass("fa-lightbulb-o");
							}
						$feedbackDesc.prepend($icon);
					$feedbackLi.append($feedbackDesc);
					var $feedbackName = $('

');
						$feedbackName.text(feedbackItem.name + " (" + feedbackItem.username + ")");
					$feedbackLi.append($feedbackName);
					var $feedbackDay = $('

');
						$feedbackDay.children("em").text("Sent " + moment(feedbackItem.timestamp).format("MM/DD/YY"));
					$feedbackLi.append($feedbackDay);
					$feedbackLi.attr("data-webpage", feedbackItem.webpage)
					$feedbackLi.click(function() {
						var iframeSrc = "";
						if ($(this).attr("data-webpage")) {
							iframeSrc = "<jqueryIsDumb>" + atob($(this).attr("data-webpage")) + "</jqueryIsDumb>";
							var $iframeSrc = $(iframeSrc);
							$iframeSrc.find("#feedback-modal").remove();
							$iframeSrc.find(".modal-backdrop").remove();
							$iframeSrc.find("link[rel=stylesheet]").each(function() {
								var oldUrl = $(this).attr("href");
								if (oldUrl) {
									if (oldUrl[0] == "/") {
										// it is a relative path
										var newUrl = window.location.protocol + "//" + window.location.host + oldUrl; // make it absolute
										$(this).attr("href", newUrl);
									}
								}
							});
							iframeSrc = $iframeSrc.html().toString();
						} else {
							iframeSrc = "No screenshot data was included with this submission.";
						}
						$("#admin-feedback-modal").find("iframe").attr("src", "data:text/html," + iframeSrc);
						if ($(this).attr("data-webpage")) {

						}
						$("#admin-feedback-modal").modal();
					});
				$("#admin-feedback-list").append($feedbackLi);
			};
		});
	});
	window.api.get('overview/announcements/get/', function(data) {
		var response = data.feedback;
		for(feed in response) {
			var $feedLi = $("

");
				$feedLi.append(response[feed].msg);
				if(!moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
					$feedLi.append(" (expired)");
				}
				$feedLi.attr("data-id", response[feed].announcementId);
				var $copyLi = $feedLi.clone();
					var $days = $('');
						$days.text(" Days: " + response[feed].days + ", Poster ID: " + response[feed].posterId);
					$copyLi.append($days)
				$("#adminAnnouncementList").append($copyLi);
				var $removeBtn = $('<button class="btn btn-xs btn-danger">  </button>');
					$removeBtn.click(function() {
						var idThingy = $(this).parent().attr("data-id");
						$(this).parent().addClass("announcementDelete");
						$(this).remove();
						window.api.post('admin/announcements/remove', {id: idThingy}, function(result){});
					});
				$feedLi.append($removeBtn)
			$("#announcement-delete-list").append($feedLi);

		}
		if($("#adminAnnouncementList").children().size() > 1) {
			$("#adminNoAnnouncements").remove()
		}
	});
	$("#announcement-submit").click(function() {
		if($("#announcement-msg").val().length != 0 && $("#announcement-days").val() > 0) {
			var postMe = {};
			postMe.days = $("#announcement-days").val();
			postMe.time = window.utils.formatDate_api(moment().toDate());
			postMe.msg = $("#announcement-msg").val();
			window.api.post('admin/announcements/post/', postMe, function(result){
				swal("Yay", "Your announcement has been posted", "success");
			});
		}
	});
	$("#announcement-clear").click(function() {
		$("#admin-announcement-modal").modal();
	});
	window.api.get('admin/users/count/', function(result) {
		$("#userNumber").text("There are " + result.number + " users!")
	});
	$("#admin-users").on("tabOpened", function() {
		window.api.get('admin/users/get/', function(result) {
			for (var userIndex in result.users) {
				var user = result.users[userIndex];
				console.log(user);
				var userTable = $("#userTable");
				var rowNumber = 1;
				var row = $("

");
				var idCell = $("	");
				var nameCell = $("	");
				var usernameCell = $("	");
				var emailCell = $("	");
				var typeCell = $("	");
				idCell.html = user.id;
				nameCell.html = user.id;
				usernameCell.html = user.id;
				emailCell.html = user.id;
				typeCell.html = user.id;
			}
		});
	});
});
<commit_msg>now will you work?<commit_after>window.admin = {};

$(document).ready(function() {
	$("#admin-feedback").on("tabOpened", function() {
		window.api.get("admin/feedback/getList", function(resp) {
			$("#admin-feedback-list").text("");
			for (var feedbackIndex in resp.feedback) {
				var feedbackItem = resp.feedback[feedbackIndex];
				var $feedbackLi = $('

');
					var $feedbackDesc = $('

');
						$feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg);
						var $icon = $('');
							if (feedbackItem.type == "smile") {
								$icon.addClass("fa-smile-o");
							} else if (feedbackItem.type == "frown") {
								$icon.addClass("fa-frown-o");
							} else if (feedbackItem.type == "idea") {
								$icon.addClass("fa-lightbulb-o");
							}
						$feedbackDesc.prepend($icon);
					$feedbackLi.append($feedbackDesc);
					var $feedbackName = $('

');
						$feedbackName.text(feedbackItem.name + " (" + feedbackItem.username + ")");
					$feedbackLi.append($feedbackName);
					var $feedbackDay = $('

');
						$feedbackDay.children("em").text("Sent " + moment(feedbackItem.timestamp).format("MM/DD/YY"));
					$feedbackLi.append($feedbackDay);
					$feedbackLi.attr("data-webpage", feedbackItem.webpage)
					$feedbackLi.click(function() {
						var iframeSrc = "";
						if ($(this).attr("data-webpage")) {
							iframeSrc = "<jqueryIsDumb>" + atob($(this).attr("data-webpage")) + "</jqueryIsDumb>";
							var $iframeSrc = $(iframeSrc);
							$iframeSrc.find("#feedback-modal").remove();
							$iframeSrc.find(".modal-backdrop").remove();
							$iframeSrc.find("link[rel=stylesheet]").each(function() {
								var oldUrl = $(this).attr("href");
								if (oldUrl) {
									if (oldUrl[0] == "/") {
										// it is a relative path
										var newUrl = window.location.protocol + "//" + window.location.host + oldUrl; // make it absolute
										$(this).attr("href", newUrl);
									}
								}
							});
							iframeSrc = $iframeSrc.html().toString();
						} else {
							iframeSrc = "No screenshot data was included with this submission.";
						}
						$("#admin-feedback-modal").find("iframe").attr("src", "data:text/html," + iframeSrc);
						if ($(this).attr("data-webpage")) {

						}
						$("#admin-feedback-modal").modal();
					});
				$("#admin-feedback-list").append($feedbackLi);
			};
		});
	});
	window.api.get('overview/announcements/get/', function(data) {
		var response = data.feedback;
		for(feed in response) {
			var $feedLi = $("

");
				$feedLi.append(response[feed].msg);
				if(!moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
					$feedLi.append(" (expired)");
				}
				$feedLi.attr("data-id", response[feed].announcementId);
				var $copyLi = $feedLi.clone();
					var $days = $('');
						$days.text(" Days: " + response[feed].days + ", Poster ID: " + response[feed].posterId);
					$copyLi.append($days)
				$("#adminAnnouncementList").append($copyLi);
				var $removeBtn = $('<button class="btn btn-xs btn-danger">  </button>');
					$removeBtn.click(function() {
						var idThingy = $(this).parent().attr("data-id");
						$(this).parent().addClass("announcementDelete");
						$(this).remove();
						window.api.post('admin/announcements/remove', {id: idThingy}, function(result){});
					});
				$feedLi.append($removeBtn)
			$("#announcement-delete-list").append($feedLi);

		}
		if($("#adminAnnouncementList").children().size() > 1) {
			$("#adminNoAnnouncements").remove()
		}
	});
	$("#announcement-submit").click(function() {
		if($("#announcement-msg").val().length != 0 && $("#announcement-days").val() > 0) {
			var postMe = {};
			postMe.days = $("#announcement-days").val();
			postMe.time = window.utils.formatDate_api(moment().toDate());
			postMe.msg = $("#announcement-msg").val();
			window.api.post('admin/announcements/post/', postMe, function(result){
				swal("Yay", "Your announcement has been posted", "success");
			});
		}
	});
	$("#announcement-clear").click(function() {
		$("#admin-announcement-modal").modal();
	});
	window.api.get('admin/users/count/', function(result) {
		$("#userNumber").text("There are " + result.number + " users!")
	});
	$("#admin-users").on("tabOpened", function() {
		window.api.get('admin/users/get/', function(result) {
			for (var userIndex in result.users) {
				var user = result.users[userIndex];
				console.log(user);
				var userTable = $("#userTable");
				var rowNumber = 1;
				var row = $("

");
				var idCell = $("	");
				var nameCell = $("	");
				var usernameCell = $("	");
				var emailCell = $("	");
				var typeCell = $("	");
				idCell.html(user.id);
				nameCell.html(user.name);
				usernameCell.html(user.username);
				emailCell.html(user.email);
				typeCell.html(user.type);
			}
		});
	});
});
<|endoftext|>


<commit_before>import Config from '../config/environment';

export function initialize(instance) {
  if (Config.mixpanel.enabled) {
    let router;
    if (typeof instance.lookup === 'function') {
      router = instance.lookup('router:main');
    } else {
      router = instance.container.lookup('router:main');
    }

    if (Config.mixpanel.autoPageviewTracking == undefined || Config.mixpanel.autoPageviewTracking) {
      router.on('didTransition', function() {
        var attributeOverrides = Config.mixpanel.attributeOverrides || {};
        let mixpanelService;
        if (typeof instance.lookup === 'function') {
          mixpanelService = instance.lookup('service:mixpanel');
        } else {
          mixpanelService = instance.container.lookup('service:mixpanel');
        }
        mixpanelService.trackPageView(this.get(Config.mixpanel.pageViewAttribute), attributeOverrides);
      });
    }
  }
}

export default {
  name: 'mixpanel',
  initialize: initialize
};
<commit_msg>Defaulted pageViewAttribute to 'url'<commit_after>import Config from '../config/environment';

export function initialize(instance) {
  if (Config.mixpanel.enabled) {
    let router;
    if (typeof instance.lookup === 'function') {
      router = instance.lookup('router:main');
    } else {
      router = instance.container.lookup('router:main');
    }

    if (Config.mixpanel.autoPageviewTracking == undefined || Config.mixpanel.autoPageviewTracking) {
      router.on('didTransition', function() {
        var attributeOverrides = Config.mixpanel.attributeOverrides || {};
        let mixpanelService;
        if (typeof instance.lookup === 'function') {
          mixpanelService = instance.lookup('service:mixpanel');
        } else {
          mixpanelService = instance.container.lookup('service:mixpanel');
        }
        let pageViewAttribute = Config.mixpanel.pageViewAttribute || 'url';
        mixpanelService.trackPageView(this.get(pageViewAttribute), attributeOverrides);
      });
    }
  }
}

export default {
  name: 'mixpanel',
  initialize: initialize
};
<|endoftext|>


<commit_before>
var viewTransitions = {
    homePageToRoom : 1,
    roomToHomePage : 2
}
var viewTransition = 0;

$(function() {
    if (DEBUG) {
        // localStorage.name = "Guest";
    }

    $("#homePageView").hide();
    $("#roomView").hide();
    var dynamicJoin = inRoom();

    globalConnect = ko.observable(new Connect());
    lobby = new Lobby();

    ko.applyBindings(lobby, $("#homePageView")[0]);

    this.windowEvent = function(e) {
        if (e.state === "lobby") {
            setStartCSSHomePage();
            $("#homePageView").show();
        } else if (e.state === "room") {
            setStartCSSRoom();
            $("#roomView").show();
        }
    }

    window.addEventListener('popstate', this.windowEvent);

    // Position views depending on whether jumping straight into game or not
    if (dynamicJoin === false) {
        // Start on Home Page
        setStartCSSHomePage();
        $("#homePageView").show();
    } else {
        // Start in Waiting Room
        setStartCSSRoom();
        $("#roomView").show();
    }
});

function inRoom() {
    var num = window.location.href.split("/").pop();
    if (typeof num === "string" && num.length>=3) {
        return num;
    }
    return false;
}

function setStartCSSHomePage() {
    // Start on Home Page
    $("#roomView").css({
        // CSS properties here
        opacity: 1,
        top : "100%"
    });
    $("#homePageView").css({
        opacity: 1,
    });
}

function setStartCSSRoom() {
    $("#roomView").css({
        // CSS properties here
        opacity: 1,
        top : "0px"
    });
    $("#homePageView").css({
        opacity: 0,
    });
}

function clickJoinRoom() {
    lobby.joinRoom();

    viewTransition = viewTransitions.homePageToRoom;
    animateTransition();
}

function clickInviteFriends() {
    lobby.createRoomPrivate(lobby);

    viewTransition = viewTransitions.homePageToRoom;
    animateTransition();
}

function clickLeaveRoom() {
    viewTransition = viewTransitions.roomToHomePage;
    animateTransition();
}

function joinRoomAnimationCallback() {
    $("#homePageView").hide();
    viewTransition = 0;
}

function leaveRoomAnimationCallback() {
    lobby.leaveRoom();
    $("#roomView").hide();
    viewTransition = 0;
}

function animateTransition() {
    if (viewTransition === viewTransitions.homePageToRoom) {
        $("#roomView").show();
        $("#roomView").animate({
            // Animation properties here
            top: 0
        }, {duration : 400, complete : joinRoomAnimationCallback});
        $("#homePageView").animate({
            opacity: 0
        }, {duration : 400});

    } else if (viewTransition === viewTransitions.roomToHomePage) {
        $("#homePageView").show();
        $("#roomView").animate({
            // Animation properties here
            top: "100%"
        }, {duration : 400, complete : leaveRoomAnimationCallback});
        $("#homePageView").animate({
            opacity: 1,
        }, {duration : 400});
    }
}

function openScreenNameOverlay() {
    $("#screenNameOverlay").show();
}

function applyScreenName(form) {
    var name = $("#screenNameInput").val();
    if (name === "" || name === "Guest") {
        // TODO: Yell at user
    } else {
        globalConnect().setName($("#screenNameInput").val())
        $("#screenNameOverlay").hide()
    }
}

<commit_msg>Actually fixed the scrolling issue this time.<commit_after>
var viewTransitions = {
    homePageToRoom : 1,
    roomToHomePage : 2
}
var viewTransition = 0;

$(function() {
    if (DEBUG) {
        // localStorage.name = "Guest";
    }

    $("#homePageView").hide();
    $("#roomView").hide();
    var dynamicJoin = inRoom();

    globalConnect = ko.observable(new Connect());
    lobby = new Lobby();

    ko.applyBindings(lobby, $("#homePageView")[0]);

    this.windowEvent = function(e) {
        if (e.state === "lobby") {
            setStartCSSHomePage();
            $("#homePageView").show();
            $("#roomView").hide();
        } else if (e.state === "room") {
            setStartCSSRoom();
            $("#roomView").show();
            $("#homePageView").hide();
        }
    }

    window.addEventListener('popstate', this.windowEvent);

    // Position views depending on whether jumping straight into game or not
    if (dynamicJoin === false) {
        // Start on Home Page
        setStartCSSHomePage();
        $("#homePageView").show();
    } else {
        // Start in Waiting Room
        setStartCSSRoom();
        $("#roomView").show();
    }
});

function inRoom() {
    var num = window.location.href.split("/").pop();
    if (typeof num === "string" && num.length>=3) {
        return num;
    }
    return false;
}

function setStartCSSHomePage() {
    // Start on Home Page
    $("#roomView").css({
        // CSS properties here
        opacity: 1,
        top : "100%"
    });
    $("#homePageView").css({
        opacity: 1,
    });
}

function setStartCSSRoom() {
    $("#roomView").css({
        // CSS properties here
        opacity: 1,
        top : "0px"
    });
    $("#homePageView").css({
        opacity: 0,
    });
}

function clickJoinRoom() {
    lobby.joinRoom();

    viewTransition = viewTransitions.homePageToRoom;
    animateTransition();
}

function clickInviteFriends() {
    lobby.createRoomPrivate(lobby);

    viewTransition = viewTransitions.homePageToRoom;
    animateTransition();
}

function clickLeaveRoom() {
    viewTransition = viewTransitions.roomToHomePage;
    animateTransition();
}

function joinRoomAnimationCallback() {
    $("#homePageView").hide();
    viewTransition = 0;
}

function leaveRoomAnimationCallback() {
    lobby.leaveRoom();
    $("#roomView").hide();
    viewTransition = 0;
}

function animateTransition() {
    if (viewTransition === viewTransitions.homePageToRoom) {
        $("#roomView").show();
        $("#roomView").animate({
            // Animation properties here
            top: 0
        }, {duration : 400, complete : joinRoomAnimationCallback});
        $("#homePageView").animate({
            opacity: 0
        }, {duration : 400});

    } else if (viewTransition === viewTransitions.roomToHomePage) {
        $("#homePageView").show();
        $("#roomView").animate({
            // Animation properties here
            top: "100%"
        }, {duration : 400, complete : leaveRoomAnimationCallback});
        $("#homePageView").animate({
            opacity: 1,
        }, {duration : 400});
    }
}

function openScreenNameOverlay() {
    $("#screenNameOverlay").show();
}

function applyScreenName(form) {
    var name = $("#screenNameInput").val();
    if (name === "" || name === "Guest") {
        // TODO: Yell at user
    } else {
        globalConnect().setName($("#screenNameInput").val())
        $("#screenNameOverlay").hide()
    }
}

<|endoftext|>


<commit_before>import React, { Component } from "react"
import PropTypes from "prop-types"

import Nav from "./Schedule/Nav"
import Ruler from "./Schedule/Ruler"
import DayView from "./Schedule/DayView"
import UnscheduledArea from "./Schedule/UnscheduledArea"
import GenerateGridButton from "./Schedule/GenerateGridButton"
import BulkCreateModal from "./Schedule/BulkCreateModal"
import BulkGenerateConfirm from "./Schedule/BulkGenerateConfirm"
import Alert from './Schedule/Alert'

import { postBulkTimeSlots } from "../apiCalls"

class Schedule extends Component {
  constructor(props) {
    super(props)
    this.state = {
      dayViewing: 1,
      startTime: 10,
      endTime: 17,
      counts: {},
      draggedSession: null,
      slots: [],
      rooms: [],
      sessionFormats: [],
      bulkTimeSlotModalOpen: false,
      previewSlots: [],
      bulkTimeSlotModalEditState: null,
      errorMessages: [],
      bulkErrorMessages: [],
    }
  }

  changeDayView = day => {
    this.setState({ dayViewing: day })
  }

  ripTime = time => {
    const hours =  parseInt(time.split("T")[1].split(":")[0])
    const minutes = parseInt(time.split(':')[1]) / 60
    return hours + minutes
  }

  determineHours = slots => {
    let hours = {
      startTime: 12,
      endTime: 12
    }

    slots.forEach(slot => {
      if (this.ripTime(slot.start_time) < hours.startTime) {
        hours.startTime = this.ripTime(slot.start_time)
      }
      if (this.ripTime(slot.end_time) > hours.endTime) {
        hours.endTime = this.ripTime(slot.end_time)
      }
    })
    return hours
  }

  changeDragged = programSession => {
    this.setState({ draggedSession: programSession })
  }

  handleMoveSessionResponse = ( sessions, unscheduledSessions, slots, session ) => {
    if (session) {
      slots.forEach(slot => {
        if (slot.id === session.slot.id) {
          slot.program_session_id = null
        }
      })
    }

    this.setState({ sessions, unscheduledSessions, slots })
  }

  openBulkTimeSlotModal = () => {
    this.setState({
      bulkTimeSlotModalOpen: true,
      previewSlots: []
    })
  }

  closeBulkTimeSlotModal = (e) => {
    e.preventDefault()
    this.setState({
      previewSlots: [],
      bulkTimeSlotModalEditState: null,
      bulkTimeSlotModalOpen: false
    })
  }

  cancelBulkPreview = () => {
    let hours = this.determineHours(this.state.slots)
    this.setState({
      previewSlots: [],
      bulkTimeSlotModalEditState: null,
      ...hours
    })
  }

  findTimeSlotConflicts = (previewSlots) => {
    const { slots } = this.state
    let conflicts = []

    previewSlots.forEach(ps => {
      slots.forEach(s => {
        let sameDaySameRoom = s.room_id === parseInt(ps.room) && s.conference_day === ps.day

        if (sameDaySameRoom) {
          let timeConflict = ps.startTime > this.ripTime(s.start_time) && ps.startTime < this.ripTime(s.end_time) || ps.endTime > this.ripTime(s.start_time) && ps.startTime < this.ripTime(s.end_time)

          if (timeConflict) {
            conflicts.push(s)
          }
        }
      })

    })

    return conflicts
  }

  handleConflicts = (conflicts, bulkTimeSlotModalEditState) => {
    const { rooms } = this.state

    let errorMessages = []

    conflicts.forEach(c => {
      let message = `You attempted to preview a slot which overlaps an existing slot. The overlap involves a previously existing slot on Day ${c.conference_day} at the ${rooms.find(r => r.id == c.room_id).name} location, between  ${c.start_time.split('T')[1].split('.')[0]} and ${c.end_time.split('T')[1].split('.')[0]}`

      errorMessages.push(message)
    })

    this.setState({
      errorMessages,
      bulkTimeSlotModalEditState,
      bulkTimeSlotModalOpen: false,
    })
  }

  createTimeSlotPreviews = (previewSlots, bulkTimeSlotModalEditState) => {
    let { startTime, endTime } = this.state

    previewSlots.forEach(preview => {
      if (preview.startTime < startTime) {
        startTime = preview.startTime
      }
      if (preview.endTime > endTime) {
        endTime = preview.endTime
      }
    })

    let conflicts = this.findTimeSlotConflicts(previewSlots)

    if (conflicts.length > 0) {
      this.handleConflicts(conflicts, bulkTimeSlotModalEditState)
    } else {
      this.setState({
        previewSlots,
        bulkTimeSlotModalEditState,
        bulkTimeSlotModalOpen: false,
        dayViewing: parseInt(bulkTimeSlotModalEditState.day),
        startTime,
        endTime
      })
    }

  }

  requestBulkTimeSlotCreate = () => {
    const {csrf, bulkTimeSlotModalEditState, bulkPath} = this.state
    const {day, duration, rooms, startTimes} = bulkTimeSlotModalEditState

    // the API expects time strings to have a minutes declaration, this following code adds a minute decaration to each time in a string, if needed.
    const formattedTimes = startTimes.replace(/\s/g, '').split(',').map(time => {
      if (time.split(':').length > 1) {
        return time
      } else {
        return time + ':00'
      }
    }).join(', ')

    postBulkTimeSlots(bulkPath, day, rooms, duration, formattedTimes, csrf)
      .then(response => response.json())
      .then(data => {
        const { errors } = data

        if (errors) {
          this.setState({ bulkErrorMessages: errors })
          return
        }

        this.setState({
          slots: data.slots,
          previewSlots: [],
          bulkTimeSlotModalEditState: null
        }, () => {
          let hours = this.determineHours(this.state.slots)
          this.setState({...hours})
        })
      })
      .catch(err => console.log('Error: ', err))
  }

  componentDidMount() {
    let hours = this.determineHours(this.props.slots)
    const trackColors = palette("tol-rainbow", this.props.tracks.length)
    this.props.tracks.forEach((track, i) => {
      track.color = "#" + trackColors[i]
    })

    this.setState(Object.assign(this.state, this.props, hours))
  }

  showErrors = messages => {
    this.setState({ errorMessages: messages })
  }

  removeErrors = () => {
    this.setState({ errorMessages: [], bulkErrorMessages: [] })
  }

  render() {
    const {
      counts,
      dayViewing,
      startTime,
      endTime,
      sessions,
      unscheduledSessions,
      draggedSession,
      csrf,
      tracks,
      bulkTimeSlotModalOpen,
      bulkTimeSlotModalEditState,
      previewSlots,
      slots,
      rooms,
      sessionFormats,
      errorMessages,
      bulkErrorMessages,
    } = this.state

    const headers = rooms.map(room => (

        {room.name}

    ))

    const headersMinWidth = (180 * rooms.length) + 'px'

    const bulkTimeSlotModal = bulkTimeSlotModalOpen && <BulkCreateModal
      closeBulkTimeSlotModal={this.closeBulkTimeSlotModal}
      dayViewing={dayViewing}
      counts={counts}
      rooms={rooms}
      createTimeSlotPreviews={this.createTimeSlotPreviews}
      editState={bulkTimeSlotModalEditState}
      sessionFormats={sessionFormats}
    />

    return (

        {errorMessages.length > 0 && (
          <Alert
            messages={errorMessages}
            onClose={this.removeErrors}
          />
        )}
        {bulkErrorMessages.length > 0 && (
          <Alert
            messages={bulkErrorMessages}
            onClose={this.removeErrors}
          />
        )}
        {bulkTimeSlotModal}

          <GenerateGridButton
            dayViewing={dayViewing}
            generateGridPath={this.props.bulk_path}
            openBulkTimeSlotModal={this.openBulkTimeSlotModal}
          />

{headers}

          {previewSlots.length > 0 && <BulkGenerateConfirm
            cancelBulkPreview={this.cancelBulkPreview}
            openBulkTimeSlotModal={this.openBulkTimeSlotModal}
            requestBulkTimeSlotCreate={this.requestBulkTimeSlotCreate}
          />}
          <Ruler startTime={startTime} endTime={endTime} />
          <DayView
            dayViewing={dayViewing}
            startTime={startTime}
            endTime={endTime}
            ripTime={this.ripTime}
            changeDragged={this.changeDragged}
            draggedSession={draggedSession}
            csrf={csrf}
            sessions={sessions}
            tracks={tracks}
            previewSlots={previewSlots}
            rooms={rooms}
            slots={slots}
            handleMoveSessionResponse={this.handleMoveSessionResponse}
            unscheduledSessions={unscheduledSessions}
            sessionFormats={sessionFormats}
            showErrors={this.showErrors}
          />
          <UnscheduledArea
            unscheduledSessions={unscheduledSessions}
            sessions={sessions}
            changeDragged={this.changeDragged}
            draggedSession={draggedSession}
            csrf={csrf}
            tracks={tracks}
            handleMoveSessionResponse={this.handleMoveSessionResponse}
          />

    )
  }
}

Schedule.propTypes = {
  schedule: PropTypes.object,
  sessions: PropTypes.array,
  counts: PropTypes.object,
  unscheduledSessions: PropTypes.array,
  csrf: PropTypes.string,
  tracks: PropTypes.array
}

export default Schedule
<commit_msg>Alert user if making two new time slots that overlap, as well as when they overlap existing slots<commit_after>import React, { Component } from "react"
import PropTypes from "prop-types"

import Nav from "./Schedule/Nav"
import Ruler from "./Schedule/Ruler"
import DayView from "./Schedule/DayView"
import UnscheduledArea from "./Schedule/UnscheduledArea"
import GenerateGridButton from "./Schedule/GenerateGridButton"
import BulkCreateModal from "./Schedule/BulkCreateModal"
import BulkGenerateConfirm from "./Schedule/BulkGenerateConfirm"
import Alert from './Schedule/Alert'

import { postBulkTimeSlots } from "../apiCalls"

class Schedule extends Component {
  constructor(props) {
    super(props)
    this.state = {
      dayViewing: 1,
      startTime: 10,
      endTime: 17,
      counts: {},
      draggedSession: null,
      slots: [],
      rooms: [],
      sessionFormats: [],
      bulkTimeSlotModalOpen: false,
      previewSlots: [],
      bulkTimeSlotModalEditState: null,
      errorMessages: [],
      bulkErrorMessages: [],
    }
  }

  changeDayView = day => {
    this.setState({ dayViewing: day })
  }

  ripTime = time => {
    const hours =  parseInt(time.split("T")[1].split(":")[0])
    const minutes = parseInt(time.split(':')[1]) / 60
    return hours + minutes
  }

  determineHours = slots => {
    let hours = {
      startTime: 12,
      endTime: 12
    }

    slots.forEach(slot => {
      if (this.ripTime(slot.start_time) < hours.startTime) {
        hours.startTime = this.ripTime(slot.start_time)
      }
      if (this.ripTime(slot.end_time) > hours.endTime) {
        hours.endTime = this.ripTime(slot.end_time)
      }
    })
    return hours
  }

  changeDragged = programSession => {
    this.setState({ draggedSession: programSession })
  }

  handleMoveSessionResponse = ( sessions, unscheduledSessions, slots, session ) => {
    if (session) {
      slots.forEach(slot => {
        if (slot.id === session.slot.id) {
          slot.program_session_id = null
        }
      })
    }

    this.setState({ sessions, unscheduledSessions, slots })
  }

  openBulkTimeSlotModal = () => {
    this.setState({
      bulkTimeSlotModalOpen: true,
      previewSlots: []
    })
  }

  closeBulkTimeSlotModal = (e) => {
    e.preventDefault()
    this.setState({
      previewSlots: [],
      bulkTimeSlotModalEditState: null,
      bulkTimeSlotModalOpen: false
    })
  }

  cancelBulkPreview = () => {
    let hours = this.determineHours(this.state.slots)
    this.setState({
      previewSlots: [],
      bulkTimeSlotModalEditState: null,
      ...hours
    })
  }

  findTimeSlotConflicts = (previewSlots) => {
    const { slots } = this.state
    let conflicts = []

    previewSlots.forEach(ps => {
      slots.forEach(s => {
        let sameDaySameRoom = s.room_id === parseInt(ps.room) && s.conference_day === ps.day

        if (sameDaySameRoom) {
          let timeConflict = ps.startTime > this.ripTime(s.start_time) && ps.startTime < this.ripTime(s.end_time) || ps.endTime > this.ripTime(s.start_time) && ps.startTime < this.ripTime(s.end_time)

          if (timeConflict) {
            conflicts.push(s)
          }
        }
      })

      previewSlots.forEach(preview => {
        if (Object.is(ps, preview)) { return }
        let sameDaySameRoom = parseInt(preview.room) === parseInt(ps.room) && preview.day === ps.day

        if (sameDaySameRoom) {
          let timeConflict = ps.startTime > preview.startTime && ps.startTime < preview.endTime || ps.endTime > preview.startTime && ps.startTime < preview.endTime

          if (timeConflict) {
            conflicts.push(Object.assign(preview, { previewConflict: true }))
          }
        }
      })

    })

    return conflicts
  }

  handleConflicts = (conflicts, bulkTimeSlotModalEditState) => {
    const { rooms } = this.state

    let errorMessages = []

    conflicts.forEach(c => {
      let message

      if (c.previewConflict) {
        message = `You attempted to make two new time slots that overlap. The overlap occurs on Day ${c.conference_day} at the ${rooms.find(r => r.id == parseInt(c.room)).name} location.`
      } else {
        message = `You attempted to preview a slot which overlaps an existing slot. The overlap involves a previously existing slot on Day ${c.conference_day} at the ${rooms.find(r => r.id == c.room_id).name} location, between  ${c.start_time.split('T')[1].split('.')[0]} and ${c.end_time.split('T')[1].split('.')[0]}`
      }

      errorMessages.push(message)
    })

    errorMessages =  [...new Set(errorMessages)];
    this.setState({
      errorMessages,
      bulkTimeSlotModalEditState,
      bulkTimeSlotModalOpen: false,
    })
  }

  createTimeSlotPreviews = (previewSlots, bulkTimeSlotModalEditState) => {
    let { startTime, endTime } = this.state

    previewSlots.forEach(preview => {
      if (preview.startTime < startTime) {
        startTime = preview.startTime
      }
      if (preview.endTime > endTime) {
        endTime = preview.endTime
      }
    })

    let conflicts = this.findTimeSlotConflicts(previewSlots)

    if (conflicts.length > 0) {
      this.handleConflicts(conflicts, bulkTimeSlotModalEditState)
    } else {
      this.setState({
        previewSlots,
        bulkTimeSlotModalEditState,
        bulkTimeSlotModalOpen: false,
        dayViewing: parseInt(bulkTimeSlotModalEditState.day),
        startTime,
        endTime
      })
    }

  }

  requestBulkTimeSlotCreate = () => {
    const {csrf, bulkTimeSlotModalEditState, bulkPath} = this.state
    const {day, duration, rooms, startTimes} = bulkTimeSlotModalEditState

    // the API expects time strings to have a minutes declaration, this following code adds a minute decaration to each time in a string, if needed.
    const formattedTimes = startTimes.replace(/\s/g, '').split(',').map(time => {
      if (time.split(':').length > 1) {
        return time
      } else {
        return time + ':00'
      }
    }).join(', ')

    postBulkTimeSlots(bulkPath, day, rooms, duration, formattedTimes, csrf)
      .then(response => response.json())
      .then(data => {
        const { errors } = data

        if (errors) {
          this.setState({ bulkErrorMessages: errors })
          return
        }

        this.setState({
          slots: data.slots,
          previewSlots: [],
          bulkTimeSlotModalEditState: null
        }, () => {
          let hours = this.determineHours(this.state.slots)
          this.setState({...hours})
        })
      })
      .catch(err => console.log('Error: ', err))
  }

  componentDidMount() {
    let hours = this.determineHours(this.props.slots)
    const trackColors = palette("tol-rainbow", this.props.tracks.length)
    this.props.tracks.forEach((track, i) => {
      track.color = "#" + trackColors[i]
    })

    this.setState(Object.assign(this.state, this.props, hours))
  }

  showErrors = messages => {
    this.setState({ errorMessages: messages })
  }

  removeErrors = () => {
    this.setState({ errorMessages: [], bulkErrorMessages: [] })
  }

  render() {
    const {
      counts,
      dayViewing,
      startTime,
      endTime,
      sessions,
      unscheduledSessions,
      draggedSession,
      csrf,
      tracks,
      bulkTimeSlotModalOpen,
      bulkTimeSlotModalEditState,
      previewSlots,
      slots,
      rooms,
      sessionFormats,
      errorMessages,
      bulkErrorMessages,
    } = this.state

    const headers = rooms.map(room => (

        {room.name}

    ))

    const headersMinWidth = (180 * rooms.length) + 'px'

    const bulkTimeSlotModal = bulkTimeSlotModalOpen && <BulkCreateModal
      closeBulkTimeSlotModal={this.closeBulkTimeSlotModal}
      dayViewing={dayViewing}
      counts={counts}
      rooms={rooms}
      createTimeSlotPreviews={this.createTimeSlotPreviews}
      editState={bulkTimeSlotModalEditState}
      sessionFormats={sessionFormats}
    />

    return (

        {errorMessages.length > 0 && (
          <Alert
            messages={errorMessages}
            onClose={this.removeErrors}
          />
        )}
        {bulkErrorMessages.length > 0 && (
          <Alert
            messages={bulkErrorMessages}
            onClose={this.removeErrors}
          />
        )}
        {bulkTimeSlotModal}

          <GenerateGridButton
            dayViewing={dayViewing}
            generateGridPath={this.props.bulk_path}
            openBulkTimeSlotModal={this.openBulkTimeSlotModal}
          />

{headers}

          {previewSlots.length > 0 && <BulkGenerateConfirm
            cancelBulkPreview={this.cancelBulkPreview}
            openBulkTimeSlotModal={this.openBulkTimeSlotModal}
            requestBulkTimeSlotCreate={this.requestBulkTimeSlotCreate}
          />}
          <Ruler startTime={startTime} endTime={endTime} />
          <DayView
            dayViewing={dayViewing}
            startTime={startTime}
            endTime={endTime}
            ripTime={this.ripTime}
            changeDragged={this.changeDragged}
            draggedSession={draggedSession}
            csrf={csrf}
            sessions={sessions}
            tracks={tracks}
            previewSlots={previewSlots}
            rooms={rooms}
            slots={slots}
            handleMoveSessionResponse={this.handleMoveSessionResponse}
            unscheduledSessions={unscheduledSessions}
            sessionFormats={sessionFormats}
            showErrors={this.showErrors}
          />
          <UnscheduledArea
            unscheduledSessions={unscheduledSessions}
            sessions={sessions}
            changeDragged={this.changeDragged}
            draggedSession={draggedSession}
            csrf={csrf}
            tracks={tracks}
            handleMoveSessionResponse={this.handleMoveSessionResponse}
          />

    )
  }
}

Schedule.propTypes = {
  schedule: PropTypes.object,
  sessions: PropTypes.array,
  counts: PropTypes.object,
  unscheduledSessions: PropTypes.array,
  csrf: PropTypes.string,
  tracks: PropTypes.array
}

export default Schedule
<|endoftext|>


<commit_before>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
})

/*
 * Function that is called when the document is ready.
 */
function initializePage() {

    $("#registerButton").click(register);

}

function register(e) {
    //window.location.href = "register";
    $("#registerButton").hide();
}
<commit_msg>Getting familar with jQuery.<commit_after>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
})

/*
 * Function that is called when the document is ready.
 */
function initializePage() {

    $("#registerButton").click(register);

}

function register(e) {
    //window.location.href = "register";
    alert("Text: " + $("#username").text());
}
<|endoftext|>


<commit_before>/**
 * Grunt plugin for generating PHP autoload files for WordPoints's autoloader.
 *
 * @package WordPoints_Dev_Lib
 * @since 2.4.0
 */

var spawnSync;

module.exports = function ( grunt ) {

	grunt.registerMultiTask( 'autoloader', 'Generate the class map files for WordPoints\'s PHP autoloader', function() {

		var src_dir = this.data.src_dir || 'src/',
			failures = false,
			class_dirs = grunt.file.expand(
				{ cwd: src_dir }
				, [ '**/classes' ]
			);

		for ( var i = 0; i < class_dirs.length; i++ ) {
			if (
				! generate_autoloader_file(
					src_dir + class_dirs[ i ] + '/'
					, this.data.filter
					, this.data.prefix
					, this.data.dependencies
				)
			) {
				failures = true;
			}
		}

		return ! failures;
	});

	/**
	 * Generate the autoloader file for a directory.
	 *
	 * Generates a class map file for the WordPoints autoloader, and verifies that
	 * it will work as a fallback when SPL autoloading is disabled. A failure
	 * usually indicates that the classes need to be sorted so that they load in a
	 * different order when SPL is disabled.
	 *
	 * @param classes_dir {string}      The path to the class directory to generate
	 *                                  the autoloader file for.
	 * @param filter      {func}        A function to pass the list of files to for
	 *                                  filtering and sorting. Note that only class
	 *                                  files are passed, not interface files. The
	 *                                  class directory is passed as the second
	 *                                  parameter.
	 * @param prefix      {string|func} A prefix for the classes in this directory,
	 *                                  or a callback function to get the prefix. The
	 *                                  callback will be passed the class directory.
	 * @param dependencies {string[]}   Autoload files for any dependencies of the
	 * 									classes.
	 *
	 * @returns {boolean} Whether the autoloader file was generated successfully.
	 */
	function generate_autoloader_file( classes_dir, filter, prefix, dependencies ) {

		var includes = '',
			contents,
			class_name,
			error,
			result,
			interfaces = [],
			file = classes_dir + 'index.php',
			class_files = grunt.file.expand(
				{ cwd: classes_dir },
				[ '**/*.php', '!index.php' ]
			);

		// Extract the interface files. To do that we need to loop backwards so that
		// we can remove elements from the array as we go.
		for ( var i = class_files.length - 1; i >= 0; i-- ) {

			// Our interface file names are currently like interfacei.php.
			if ( class_files[ i ].substr( -5 ) === 'i.php' ) {

				interfaces.push( class_files[ i ] );
				class_files.splice( i, 1 );
			}
		}

		// Allow the class files to be sorted by a custom function.
		if ( filter ) {
			class_files = filter( class_files, classes_dir );
		}

		// We load interfaces first.
		class_files = interfaces.concat( class_files );

		// Prepare the class map.
		if ( typeof prefix === 'function' ) {
			prefix = prefix( classes_dir );
		}

		for ( i = 0; i < class_files.length; i++ ) {

			class_name = class_files[ i ].substr( 0, class_files[ i ].length - 4 /* .php */ );
			class_name = class_name.replace( /\//g, '_' );

			includes += '\t\'' + prefix + class_name + '\' => \''
				+ class_files[ i ] + '\',\n';
		}

		if ( grunt.file.exists( file ) ) {
			contents = grunt.file.read( file );
		} else {
			contents = '<?php\nreturn array(\n\t// auto-generated {}\n);\n';
		}

		contents = contents.replace(
			/auto-generated \{[^}]*}/,
			'auto-generated {\n' + includes + '\t// }'
		);

		grunt.file.write( file, contents );

		// Test that the file executes properly.
		if ( ! spawnSync ) {
			spawnSync = require( 'child_process' ).spawnSync;
		}

		result = spawnSync(
			__dirname + '/../../bin/verify-php-autoloader'
			, [ classes_dir ].concat( dependencies )
		);

		if ( result.error ) {
			error = result.error.message;
		} else if ( result.stderr && result.stderr.length ) {
			error = result.stderr.toString();
		}

		if ( error ) {

			grunt.log.error(
				'Error testing autoload file ' + file + ':\n' + error
			);

			return false;

		} else {

			grunt.log.ok( 'Updated autoload file ' + file );

			return true;
		}
	}
};

// EOF
<commit_msg>grunt: Don't error if no autoloader deps<commit_after>/**
 * Grunt plugin for generating PHP autoload files for WordPoints's autoloader.
 *
 * @package WordPoints_Dev_Lib
 * @since 2.4.0
 */

var spawnSync;

module.exports = function ( grunt ) {

	grunt.registerMultiTask( 'autoloader', 'Generate the class map files for WordPoints\'s PHP autoloader', function() {

		var src_dir = this.data.src_dir || 'src/',
			failures = false,
			class_dirs = grunt.file.expand(
				{ cwd: src_dir }
				, [ '**/classes' ]
			);

		for ( var i = 0; i < class_dirs.length; i++ ) {
			if (
				! generate_autoloader_file(
					src_dir + class_dirs[ i ] + '/'
					, this.data.filter
					, this.data.prefix
					, this.data.dependencies
				)
			) {
				failures = true;
			}
		}

		return ! failures;
	});

	/**
	 * Generate the autoloader file for a directory.
	 *
	 * Generates a class map file for the WordPoints autoloader, and verifies that
	 * it will work as a fallback when SPL autoloading is disabled. A failure
	 * usually indicates that the classes need to be sorted so that they load in a
	 * different order when SPL is disabled.
	 *
	 * @param classes_dir {string}      The path to the class directory to generate
	 *                                  the autoloader file for.
	 * @param filter      {func}        A function to pass the list of files to for
	 *                                  filtering and sorting. Note that only class
	 *                                  files are passed, not interface files. The
	 *                                  class directory is passed as the second
	 *                                  parameter.
	 * @param prefix      {string|func} A prefix for the classes in this directory,
	 *                                  or a callback function to get the prefix. The
	 *                                  callback will be passed the class directory.
	 * @param dependencies {string[]}   Autoload files for any dependencies of the
	 * 									classes.
	 *
	 * @returns {boolean} Whether the autoloader file was generated successfully.
	 */
	function generate_autoloader_file( classes_dir, filter, prefix, dependencies ) {

		var includes = '',
			contents,
			class_name,
			error,
			result,
			interfaces = [],
			file = classes_dir + 'index.php',
			class_files = grunt.file.expand(
				{ cwd: classes_dir },
				[ '**/*.php', '!index.php' ]
			);

		// Extract the interface files. To do that we need to loop backwards so that
		// we can remove elements from the array as we go.
		for ( var i = class_files.length - 1; i >= 0; i-- ) {

			// Our interface file names are currently like interfacei.php.
			if ( class_files[ i ].substr( -5 ) === 'i.php' ) {

				interfaces.push( class_files[ i ] );
				class_files.splice( i, 1 );
			}
		}

		// Allow the class files to be sorted by a custom function.
		if ( filter ) {
			class_files = filter( class_files, classes_dir );
		}

		// We load interfaces first.
		class_files = interfaces.concat( class_files );

		// Prepare the class map.
		if ( typeof prefix === 'function' ) {
			prefix = prefix( classes_dir );
		}

		for ( i = 0; i < class_files.length; i++ ) {

			class_name = class_files[ i ].substr( 0, class_files[ i ].length - 4 /* .php */ );
			class_name = class_name.replace( /\//g, '_' );

			includes += '\t\'' + prefix + class_name + '\' => \''
				+ class_files[ i ] + '\',\n';
		}

		if ( grunt.file.exists( file ) ) {
			contents = grunt.file.read( file );
		} else {
			contents = '<?php\nreturn array(\n\t// auto-generated {}\n);\n';
		}

		contents = contents.replace(
			/auto-generated \{[^}]*}/,
			'auto-generated {\n' + includes + '\t// }'
		);

		grunt.file.write( file, contents );

		// Test that the file executes properly.
		if ( ! spawnSync ) {
			spawnSync = require( 'child_process' ).spawnSync;
		}

		result = spawnSync(
			__dirname + '/../../bin/verify-php-autoloader'
			, [ classes_dir ].concat( dependencies || [] )
		);

		if ( result.error ) {
			error = result.error.message;
		} else if ( result.stderr && result.stderr.length ) {
			error = result.stderr.toString();
		}

		if ( error ) {

			grunt.log.error(
				'Error testing autoload file ' + file + ':\n' + error
			);

			return false;

		} else {

			grunt.log.ok( 'Updated autoload file ' + file );

			return true;
		}
	}
};

// EOF
<|endoftext|>


<commit_before>var listeApp = angular.module('listeApp', ['ngSanitize','ngMaterial']);
listeApp.service('recettesService',
    function($http){
        this.getRecettesJsonData = function() {
            return $http({method: "GET", url: "/recettes.json"});
        };
        this.getRecettesMatinJsonData = function() {
            return $http({method: "GET", url: "/matin.json"});
        };
});
listeApp.controller('ListeCtrl', ListeCtrl);
listeApp.controller('LoadCtrl', LoadCtrl);

range = function(max) {
    // No, JS has no such function. Thanks Obama.
    var res = [];
    for (var i=1; i<=max; i++) {res.push(i)};
    return res;
};

function ListeCtrl($scope, $http, $mdDialog, recettesService) {
    recettesService.getRecettesJsonData().then(
        // Calls the service to populate $scope.recettes
        function (r) {
            $scope.recettes = r.data['recettes'].sort(
                function(a,b){
                    return ((a.name  b.name) ? 1 : 0));
                }
            )
        }
    );
    recettesService.getRecettesMatinJsonData().then(
        // Calls the service to populate $scope.recettes_matin
        function (r) {
            $scope.recettes_matin = r.data['recettes'].sort(
                function(a,b){
                    return ((a.name  b.name) ? 1 : 0))
                }
            )
        }
    );

    // Let's initialize some default values
    // TODO Make that an int
    var nb_gens_default = "10"; // srsly, we need a string!
    var liste_courses_json = []; // List of ingredients

    $scope.nb_jours = 5;
    $scope.range_jours = new Array($scope.nb_jours);
    $scope.range_jours_default = range(20);
    $scope.range_gens_default = range(25);

    $scope.extras = [
        {"name": "Capitaaaaaine", enabled: false,
            calc_qty:function() {return parseInt($scope.nb_jours) / 2  },
            unit:" bouteilles (1 pour 2 jours)"},
        {"name": "Crème de marron", enabled:false,
        // TODO avoir une moyenne de gens par jour
            calc_qty:function() {return parseInt($scope.nb_jours) * 3 },
            unit:" Plein (1 plein par jour)"},
        {"name": "Fruits divers", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) / 2 },
            unit:" kg (0.5*nb jours)"},
        {"name": "Gateau apéro", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 3 },
            unit:" Paquets divers (chips, bretzels, etc) (3*nb jours)"},
        {"name": "Pastille lave-vaisselle", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 2 },
            unit:" (2*nb jours)"},
        {"name": "Produit vaisselle", enabled:false,
            calc_qty:function() {return Math.ceil(parseInt($scope.nb_jours) / 5) },
            unit:" bidon (1 pour 5 jours)"},
        {"name": "PQ", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 6 },
            unit:" rouleau (6*nb jours)"},
        {"name": "Sacs poubelle", enabled:false,
            calc_qty:function() {return Math.round(parseInt($scope.nb_jours) * 0.3) },
            unit:" rouleaux (3 sacs * nb jours)"},
        {"name": "Saucisson", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 3 },
            unit:" saucissons (3*nb jours)"},
        {"name": "Torchons", enabled:false,
            calc_qty:function() {return 2 },
            unit:" "},
        {"name": "Yaourts", enabled:false,
        // TODO avoir une moyenne de gens par jour
            calc_qty:function() {return parseInt($scope.nb_jours)  },
            unit:" * nb_gens == nb pots"},
    ];

    // These arrays will hold the nb person per day per meal recipes
    $scope.gens_par_matin = new Array(parseInt($scope.nb_jours)).fill(parseInt(nb_gens_default));
    $scope.recette_matin_par_jour = new Array(parseInt($scope.nb_jours)).fill("");
    $scope.gens_par_diner = new Array( parseInt($scope.nb_jours)).fill(nb_gens_default);
    $scope.recette_diner_par_jour = new Array( parseInt($scope.nb_jours)).fill("");
    $scope.gens_par_dejeuner = new Array( parseInt($scope.nb_jours)).fill(nb_gens_default);
    $scope.recette_dejeuner_par_jour = new Array( parseInt($scope.nb_jours)).fill("");

    // Helper functions
    getIngredients = function(recette_name, liste_recettes) {
        for (a in liste_recettes) {
            var r = liste_recettes[a];
            if (r.name == recette_name) { return r.ingredients; }
        }
    };

    arrondi = function(nb, unit) {
        if ((typeof nb === "undefined") || (nb == null)){
            if ((typeof unit === "undefined") || (unit == null)) {
                return "";
            } else {
                return unit;
            }
        } else {
            if ((typeof unit === "undefined") || (unit == null)) {
                return nb
            }
        }
        var n = 0;
        switch(unit) {
            case "g":
                if (nb>=1000) {
                    n = Math.round(nb / 100) / 10;
                    return n+"kg";
                }
                break;
            case "cL":
                if (nb>=100) {
                    n = Math.round(nb / 10) / 10;
                    return n+"L";
                }
                break;
        }
        if (nb > 10) {
            return Math.round(nb)+""+unit;
       } else {
           return nb+unit;
       }
    }

    addToListe = function(liste_json, ingredient, nb_gens) {
        var found = false;
        for (i in liste_json) {
            var item = liste_json[i];
            if (item.name == ingredient.name) {
                if ('qty' in ingredient) {
                    item.qty = item.qty + (ingredient.qty * nb_gens);
                };
                found = true;
            };
        };
        if (!found) {
            var item = {};
            item.name = ingredient.name;
            if ('qty' in ingredient) {
                item.qty = ingredient.qty * nb_gens;
                item.unit = ingredient.unit;
            };
            liste_json.push(item);
        };
    };

    $scope.loadStoredList = function(json_from_http, name) {
        // takes the result from the HTTP json, and populates the local $scope var
        var jours = json_from_http['liste']['jours'];
        for (var i in jours) {
            // first, every day's meals
            var jour = jours[i]
            $scope.recette_matin_par_jour[i] = jour['matin']['recette'];
            $scope.gens_par_matin[i] = jour['matin']['gens'];
            $scope.recette_dejeuner_par_jour[i] = jour['dejeuner']['recette'];
            $scope.gens_par_dejeuner[i] = jour['dejeuner']['gens'];
            $scope.recette_diner_par_jour[i] = jour['diner']['recette'];
            $scope.gens_par_diner[i] = jour['diner']['gens'];
        };
        // then, 'extras'
        var _extras = json_from_http['liste']['extras'];
        var setExtraState = function(extra_name, state) {
            for (var i=0; i < $scope.extras.length; i++) {
                var e = $scope.extras[i];
                if (e.name == extra_name) {e.enabled = state}
            }
        };
        for (var i = 0; i < _extras.length; i++) {
            var extra = _extras[i];
            setExtraState(extra.name, extra.enabled);
        };
        $scope.updateListe();
    };

    generate_saved_liste = function() {
        // Generates the JSON object used for storage of the list
        var json_result = {'jours':[], 'extras':[]};
        for (var i = 0; i < $scope.nb_jours; i++) {
            var jour = {'matin': {'recette':null, 'gens':0 }, 'diner': {'recette': null, 'gens': 0}, 'dejeuner': {'recette': null, 'gens': 0}};
            recette_matin = $scope.recette_matin_par_jour[i];
            recette_dejeuner = $scope.recette_dejeuner_par_jour[i];
            recette_diner = $scope.recette_diner_par_jour[i];
            jour['matin']['recette'] = recette_matin;
            jour['matin']['gens'] = parseInt($scope.gens_par_matin[i]);
            jour['dejeuner']['recette'] = recette_dejeuner;
            jour['dejeuner']['gens'] = parseInt($scope.gens_par_dejeuner[i]);
            jour['diner']['recette'] = recette_diner;
            jour['diner']['gens'] = parseInt($scope.gens_par_diner[i]);

            json_result['jours'].push(jour);
        };
        for (var i in $scope.extras) {
            var extra = $scope.extras[i];
            var item = {'name': extra.name, 'enabled':extra.enabled};
            json_result['extras'].push(item);
        }
        return json_result;
    };

    $scope.updateListe = function() {
        // Re-builds the internal liste de course
        liste_courses_json = [];
        for (var i=0; i< $scope.nb_jours; i++) {
            var recette_matin = $scope.recette_matin_par_jour[i];
            var gens_matin = parseInt($scope.gens_par_matin[i]);
            if (recette_matin != "") {
                var ings = getIngredients(recette_matin, $scope.recettes_matin);
                for (ing in ings) {
                    ingredient = ings[ing];
                    addToListe(liste_courses_json, ingredient, gens_matin);
                }
            }

            var recette_dejeuner = $scope.recette_dejeuner_par_jour[i];
            var gens_dejeuner = parseInt($scope.gens_par_dejeuner[i]);
            if (recette_dejeuner != "") {
                var ings = getIngredients(recette_dejeuner, $scope.recettes);
                for (ing in ings) {
                    ingredient = ings[ing];
                    addToListe(liste_courses_json, ingredient, g);
                }
            };

            var recette_diner = $scope.recette_diner_par_jour[i];
            var gens_diner = parseInt($scope.gens_par_diner[i]);
            if (recette_diner != "") {
                var ings = getIngredients(recette_diner, $scope.recettes);
                for (ing in ings) {
                    ingredient = ings[ing];
                    addToListe(liste_courses_json, ingredient, gens_diner);
                }
            };
        };

        for (var i in $scope.extras) {
            var liste_extras_json = [];
            var e = $scope.extras[i];
            if (e.enabled) {
                if (typeof e.calc_qty !== "undefined") {
                    e.qty = e.calc_qty();
                };
                addToListe(liste_courses_json, e, 1);
            };
        };
        updateHTMLListe(liste_courses_json);
    };

    updateHTMLListe = function(liste_json){
        var html_result = "
\n";
        for (var i in liste_json) {
            var item = liste_json[i];
            var qty_txt = arrondi(item.qty, item.unit);
            html_result += "
"+item.name
            if (qty_txt == "") {
                html_result += "
\n" ;
            } else {
                html_result += ": "+qty_txt+"
\n" ;
            }
        };
        html_result += "
";
        $scope.liste_html = html_result;
    };

    $scope.joursChanged = function() {
        // Update number of days
        $scope.range_jours = new Array($scope.nb_jours);
    }

    save = function(name) {
        $http({
            method: "POST",
            url: "/save",
            data: {'name' :name, "liste": generate_saved_liste()}
        }).then(
            function(response){
                // console.log('success');
                return response.body;
            },
            function(response){
                //console.log('fail');
            }
        );
    };
	$scope.showPromptSave = function(ev) {
        var confirm = $mdDialog.prompt()
        .title('Renseigner un nom pour la liste')
        .textContent('(ie: \'Kinzout 2019\')')
        .placeholder('Liste')
        .ariaLabel('Liste')
        .targetEvent(ev)
        .ok('Done!')
        .cancel('Cancel');

        $mdDialog.show(confirm).then(
            function(result) {
                save(result);
            },
            function() {console.log("Echec de save la liste")});
    };

	$scope.showPromptLoad = function($event) {
        var parentEl = angular.element(document.body);
        var confirm = $mdDialog.show({
            parent: parentEl,
            targetEvent: $event,
            controller: LoadCtrl,
            scope: $scope,
            templateUrl: 'loadtemplate.html',
            preserveScope: true,
            locals: {load_liste: $scope.load_liste},
            clickOutsideToClose: true
        });
    };

};

function LoadCtrl ($scope, $mdDialog, $http){
    // This controller handles the "Load" dialog
    $scope.loadhide = function() {$mdDialog.hide();};
    $scope.loadcancel = function() {$mdDialog.cancel();};
    $scope.loadanswer = function(answer) {
        var liste_name = "";
        liste_name = $scope.liste_select;
        fetch_stored_liste(liste_name);
        $mdDialog.hide(answer);
    };
    function fetch_stored_liste(list_name) {
        $http({
            method: "GET",
            url: "/get-stored-liste?name="+list_name,
        }).then(
            function(response){
                $scope.loadStoredList(response.data, list_name);
            },
            function(response){
                console.log('liste load fail');
            }
        );
    };

    function fetch_recettes() {
        $http({
            method: "GET",
            url: "/get-stored-listes",
        }).then(
            function(response){
                var data = response.data;
                $scope.load_liste=[];
                for (var i =0; i< data.length; i++) {
                    $scope.load_liste.push(data[i]['name']+" - "+data[i]['date']);
                };
                $scope.liste_select = $scope.load_liste[0];
            },
            function(response){ console.log('liste load fail'); }
        );
    };
    fetch_recettes();
};
<commit_msg>fix update recette dejeuner<commit_after>var listeApp = angular.module('listeApp', ['ngSanitize','ngMaterial']);
listeApp.service('recettesService',
    function($http){
        this.getRecettesJsonData = function() {
            return $http({method: "GET", url: "/recettes.json"});
        };
        this.getRecettesMatinJsonData = function() {
            return $http({method: "GET", url: "/matin.json"});
        };
});
listeApp.controller('ListeCtrl', ListeCtrl);
listeApp.controller('LoadCtrl', LoadCtrl);

range = function(max) {
    // No, JS has no such function. Thanks Obama.
    var res = [];
    for (var i=1; i<=max; i++) {res.push(i)};
    return res;
};

function ListeCtrl($scope, $http, $mdDialog, recettesService) {
    recettesService.getRecettesJsonData().then(
        // Calls the service to populate $scope.recettes
        function (r) {
            $scope.recettes = r.data['recettes'].sort(
                function(a,b){
                    return ((a.name  b.name) ? 1 : 0));
                }
            )
        }
    );
    recettesService.getRecettesMatinJsonData().then(
        // Calls the service to populate $scope.recettes_matin
        function (r) {
            $scope.recettes_matin = r.data['recettes'].sort(
                function(a,b){
                    return ((a.name  b.name) ? 1 : 0))
                }
            )
        }
    );

    // Let's initialize some default values
    // TODO Make that an int
    var nb_gens_default = "10"; // srsly, we need a string!
    var liste_courses_json = []; // List of ingredients

    $scope.nb_jours = 5;
    $scope.range_jours = new Array($scope.nb_jours);
    $scope.range_jours_default = range(20);
    $scope.range_gens_default = range(25);

    $scope.extras = [
        {"name": "Capitaaaaaine", enabled: false,
            calc_qty:function() {return parseInt($scope.nb_jours) / 2  },
            unit:" bouteilles (1 pour 2 jours)"},
        {"name": "Crème de marron", enabled:false,
        // TODO avoir une moyenne de gens par jour
            calc_qty:function() {return parseInt($scope.nb_jours) * 3 },
            unit:" Plein (1 plein par jour)"},
        {"name": "Fruits divers", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) / 2 },
            unit:" kg (0.5*nb jours)"},
        {"name": "Gateau apéro", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 3 },
            unit:" Paquets divers (chips, bretzels, etc) (3*nb jours)"},
        {"name": "Pastille lave-vaisselle", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 2 },
            unit:" (2*nb jours)"},
        {"name": "Produit vaisselle", enabled:false,
            calc_qty:function() {return Math.ceil(parseInt($scope.nb_jours) / 5) },
            unit:" bidon (1 pour 5 jours)"},
        {"name": "PQ", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 6 },
            unit:" rouleau (6*nb jours)"},
        {"name": "Sacs poubelle", enabled:false,
            calc_qty:function() {return Math.round(parseInt($scope.nb_jours) * 0.3) },
            unit:" rouleaux (3 sacs * nb jours)"},
        {"name": "Saucisson", enabled:false,
            calc_qty:function() {return parseInt($scope.nb_jours) * 3 },
            unit:" saucissons (3*nb jours)"},
        {"name": "Torchons", enabled:false,
            calc_qty:function() {return 2 },
            unit:" "},
        {"name": "Yaourts", enabled:false,
        // TODO avoir une moyenne de gens par jour
            calc_qty:function() {return parseInt($scope.nb_jours)  },
            unit:" * nb_gens == nb pots"},
    ];

    // These arrays will hold the nb person per day per meal recipes
    $scope.gens_par_matin = new Array(parseInt($scope.nb_jours)).fill(parseInt(nb_gens_default));
    $scope.recette_matin_par_jour = new Array(parseInt($scope.nb_jours)).fill("");
    $scope.gens_par_diner = new Array( parseInt($scope.nb_jours)).fill(nb_gens_default);
    $scope.recette_diner_par_jour = new Array( parseInt($scope.nb_jours)).fill("");
    $scope.gens_par_dejeuner = new Array( parseInt($scope.nb_jours)).fill(nb_gens_default);
    $scope.recette_dejeuner_par_jour = new Array( parseInt($scope.nb_jours)).fill("");

    // Helper functions
    getIngredients = function(recette_name, liste_recettes) {
        for (a in liste_recettes) {
            var r = liste_recettes[a];
            if (r.name == recette_name) { return r.ingredients; }
        }
    };

    arrondi = function(nb, unit) {
        if ((typeof nb === "undefined") || (nb == null)){
            if ((typeof unit === "undefined") || (unit == null)) {
                return "";
            } else {
                return unit;
            }
        } else {
            if ((typeof unit === "undefined") || (unit == null)) {
                return nb
            }
        }
        var n = 0;
        switch(unit) {
            case "g":
                if (nb>=1000) {
                    n = Math.round(nb / 100) / 10;
                    return n+"kg";
                }
                break;
            case "cL":
                if (nb>=100) {
                    n = Math.round(nb / 10) / 10;
                    return n+"L";
                }
                break;
        }
        if (nb > 10) {
            return Math.round(nb)+""+unit;
       } else {
           return nb+unit;
       }
    }

    addToListe = function(liste_json, ingredient, nb_gens) {
        var found = false;
        for (i in liste_json) {
            var item = liste_json[i];
            if (item.name == ingredient.name) {
                if ('qty' in ingredient) {
                    item.qty = item.qty + (ingredient.qty * nb_gens);
                };
                found = true;
            };
        };
        if (!found) {
            var item = {};
            item.name = ingredient.name;
            if ('qty' in ingredient) {
                item.qty = ingredient.qty * nb_gens;
                item.unit = ingredient.unit;
            };
            liste_json.push(item);
        };
    };

    $scope.loadStoredList = function(json_from_http, name) {
        // takes the result from the HTTP json, and populates the local $scope var
        var jours = json_from_http['liste']['jours'];
        for (var i in jours) {
            // first, every day's meals
            var jour = jours[i]
            $scope.recette_matin_par_jour[i] = jour['matin']['recette'];
            $scope.gens_par_matin[i] = jour['matin']['gens'];
            $scope.recette_dejeuner_par_jour[i] = jour['dejeuner']['recette'];
            $scope.gens_par_dejeuner[i] = jour['dejeuner']['gens'];
            $scope.recette_diner_par_jour[i] = jour['diner']['recette'];
            $scope.gens_par_diner[i] = jour['diner']['gens'];
        };
        // then, 'extras'
        var _extras = json_from_http['liste']['extras'];
        var setExtraState = function(extra_name, state) {
            for (var i=0; i < $scope.extras.length; i++) {
                var e = $scope.extras[i];
                if (e.name == extra_name) {e.enabled = state}
            }
        };
        for (var i = 0; i < _extras.length; i++) {
            var extra = _extras[i];
            setExtraState(extra.name, extra.enabled);
        };
        $scope.updateListe();
    };

    generate_saved_liste = function() {
        // Generates the JSON object used for storage of the list
        var json_result = {'jours':[], 'extras':[]};
        for (var i = 0; i < $scope.nb_jours; i++) {
            var jour = {'matin': {'recette':null, 'gens':0 }, 'diner': {'recette': null, 'gens': 0}, 'dejeuner': {'recette': null, 'gens': 0}};
            recette_matin = $scope.recette_matin_par_jour[i];
            recette_dejeuner = $scope.recette_dejeuner_par_jour[i];
            recette_diner = $scope.recette_diner_par_jour[i];
            jour['matin']['recette'] = recette_matin;
            jour['matin']['gens'] = parseInt($scope.gens_par_matin[i]);
            jour['dejeuner']['recette'] = recette_dejeuner;
            jour['dejeuner']['gens'] = parseInt($scope.gens_par_dejeuner[i]);
            jour['diner']['recette'] = recette_diner;
            jour['diner']['gens'] = parseInt($scope.gens_par_diner[i]);

            json_result['jours'].push(jour);
        };
        for (var i in $scope.extras) {
            var extra = $scope.extras[i];
            var item = {'name': extra.name, 'enabled':extra.enabled};
            json_result['extras'].push(item);
        }
        return json_result;
    };

    $scope.updateListe = function() {
        // Re-builds the internal liste de course
        liste_courses_json = [];
        for (var i=0; i< $scope.nb_jours; i++) {
            var recette_matin = $scope.recette_matin_par_jour[i];
            var gens_matin = parseInt($scope.gens_par_matin[i]);
            if (recette_matin != "") {
                var ings = getIngredients(recette_matin, $scope.recettes_matin);
                for (ing in ings) {
                    ingredient = ings[ing];
                    addToListe(liste_courses_json, ingredient, gens_matin);
                }
            }

            var recette_dejeuner = $scope.recette_dejeuner_par_jour[i];
            var gens_dejeuner = parseInt($scope.gens_par_dejeuner[i]);
            if (recette_dejeuner != "") {
                var ings = getIngredients(recette_dejeuner, $scope.recettes);
                for (ing in ings) {
                    ingredient = ings[ing];
                    addToListe(liste_courses_json, ingredient, gens_dejeuner);
                }
            };

            var recette_diner = $scope.recette_diner_par_jour[i];
            var gens_diner = parseInt($scope.gens_par_diner[i]);
            if (recette_diner != "") {
                var ings = getIngredients(recette_diner, $scope.recettes);
                for (ing in ings) {
                    ingredient = ings[ing];
                    addToListe(liste_courses_json, ingredient, gens_diner);
                }
            };
        };

        for (var i in $scope.extras) {
            var liste_extras_json = [];
            var e = $scope.extras[i];
            if (e.enabled) {
                if (typeof e.calc_qty !== "undefined") {
                    e.qty = e.calc_qty();
                };
                addToListe(liste_courses_json, e, 1);
            };
        };
        updateHTMLListe(liste_courses_json);
    };

    updateHTMLListe = function(liste_json){
        var html_result = "
\n";
        for (var i in liste_json) {
            var item = liste_json[i];
            var qty_txt = arrondi(item.qty, item.unit);
            html_result += "
"+item.name
            if (qty_txt == "") {
                html_result += "
\n" ;
            } else {
                html_result += ": "+qty_txt+"
\n" ;
            }
        };
        html_result += "
";
        $scope.liste_html = html_result;
    };

    $scope.joursChanged = function() {
        // Update number of days
        $scope.range_jours = new Array($scope.nb_jours);
    }

    save = function(name) {
        $http({
            method: "POST",
            url: "/save",
            data: {'name' :name, "liste": generate_saved_liste()}
        }).then(
            function(response){
                // console.log('success');
                return response.body;
            },
            function(response){
                //console.log('fail');
            }
        );
    };
	$scope.showPromptSave = function(ev) {
        var confirm = $mdDialog.prompt()
        .title('Renseigner un nom pour la liste')
        .textContent('(ie: \'Kinzout 2019\')')
        .placeholder('Liste')
        .ariaLabel('Liste')
        .targetEvent(ev)
        .ok('Done!')
        .cancel('Cancel');

        $mdDialog.show(confirm).then(
            function(result) {
                save(result);
            },
            function() {console.log("Echec de save la liste")});
    };

	$scope.showPromptLoad = function($event) {
        var parentEl = angular.element(document.body);
        var confirm = $mdDialog.show({
            parent: parentEl,
            targetEvent: $event,
            controller: LoadCtrl,
            scope: $scope,
            templateUrl: 'loadtemplate.html',
            preserveScope: true,
            locals: {load_liste: $scope.load_liste},
            clickOutsideToClose: true
        });
    };

};

function LoadCtrl ($scope, $mdDialog, $http){
    // This controller handles the "Load" dialog
    $scope.loadhide = function() {$mdDialog.hide();};
    $scope.loadcancel = function() {$mdDialog.cancel();};
    $scope.loadanswer = function(answer) {
        var liste_name = "";
        liste_name = $scope.liste_select;
        fetch_stored_liste(liste_name);
        $mdDialog.hide(answer);
    };
    function fetch_stored_liste(list_name) {
        $http({
            method: "GET",
            url: "/get-stored-liste?name="+list_name,
        }).then(
            function(response){
                $scope.loadStoredList(response.data, list_name);
            },
            function(response){
                console.log('liste load fail');
            }
        );
    };

    function fetch_recettes() {
        $http({
            method: "GET",
            url: "/get-stored-listes",
        }).then(
            function(response){
                var data = response.data;
                $scope.load_liste=[];
                for (var i =0; i< data.length; i++) {
                    $scope.load_liste.push(data[i]['name']+" - "+data[i]['date']);
                };
                $scope.liste_select = $scope.load_liste[0];
            },
            function(response){ console.log('liste load fail'); }
        );
    };
    fetch_recettes();
};
<|endoftext|>


<commit_before>window.myDay = {

};

window.myDay.loadClubs = function(target, callback) {
	window.api.get("myDay/clubs/getAll", function(data) {
		for (var clubIndex in data.clubs) {
			var club = data.clubs[clubIndex];
			var option = $('<option></option>');
				option.val(club.clubId);
				option.text(club.name);
			target.append(option);
		};
		callback();
	});
};

$(document).ready(function() {
	window.myDay.loadClubs($(".myDay-club-select"), function() {
		$(".myDay-club-select").chosen();
	});
	$("#myDayHome").on("tabOpened", function() {
		window.page.showLoading();
		var monday = window.planner.findThisMonday();
		window.api.get("planner/announcements/getWeek/" + window.utils.formatDate_api(monday), function(data) {
			var announcements = [];
			if (data.status == "ok") {
				announcements = data.announcements;
			}
			$("#myDayCalendar").fullCalendar({
				header: {
					left: "title",
					middle: "",
					right: "agendaWeek,agendaDay today prev,next"
				},
				editable: true,
				droppable: true,
				drop: function() {
					// will do backendy stuff later
				}
			}).fullCalendar("changeView", "agendaWeek");
			for (var announcementIndex in announcements) {
				var announcement = announcements[announcementIndex];
				$("#myDayCalendar").fullCalendar("renderEvent", {
					title: announcement.text,
					start: announcement.date,
					allDay: true
				});
			}
			window.page.hideLoading();
		});

		$("#myDayEvents ul li").each(function() {
			$(this).data('event', {
				title: $.trim($(this).text()), // use the element's text as the event title
				stick: true // maintain when user navigates (see docs on the renderEvent method)
			});
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 0  //  original position after the drag
			});
		});
	});
	$("#myDay-welcome-submit").click(function() {
		if ($("input[name=sleepHrs]").val().trim() == "" || $("input[name=WakeUpTime]").val().trim() == "" || $("input[name=Address]").val().trim() == "") {
			swal("You did something wrong, are all your forms filled out?")
		}
		else {
			swal("Yay!", "Now we will calculate your schedule.", "success")
			// Do Backend Crappy Algorithm complicated stuff
			setPage("myDayHome")
		}
		var prefs = {};
		prefs.sleep = $("input[name=sleepHrs]").val();
		prefs.wake = $("input[name=WakeUpTime]").val();
		prefs.address = $("input[name=Address]").val();
		prefs.clubs = "notsureifthisworkssoimputtingastringhere";
		prefs.schoolId = 42;
		window.api.post("myDay/info/set", prefs, function(resp) {});
	});
});
<commit_msg>you can't move announcements<commit_after>window.myDay = {

};

window.myDay.loadClubs = function(target, callback) {
	window.api.get("myDay/clubs/getAll", function(data) {
		for (var clubIndex in data.clubs) {
			var club = data.clubs[clubIndex];
			var option = $('<option></option>');
				option.val(club.clubId);
				option.text(club.name);
			target.append(option);
		};
		callback();
	});
};

$(document).ready(function() {
	window.myDay.loadClubs($(".myDay-club-select"), function() {
		$(".myDay-club-select").chosen();
	});
	$("#myDayHome").on("tabOpened", function() {
		window.page.showLoading();
		var monday = window.planner.findThisMonday();
		window.api.get("planner/announcements/getWeek/" + window.utils.formatDate_api(monday), function(data) {
			var announcements = [];
			if (data.status == "ok") {
				announcements = data.announcements;
			}
			$("#myDayCalendar").fullCalendar({
				header: {
					left: "title",
					middle: "",
					right: "agendaWeek,agendaDay today prev,next"
				},
				editable: true,
				droppable: true,
				drop: function() {
					// will do backendy stuff later
				}
			}).fullCalendar("changeView", "agendaWeek");
			for (var announcementIndex in announcements) {
				var announcement = announcements[announcementIndex];
				$("#myDayCalendar").fullCalendar("renderEvent", {
					title: announcement.text,
					start: announcement.date,
					allDay: true,
					editable: false
				});
			}
			window.page.hideLoading();
		});

		$("#myDayEvents ul li").each(function() {
			$(this).data('event', {
				title: $.trim($(this).text()), // use the element's text as the event title
				stick: true // maintain when user navigates (see docs on the renderEvent method)
			});
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 0  //  original position after the drag
			});
		});
	});
	$("#myDay-welcome-submit").click(function() {
		if ($("input[name=sleepHrs]").val().trim() == "" || $("input[name=WakeUpTime]").val().trim() == "" || $("input[name=Address]").val().trim() == "") {
			swal("You did something wrong, are all your forms filled out?")
		}
		else {
			swal("Yay!", "Now we will calculate your schedule.", "success")
			// Do Backend Crappy Algorithm complicated stuff
			setPage("myDayHome")
		}
		var prefs = {};
		prefs.sleep = $("input[name=sleepHrs]").val();
		prefs.wake = $("input[name=WakeUpTime]").val();
		prefs.address = $("input[name=Address]").val();
		prefs.clubs = "notsureifthisworkssoimputtingastringhere";
		prefs.schoolId = 42;
		window.api.post("myDay/info/set", prefs, function(resp) {});
	});
});
<|endoftext|>


<commit_before>window.prefs = {};

$(document).ready(function() {
  window.api.get("prefs/get/name-subj", function(data) {
    var btnTrue = data.val;
    if(btnTrue == 1) {
      $("prefs-hwView-swap").prop("checked", true);
    }
    $("#usr-btn").click(function() {
      if(btnTrue == 1) {
        btnTrue = 0;
      } else {
        btnTrue = 1;
      };
      window.api.post("prefs/set", { name: "name-subj", value: btnTrue}, function() {});
    });
  });
});
<commit_msg>FIX ALL THE ERRORS<commit_after>window.prefs = {};

$(document).ready(function() {
  window.api.get("prefs/get/name-subj", function(data) {
    var btnTrue = data.val;
    if(btnTrue == "1") {
      $("prefs-hwView-swap").prop("checked", true);
    }
    $("#prefs-hwView-swap").change(function() {
      if(btnTrue == "1") {
        btnTrue = "0";
      } else {
        btnTrue = "1";
      };
      window.api.post("prefs/set", { name: "name-subj", value: btnTrue}, function() {});
    });
  });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         deck view: different tweaks
// @description  deckstats.net
// @grant        none
// @version      1.0.4
// @icon         http://www.google.com/s2/favicons?domain=www.deckstats.net
// @namespace    https://github.com/solygen/userscripts
// @repository   https://github.com/solygen/userscripts.git
// @license      MIT
// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
//
// @include      http://deckstats.net/*
// @include      https://deckstats.net/*
//
// @updateURL    https://rawgithub.com/solygen/userscripts/master/scripts/deckstats.net/deck-view.user.js
// @downloadURL  https://rawgithub.com/solygen/userscripts/master/scripts/deckstats.net/deck-view.user.js
// @homepage     https://github.com/solygen/userscripts

// ==/UserScript==

(function () {

    'use strict';

    var $ = $ || jQuery,
        RARE = 'rgb(196, 159, 39)',
        UNCOMMON = 'rgb(119, 119, 119)',
        COMMON = 'rgb(0, 0, 0)',
        MYTHIC = 'rgb(132, 47, 7)',
        BASIC = 'rgb(4, 26, 72)',
        current = {},
        data = {
            proxies: [],
            rarity: {
                rare: [],
                uncommon: [],
                common: [],
                mythic: [],
                basic: []
            }
        };

    var page = {
        remove: function () {
            var table = $('.cardtable');
            //remove flag and sum
            $(table.find('.card_price.header')[1]).empty();
            $(table.find('.deck_footer').find('.card_price')[1]).empty();

        },

        set: function () {
            //set banner link to list view
            var listview = $($('ul#user_menu a')[0]).attr('href');
            if (listview) {
                $($('#header_left a')).attr('href', listview);
            }
        },

        //bigger card preview
        register: function () {
            function adjust() {
                $('#kartenOverlay')
                    .css('border', '0px')
                    .css('width', 'auto');
                $('#kartenOverlayBild')
                    .css('height', '380px')
                    .css('width', '266px');
                $('#kartenOverlayContent')
                    .css('display', 'none');
                if ($('#kartenOverlay').length) {
                    clearInterval(id);
                }
            }
            var id = setInterval(adjust, 1000);
        },

        //replace link
        replace: function () {
            var list = $('a.cardlink');
            for (var i = 0; i < list.length; i++) {
                var link = $(list[i]),
                    href = link.attr('href'),
                    card = href.split('=').pop(),
                    newl = 'https://www.magickartenmarkt.de/?mainPage=showSearchResult&searchFor=' + card + '&v=card&s=cname&card=' + card + '&redirect=true&referrer=solygen';
                link.attr('href', newl);
            }

        },

        tab: function () {
            //TODO: own tab
            // var bar = $('.ui-tabs-nav'),
            //     tab = $(bar.children()[1]).clone(),
            //     tabcontent = $('#deck_tabs-spoiler').clone();
            // //set tab link
            // tab.find('a')
            //     .attr('href', '#deck_tabs-#ies')
            //     .text('Proxies (' + data.proxies.length +  ')');

            // $(tab.find('a'))
            //     .on('click', function () {
            //         $('.ui-tabs-panel').hide();
            //         $('#deck_tabs-proxies').show();
            //     });

            // //listener
            // var others = $('.ui-tabs-nav').find('a'),
            //     fn = function () {
            //             $('#deck_tabs-proxies').hide();
            //         };
            // for (var i = 0; i < others.length; i++) {
            //     var tmp = $(others[i]);
            //     if (tmp.attr('href') !== '#deck_tabs-proxies') {
            //         tmp.on('click', fn);
            //     }
            // }

            // //insert
            // tab.insertAfter($(bar.children()[1]));

            // tabcontent.attr('id', 'deck_tabs-proxies').find('.inhalt').empty();

            // //create tab content
            // $('#deck_tabs').append(tabcontent);
            //write proxie block
            if (data.proxies.length) {
                data.proxies.sort(function (a, b) {
                    return a.substr(2, 1).charCodeAt(0) - b.substr(2, 1).charCodeAt(0);
                });
                $('.custom').remove();
                var node = $($('div.ui-widget')[1]).clone();
                //set content
                $(node).empty()
                                    .append(data.proxies.join('
'));
                //remove title and add bottom margin
                node.attr('title', '')
                    .css('margin', '1em .5em');
                //prepend to main container
                $('.inhalt').prepend(node.addClass('custom'));
            }
        },

        process: function () {
            this.remove();
            this.set();
            this.register();
            this.replace();
            this.tab();
        }
    };

    var cards = {

        //update rarity
        rarity: function () {
            if (current.color === RARE) {
                data.rarity.rare.push(current.num + ' ' + current.name);
            }
            if (current.color === UNCOMMON) {
                data.rarity.uncommon.push(current.num + ' ' + current.name);
            }
            if (current.color === COMMON) {
                data.rarity.common.push(current.num + ' ' + current.name);
            }
            if (current.color === MYTHIC) {
                data.rarity.mythic.push(current.num + ' ' + current.name);
            }
            if (current.color === BASIC) {
                data.rarity.basic.push(current.num + ' ' + current.name);
            }
        },

        //reorder edition column
        reorder: function () {
            var cell = $($(current.row.find('.info_link'))[0]),
                span = cell.find('span').remove(),
                leg = cell.text().trim().replace('(', '').replace(')', '').trim();
            span.text(span.text().trim());
            cell.text(leg + ' (')
                .append(span)
                .append(')');
            //update rarity statistics
            this.rarity(span.css('color'), current.num, current.name);
        },

        //identify proxies
        identify: function () {
            var comment = current.comment;
            if (comment && (comment.length === 1 || comment === 'proxy')) {
                $(current.row.find('.deck_card_comment')[0])
                    .prop('src', 'http://i.hbtronix.de/picture_empty.png')
                    .css('height', '11px')
                    .css('width', '11px');

                if (comment.length === 1) {
                    data.proxies.push(comment + ' ' + current.name);
                } else {
                    data.proxies.push(current.num + ' ' + current.name);
                }
            }
        },

        //replace us price
        price: function () {
            $(current.row.find('.card_price')[1]).text(current.each + ' \u20AC');
        },

        process: function () {
            var rows = $('.cardtable').find('tr.deck_card');
            for (var i = 0; i < rows.length; i++) {
                var row = $(rows[i]);
                current = {
                    row: row,
                    price: $(row.find('.card_price')[0]).text().trim().replace('\u20AC', ''),
                    num: $(row.find('.card_amount')[0]).text().trim(),
                    name: $(row.find('a')[0]).text().trim(),
                    comment: $(row.find('.deck_card_comment')[0]).attr('title'),
                    color: $($(row.find('.info_link'))[0]).find('span').css('color')
                };
                current.each = (current.price / current.num).toFixed(2);

                this.price();
                this.identify();
                this.reorder();
            }
        }
    };

    return {
        run: function () {
            cards.process();
            page.process();
        }

    };
})().run();
<commit_msg>Update deck-view.user.js<commit_after>// ==UserScript==
// @name         deck view: different tweaks
// @description  deckstats.net
// @grant        none
// @version      1.0.5
// @icon         http://www.google.com/s2/favicons?domain=www.deckstats.net
// @namespace    https://github.com/solygen/userscripts
// @repository   https://github.com/solygen/userscripts.git
// @license      MIT
// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
//
// @include      http://deckstats.net/*
// @include      https://deckstats.net/*
//
// @updateURL    https://rawgithub.com/solygen/userscripts/master/scripts/deckstats.net/deck-view.user.js
// @downloadURL  https://rawgithub.com/solygen/userscripts/master/scripts/deckstats.net/deck-view.user.js
// @homepage     https://github.com/solygen/userscripts

// ==/UserScript==

(function () {

    'use strict';

    var $ = $ || jQuery,
        RARE = 'rgb(196, 159, 39)',
        UNCOMMON = 'rgb(119, 119, 119)',
        COMMON = 'rgb(0, 0, 0)',
        MYTHIC = 'rgb(132, 47, 7)',
        BASIC = 'rgb(4, 26, 72)',
        current = {},
        data = {
            proxies: [],
            rarity: {
                rare: [],
                uncommon: [],
                common: [],
                mythic: [],
                basic: []
            }
        };

    var page = {
        remove: function () {
            var table = $('.cardtable');
            //remove flag and sum
            $(table.find('.card_price.header')[1]).empty();
            $(table.find('.deck_footer').find('.card_price')[1]).empty();

        },

        set: function () {
            //set banner link to list view
            var listview = $($('ul#user_menu a')[0]).attr('href');
            if (listview) {
                $($('#header_left a')).attr('href', listview);
            }
        },

        //bigger card preview
        register: function () {
            function adjust() {
                $('#cardlink_overlay')
                    .css('border', '0px')
                    .css('width', 'auto');
                $('#cardlink_overlay_image')
                    .css('height', '380px')
                    .css('width', '266px');
                $('#cardlink_overlay_details')
                    .css('display', 'none');
                if ($('#kartenOverlay').length) {
                    clearInterval(id);
                }
            }
            var id = setInterval(adjust, 1000);
        },

        //replace link
        replace: function () {
            var list = $('a.cardlink');
            for (var i = 0; i < list.length; i++) {
                var link = $(list[i]),
                    href = link.attr('href'),
                    card = href.split('=').pop(),
                    newl = 'https://www.magickartenmarkt.de/?mainPage=showSearchResult&searchFor=' + card + '&v=card&s=cname&card=' + card + '&redirect=true&referrer=solygen';
                link.attr('href', newl);
            }

        },

        tab: function () {
            //TODO: own tab
            // var bar = $('.ui-tabs-nav'),
            //     tab = $(bar.children()[1]).clone(),
            //     tabcontent = $('#deck_tabs-spoiler').clone();
            // //set tab link
            // tab.find('a')
            //     .attr('href', '#deck_tabs-#ies')
            //     .text('Proxies (' + data.proxies.length +  ')');

            // $(tab.find('a'))
            //     .on('click', function () {
            //         $('.ui-tabs-panel').hide();
            //         $('#deck_tabs-proxies').show();
            //     });

            // //listener
            // var others = $('.ui-tabs-nav').find('a'),
            //     fn = function () {
            //             $('#deck_tabs-proxies').hide();
            //         };
            // for (var i = 0; i < others.length; i++) {
            //     var tmp = $(others[i]);
            //     if (tmp.attr('href') !== '#deck_tabs-proxies') {
            //         tmp.on('click', fn);
            //     }
            // }

            // //insert
            // tab.insertAfter($(bar.children()[1]));

            // tabcontent.attr('id', 'deck_tabs-proxies').find('.inhalt').empty();

            // //create tab content
            // $('#deck_tabs').append(tabcontent);
            //write proxie block
            if (data.proxies.length) {
                data.proxies.sort(function (a, b) {
                    return a.substr(2, 1).charCodeAt(0) - b.substr(2, 1).charCodeAt(0);
                });
                $('.custom').remove();
                var node = $($('div.ui-widget')[1]).clone();
                //set content
                $(node).empty()
                                    .append(data.proxies.join('
'));
                //remove title and add bottom margin
                node.attr('title', '')
                    .css('margin', '1em .5em');
                //prepend to main container
                $('.inhalt').prepend(node.addClass('custom'));
            }
        },

        process: function () {
            this.remove();
            this.set();
            this.register();
            //this.replace();
            //this.tab();
        }
    };

    var cards = {

        //update rarity
        rarity: function () {
            if (current.color === RARE) {
                data.rarity.rare.push(current.num + ' ' + current.name);
            }
            if (current.color === UNCOMMON) {
                data.rarity.uncommon.push(current.num + ' ' + current.name);
            }
            if (current.color === COMMON) {
                data.rarity.common.push(current.num + ' ' + current.name);
            }
            if (current.color === MYTHIC) {
                data.rarity.mythic.push(current.num + ' ' + current.name);
            }
            if (current.color === BASIC) {
                data.rarity.basic.push(current.num + ' ' + current.name);
            }
        },

        //reorder edition column
        reorder: function () {
            var cell = $($(current.row.find('.info_link'))[0]),
                span = cell.find('span').remove(),
                leg = cell.text().trim().replace('(', '').replace(')', '').trim();
            span.text(span.text().trim());
            cell.text(leg + ' (')
                .append(span)
                .append(')');
            //update rarity statistics
            this.rarity(span.css('color'), current.num, current.name);
        },

        //identify proxies
        identify: function () {
            var comment = current.comment;
            if (comment && (comment.length === 1 || comment === 'proxy')) {
                $(current.row.find('.deck_card_comment')[0])
                    .prop('src', 'http://i.hbtronix.de/picture_empty.png')
                    .css('height', '11px')
                    .css('width', '11px');

                if (comment.length === 1) {
                    data.proxies.push(comment + ' ' + current.name);
                } else {
                    data.proxies.push(current.num + ' ' + current.name);
                }
            }
        },

        //replace us price
        price: function () {
            $(current.row.find('.card_price')[1]).text(current.each + ' \u20AC');
        },

        process: function () {
            var rows = $('.cardtable').find('tr.deck_card');
            for (var i = 0; i < rows.length; i++) {
                var row = $(rows[i]);
                current = {
                    row: row,
                    price: $(row.find('.card_price')[0]).text().trim().replace('\u20AC', ''),
                    num: $(row.find('.card_amount')[0]).text().trim(),
                    name: $(row.find('a')[0]).text().trim(),
                    comment: $(row.find('.deck_card_comment')[0]).attr('title'),
                    color: $($(row.find('.info_link'))[0]).find('span').css('color')
                };
                current.each = (current.price / current.num).toFixed(2);

                this.price();
                this.identify();
                this.reorder();
            }
        }
    };

    return {
        run: function () {
            cards.process();
            page.process();
        }

    };
})().run();
<|endoftext|>