//##############################################################################
// Library: Bulletins
// Dependencies: jquery 1.4+
//##############################################################################

Bulletins = function() {
	//##########################################################################
    // Private vars
    //##########################################################################

    // vars to initialize
    var uploader = '';

    // Contants
	var CONFIG = {
		listId: '#bulletins_list',
		fileLinkUrl: '<a href="http://parkdalegrace.ca/bulletin/files/{file}">download PDF</a>',
		activeText: 'Active',
		inactiveText: 'Inactive',
        jsonUrl: 'http://parkdalegrace.ca/bulletin/json.php'
	};
	
	var LIST = {
            template: '<li class="file_list"><ul><li class="file_date">{date}</li><li class="file_link">{link}</li></ul></li>',
            // class names
            LI: {
                parent: 'file_list',
                date: 'file_date',
                fileLink: 'file_link'
            }
	};
	
	// private functions

    // trigger and update
    function triggerUpdate(){$('body').trigger(EVENTS.listModified)}

    // formats strings
	function format(string, data) {
        $.each(data, function(key, value) {
            var pattern = new RegExp('{' + key + '}', 'g');
            string = string.replace(pattern, value);
        });
        return string;
    }

	// clone list item
	function cloneItem(item) {
        if (item.active != 1) return false;
        var fileLink = format(CONFIG.fileLinkUrl, {file: item.file});
		listItem = format(LIST.template, {
			id: item.id,
			date: item.datename,
			link: fileLink
		});

		return $(listItem).data({
                    id:item.id,
                    active: item.active,
                    date: item.date,
                    file: item.file
               });
	}
	
	// grab the json and build the list
	function buildList() {
		$.getJSON(CONFIG.jsonUrl, function(json) {
			$(CONFIG.listId).empty();
			$.each(json, function(i,item){
				$(CONFIG.listId).append(cloneItem(item));
			});
		});
	}
	
	
	
	// public
	return {
		initialize: function () {
			buildList();
		}
	}
}();

$(document).ready(Bulletins.initialize);