// JavaScript Document
//scripts referentes ao quero-comprar (todos os passos + simule)
var dataescolhida;
var wsdir;
var raiz;
var xmlhttp;
var xmlhttp2;
var calendariosInstanciados = false;
var cia = 0;
var ws = Array();
var CodUsuarioPerfil = 1;
ws["origens"] = "getOrigens.php";
ws["destinos"] = "getDestinos.php";
/*ws["datasIda"] = "getCalendarioIdaNovo.php";
ws["datasVolta"] = "getCalendarioVoltaNovo.php";*/
ws["datasIda"] = "MyCalendarioIda.php";
ws["datasVolta"] = "MyCalendarioVolta.php";


$(function() {
		   
	adicionaListeners();
			   
	//settings padrão do DatePicker
	$('input.hasDatepicker').live('keypress', function() {
	  return false;
	});
	
	var dataminima = new Date();
	dataminima.setTime( dataminima.getTime() + (3 * 31 * 24 * 60 * 60 * 1000));
	
	$.datepicker.setDefaults({
		closeText: 'Fechar',
		prevText: '&#x3c;Anterior',
		nextText: 'Pr&oacute;ximo&#x3e;',
		currentText: 'Hoje',
		monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho', 'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun', 'Jul','Ago','Set','Out','Nov','Dez'],
		dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
		dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
		dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: '',
		showButtonPanel: true,
		constrainInput: true,
		showAnim: 'slide',
		duration: 'fast',
		showOptions: {direction: 'up' },
		minDate: dataminima
		});
	
		if ($("input#ida").is(":checked")) $("#div_data_volta").hide();
		
		var obsParcelas = $("#obs_parcelas");
		if (obsParcelas.length > 0) {
			obsParcelas = $(obsParcelas[0]);
			obsParcelas.css("top", ( $("#tdValorParcela").position().top - obsParcelas.height() + 20 ));
		}
});

//----- listeners do form
function adicionaListeners () {
	//adiciona listeners aos elementos do formulario
	$("select#origem").change( function () {selecionouOrigem($(this).val())});
	$("select#destino").change( function () {selecionouDestino($(this).val())});
	$("input#ida, input#volta").change( function () {mudaTipoTrecho($(this).val())});
}

//-------------------------------------------------------------
//aviso de origens repetidas
var msgOrigens = ", confira também os voos a partir ";
var origensRepetidas = new Array ();
//são paulo
origensRepetidas[7]  = "Em São Paulo" + msgOrigens  + "dos aeroportos de Guarulhos e Congonhas."; //sp- viracopos
origensRepetidas[32] = "Em São Paulo" + msgOrigens  + "dos aeroportos de Guarulhos e Campinas-Viracopos."; //sp- congonhas
origensRepetidas[33] = "Em São Paulo" + msgOrigens  + "dos aeroportos de Campinas-Viracopos e Congonhas."; //sp- guarulhos
//rio de janeiro
origensRepetidas[28] = "No Rio de Janeiro" + msgOrigens  + "do aeroporto Santos Dummont."; //rj - galeão
origensRepetidas[29] = "No Rio de Janeiro" + msgOrigens  + "do aeroporto Galeão."; //rj - santos dummont

//-----------------------------------------------------------

function setWSdir (str) {
	wsdir = str;
}

function setRaiz (str) {
	raiz = str;
}

function ajax () {
	var temp;
	
	if (window.XMLHttpRequest) {
		temp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		temp = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Seu navegador não dá suporte à AJAX!\nAbra este site em um navegador mais recente.");
	}

	return temp;
}

function selecionouOrigem (cod) {
	//função triggered quando seleciona uma origem
	limpaDependentes("origem");
	var codOrigem = pegaCodigo(cod);
	var php = wsdir + ws["destinos"];
	
	$("#origensRepetidas").html("");
	$("#origensRepetidas").hide();
	
	if (origensRepetidas[Number(codOrigem)]) {
		$("#origensRepetidas").html(origensRepetidas[Number(codOrigem)]);
		$("#origensRepetidas").show();
	}
	
	if (selecionouNulo(document.getElementById("origem"))) {
		return;
	}
	
	var url = php + "?rand=" + Math.round(Math.random() * 1000);
	var params = "CodOrigem=" + codOrigem + "&CodCompanhia=" + cia;
	
	xmlhttp = ajax();
	
	xmlhttp.open("POST", url, true);
	xmlhttp.onreadystatechange=exibeDestinos;
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.send(params);
	
	document.getElementById("destino").options[0].innerHTML = "aguarde, carregando ...";
	document.getElementById("destino").selectedIndex = 0;
	
	carregando();
}

function exibeDestinos () {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			
			carregado();
			
			var sel = document.getElementById("destino");
			//limpa o select antes de popular de novo
			for (var j = sel.length - 1; j >= 1; j--) {
				sel.remove(j);
			}
			
			var raiz 	= xmlhttp.responseXML.getElementsByTagName('ArrayOfCidadesOrigensDestinosTO')[0];
			var destino = raiz.getElementsByTagName('CidadesOrigensDestinosTO');
			var qtd 	= raiz.getElementsByTagName('CidadesOrigensDestinosTO').length;
			
			for (var i = 0; i < qtd; i++) {
				
				var option = document.createElement("option");
					option.setAttribute("value", valorNoh(destino[i].getElementsByTagName("cod_cidade")[0]) + "__" + valorNoh(destino[i].getElementsByTagName("descricao")[0]));
					option.appendChild(document.createTextNode(valorNoh(destino[i].getElementsByTagName("descricao")[0])));
					
				sel.appendChild(option);
				
			}
			sel.options[0].innerHTML = "-- Selecione um destino --";
		}
	}
}

function selecionouDestino (cod_dest) {
	onChange="javascript: selecionouDestino(this.options[this.selectedIndex].value, <?php echo $cia; ?>, 'getCalendarioIda.php');"
	
	limpaDependentes("destino");
	if (selecionouNulo(document.getElementById("destino"))) return;
	
	carregando();
	
	var php = wsdir + ws["datasIda"];
	
	var cod_o = selectedOptionValue("origem");
		cod_o = pegaCodigo(cod_o);
		
	var cod_d = pegaCodigo(cod_dest);
	
	var cod_u = document.getElementById("cod_usuario_perfil").value;
	
	var url = php + "?rand=" + Math.round(Math.random() * 1000);
	var params = "CodOrigem=" + cod_o + "&CodDestino=" + cod_d + "&CodCompanhia=" + cia + "&CodUsuarioPerfil=" + cod_u;
	
	xmlhttp = ajax();
	
	xmlhttp.open("POST", url, true);
	xmlhttp.onreadystatechange=exibeCalendarioIda;
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.send(params);	
}

function exibeCalendarioIda (carregaVolta) {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			
			carregado();
			
			var raiz 	= xmlhttp.responseXML.getElementsByTagName('datas')[0];
			var inicio  = raiz.getElementsByTagName('data_inicial')[0];
				inicio  = valorNoh(inicio).split("/");
				inicio  = inicio[0] + "/" + inicio[1] + "/" + inicio[2].substr(2);
			var final   = raiz.getElementsByTagName('data_final')[0];
				final   = valorNoh(final).split("/");
				final   = final[0] + "/" + final[1] + "/" + final[2].substr(2);
			var bloqueadas  = raiz.getElementsByTagName('bloqueadas');
			
			//coloca os dados de inicio e final num input hidden
			var df = false;
			for (var ii = 0; ii <document.getElementById('origem').form.elements.length; ii++ ) {
				if (document.getElementById('origem').form.elements[ii].name == "data_final") {
					df = true;
				}
			}
			
			if (!df) {
			var datafinal = document.createElement("input");
				datafinal.setAttribute("type", "hidden");
				datafinal.setAttribute("id", "data_final");
				datafinal.setAttribute("name", "data_final");
				datafinal.setAttribute("value", valorNoh(raiz.getElementsByTagName('data_final')[0]));
				
			document.getElementById('origem').form.appendChild(datafinal);
			
			} else {
				document.getElementById('data_final').value = valorNoh(raiz.getElementsByTagName('data_final')[0]);
			}
			
			var datasBloqueadas = Array();
			if (bloqueadas.length >= 1 && valorNoh(bloqueadas[0])) {
				for (var i = 0; i < bloqueadas.length; i++) {
					datasBloqueadas[i] = Array(valorNoh(bloqueadas[i]).split("/")[0], valorNoh(bloqueadas[i]).split("/")[1], valorNoh(bloqueadas[i]).split("/")[2]);
				}
			}
		
			
			$("input#"+ "data_ida").datepicker({
									minDate: inicio,
									maxDate: final,
								    onSelect: selecionouDataIda
																		
																});
			
			if (datasBloqueadas.length > 0) {
				$("input#"+ "data_ida").datepicker("option", "beforeShowDay", 
												  function (date) {
														if (datasBloqueadas.length > 0) {
																var disponivel = true;
																for (j = 0; j < datasBloqueadas.length; j++) {
																	if (date.getDate() == datasBloqueadas[j][0] && 
																		date.getMonth() == datasBloqueadas[j][1] - 1 &&
																		date.getFullYear() == datasBloqueadas[j][2]) {
																		disponivel = false;
																		break;
																	}
																}
																return [disponivel, ""];
														}
												  });
			}
			
			document.getElementById("data_ida").disabled = false;
			
			if (exibeCalendarioIda.arguments.length > 0 && carregaVolta == true) {
				instanciaCalendarioVolta();
			}
		}
	}
}

function selecionouDataIda (dateText, inst) {
	
	limpaDependentes("data_ida");
	carregando();
	
	if (document.getElementById("ida").checked) {
		//se a viagem é só de ida, já exibe botao continuar e sai
		carregado();
		exibe("div_submit");
		return;
	}
	
	//calcula as datas possíveis para a volta se o ida e volta estiver checked.
	var php = wsdir + ws["datasVolta"];
	var cod_o = selectedOptionValue("origem");
		cod_o = pegaCodigo(cod_o);
		
	var cod_d = selectedOptionValue("destino");
		cod_d = pegaCodigo(cod_d);
	
	var url = php + "?rand=" + Math.round(Math.random() * 1000);
	var params  =  "CodOrigem=" + cod_o;
		params += "&CodDestino=" + cod_d;
		params += "&CodCompanhia=" + cia;
		params += "&DataIda=" + dateText;
	
	
	xmlhttp2 = ajax();
	
	xmlhttp2.open("POST", url, true);
	xmlhttp2.onreadystatechange=exibeCalendarioVolta;
	xmlhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp2.setRequestHeader("Content-length", params.length);
	xmlhttp2.send(params);
}

function exibeCalendarioVolta () {
	
	if (xmlhttp2.readyState == 4) {
		if (xmlhttp2.status == 200) {
			
			carregado();
			
			var raiz 	= xmlhttp2.responseXML.getElementsByTagName('datas')[0];
			var inicio  = raiz.getElementsByTagName('data_inicial')[0];
				inicio  = valorNoh(inicio).split("/");
				inicio  = inicio[0] + "/" + inicio[1] + "/" + inicio[2].substr(2);
			var final   = raiz.getElementsByTagName('data_final')[0];
				final   = valorNoh(final).split("/");
				final   = final[0] + "/" + final[1] + "/" + final[2].substr(2);
			var bloqueadas  = raiz.getElementsByTagName('bloqueadas');
			
			var datasBloqueadas = Array();
			if (bloqueadas.length >= 1 && valorNoh(bloqueadas[0])) {
				for (var i = 0; i < bloqueadas.length; i++) {
					datasBloqueadas[i] = Array(valorNoh(bloqueadas[i]).split("/")[0], valorNoh(bloqueadas[i]).split("/")[1], valorNoh(bloqueadas[i]).split("/")[2]);
				}
			}
			
			var inputdtv = $("input#data_volta");
			
				if (inputdtv.hasClass("hasDatepicker")) inputdtv.datepicker("destroy");
			
				inputdtv.datepicker({
										minDate: inicio,
										maxDate: final,
										defaultDate: inicio,
									    onSelect: selecionouDataVolta		
								  });
				
			if (datasBloqueadas.length > 0) {
				inputdtv.datepicker("option", "beforeShowDay", function (date) {
																		if (datasBloqueadas.length > 0) {
																				var disponivel = true;
																				for (j = 0; j < datasBloqueadas.length; j++) {
																					
																					if (date.getDate() == datasBloqueadas[j][0] && 
																						date.getMonth() == datasBloqueadas[j][1] - 1 &&
																						date.getFullYear() == datasBloqueadas[j][2]) {
																						disponivel = false;
																						break;
																					}
																					
																				}
																				return [disponivel, ""];
																		}
																  });
			}
				
			document.getElementById("data_volta").disabled = false;	
		}
	}
}

function selecionouDataVolta (date) {
	document.getElementById("volta").checked = true;
	exibe("div_submit");
}

function mudaTipoTrecho (tipoTrecho) {
	limpaValor("data_volta");
	
	if (tipoTrecho == 1) {
		//se for só ida apaga e esconde o data volta e exibe o botao submit se a data ida já estiver escolhida
		var di = $("#data_ida").val();
		if (di && di != null && di != "" && di != "undefined") {
			exibe("div_submit");
		}
		$("#data_volta").val("");
		$("#div_data_volta").fadeOut();
		
	} else {
		//se mudar pra ida e volta (a data volta vai estar em branco, então exibe o input data volta esconde botão de submit)
		esconde("div_submit");
		$("#data_volta").val("");
		$("#div_data_volta").fadeIn();
	}
}

function instanciaCalendarios (cia) {
	
	if (!calendariosInstanciados) {
		carregando();
		calendariosInstanciados = true;
		
		//calcula as datas possíveis para a ida
		var php = wsdir + ws["datasIda"];
		
		var cod_o = selectedOptionValue("origem");
			cod_o = pegaCodigo(cod_o);
			
		var cod_d = selectedOptionValue("destino");
			cod_d = pegaCodigo(cod_d);
		
		var cod_u = document.getElementById("cod_usuario_perfil").value;
		
		var url = php + "?rand=" + Math.round(Math.random() * 1000);
		var params = "CodOrigem=" + cod_o + "&CodDestino=" + cod_d + "&CodCompanhia=" + cia + "&CodUsuarioPerfil=" + cod_u;
		
		xmlhttp = ajax();
		
		xmlhttp.open("POST", url, true);
		xmlhttp.onreadystatechange=exibeIdaInstanciaVolta;
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", params.length);
		xmlhttp.send(params);
	}
}

function exibeIdaInstanciaVolta () {
	exibeCalendarioIda(true);
}

function instanciaCalendarioVolta () {
	
	carregando();
	//calcula as datas possíveis para a volta se o ida e volta estiver checked.
	var php = wsdir + ws["datasVolta"];
	var cod_o = selectedOptionValue("origem");
		cod_o = pegaCodigo(cod_o);
		
	var cod_d = selectedOptionValue("destino");
		cod_d = pegaCodigo(cod_d);
	
	var url = php + "?rand=" + Math.round(Math.random() * 1000);
	var params  =  "CodOrigem=" + cod_o;
		params += "&CodDestino=" + cod_d;
		params += "&CodCompanhia=" + cia;
		params += "&DataIda=" + document.getElementById('data_ida').value;
	
	xmlhttp2 = ajax();
	
	xmlhttp2.open("POST", url, true);
	xmlhttp2.onreadystatechange=exibeCalendarioVolta;
	xmlhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp2.setRequestHeader("Content-length", params.length);
	xmlhttp2.send(params);
}

//-------------------------validacao
function validaSimule (form) {
	
	var tipo = Number(valorTipoTrecho());
	
	var output = "";
	var el;
	
	var msg = "";
	
	for (var i = 0; i < form.elements.length; i++) {
		
		el = form.elements[i];
		
		output += "id = " + el.id + " - tagname = " + el.tagName + " -  valor = " +  el.value;
		
		if ((el.id == "origem" || el.id == "destino") && el.options[el.selectedIndex].value == "-1") {
			alert ("Selecione um destino e uma origem.");
			return false;
		}
		
		if (el.id == "data_ida" || (el.id == "data_volta" && tipo == 2)) {
			var input = (el.id == "data_ida")? $("input#data_ida") : $("input#data_volta");
			var mind = toDate(fullYear(input.datepicker( "option" , "minDate")));
			var maxd = toDate(fullYear(input.datepicker( "option" , "maxDate")));
			var d = toDate(fullYear(input.val()));
			
			msg += "--" + el.id + ":\nval: " + d + "\nmin: " + mind + "\nmax: " + maxd + "\n--\n\n";
			
			if (d < mind || d > maxd) {
				if (el.id == "data_ida") {
					alert("Selecione a data de ida dentre as disponíveis no calendário.");
				} else {
					alert("Selecione a data de volta dentre as disponíveis no calendário.");
				}
				return false;
			}
		}
	}
	
	//monta loading do formulário
	$("#submit_simule", form).fadeTo("fast", 0.4);
	$(form).css("position", "relative").append("<div class='modal'></div><div class='msg'></div>");
	$(".modal", form).css({
			width: $(form).width(),
			height: $(form).height(),
			position: "absolute",
			zIndex: "9999",
			top: 0,
			left: 0,
			background: "#82B2F2",
			opacity: 0
		});
	$(".msg", form).html("aguarde ...")
					.css({
			width: "120px",
			textAlign: "center",
			fontWeight: "bold",
			clear: "both",
			margin: "0 auto",
			padding: "10px 20px 10px 0",
			background: "url(imagens/loading.gif) no-repeat right center"
		});
	
	//ok
	return true;
}

//------------------------ auxiliares
function fullYear (d, y) {
	if (y == "undefined" || y == null) y = "20";
	d = d.split("/");
	if (d[2].toString().length < 4) d[2] = y + d[2];
	return d[0] + "/" + d[1] + "/" + d[2];
}
function toDate (d) {
	//dd/mm/yy || dd/mm/yyyy
	d = d.split("/");
	return new Date(d[2], (d[1] - 1), d[0]);
}

//---- informações
function selectedOptionValue (selectID) {
	return document.getElementById(selectID).options[document.getElementById(selectID).selectedIndex].value;
}
function pegaCodigo (cod__assim, separador) {
	var sep = (pegaCodigo.arguments.length > 1)? separador : "__";
	return cod__assim.substring(0, cod__assim.indexOf(sep));
}
function valorTipoTrecho () {
	return $("input:radio[name=tipo_trecho]:checked").val();
}

function valorNoh (noh) {
	for (var i = 0; i < noh.childNodes.length; i++) {
		
		if (noh.childNodes[i].nodeType == 3) {
			return noh.childNodes[i].nodeValue;
		}
		
	}
}

function limpaDependentes (id) {
	if (id == 'data_volta') return;
	
	esconde('div_submit');
	limpaValor("data_volta");
	
	if (id == 'data_ida') return;
	
	limpaValor("data_ida");
	limpaValor("data_volta");
	
	//se for o destino, sai
	if (id == 'destino') return;
	
	limpaSelect("destino");
	//vai até o fim se for origem
}

function limpaValor (id) {
	document.getElementById(id).value = "";
}

function limpaSelect (id) {
	var sel = document.getElementById(id);
	//limpa o select antes de popular de novo
	for (var i = sel.length - 1; i >= 1; i--) {
		sel.remove(i);
	}
}

function selecionouNulo (sel) {
	if (
		sel.options[sel.selectedIndex].value == "-1" ||
		sel.options[sel.selectedIndex].value == -1 ||
		Number(sel.options[sel.selectedIndex].value) < 0		
		) {
		return true;
	}
	
	return false;
}

// ---- carregamento do ajax
function carregando () {
	var form = document.getElementById("simule");
	
	for (var i = 0; i < form.elements.length; i++) {
		
		if (form.elements[i].id.indexOf("opt_venc") < 0) {
			form.elements[i].disabled = true;
		}
	}
	
	$('#carregando').fadeIn();
}

function carregado () {
	var form = document.getElementById("simule");
	
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].id.indexOf("opt_venc") < 0) {
			form.elements[i].disabled =false;
		}
	}
	
	$('#carregando').fadeOut();
}

function carregandoOutraPagina (form) {
	/*var size = 12;
	var botao = (carregandoOutraPagina.arguments.length >= 1) ? $(botao) : $("input[type='submit'], input[type='image']", form);
	
	if (botao.length <= 0) return;
	
		botao.attr("disabled", "disabled");
		$(form).append("<div id='carregandoDiv'><img src='imagens/loading.gif' alt='' width='"+size+"' height='"+size+"' /></div>");
		$("#carregandoDiv").css({
								position: "absolute",
								width: size,
								height: height,
								top: botao.position().top + ((botao.height()/2) - (size/2)) ,
								left: botao.position().left - size - 10
								});*/
}

//-----animacao

function abreTip (id) {
	if ($("#" + id).is(":hidden")) {
		$("#" + id).slideDown(200);
	}
}

function fechaTip (id) {
	if (!$("#" + id).is(":hidden")) {
		$("#" + id).slideUp(200);
	}
}

function abreContrato (url) {
	window.open(url, 
				"_blank", 
				"width=700, height=550, top=0, left=0, scrollbars=1, toolbar=0, location=1, directories=0, menubar=1, resizable=1, status=1",
				false);
	return false;
}

