main.addFunction("initDesejoReservar()");

var desejo;
var buscaDesejo;
function initDesejoReservar(){
	desejo = new DesejoReservar();
	buscaDesejo = new BuscaDesejo();
}

function DesejoReservar(){
	selectEstabelecimento = $("codigo");

	//(construtor)
	this.init = function(){
		this.attachEvents();
	}

	//adiciona os eventos aos componentes...
	this.attachEvents = function(){
		$("form-desejo").onsubmit = function() {
			if(!parseInt(selectEstabelecimento.value)) {
				alert("Selecione um estabelecimento!");
				return false;
			}
		}

		//quando escolher um estabelecimeto no select...
		selectEstabelecimento.onchange = function() {
			var oldVejaMais = $("veja-mais");

			var aguarde = document.createTextNode("Aguarde...");
			$("veja-mais").parentNode.insertBefore(aguarde, $("veja-mais"));
			$("veja-mais").parentNode.removeChild($("veja-mais"));

			//busco a cidade relacionada ao cliente, por Ajax
			new Ajax.Request(
				'./__model/business/xml/?action=dados-cliente&cliente=' + selectEstabelecimento.value,
				{
					method: 'get',

					//quando carregar...
					onSuccess: function(transport){
						var cid = transport.responseXML;
						cid = cid.getElementsByTagName("cidade");

						oldVejaMais.href = "./?Hotsite/" + selectEstabelecimento.value + "/" + cid[0].getAttribute("codigo") + "/todos/todos";

						aguarde.parentNode.insertBefore(oldVejaMais, aguarde);
						aguarde.parentNode.removeChild(aguarde);
					},

					onFailure: function(){
						window.location.reload();
					}
				}
			)
		}

		$("veja-mais").onclick = function() {
			if(!parseInt($("codigo").value)) {
				alert("Selecione um estabelecimento para obter mais informações!");
				return false;
			}
		}
	}


	//processamento...
	this.init();
}

function BuscaDesejo(){
	var formulario;
	var selectEstado, selectCidade, selectBairro, selectSegmento;
	var cidades, bairros, segmentos;
	var estadoAtual, cidadeAtual, bairroAtual, segmentoAtual;

	this.attachEvents = function(){
		selectEstado = $("estadocad");
		selectCidade = $("cidadecad");
		selectEstabelecimento = $("codigo");

		cidades = Array();
		clientes = Array();

		estadoAtual = selectEstado.options[selectEstado.selectedIndex].getAttribute('value');
		cidadeAtual = selectCidade.options[selectCidade.selectedIndex].getAttribute('value');

		selectEstado.onchange = function(){
			estadoAtual = selectEstado.options[selectEstado.selectedIndex].getAttribute('value');

			if(selectEstado.options[0].value == "null") {
				selectEstado.removeChild(selectEstado.options[0]);
			}

			buscaDesejo.atualizaCidade();
		}

		selectCidade.onchange = function(){
			cidadeAtual = selectCidade.options[selectCidade.selectedIndex].getAttribute('value');
			buscaDesejo.atualizaClientes();
		}
	}

	this.atualizaCidade = function(){
		if(!(cidades[estadoAtual])){ //se não existir mapeamento para este estado...
			//-- loader --
			selectCidade.disabled = true;
			selectEstabelecimento.disabled = true;
			selectCidade.innerHTML = "<option value='null'>Carregando...</option>";

			new Ajax.Request(
				'./__model/business/xml/?action=cidades&estado=' + estadoAtual,
				{
					method: 'get',

					//quando carregar...
					onSuccess: function(transport){
						var cids = transport.responseXML;
						cids = cids.getElementsByTagName("cidade");

						var auxArray = new HashMap();
						for(var i = 0; i < cids.length; i++){
							var codCid = cids[i].getAttribute("codigo");
							var nomeCid = cids[i].childNodes[0].data;

							//jogo pro meu array...
//							auxArray[codCid] = nomeCid;
							auxArray.put(codCid, nomeCid)
						}

						cidades[estadoAtual] = auxArray;

						//chamo recursivamente a esta função
						buscaDesejo.atualizaCidade();
					},

					onFailure: function(){
						window.location.reload();
					}
				}
			)
		}
		else{
			var childs = selectEstabelecimento.getElementsByTagName("option");

			//aqui tenho tudo no meu array, na memória...
			selectCidade.innerHTML = "<option value='null" + cidadeAtual + "'>Selecione uma cidade</option>";

			while(cidades[estadoAtual].hasNext()){
				var auxOption = document.createElement("option");
				auxOption.appendChild(document.createTextNode(cidades[estadoAtual].next()));
				auxOption.setAttribute("value", cidades[estadoAtual].getActualKey());

				selectCidade.appendChild(auxOption);
			}

			cidades[estadoAtual].resetIterator();
			selectCidade.disabled = false;
			selectEstabelecimento.disabled = false;

			selectCidade.onchange();
		}
	}

	this.atualizaClientes = function(){
		if(!(clientes[cidadeAtual])) { //se não existir mapeamento para esta cidade...
			//-- loader --
			selectEstabelecimento.disabled = true;
			selectEstabelecimento.innerHTML = "<option value='null'>Carregando...</option>";

			new Ajax.Request(
				'./__model/business/xml/?action=clientes&estado=' + estadoAtual + "&cidade=" + cidadeAtual,
				{
					method: 'get',

					//quando carregar...
					onSuccess: function(transport){
						var clis = transport.responseXML;
						clis = clis.getElementsByTagName("cliente");

						var auxArray = new HashMap();
						for(var i = 0; i < clis.length; i++){
							var codCli = clis[i].getAttribute("codigo");
							var nomeCli = clis[i].getAttribute("nome");

							//jogo pro meu array...
							auxArray.put(codCli, nomeCli)
						}

						clientes[cidadeAtual] = auxArray;

						//chamo recursivamente a esta função
						buscaDesejo.atualizaClientes();
					},

					onFailure: function(){
						window.location.reload();
					}
				}
			)
		}
		else{
			var childs = selectEstabelecimento.getElementsByTagName("option");

			//aqui tenho tudo no meu array, na memória...
			selectEstabelecimento.innerHTML = "<option value='null'>Selecione um estabelecimento</option>";

			while(clientes[cidadeAtual].hasNext()){
				var auxOption = document.createElement("option");
				auxOption.appendChild(document.createTextNode(clientes[cidadeAtual].next()));
				auxOption.setAttribute("value", clientes[cidadeAtual].getActualKey());

				selectEstabelecimento.appendChild(auxOption);
			}

			clientes[cidadeAtual].resetIterator();
			selectEstabelecimento.disabled = false;
		}
	}

	//processo...
	this.attachEvents();
}
