/**
 * Load archive listings from external files.
 * Display date picker to select archives.
 * 
 * Archives are stored in /archive/<year>/ folder
 * 
 * @author bsawert
 */


// default date range - will be updated by code
var firstDate = new Date('01/01/2009');
var lastDate = new Date('12/31/2012');
var yearRange = '';

var archivePath = '/archive';
var loadedYear = '';

var yearPattern = '^20\\d{2}';
var datePattern = '\\d{8}[a-z]?\\';
var dateFormat = 'yymmdd';
var displayFormat = 'MM d, yy';

var archives = {
	'bulletins': {'files': [], 'matchPattern': 'Bulletin' + datePattern + '.pdf', 'labelText': 'Bulletin'},
	'sermons': {'files': [], 'matchPattern': 'Sermon' + datePattern + '.pdf', 'labelText': 'Sermon Text'},
	'audio': {'files': [], 'matchPattern': 'Sermon' + datePattern + '.mp3', 'labelText': 'Sermon Audio'}
 };


// set min and max date from archive directories
var setDateRange = function(archivePath) {
	var fullPath = archivePath;
	var years = [];
   
    var req = $.get(fullPath, function(data) {
    	// get list of links
        var links = $(data).find('a');
        
    	// extract the year entries
	    var pattern=RegExp(yearPattern);
        links.each(function() {
        	// extract year from link
			var href = $(this).attr('href');
			var year = pattern.exec(href);
			
            if (year != null) {
            	// store file name into archive list
                years.push(year);
            }
		});		
	});
	
	if (years.length > 0) {
		// array is already sorted - use first and last entries
		firstDate = new Date('01/01/' + years[0]);
		lastDate = new Date('12/31/' + years[years.length - 1]);
		yearRange = years[0] + ':' + years[years.length - 1];
	}
}


// load archives using AJAX call
var loadArchive = function(archivePath, archiveYear) {
	var fullPath = archivePath + '/' + archiveYear;
   
    var req = $.get(fullPath, function(data) {
    	// get list of links
        var links = $(data).find('a');
        
        // for each archive type
        $.each(archives, function(section, archive) {
        	archive.files = [];
        	
        	// match each linked file against the archive pattern
		    var pattern=RegExp(archive.matchPattern);
	        links.each(function() {
	        	// extract file name from link
	            var parts = $(this).attr('href').split('/');
				var href = parts.pop();
				
	            if (pattern.test(href)) {
	            	// store file name into archive list
	                archive.files.push(href);
	            }
			});
        });         
    });
    
    loadedYear = archiveYear;
}


// get a list of matching archive files for a date and file type
var getFilesForDate = function(date, archive) {
	var dateFiles = [];
	var dateStr = $.datepicker.formatDate(dateFormat, date);
	
	$.each(archive.files, function(index, fname) {
    	// search for date string in file name
    	if (fname.indexOf(dateStr) != -1) {
    		// found a matching file
    		dateFiles.push(fname);
    	}
    });

	return dateFiles;
}


// query whether archives exist for a specific date 
var hasArchives = function(date) {
	var exist = false;

	$.each(archives, function(section, archive) {
		if (getFilesForDate(date, archive).length > 0) {
			exist = true;
			// break each() loop
			return false;
		}
	});
	
	return exist;
}


// get archive link text for this date
var getLinkText = function(date, archive) {
	var text = '';
	var dateFiles = getFilesForDate(date, archive);
	var year = date.getFullYear();
	
	if (dateFiles.length > 0) {
		// build link text for matching files
		$.each(dateFiles, function(index, fname) {
			// extract file type from file name
			var ftype = fname.substr(fname.lastIndexOf('.') + 1).toUpperCase();
	    	text = text.concat('<a href="', archivePath, '/', year, '/', fname, '" title="', fname, '">', archive.labelText, '</a> (', ftype, ')<br />');
	    });
	}
	else {
		// no matching files - build default message
    	text = text.concat('No ', archive.labelText.toLowerCase(), ' available');
	}
	
    return text;
}


// callback for datepicker onChangeMonthYear
var onChangeMonthYearHandler = function(year, month, inst) {
	// if this is not the currently loaded year, load archives
	if (year != loadedYear) {
		loadArchive(archivePath, year);
	}

	// clear heading and section text
	$("#heading").hide();
	
	$.each(archives, function(section, archive) {
		$('#' + section).html('');
	});
}


// callback for datepicker beforeShowDay
var beforeShowDayHandler = function(date) {
	var selectable = hasArchives(date);
	var style = (selectable) ? 'ui-state-hover' : '';
	
	return [selectable, style];
}


// callback for datepicker onSelect
var onSelectHandler = function(dateText, inst) {
    var selectDate = $(this).datepicker('getDate');
    var displayDateStr = $('#formattedDate').val();
	
	$("#displayDate").text(displayDateStr);
	$("#heading").show();
	
	$.each(archives, function(section, archive) {
		var linkText = getLinkText(selectDate, archive);
		$('#' + section).html(linkText);
	});

	return;
}


$(document).ready(function() {
    $.ajaxSetup({ async: false });
	
    // set min and max dates for calendar
    setDateRange(archivePath);
	
	// get the current year and preload archive
    year = new Date().getFullYear();
    loadArchive(archivePath, year);
    		
    $('#datepicker').css('font-size', '70%');
    $("#datepicker").datepicker({
    	minDate: firstDate,
    	maxDate: lastDate,
        altField: '#formattedDate',
        altFormat: displayFormat,
        changeYear: true,
        yearRange : yearRange,
        onChangeMonthYear: onChangeMonthYearHandler,
        beforeShowDay: beforeShowDayHandler,
        onSelect: onSelectHandler
    });
});

