var InstanciaRepeater = null;
var http = null;
function Repeater() {
	/// <summary>
	/// Define o <div> que conterá o template das repetições.
	/// <access mode="public"/>
	/// </summary>
	this.DivTemplate = null;

	/// <summary>
	/// Define o <div> que receberá a lista final.
	/// <access mode="public"/>
	/// </summary>
	this.DivResultado = null;

	/// <summary>
	/// Define a URL que contém o XML para popular a lista
	/// <access mode="public"/>
	/// </summary>
	this.PostUrl = null;

	/// <summary>
	/// Define o nome do nó XML que contém as informações do registro.
	/// <access mode="public"/>
	/// </summary>
	this.NoRegistro = null;

	/// <summary>
	/// Define um <form> para ser enviado junto à requisição para "PostUrl"
	/// <access mode="public"/>
	/// </summary>
	this.Form = null;

	/// <summary>
	/// Define as substituições que devem ser feitas a cada iteração do loop
	/// <access mode="public"/>
	/// </summary>
	this.Replaces = Array();

	
	/// <summary>
	/// Popula a lista com base nos parâmetros configurados.
	/// <access mode="public"/>
	/// </summary>
	this.Popular = function() {
		if (this.DivTemplate == null)
			throw new Error("Propriedade \"DivTemplate\" não definida.");
		else if (this.DivResultado == null)
			throw new Error("Propriedade \"DivResultado\" não definida.");
		else if (this.PostUrl == null)
			throw new Error("Propriedade \"PostUrl\" não definida.");

		InstanciaRepeater = this;

		http = this.ObterHttp();
		http.onreadystatechange = this.GerarLista;

		var strPost = null;
		if (this.Form != null) {
			strPost = this.GerarStrPost(this.Form);
			http.open("POST",this.PostUrl,true);
			http.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		} else {
			http.open("GET",this.PostUrl,true);
		}
		http.send(strPost);
		return http;


	}

	this.addReplace = function(nome, valor) {
		this.Replaces[this.Replaces.length] = {"nome":nome,"valor":valor};
	}

	this.GerarLista = function() {
		if (http.readyState == 4) {
			var template = InstanciaRepeater.DivTemplate.innerHTML;
			var lista = InstanciaRepeater.DivResultado;
			
			lista.innerHTML = "";

			var registros = http.responseXML.getElementsByTagName(InstanciaRepeater.NoRegistro);
			for(var i=0;i<registros.length;i++) {
				var div = document.createElement("div");

				var html = template;
				for(var j=0;j<registros[i].childNodes.length;j++) {
					if (registros[i].childNodes[j].childNodes[0] != undefined) {
    				    var col = registros[i].getElementsByTagName(registros[i].childNodes[j].nodeName);
    				    var rep = "";
    				    for(var k=0;k<col.length;k++)
    				        rep += col[k].childNodes[0].nodeValue +", ";
    				    rep = rep.substring(0,rep.length-2);
						html = html.replace("{"+ registros[i].childNodes[j].nodeName +"}",rep);
					}
				}
				for(var j=0;j<InstanciaRepeater.Replaces.length;j++) {
					html = html.replace("{"+ InstanciaRepeater.Replaces[j].nome +"}",InstanciaRepeater.Replaces[j].valor);
				    for(var k=0;k<registros[i].childNodes.length;k++) {
					    if (registros[i].childNodes[k].childNodes[0] != undefined) {
    				        var col = registros[i].getElementsByTagName(registros[i].childNodes[k].nodeName);
    				        var rep = "";
    				        for(var l=0;l<col.length;l++)
    				            rep += col[l].childNodes[0].nodeValue +", ";
    				        rep = rep.substring(0,rep.length-2);
						    html = html.replace("{"+ registros[i].childNodes[k].nodeName +"}",rep);
					    }
				    }
				}

				div.innerHTML = html;
				lista.appendChild(div);
			}
		}
	}

	// <summary>
	/// Obtem uma instância do objeto responsável por efetuar as chamadas Ajax.
	/// <access mode="private"/>
	/// </summary>
	this.ObterHttp = function() {
	    var http = false;

	    try {
	        http = new XMLHttpRequest();
	    }
	    catch (e) {
	        try {
	            http = new ActiveXObject("Microsoft.XMLHTTP");
	        }
	        catch (E) {
	            http = new ActiveXObject("Msxml2.XMLHTTP");
	            //http = false;
	        }
	    }

	    //		if (!http && typeof XMLHttpRequest!='undefined') {
	    //			http = new XMLHttpRequest();
	    //		}

	    return http;
	}

	// <summary>
	/// Obtém uma string no formato "nome1=valor1&nome2=valor2", contendo os campos formulário passado como parâmetro.
	/// <access mode="private"/>
	/// <param name="form">Objeto "<form>" para buscar os campos e gerar a string.</param>
	/// </summary>
	this.GerarStrPost = function(form) {
		var strPost = "";
		for(var i=0;i<form.elements.length;i++)
		{
			var el = form.elements[i];
			if (el.type == "text" || el.type == "hidden" || el.type == "password")
				strPost += el.id +"="+ escape(el.value) +"&";
			else if (el.type == "select-one" || el.type == "select-multiple")
				strPost += el.id +"="+ escape(el.options[el.selectedIndex].value) +"&";
			else if (el.type == "radio" || el.type == "checkbox") {
				if(el.checked)
					strPost += el.id + (this.PostUrl.indexOf(".php") > 0 ? "[]" : "") +"="+ escape(el.value) +"&";
			}
		}

		return strPost;
	}
}
