
window.onload = function(){
	//faz o preload das imagens necessárias
	preload();
	//chama a função de criação da busca
	makeBusca();

	//chamo a função de inserção dos flashs necessários
	insertFlashs();

	//cria os menus dropdown
	criaMenusDropDown();

	//implemento a troca dos nomes dos serviços onmouseover
	trocaTextoServicos();

	//thumbnails do hotsite
	thumbnailshotsite();

	//crio os botões de troca das imagens em ./?O-Sistema/Vantagens/Expositores
	criaBotoesTrocaExpositor();

	//funções quando for clicado em qualquer espaço do body
	var body = document.getElementsByTagName("body");
	body = body[0];
	body.onclick = function(){
		getDropDownBodyOnClick();
	}


	//promoções
	{
		promo001();
		promo002();
		promo005();
		promo006();
		cooperativado2007();
	}
	dragdrop('popfoto','popfoto');
}


//inicio  drag drop galeria
var objSelecionado = null;
var mouseOffset = null;
function addEvent(obj, evType, fn) { //Função adaptada da original de Christian Heilmann, em [url="http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html"]http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html[/url]
if (typeof obj == "string") {
  if (null == (obj = document.getElementById(obj))) {
   throw new Error("Elemento HTML não encontrado. Não foi possível adicionar o evento.");
  }
}
if (obj.attachEvent) {
  return obj.attachEvent(("on" + evType), fn);
} else if (obj.addEventListener) {
  return obj.addEventListener(evType, fn, true);
} else {
  throw new Error("Seu browser não suporta adição de eventos.");
}
}
document.onmousemove = function(ev) {
var ev = ev || window.event;
var mousePos = mouseCoords(ev);
if (objSelecionado) {
  document.getElementById(objSelecionado).style.left = mousePos.x - mouseOffset.x + 'px';
  document.getElementById(objSelecionado).style.top = mousePos.y - mouseOffset.y + 'px';
  document.getElementById(objSelecionado).style.margin = '0px';
  return false;
}
}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
  return {x:ev.pageX, y:ev.pageY};
}
return {
  x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
  y:ev.clientY + document.body.scrollTop  - document.body.clientTop
};
}
function getPosition(e, ev){
e = document.getElementById(e);
var left = 0;
var top  = 0;
var coords = mouseCoords(ev);
while (e.offsetParent){
  left += e.offsetLeft;
  top  += e.offsetTop;
  e     = e.offsetParent;
}
left += e.offsetLeft;
top  += e.offsetTop;
return {x: coords.x - left, y: coords.y - top};
}
document.onmouseup = function() {
objSelecionado = null;
}
function dragdrop(local_click, caixa_movida) {

document.getElementById(local_click).style.cursor = 'move';
addEvent(local_click, 'mousedown', function(ev) {
  objSelecionado = caixa_movida;
  mouseOffset = getPosition(objSelecionado, ev);
});
}
//fim drag drop
/*
	Faz a inserção dos flash necessários
*/
function insertFlashs(){
	//Flash do cabeçalho
	{
		var cabecalho = document.getElementById("cabecalho");
		if(cabecalho){
			var FO = { movie:"./layout/images/dc_cima.swf", width:"756", height:"125", wmode:"transparent", majorversion:"7", build:"40", xi:"true", ximovie:" http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" };
			UFO.create(FO, "cabecalho");
		}
	}

	//Flash da caixa da homepage
	{
		/*var caixahomepage = document.getElementById("caixahomepage");
		if(caixahomepage){
			var FO = { movie:"./layout/images/bannerhome/1.swf", width:"412", height:"161", wmode:"transparent", majorversion:"6", build:"40", xi:"true", ximovie:" http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" };
			UFO.create(FO, "caixahomepage");
		}*/
	}

	//Flash com os banners dos parceiros
	{
		var caixaparceiros = document.getElementById("caixalogotiposparceiros");
		if(caixaparceiros){
			var FO = { movie:"./layout/images/parceiros.swf", width:"124", height:"401", wmode:"transparent", majorversion:"6", build:"40", xi:"true", ximovie:" http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" };
			UFO.create(FO, "caixalogotiposparceiros");
		}
	}
}


/*
	Cria os campos de busca
*/
function makeBusca(){
	var busca = document.getElementById("buscageral");

	if(!busca)
		return;

	//Busco os selects e adiciono a interatividade à eles
	var selects = busca.getElementsByTagName("select");
	var estado = selects[0];
	var cidade = selects[1];

	/*
		Interatividade dos selects
	*/
	estado.onchange = function(){
		//Carrega as cidades dos estados passados por parâmetro
		loadCidades(estado.options[estado.selectedIndex].getAttribute("value"));
	}

	cidade.onchange = function(){
		botoesBuscaMain();
	}

	//Chamo ele aqui também pra tomar as atitudes default
	botoesBuscaMain();

	/*
		Funcionalidades dos botões
	*/
//	var listabotoes = document.getElementById("buscalistabotoes");
//	var caixabotao = listabotoes.getElementsByTagName("li");

	/*var auxbotoes = new Array(caixabotao.lenght);
	//Removo do array o botão atualmente selecionado. Pois ele mantém a cor e não muda onmouseout
	var count = 0;
	for(var i = 0; i < caixabotao.length; i++){
		auxbotoes[i] = null;

//		if(caixabotao[i].getAttribute("class") != "selectedramo" &&
//			caixabotao[i].getAttribute("value") > 0){
			auxbotoes[count] = caixabotao[i];

			count++;
//		}
	}*/

	//Chamo a função que dá estilo e interatividade aos botões passados no array por parâmetro
//	styleToButtons(caixabotao);
}

/*
	Função que verifica o que fazer referente aos botões
*/
function botoesBuscaMain(){
	var listabotoes = document.getElementById("buscalistabotoes");
	var caixabotao = listabotoes.getElementsByTagName("li");

	var busca = document.getElementById("buscageral");
	if(!busca)
		return;

	//pego o valor atualmente selecionado no select de cidade
	var selects = busca.getElementsByTagName("select");
	var selectcidade = selects[1];
	var cidadeAtual = selectcidade.options[selectcidade.selectedIndex].getAttribute("value");

	if(cidadeAtual > -1){
		if(!cidade[cidadeAtual])
			return;

		var habilitados = Array();
		var desabilitados = Array();

		//verifica os ramos com "true"
		var contH = 0;
		var contD = 0;
		for(var i = 0; i < caixabotao.length; i++){
			var ramoAtual = caixabotao[i].getAttribute("value");
			if(cidade[cidadeAtual][ramoAtual] == "true"){
				habilitados[contH] = caixabotao[i];
				contH++;
			}
			else{
				desabilitados[contD] = caixabotao[i];
				contD++;
			}
		}

		//chamo os métodos responsáveis
		disableButtons(desabilitados);
		styleToButtons(habilitados);
	}
	else{
		//desabilita todos
		disableButtons(caixabotao);
	}
}

//Variáveis globais que armazenam as listas de cidades já carregadas
var cidadesCarregadas = Array();
function loadCidades(estado){
	var selects = document.getElementsByTagName("select");
	var selectcidade = selects[1];

	//É restaurada lá em createOptionsCidades
	selectcidade.disabled = true;

	//Verifico se não estão carregadas na memória as cidades do estado
	//Se estiverem, somente as mostro. Senão, chamo o XML
	var cidades;
	if(cidadesCarregadas[estado]){
		cidades = cidadesCarregadas[estado];

		createOptionsCidade(cidades);
	}
	else{
		//A chamada de createOptionsCidade está dentro de loadCidadesFromXML
		cidades = loadCidadesFromXML(estado);
	}
}

function fechafoto(){
	document.getElementById('popfoto').style.display='none';
}
function foto(foto,extencao,largurafoto,legenda) {
	document.getElementById('popfoto').innerHTML = "<div id='popfotoTituloBarra'><div id='popfototextofechar'><a href='javascript:fechafoto()'> [Fechar]</a></div>";
	document.getElementById('popfoto').innerHTML += "<div id='popfotoTitulo'><a href='javascript:fechafoto()'> <img src='./layout/images/fechar.jpg' /></a></div></div>";
	document.getElementById('popfoto').innerHTML += "<img src='http://samarket.com.br/admins/imagens%5Fgerenciador%5FSA%5Fadmin/galerias/" + foto + "." +extencao + "'width='380px' alt='"+legenda+"' />";
	document.getElementById('popfoto').innerHTML += "<div id='popfotolegenda'>" + legenda + "</div>"; ;
	document.getElementById('popfoto').style.display='block';

}


function loadCidadesFromXML(estado){
	ajax = ajaxInit();

	if(ajax){
		ajax.open("GET", "./controller/xml/CidadesCadastradas.php?estado=" + estado, true);

		ajax.onreadystatechange = function(){
			if(ajax.readyState == 4) {
				if(ajax.status == 200){
					var result = ajax.responseXML;
					var cidades = result.getElementsByTagName("nome");

					cidadesCarregadas[estado] = cidades;

					createOptionsCidade(cidades);
				}
				else{
					alert(ajax.statusText);
				}
			}
		}
		ajax.send(null);
		return;
	}
}

function createOptionsCidade(cidades){
	var selects = document.getElementsByTagName("select");
	var selectestado = selects[0];
	var selectcidade = selects[1];

	//Limpo os filhos do select de cidades atual
	selectcidade.innerHTML = "";

	var opt = document.createElement("option");
	opt.setAttribute("value", "-1");
	opt.appendChild(document.createTextNode("Selecione uma cidade"));
	selectcidade.appendChild(opt);

	//Insiro os novos
	for(var i = 0; i < cidades.length; i++){
		opt = document.createElement("option");
		opt.setAttribute("value", cidades[i].getAttribute("codigo"));
		opt.appendChild(document.createTextNode(cidades[i].childNodes[0].data));

		selectcidade.appendChild(opt);
	}

	//É definida como true lá na chamada de loadCidades
	selectcidade.disabled = false;

	//altera os botões.
	botoesBuscaMain();
}


function styleToButtons(botoes){
	var enabledimages = Array();
	enabledimages[1] = "./layout/images/icon_hotelaria.gif";
	enabledimages[2] = "./layout/images/icon_compras.gif";
	enabledimages[3] = "./layout/images/icon_servicos.gif";
	enabledimages[4] = "./layout/images/icon_gastronomia.gif";
	enabledimages[5] = "./layout/images/icon_lazer.gif";

	for(var i = 0; i < botoes.length; i++){
		if(botoes[i]){
			botoes[i].onmouseover = function(){
				this.style.backgroundColor = "#E3E3E3";
			}

			botoes[i].onmouseout = function(){
				this.style.backgroundColor = "#fff";
			}

			botoes[i].onclick = function(){
				var ramo = this.getAttribute("value");

				//Pego os valores dos meus selects de estado e cidade
				var selects = document.getElementsByTagName("select");
				var estado = selects[0];
				var cidade = selects[1];

				estado = estado.options[estado.selectedIndex].getAttribute("value");
				cidade = cidade.options[cidade.selectedIndex].getAttribute("value");

				if(cidade > 0){
					location.href = "./controller/ProcessaBusca.php?estado=" + estado + "&cidade=" + cidade + "&ramo=" + ramo;
				}
				else{
					selects[1].style.borderColor = "#CB7336";
					selects[1].style.backgroundColor = "#EAC7AF";

				}
			}

			//Adiciono o cursor de "mão" à ele e aos filhos
			botoes[i].style.cursor = "pointer";
			var label = botoes[i].getElementsByTagName("label");
			label = label[0];
			label.style.cursor = "pointer";

			//mudo o src da imagem
			var value = botoes[i].getAttribute("value");

			var img = botoes[i].getElementsByTagName("img");
			img = img[0];
			img.setAttribute("src", enabledimages[value]);
		}
	}
}

/*
	Processa as "desabilitações" dos botões.
*/
function disableButtons(botoes){
	var disabledimages = Array();
	disabledimages[1] = "./layout/images/icon_hotelaria_pb.gif";
	disabledimages[2] = "./layout/images/icon_compras_pb.gif";
	disabledimages[3] = "./layout/images/icon_servicos_pb.gif";
	disabledimages[4] = "./layout/images/icon_gastronomia_pb.gif";
	disabledimages[5] = "./layout/images/icon_lazer_pb.gif";

	for(var i = 0; i < botoes.length; i++){
		botoes[i].onclick = function(){}
		botoes[i].onmouseover = function(){}

		var value = botoes[i].getAttribute("value");

		var img = botoes[i].getElementsByTagName("img");
		img = img[0];
		img.setAttribute("src", disabledimages[value]);

		botoes[i].style.cursor = "auto";

		var label = botoes[i].getElementsByTagName("label");
		label = label[0];
		label.style.cursor = "auto";
	}
}

//Hotsite
function trocaTextoServicos(){
	//Faço as implementações de serviços. Quando passar o mouse, mostra o nome do serviço na caixa
	servicos = document.getElementById("colunadoishotsite");
	if(!servicos)
		return;

	servicos = servicos.getElementsByTagName("dl");
	if(servicos){
		//Chegando aqui, tenho uma lista de serviços
		servicos = servicos[0];

		if(servicos){
			var filhos = servicos.childNodes;

			//Identifico os dt (Títulos)
			textoTitulo = "";
			title = "";
			for(i = 0; i < filhos.length; i++){
				if(filhos[i].nodeName == "DD"){
					//Mudo o curso
					filhos[i].style.cursor = "help";

					filhos[i].onmouseover = function(){
						var imagem = this.getElementsByTagName("img");
						imagem = imagem[0];

						//alert(imagem.getAttribute("title"));

						//Busco o DT anterior, e dou um replace no valor dele
						var atualNode = this;
						while(atualNode.nodeName != "DT"){
							atualNode = atualNode.previousSibling;
						}

						title = atualNode;
						textoTitulo = title.childNodes[0].nodeValue;
						title.childNodes[0].nodeValue = imagem.getAttribute("title");
					}

					filhos[i].onmouseout = function(){
						title.childNodes[0].nodeValue = textoTitulo;
					}
				}
			}
		}
	}
}

function thumbnailshotsite(){
	var listathumbs = document.getElementById("colunatreshotsite");

	if(!listathumbs)
		return;

	var links = listathumbs.getElementsByTagName("a");

	for(i = 0; i < links.length; i++){
		links[i].onclick = function(){
			var imagem = this.firstChild;
			var campoimagematual = document.getElementById("caixaimagemhotsite");
			var imagemAtual = campoimagematual.getElementsByTagName("img")[0];
			var legendaAtual = campoimagematual.getElementsByTagName("p")[0];

			imagemAtual.setAttribute("src", imagem.getAttribute("src"));
			imagemAtual.setAttribute("alt", imagem.getAttribute("alt"));
//			imagemAtual.setAttribute("width", imagem.getAttribute("width"));

			legendaAtual.innerHTML = imagem.getAttribute("alt");

			return false;
		}
	}
}

function criaBotoesTrocaExpositor(){
	var div = document.getElementById("imagensexpositores");

	if(!div)
		return;

	var campos = new Array(3);
	var aux = Array();
	aux['nome'] = "Parede";
	aux['img'] = "./layout/images/display_parede.jpg";

	campos[0] = aux;


	//--

	var aux2 = Array();
	aux2['nome'] = "Balcão";
	aux2['img'] = "./layout/images/display_balcao.jpg";

	campos[1] = aux2;

	//--

	var aux3 = Array();
	aux3['nome'] = "Chão";
	aux3['img'] = "./layout/images/display_chao.gif";

	campos[2] = aux3;

	//--

	var ul = document.createElement("ul");
	ul.setAttribute("id", "listabotoestrocaexpositor");

	for(var i = 0; i < campos.length; i++){
		var li = document.createElement("li");
		var a  = document.createElement("a");

		a.setAttribute("href", campos[i]['img']);
		a.setAttribute("title", campos[i]['nome']);
		a.setAttribute("target", "_blank");
		a.appendChild(document.createTextNode(campos[i]['nome']));

		li.appendChild(a);
		ul.appendChild(li);

		a.onclick = function(){
			var img = div.getElementsByTagName("img");
			img = img[0];

			img.setAttribute("src", this.getAttribute("href"));
			img.setAttribute("alt", this.getAttribute("nome"));

			return false;
		}


	}

	div.appendChild(ul);
}

function criaMenusDropDown(){
//	Notícias
//	var menuNavegacao = document.getElementById("menunaveg");
//	var parentNoticias = getElementsByClassName("noticias", menuNavegacao);
//	parentNoticias = parentNoticias[0];
//
//	var noticias = Array();
//	var aux = Array();
//
//	aux['nome'] = "Nono non ononno no";
//	aux['link'] = "www.teste.com.br";
//
//	noticias[0] = aux;
//
//	var aux = Array();
//	aux['nome'] = "Lorem ipsun dolor";
//	aux['link'] = "www.teste.com.br";
//	noticias[1] = aux;
//
//	var dropNoticias;
//	parentNoticias.onmouseover = function(){
//		dropNoticias = createDropDown(noticias, document.body, 84);
//	}
//
//	parentNoticias.onmouseout = function(){
//		dropNoticias = removeDropDown(dropNoticias, 500);
//	}
}

//Faz o preload das imagens necessárias
function preload(){
	var imagens = Array();
	imagens[0] = "./layout/images/icon_hotelaria_pb.gif";
	imagens[1] = "./layout/images/icon_servicos_pb.gif";
	imagens[2] = "./layout/images/icon_compras_pb.gif";
	imagens[3] = "./layout/images/icon_gastronomia_pb.gif";
	imagens[4] = "./layout/images/icon_lazer_pb.gif";


	for(var i = 0; i < imagens.length; i++){
		preloadImage(imagens[i]);
	}
}


