godo.util = {
    template: {
        cache: {},
        
        make: function(templateName, data, callback){
            var self = this;

            if (self.cache[templateName]){
                var html = self.render(self.cache[templateName], data);
                callback(html);
            } else {
                self.fetch(templateName, function(template){
                    var html = self.render(template, data);
                    callback(html);
                });
            }            
        },
        
        fetch: function(templateName, callback) {
            var self = this;
            
            // Check for override template in the DOM
            if ($("#" + templateName + "-template").length > 0) {
                self.cache[templateName] = $("#" + templateName + "-template").html(); 
                
                callback(self.cache[templateName]);                          
            } else {
                $.ajax({
                    //url: '/templates/' + templateName + ".template",
                	url: '/template/' + templateName,
                    jsonpCallback: +templateName+"Callback",
                    success: function(template){
                        self.cache[templateName] = template;   
                        callback(self.cache[templateName]);
                    },
                    dataType: "text"
                });
            }            
        },
        
        render: function(template, data){
            return $(Mustache.to_html(template, data));
        }
    },
    
    // Adds zeros to the start of a number to match given size
    padNumber: function(number, size) {
        number = number.toString();
        if (number.length < size) {
            number = "0" + number;
        }
        return number;
    },
    
    // Parse a javascript date to the same string format used by the API
    dateToString: function(date) {   
        return date.getFullYear() + "-" + godo.util.padNumber((date.getMonth() + 1), 2) + "-" + godo.util.padNumber(date.getDate(), 2);    
    },
    
    // Create a javascript date object from the API date string format
    stringToDate: function(dateStr) {
        dateStr = dateStr.replace(/-/g, "");
        var year = dateStr.substr(0,4);
        var month = dateStr.substr(4,2);
        var day = dateStr.substr(6,2);

        var newDate = new Date(year, month-1, day);
        return newDate;
    },
    
    
    pluralise: function(count, word, hideZero) {
        count = parseInt(count);
        return (count === 0 && hideZero ? '' : count + ' ' + word + (count === 1 ? '' : 's'));
    }
        
}
