function unique(a) {
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++) {
      for(var x = i + 1 ; x < n; x++)
      {
         if(a[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
}

jQuery(function() {
	jQuery.getJSON('/__bang_schedule.json', function(response) {
		var schedule = response;
		
		var $tbody = jQuery('#bang-calendar tbody');
		
		var timeStarts = [];
		
		jQuery.each(schedule, function(day) {
			jQuery.each(this, function() {
				timeStarts.push(this.time_start);
			});
		});
		
		timeStarts = unique(timeStarts);
		
		var timeFormatter = function(t) {
			var isPM = (t.toLowerCase().indexOf('p') !== -1);
			
			t = t.replace(':', '.');
			t = parseFloat(t);
			
			if (isPM) {
				if (parseInt(t) !== 12) {
					t += 12;
				}
			}
			
			return t;
		};
		
		timeStarts.sort(function(a, b) {
			return timeFormatter(a) > timeFormatter(b);
		});
		
		jQuery.each(timeStarts, function() {
			var timeStart = this;
			var id = md5(timeStart);
			
			var timeStartFormatted = timeStart.replace(/(pm|am)/i, ' $1').toUpperCase();
			
			$tbody.append('<tr id="' + id + '">\
					<td class="time">' + timeStartFormatted + '</td>\
					<td class="mon">&nbsp;</td>\
					<td class="tue">&nbsp;</td>\
					<td class="wed">&nbsp;</td>\
					<td class="thurs">&nbsp;</td>\
					<td class="fri">&nbsp;</td>\
					<td class="sat">&nbsp;</td>\
					<td class="sun">&nbsp;</td>\
				</tr>');
		});
		
		jQuery.each(schedule, function(day) {
			jQuery.each(this, function() {
				var rowid = md5(this.time_start);
				
				var $row = jQuery('#' + rowid);
				var $col = $row.find('td.' + day);
				
				this.title = this.title || '&nbsp;';
				
				$col.html(this.title);
			});
		});
	});
});
