/**
* @author Gonzalo Lamatta C.
* 
* Requiere: prototype.js (o protoculous-packer.js)
*/

/**
* fileCache almacena los contenidos de los archivos que ya fueron 
* llamados (si la opción de noCaching es distinta de "true").
*/
var fileCache = new Hash();

function getFileContent(fileUrl, isTemplate, encoding, noCaching) {
	var fileContent = "";
	var encoding = ((encoding == undefined) || (encoding == null) || (encoding == "")) ? "ISO-8859-1" : encoding; 
	if (fileUrl == undefined || fileUrl == null || fileUrl == "") {
		fileContent = "Url del archivo nula";
	}
	if(fileCache.get(fileUrl) && noCaching != true ) {
		fileContent = fileCache.get(fileUrl);
	} else {
		try {
			new Ajax.Request(fileUrl, {
				asynchronous: false,
				method: 'post',
				encoding: encoding,
				requestHeaders: {Accept: 'text/html'},
				onSuccess: function(resp) {
					fileContent = resp.responseText;
					if (isTemplate) {
						fileContent = fileContent.replace(/#%7B([a-zA-Z0-9_-]+)%7D/gi, "#{$1}");
					}
					if (noCaching != true) {
						fileCache.set(fileUrl, fileContent);
					}
				},
				onFailure: function() {
					fileContent = "No se puede acceder al archivo \""+ fileUrl + "\"";
				}
			});
		} catch (e) {
			fileContent = "No se puede acceder al archivo \""+ fileUrl + "\". Error: " + e.description;
		}
	}
	return fileContent;
}

function getEvaluateTemplate(fileUrl, data, encoding, noCaching) {
	var toReturn = "";
	var myTpl = new Template(getFileContent(fileUrl, true, encoding, noCaching));
	try {
		toReturn = myTpl.evaluate(data);
	} catch (e) {
		toReturn = "Error: " + e;
	}
	return toReturn;
}