/*
    NAME:    DisplayTemplate
    AUTHOR:  Jay Allen, Endevver Consulting, http://endevver.com
    URL:     https://trac.endevver.com/movabletype/wiki/code/displaytemplate
    DATE:    June 6, 2007
    VERSION: 1.0
    LICENSE: This code is licensed under the Artistic License

    SUMMARY:
    
        The DisplayTemplate object provides methods for merging variables
        into a template string.  The variables and the substrings they
        replace are represented by a Javascript object or a key/value pair
        array.  Replacement substrings are key identifiers surrounded by
        square brackets.  

        For details on usage, please see 
        https://trac.endevver.com/movabletype/wiki/code/displaytemplate

*/
function DisplayTemplate(template, params) {
    this.template = template
    this.params = params
    this.strict = 0          // Specifies strict mode
    this.nocase = undefined
    this.parsedString = ""
}

DisplayTemplate.prototype.toString = function() { return this.parsedString }

DisplayTemplate.prototype.eval = function() { 

    // Make sure that template and params are set
    if (this.template == undefined)
        throw new Error("DisplayTemplate template propertie not defined")
    if (this.params == undefined)
        throw new Error("Property 'params' not defined for DisplayTemplate: "+this.template)

    // Set options: Global plus optional case-insensitive flag
    var opts = "g"
    if (this.nocase == 1) opts = opts + "i";

    // Replace parameter keys with associate values
    var tmpl = this.template
    for (var name in this.params) {
        var str = name
        var replacement = this.params[str]

        if (this.strict && tmpl.indexOf("["+str+"]") < 0)
            throw new Error("Replacement key '"+str+"' not found in display template string under strict mode: "+this.template)

        var re = new RegExp("\\["+str+"\\]", opts)
        tmpl = tmpl.replace(re, replacement)
    }

    // Setting for internal toString() method
    this.parsedString = tmpl

    // Return evaluated template
    return this.parsedString
}
 