Skip to content

Instantly share code, notes, and snippets.

@xtai
Last active Jul 1, 2016
Embed
What would you like to do?
/**
This script is used by hours daily and weekly view
https://issues.umd.edu/browse/LIBWEB-3255
@Author: Xiaoyu Tai
*/
var current_branch, current_date; // used by daily and weekly view
var highlight = true; // weekly view highlight option
// actions are triggered from the page
function setNewDate(date_str) {
highlight = true;
setWindowHash(current_branch, date_str);
}
// actions are triggered from the weekly page only
function setWeek(offset) {
var date_obj = new Date(current_date);
date_obj.setDate(date_obj.getDate() + 7 * offset);
setNewDate(date_obj.toISOString().slice(0, 10));
highlight = false;
}
function setWindowHash(branch_str, date_str) {
date_str = validateDateStr(date_str);
branch_str = validateBranchStr(branch_str);
window.location.hash = '#branch=' + branch_str + '&date=' + date_str;
}
function updateDaily() {
var hash_str = window.location.hash.substr(1);
var new_date_str = validateDateStr(hashParser(hash_str).date);
current_branch = validateBranchStr(hashParser(hash_str).branch);
if (new_date_str !== current_date) {
fetchData(new_date_str, current_branch, 'daily');
}
updateDailyHighlight()
}
function updateWeekly() {
var hash_str = window.location.hash.substr(1);
var new_date_str = validateDateStr(hashParser(hash_str).date);
current_branch = validateBranchStr(hashParser(hash_str).branch);
if (current_branch === '')
current_branch = 'mckeldin';
fetchData(new_date_str, current_branch, 'weekly');
}
// Fetch Hours info AJAX-ly
function fetchData(date_str, branch_str, option) {
$.ajax({
type: 'POST',
url: component_rendering_URL + '?date=' + date_str + '&branch=' + branch_str,
dataType: 'html',
success: function(data) {
current_date = date_str;
if (option === 'daily') {
updateDailyDOM(data);
} else if (option === 'weekly') {
updateWeeklyDOM(data);
}
},
error: function() {
alert('Sorry, hours data loading error; please refresh.');
}
});
}
// Update hours daily page content, with new link refers
function updateDailyDOM(data){
updateBothHoursDOM(data);
updateDailyHighlight();
}
// Update hours weekly page content, with new link refers
function updateWeeklyDOM(data) {
updateBothHoursDOM(data);
// Remove highlight in weekly view if user broswing weeks
if (!highlight)
$('.hours-highlight-clone').removeClass('hours-highlight-clone');
// Update weekly dropdown links
$('.hours-weekly-dropdown a').each(function() {
var link_str = $(this).prop('href');
link_str = link_str.replace(/(?!#.*)date=.*/, 'date=' + current_date);
$(this).prop('href', link_str);
});
// Update new date to weekly content
var date_obj = new Date(current_date);
date_obj.setDate(date_obj.getDate() - date_obj.getDay());
var days = [date_obj];
for (var i = 0; i < 7; i++) {
$('#weekly-day' + i).text(generateAbbrDate(days[i]));
var d = new Date(days[i]);
d.setDate(d.getDate() + 1);
days.push(d);
}
var title = generateFullDate(days[0]) + ' - ' + generateFullDate(days[6]);
$('#currentWeek').text(title);
// Update weekly heading for new branch
var weekly_header2_html = '<a href=\"' + branch_name_map[current_branch][1] + '\">' + branch_name_map[current_branch][0] + '</a>';
$('#hours-weekly-header-2').html(weekly_header2_html);
$('.hours-weekly-dropdown').removeClass('active');
$('#hours-weekly-dropdown-' + current_branch).addClass('active');
}
function updateBothHoursDOM(data) {
// Apply Ajax content
$('#dateTimeCarousel').html($(data).find('#dateTimeCarousel').html());
// Update hash date to all links
$('.hours-list-link.internal-link').each(function() {
var link_str = $(this).prop('href');
link_str = link_str.replace(/(?!#.*)date=.*/, 'date=' + current_date);
$(this).prop('href', link_str);
});
// Update datetimepicker choice
var date_obj = new Date(current_date);
date_obj.setDate(date_obj.getDate() + 1);
$('.hours-datepicker').datepicker('setDate', date_obj);
}
// Update branch highlighting on daily page
function updateDailyHighlight(){
$('.hours-list-link').removeClass('hidden');
$('.hours-highlight-clone').remove();
if (current_branch !== '') {
$('#lib-' + current_branch).addClass('hidden');
$('.hours-selected').after($('#lib-' + current_branch).clone().addClass('hours-highlight-clone').removeClass('hidden'));
}
}
// date object -> string: e.g. July 1, 2016
function generateFullDate(date_obj) {
var month_full = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return month_full[date_obj.getMonth()] + ' ' + date_obj.getDate() + ', ' + date_obj.getFullYear();
}
// date object -> abbreviation string: e.g. Fri, Jul 1
function generateAbbrDate(date_obj) {
var month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var days_abbr = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
return days_abbr[date_obj.getDay()] + ', ' + month_abbr[date_obj.getMonth()] + ' ' + date_obj.getDate();
}
// validate date string with "yyyy-mm-dd" or "yyyy-m-d" -> bool
function isDateStrValid(date_str) {
if (!/^\d{4}-\d{1,2}-\d{1,2}$/.test(date_str))
return false;
var parts = date_str.split('-');
var year = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var day = parseInt(parts[2], 10);
// http://ter.ps/bue
if (year < 1856 || year > 2500 || month === 0 || month > 12)
return false;
var month_length = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0))
month_length[1] = 29;
return (day > 0 && day <= month_length[month - 1]);
}
// validate date string -> vaild date string or today's date string
function validateDateStr(date_str) {
if (typeof date_str === 'undefined' || !isDateStrValid(date_str))
return (new Date()).toISOString().slice(0, 10);
return date_str;
}
// validate branch string -> vaild branch string or ''
function validateBranchStr(branch_str) {
var branch_names = ['architecture', 'art', 'chemistry', 'epsl', 'lms', 'mckeldin', 'mspal', 'special'];
if (typeof branch_str === 'undefined' || branch_names.indexOf(branch_str.toLowerCase()) === -1)
return '';
return branch_str.toLowerCase();
}
// Parser the location.hash query -> JS map
function hashParser(hash_str) {
if (hash_str.length < 1)
return {};
var variable_str = hash_str.split('&');
var variables = {};
for (var i = 0; i < variable_str.length; i++) {
var pair = variable_str[i].split('=');
variables[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return variables;
}
// Initialize datetimepicker
function initDatepicker(){
$('.hours-datepicker').datepicker({
prevText: '<i class="fa fa-angle-left"></i>',
nextText: '<i class="fa fa-angle-right"></i>',
dateFormat: 'yy-mm-dd',
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(selected_date) {
setNewDate(selected_date);
}
});
}
function setNewDate(e){highlight=!0,setWindowHash(current_branch,e)}function setWeek(e){var t=new Date(current_date);t.setDate(t.getDate()+7*e),setNewDate(t.toISOString().slice(0,10)),highlight=!1}function setWindowHash(e,t){t=validateDateStr(t),e=validateBranchStr(e),window.location.hash="#branch="+e+"&date="+t}function updateDaily(){var e=window.location.hash.substr(1),t=validateDateStr(hashParser(e).date);current_branch=validateBranchStr(hashParser(e).branch),t!==current_date&&fetchData(t,current_branch,"daily"),updateDailyHighlight()}function updateWeekly(){var e=window.location.hash.substr(1),t=validateDateStr(hashParser(e).date);current_branch=validateBranchStr(hashParser(e).branch),""===current_branch&&(current_branch="mckeldin"),fetchData(t,current_branch,"weekly")}function fetchData(e,t,a){$.ajax({type:"POST",url:component_rendering_URL+"?date="+e+"&branch="+t,dataType:"html",success:function(t){current_date=e,"daily"===a?updateDailyDOM(t):"weekly"===a&&updateWeeklyDOM(t)},error:function(){alert("Sorry, hours data loading error; please refresh.")}})}function updateDailyDOM(e){updateBothHoursDOM(e),updateDailyHighlight()}function updateWeeklyDOM(e){updateBothHoursDOM(e),highlight||$(".hours-highlight-clone").removeClass("hours-highlight-clone"),$(".hours-weekly-dropdown a").each(function(){var e=$(this).prop("href");e=e.replace(/(?!#.*)date=.*/,"date="+current_date),$(this).prop("href",e)});var t=new Date(current_date);t.setDate(t.getDate()-t.getDay());for(var a=[t],r=0;7>r;r++){$("#weekly-day"+r).text(generateAbbrDate(a[r]));var n=new Date(a[r]);n.setDate(n.getDate()+1),a.push(n)}var h=generateFullDate(a[0])+" - "+generateFullDate(a[6]);$("#currentWeek").text(h);var i='<a href="'+branch_name_map[current_branch][1]+'">'+branch_name_map[current_branch][0]+"</a>";$("#hours-weekly-header-2").html(i),$(".hours-weekly-dropdown").removeClass("active"),$("#hours-weekly-dropdown-"+current_branch).addClass("active")}function updateBothHoursDOM(e){$("#dateTimeCarousel").html($(e).find("#dateTimeCarousel").html()),$(".hours-list-link.internal-link").each(function(){var e=$(this).prop("href");e=e.replace(/(?!#.*)date=.*/,"date="+current_date),$(this).prop("href",e)});var t=new Date(current_date);t.setDate(t.getDate()+1),$(".hours-datepicker").datepicker("setDate",t)}function updateDailyHighlight(){$(".hours-list-link").removeClass("hidden"),$(".hours-highlight-clone").remove(),""!==current_branch&&($("#lib-"+current_branch).addClass("hidden"),$(".hours-selected").after($("#lib-"+current_branch).clone().addClass("hours-highlight-clone").removeClass("hidden")))}function generateFullDate(e){var t=["January","February","March","April","May","June","July","August","September","October","November","December"];return t[e.getMonth()]+" "+e.getDate()+", "+e.getFullYear()}function generateAbbrDate(e){var t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return a[e.getDay()]+", "+t[e.getMonth()]+" "+e.getDate()}function isDateStrValid(e){if(!/^\d{4}-\d{1,2}-\d{1,2}$/.test(e))return!1;var t=e.split("-"),a=parseInt(t[0],10),r=parseInt(t[1],10),n=parseInt(t[2],10);if(1856>a||a>2500||0===r||r>12)return!1;var h=[31,28,31,30,31,30,31,31,30,31,30,31];return(a%400===0||a%100!==0&&a%4===0)&&(h[1]=29),n>0&&n<=h[r-1]}function validateDateStr(e){return"undefined"!=typeof e&&isDateStrValid(e)?e:(new Date).toISOString().slice(0,10)}function validateBranchStr(e){var t=["architecture","art","chemistry","epsl","lms","mckeldin","mspal","special"];return"undefined"==typeof e||-1===t.indexOf(e.toLowerCase())?"":e.toLowerCase()}function hashParser(e){if(e.length<1)return{};for(var t=e.split("&"),a={},r=0;r<t.length;r++){var n=t[r].split("=");a[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return a}function initDatepicker(){$(".hours-datepicker").datepicker({prevText:'<i class="fa fa-angle-left"></i>',nextText:'<i class="fa fa-angle-right"></i>',dateFormat:"yy-mm-dd",showOtherMonths:!0,selectOtherMonths:!0,onSelect:function(e){setNewDate(e)}})}var current_branch,current_date,highlight=!0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment