var initCloseOverlay = function () {
  $('.close_overlay').click(function(e) {
    $('#overlay').hide();
    $('#overlay_message').hide();
    e.preventDefault();
  });
}

// This is global because it can be re-sorted and re-displayed
var eventShiftsGlobal;
function getAllEventShifts(event_id) {
  var checked_shifts = $('#checked_shifts').val();
// Ajax call to get shift JSON data
  $.ajax({
    url: '/api/api.php?fn=getAllEventShifts&id=' + event_id + '&checked_shifts=' + checked_shifts,
    type: 'GET',
    async: false,
    cache: false,
    timeout: 30000,
    error: function(){
      return true;
    },
    success: function(data){
      if (data) {
// Convert to an object and save to global variable
        eventShiftsGlobal = jQuery.parseJSON(data);
      } else {
        eventShiftsGlobal = '';
      }
    }
  });
}

function displayAllEventShifts(sorted_by) {
// Set sort_by default if it was blank
  if (!sorted_by) var sorted_by = $('#sorted_by').val();
  if (!sorted_by) var sorted_by = 'start_date';

// Temp switch b/c I think eventShiftsGlobal.sort() doesn't like 'date' as a parameter
if (sorted_by == 'name') sorted_by = 'job_name';
if (sorted_by == 'date') sorted_by = 'start_date';

// Sort data
  sortEventShifts(sorted_by);
// Build html display
  shiftsHTML = createShiftsHTML(sorted_by);
// Set it on page
  if (shiftsHTML) { $('#shifts').html(shiftsHTML); }
  else { $('#shifts_header').css('display', 'none'); $('#additional_volunteers').css('display', 'none'); $('#shifts').html(''); }
// Apply events to new HTML
  applyShiftEvents();

}


function sortEventShifts(field) {
  if (field == 'start_date') eventShiftsGlobal.sort(sort_by(field, false, function(a){ return a.toLocaleString(); } ));
  if (field == 'job_name') eventShiftsGlobal.sort(sort_by(field, false, function(a){ return a; } ));
//  if (field == 'shift_id') eventShiftsGlobal.sort(sort_by(field, true, parseInt));
}

var sort_by = function(field, reverse, primer) {
  reverse = (reverse) ? -1 : 1;
  return function(a,b){
    a = a[field];
    b = b[field];

    if (typeof(primer) != 'undefined'){
      a = primer(a);
      b = primer(b);
    }
    if (a<b) return reverse * -1;
    if (a>b) return reverse * 1;
    return 0;
  }
}


function createShiftsHTML(sorted_by) {
// Variables

// eventShiftsGlobal elements:
// - job_id
// - job_name
// - shift_id
// - location_name
// - spots
// - start_date_time_array: year, month, day, hour, minute
// - end_date_time_array: year, month, day, hour, minute

//********************************
// ^^^^^ Sorted by JOB_NAME
  if (sorted_by == 'job_name') {
    var shiftsHTML = '';
    var shiftNameHTML;
    var shiftMonthDayHTML;
    var shiftDetailHTML;
    var i=0;
    var last_job_id;
    var last_start_month_day;
    var description;
    var location;
    var start_ampm = '';
    var end_ampm = '';
    var checked_style = '';
    var spots_label = '';
    $.each(eventShiftsGlobal, function() {

// Error check
      if (eventShiftsGlobal[i].shift_id == 1) return false;

// ^^^^^ Location HTML
      if (eventShiftsGlobal[i].location_name) location = eventShiftsGlobal[i].location_name;
      else location = '';

// ^^^^^ Start hour + AM/PM
      if (eventShiftsGlobal[i].start_date_time_array.hour == '00') { start_hour = '12'; start_ampm = 'am'; }
      else if (eventShiftsGlobal[i].start_date_time_array.hour < 12) { start_hour = parseFloat(eventShiftsGlobal[i].start_date_time_array.hour); start_ampm = 'am'; }
      else if (eventShiftsGlobal[i].start_date_time_array.hour == '12') { start_hour = '12'; start_ampm = 'pm'; }
      else { start_hour = eval(eventShiftsGlobal[i].start_date_time_array.hour) - 12; start_ampm = 'pm'; }
// ^^^^^ End hour + AM/PM
      if (eventShiftsGlobal[i].end_date_time_array.hour == '00') { end_hour = '12'; end_ampm = 'am'; }
      else if (eventShiftsGlobal[i].end_date_time_array.hour < 12) { end_hour = parseFloat(eventShiftsGlobal[i].end_date_time_array.hour); end_ampm = 'am'; }
      else if (eventShiftsGlobal[i].end_date_time_array.hour == '12') { end_hour = '12'; end_ampm = 'pm'; }
      else { end_hour = eval(eventShiftsGlobal[i].end_date_time_array.hour) - 12; end_ampm = 'pm'; }


// ^^^^^ Change of job
      if (last_job_id != eventShiftsGlobal[i].job_id) {
        if (eventShiftsGlobal[i].job_description) job_description = '<span class="job_description">view job description<span class="job_description_content">' + eventShiftsGlobal[i].job_description + '</span></span>';
        else job_description = '';
        shiftNameHTML = '<span class="job_sort_job_title">&nbsp;<span class="expand_collapse_icon">-</span>&nbsp;' + eventShiftsGlobal[i].job_name + '</span>' + job_description;
        last_start_month_day = '';
      } else {
        shiftNameHTML = '';
      }

// ^^^^^ Change of start_month + start_day, change of name also triggers this
      if (shiftNameHTML || last_start_month_day != eventShiftsGlobal[i].start_date_time_array.month + eventShiftsGlobal[i].start_date_time_array.day) {
        shiftMonthDayHTML = '<span class="job_sort_date_title">&nbsp;<span class="expand_collapse_icon">-</span>&nbsp;' + getDayName(eventShiftsGlobal[i].start_date_time_array.year, eventShiftsGlobal[i].start_date_time_array.month, eventShiftsGlobal[i].start_date_time_array.day) + ', ' + getMonthName(eventShiftsGlobal[i].start_date_time_array.month) + ' ' + parseFloat(eventShiftsGlobal[i].start_date_time_array.day) + getDaySuffix(eventShiftsGlobal[i].start_date_time_array.day) + '</span>';
      } else {
        shiftMonthDayHTML = '';
      }
// Color div if it is checked
      if (eventShiftsGlobal[i].checked) checked_style = 'style="background-color: rgb(255, 255, 255);"';
      else checked_style = '';

// SPOTS vs SPOT
      if (eventShiftsGlobal[i].spots == 1) spots_label = 'SPOT';
      else spots_label = 'SPOTS';

      shiftDetailHTML = '';
      shiftDetailHTML += '<div class="job_sort_shift_detail"' + checked_style + '>';
      shiftDetailHTML += '	<div class="job_sort_spots"><span class="job_sort_spots_number">' + eventShiftsGlobal[i].spots + '</span><br />' + spots_label + '<br />LEFT</div>';
      shiftDetailHTML += '	<div class="job_sort_checkbox"><input type="checkbox" class="shift_checkbox" id="shift_' + eventShiftsGlobal[i].shift_id + '" name="shift[]" value="' + eventShiftsGlobal[i].shift_id + '"' + eventShiftsGlobal[i].checked + ' /></div>';
      shiftDetailHTML += '	<div class="shift_detail_width">';
      shiftDetailHTML += '		<div class="job_sort_time"><label style="cursor: pointer;" for="shift_' + eventShiftsGlobal[i].shift_id + '">' + start_hour + ':' + eventShiftsGlobal[i].start_date_time_array.minute + start_ampm;
      if (start_hour + eventShiftsGlobal[i].start_date_time_array.minute + start_ampm != end_hour + eventShiftsGlobal[i].end_date_time_array.minute + end_ampm) shiftDetailHTML += ' to ' + end_hour + ':' + eventShiftsGlobal[i].end_date_time_array.minute + end_ampm;
      shiftDetailHTML += '</label></div>';
      shiftDetailHTML += '		<div class="job_sort_location">' + location + '</div>';
      shiftDetailHTML += '	</div>';

      shiftDetailHTML += '	<div style="clear: both;"></div>';
      shiftDetailHTML += '</div>';


// ^^^^^ Put it all together
      if (shiftNameHTML) {
// ^^^^^ Name changes:: Close: Last MonthDay Shift, Last MonthDay Item, All MonthDays Items (for this job), close Last Job :: Open new Job
        shiftsHTML += '	</div></div></div></div>\n<div class="job_sort_top">' + shiftNameHTML + '	<div class="job_sort_name_monthdays">\n		<div class="job_sort_monthday">' + shiftMonthDayHTML + '\n			<div class="job_sort_monthday_shifts">' + shiftDetailHTML;
      } else {
        if (shiftMonthDayHTML) {
// ^^^^^ MonthDay changes:: Close: Last MonthDay Shift, Last MonthDay Item :: Open new MonthDay Item
          shiftsHTML += '</div></div>\n		<div class="job_sort_monthday">' + shiftMonthDayHTML + '\n			<div class="job_sort_monthday_shifts">' + shiftDetailHTML;
        } else {
// ^^^^^ New shift
          shiftsHTML += shiftDetailHTML;
        }
      }


      last_job_id = eventShiftsGlobal[i].job_id;
      last_start_month_day = eventShiftsGlobal[i].start_date_time_array.month + eventShiftsGlobal[i].start_date_time_array.day;
      i++;
    });

//********************************
// ##### Sorted by START_DATE
  } else if (sorted_by == 'start_date') {
    var shiftsHTML = '';
    var shiftMonthDayHTML;
    var shiftStartTimeHTML;
    var shiftDetailHTML;
    var i=0;
    var last_start_month_day;
    var last_start_hour_minute;
    var location;
    var start_ampm = '';
    var end_ampm = '';
    var checked_style = '';
    var spots_label = '';

    $.each(eventShiftsGlobal, function() {

// Error check
      if (eventShiftsGlobal[i].shift_id == 1) return false;

// ##### Location HTML
      if (eventShiftsGlobal[i].location_name) location = eventShiftsGlobal[i].location_name;
      else location = '';

// ##### Start hour + AM/PM
      if (eventShiftsGlobal[i].start_date_time_array.hour == '00') { start_hour = '12'; start_ampm = 'am'; }
      else if (eventShiftsGlobal[i].start_date_time_array.hour < 12) { start_hour = parseFloat(eventShiftsGlobal[i].start_date_time_array.hour); start_ampm = 'am'; }
      else if (eventShiftsGlobal[i].start_date_time_array.hour == '12') { start_hour = '12'; start_ampm = 'pm'; }
      else { start_hour = eval(eventShiftsGlobal[i].start_date_time_array.hour) - 12; start_ampm = 'pm'; }
// ##### End hour + AM/PM
      if (eventShiftsGlobal[i].end_date_time_array.hour == '00') { end_hour = '12'; end_ampm = 'am'; }
      else if (eventShiftsGlobal[i].end_date_time_array.hour < 12) { end_hour = parseFloat(eventShiftsGlobal[i].end_date_time_array.hour); end_ampm = 'am'; }
      else if (eventShiftsGlobal[i].end_date_time_array.hour == '12') { end_hour = '12'; end_ampm = 'pm'; }
      else { end_hour = eval(eventShiftsGlobal[i].end_date_time_array.hour) - 12; end_ampm = 'pm'; }


// ##### Change of start_month + start_day
      if (last_start_month_day != eventShiftsGlobal[i].start_date_time_array.month + eventShiftsGlobal[i].start_date_time_array.day) {
        shiftMonthDayHTML = '<span class="date_sort_date_title">&nbsp;<span class="expand_collapse_icon">-</span>&nbsp;' + getDayName(eventShiftsGlobal[i].start_date_time_array.year, eventShiftsGlobal[i].start_date_time_array.month, eventShiftsGlobal[i].start_date_time_array.day) + ', ' + getMonthName(eventShiftsGlobal[i].start_date_time_array.month) + ' ' + parseFloat(eventShiftsGlobal[i].start_date_time_array.day) + getDaySuffix(eventShiftsGlobal[i].start_date_time_array.day) + '</span>';
        last_start_hour_minute = '';
      } else {
        shiftMonthDayHTML = '';
      }

// ##### Change of start_hour + start_minute, change of month_day also triggers this
      if (shiftMonthDayHTML || last_start_hour_minute != eventShiftsGlobal[i].start_date_time_array.hour + eventShiftsGlobal[i].start_date_time_array.minute) {
        shiftStartTimeHTML = '<span class="date_sort_time_title">&nbsp;<span class="expand_collapse_icon">-</span>&nbsp;Starting ' + start_hour + ':' + eventShiftsGlobal[i].start_date_time_array.minute + start_ampm + '</span>';
      } else {
        shiftStartTimeHTML = '';
      }

      if (eventShiftsGlobal[i].job_description) job_description = '<span class="job_description">view job description<span class="job_description_content">' + eventShiftsGlobal[i].job_description + '</span></span>';
      else job_description = '';

// Color div if it is checked
      if (eventShiftsGlobal[i].checked) checked_style = 'style="background-color: rgb(255, 255, 255);"';
      else checked_style = '';

// SPOTS vs SPOT
      if (eventShiftsGlobal[i].spots == 1) spots_label = 'SPOT';
      else spots_label = 'SPOTS';

      shiftDetailHTML = '';
      shiftDetailHTML += '<div class="date_sort_shift_detail"' + checked_style +'>';
      shiftDetailHTML += '	<div class="date_sort_spots"><span class="date_sort_spots_number">' + eventShiftsGlobal[i].spots + '</span><br />' + spots_label + '<br />LEFT</div>';
      shiftDetailHTML += '	<div class="date_sort_checkbox"><input type="checkbox" class="shift_checkbox" id="shift_' + eventShiftsGlobal[i].shift_id + '" name="shift[]" value="' + eventShiftsGlobal[i].shift_id + '"' + eventShiftsGlobal[i].checked + ' /></div>';
      shiftDetailHTML += '	<div class="shift_detail_width">';
      shiftDetailHTML += '		<div class="date_sort_time"><label style="cursor: pointer;" for="shift_' + eventShiftsGlobal[i].shift_id + '">' + eventShiftsGlobal[i].job_name + '</label>' + job_description + '<br />' + start_hour + ':' + eventShiftsGlobal[i].start_date_time_array.minute + start_ampm;
      if (start_hour + eventShiftsGlobal[i].start_date_time_array.minute + start_ampm != end_hour + eventShiftsGlobal[i].end_date_time_array.minute + end_ampm) shiftDetailHTML += ' to ' + end_hour + ':' + eventShiftsGlobal[i].end_date_time_array.minute + end_ampm;
      shiftDetailHTML += '</div>';
      shiftDetailHTML += '		<div class="date_sort_location">' + location + '</div>';
      shiftDetailHTML += '	</div>';

      shiftDetailHTML += '	<div style="clear: both;"></div>';
      shiftDetailHTML += '</div>';

// ##### Put it all together
      if (shiftMonthDayHTML) {
// ##### Name changes:: Close: Last Job Shift, Last Time Item, All Time Items (for the MonthDay), Last MonthDay :: Open new MonthDay
        shiftsHTML += '	</div></div></div></div>\n<div class="date_sort_top">' + shiftMonthDayHTML + '	<div class="date_sort_date_times">\n		<div class="date_sort_start_time">' + shiftStartTimeHTML + '\n			<div class="date_sort_time_shifts">' + shiftDetailHTML;
      } else {
        if (shiftStartTimeHTML) {
// ##### Time changes:: Close: Last Job Shift, Last Time Item :: Open new Time Item
          shiftsHTML += '</div></div>\n		<div class="date_sort_start_time">' + shiftStartTimeHTML + '\n			<div class="date_sort_time_shifts">' + shiftDetailHTML;
        } else {
// ##### New shift
          shiftsHTML += shiftDetailHTML;
        }
      }


      last_start_month_day = eventShiftsGlobal[i].start_date_time_array.month + eventShiftsGlobal[i].start_date_time_array.day;
      last_start_hour_minute = eventShiftsGlobal[i].start_date_time_array.hour + eventShiftsGlobal[i].start_date_time_array.minute;
      i++;
    });
  } else {
    shiftsHTML = '';
  }

// Wrap result in 4 DIV's because the loop function doesn't accommodate for the opening of the first item nor closing of the last; both sort methods use 4 DIV's per 'item'  
  if (shiftsHTML) shiftsHTML = '<div><div><div><div>' + shiftsHTML + '</div></div></div></div>';

// Return the HTML
  return shiftsHTML;
}


function applyShiftEvents() {

// Overlay shows job description
  $('.job_description').click(function(e) {
    $('#overlay').show();
//    $('#overlay_message').offset({ top: e.pageY, left: e.pageX })
//    $('#overlay_message').css('left', e.pageX);
    $('#overlay_message').css('top', e.pageY + 25);
    $('#overlay_message').html('<div class="close_overlay">[x] Close</div>' + $(this).children('.job_description_content').html());
    $('#overlay_message').show();
    initCloseOverlay();
  });

// Change shift background when clicked
  $('.job_sort_shift_detail, .date_sort_shift_detail').click(function() {
    if ($(this).children().children('.shift_checkbox').is(':checked')) { $(this).css('background-color', '#FFFFFF'); } //isFirstCheckbox();
    else { $(this).css('background-color', ''); }
  });

// Sorted by job
  $('.job_sort_job_title').click(function() {
    if ($(this).parent().children('.job_sort_name_monthdays').css('display') == 'block') {
      $(this).children('.expand_collapse_icon').html('+');
      $(this).parent().children('.job_sort_name_monthdays').slideUp('slow');
    } else {
      $(this).children('.expand_collapse_icon').html('-');
      $(this).parent().children('.job_sort_name_monthdays').slideDown('slow');
    }
  });

  $('.job_sort_date_title').click(function() {
    if ($(this).parent().children('.job_sort_monthday_shifts').css('display') == 'block') {
      $(this).children('.expand_collapse_icon').html('+');
      $(this).parent().children('.job_sort_monthday_shifts').slideUp('slow');
    } else {
      $(this).children('.expand_collapse_icon').html('-');
      $(this).parent().children('.job_sort_monthday_shifts').slideDown('slow');
    }
  });

// Sorted by date
  $('.date_sort_date_title').click(function() {
    if ($(this).parent().children('.date_sort_date_times').css('display') == 'block') {
      $(this).children('.expand_collapse_icon').html('+');
      $(this).parent().children('.date_sort_date_times').slideUp('slow');
    } else {
      $(this).children('.expand_collapse_icon').html('-');
      $(this).parent().children('.date_sort_date_times').slideDown('slow');
    }
  });

  $('.date_sort_time_title').click(function() {
    if ($(this).parent().children('.date_sort_time_shifts').css('display') == 'block') {
      $(this).children('.expand_collapse_icon').html('+');
      $(this).parent().children('.date_sort_time_shifts').slideUp('slow');
    } else {
      $(this).children('.expand_collapse_icon').html('-');
      $(this).parent().children('.date_sort_time_shifts').slideDown('slow');
    }
  });
}

/*
var is_first_checkbox;
function isFirstCheckbox() {
  if (!is_first_checkbox && $('#notification_message').html() == '') {
    $('#notification_message').html('<b>When you are finished choosing shifts, scroll to the bottom of the page</b>');
    $('#notification').slideDown('slow').delay(3000).slideUp('fast');
    is_first_checkbox = 1;
  }
}
*/

function getMonthName(month) {
  var month = parseFloat(month);
  switch (month) {
    case 1: result = 'January'; break;
    case 2: result = 'February'; break;
    case 3: result = 'March'; break;
    case 4: result = 'April'; break;
    case 5: result = 'May'; break;
    case 6: result = 'June'; break;
    case 7: result = 'July'; break;
    case 8: result = 'August'; break;
    case 9: result = 'September'; break;
    case 10: result = 'October'; break;
    case 11: result = 'November'; break;
    case 12: result = 'December'; break;
    default: result = '';
  }
  return result;
}

function getDayName(year, month, day) {
  var date = new Date(year, month - 1, day);
  switch (date.getDay()) {
    case 0: result = 'Sunday'; break;
    case 1: result = 'Monday'; break;
    case 2: result = 'Tuesday'; break;
    case 3: result = 'Wednesday'; break;
    case 4: result = 'Thursday'; break;
    case 5: result = 'Friday'; break;
    case 6: result = 'Saturday'; break;
    default: result = '';
  }
  return result;
}

function getDaySuffix(day) {
  if (!day) return;
  if (day.charAt(0) == 1) day = 4; // teens
  else if (day.length > 1) day = day.substring(1); // 20's and 30's, cut first character
  switch (day) {
    case '1': result = 'st'; break;
    case '2': result = 'nd'; break;
    case '3': result = 'rd'; break;
    default: result = 'th';
  }
  return result;
}
