/*
 * pesquisa.js
 * arquivo de funcoes para o portlet zpt_pesquisa
 * @author Lincoln de Sousa (lincoln@2xt.com.br)
 * @org 2XT
 */

function menuAtivo(){
    var finaldaurl = document.getElementById('finaldaurl').value;
    var e_menu = document.getElementById('menu');
    var v_class = document.all ? 'className' : 'class';
    for (i=0; i < e_menu.childNodes.length; i++){
		try{
	        var e_item = e_menu.childNodes[i];

	        if(e_item.nodeName.toLowerCase() == '#text') continue;

	        if(e_item.getAttribute(v_class) == 'menu_ativo'){
	           e_item.className = '';
	           if (finaldaurl == 'pesquisa'){
	               document.getElementById('nav_pesquisa').className = 'menu_ativo';
	           } else if (finaldaurl == 'minhas_reservas'){
	               document.getElementById('nav_minhasreservas').className = 'menu_ativo';
	           } else if (finaldaurl == 'minhas_compras'){
	               document.getElementById('nav_minhascompras').className = 'menu_ativo';
	           } else if (finaldaurl == 'reservas_cliente'){
	               document.getElementById('nav_reservacliente').className = 'menu_ativo';
	           } else if (finaldaurl == 'reservas_agencia_geral'){
	               document.getElementById('nav_reservaagencia').className = 'menu_ativo';	       
	           } else if (finaldaurl == 'adm_funcionario'){
	               document.getElementById('adm_funcionario').className = 'menu_ativo';	       
	           } else if (finaldaurl == 'meus_clientes'){
	               document.getElementById('nav_meusclientes').className = 'menu_ativo';	       
			   }			   
			}
		}
		catch(e){}
     }
}

function versaoDemo()
{
    document.getElementById('versaodemo').style['display'] = 'block'
}
var today = new Date("2010/09/06");
var months = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"];

/**
 * cria tas option
 * @param {string} value contem o valor que sera setado no atributo value da tag
 * @param {string} show o valor que sera exibido dentro do campo
 * @type htmlObj
 */
function createOptionTag(value, show)
{
    var option = document.createElement("option");
    option.setAttribute("value", value);
    option.appendChild(document.createTextNode(show));
    return option;
}

/**
 * habilita e desabilita campo de volta
 * @type void
 */
function desabilitavolta(opcao)
{
    var frm = document.forms["busca_form"];
  try
  {
    with (frm) {
      if (opcao) {
        //frm.dia_volta.disabled = true;
        //frm.mes_volta.disabled = true;
        frm.DataVoltaAereo.disabled = true;
        frm.CalVoltaAereo.style['display'] = 'none';
        frm.DataVoltaAereo.setAttribute('require', '');
        frm.DataVoltaAereo.style['border'] = '1px solid'
      }
      else {
        //frm.dia_volta.disabled = false;
        //frm.mes_volta.disabled = false;
        frm.DataVoltaAereo.disabled = false;
        frm.DataVoltaAereo.setAttribute('require', 'Campo data de volta obrigatório');
        frm.CalVoltaAereo.style['display'] = 'block';
      }
    }
  }catch(e){}
}


/**
 * pega o id do mes que foi passado de parametro
 * @type str
 */
function getMonth(month)
{
    for (i = 0; i < months.length; i++)
    {
        if (months[i] == month)
        {
            return i;
            break;
        }
    }
}

function getMonthtratado(month)
{
    for (i = 0; i < months.length; i++)
    {
        if (months[i] == month)
        {
            if (i <9) {
                return '0'+ (i+1);
            }
            else {
                return i+1;
            }
            break;
        }
    }
}

function indicaPesquisa(nacional_internacional, nomeCampo){
 try{
    var v_int = nacional_internacional == 'internnacional' ? true : false;
    var disp_int = v_int ? 'block' : 'none';
    var disp = v_int ? 'none' : 'block';
    // apanhando os objetos
    var ipt_de = document.getElementById('busca_de_view');
    var ipt_de_hidden = document.getElementById('busca_de');
    var ipt_de_int = document.getElementById('busca_de_int_view');
    var ipt_de_int_hidden = document.getElementById('busca_de_int');
    var ipt_para = document.getElementById('busca_para_view');
    var ipt_para_hidden = document.getElementById('busca_para');
    var ipt_para_int = document.getElementById('busca_para_int_view');
    var ipt_para_int_hidden = document.getElementById('busca_para_int');
    var ipt_idaevolta = document.getElementById('idaevolta');
    var ipt_ida = document.getElementById('ida');
    //var ipt_dia_volta = document.getElementById('dia_volta');
    //var ipt_mes_volta = document.getElementById('mes_volta');
    var ipt_tipo_pesquisa = document.getElementById('tipo_pesquisa');
    // caso seja internacional

    // modificando a visualizacao
    ipt_de.style.display = disp;
    ipt_para.style.display = disp;
    ipt_de_int.style.display = disp_int;
    ipt_para_int.style.display = disp_int;

    // modificando o nome
    if(v_int) {
        //ipt_de.removeAttribute('name');
        ipt_de.value = '';
        ipt_de_hidden.value = '';
        ipt_de.setAttribute('require', '');
        ipt_de.style['border'] = '1px solid'
        //ipt_para.removeAttribute('name');
        ipt_para.value = '';
        ipt_para_hidden.value = '';
        ipt_para.setAttribute('require', '');
        ipt_para.style['border'] = '1px solid'
        ipt_tipo_pesquisa.value = 'internacional'; 
        //ipt_ida.disabled = "disabled"
        ipt_idaevolta.checked = "checked"
        //ipt_dia_volta.disabled = ""
        //ipt_mes_volta.disabled = ""
        ipt_de_int.setAttribute('require', 'Campo origem obrigatório');
        ipt_para_int.setAttribute('require', 'Campo destino obrigatório');
        //ipt_de_int.setAttribute('name', 'origem_view');
        //ipt_para_int.setAttribute('name', 'destino_view');
		document.getElementById('filtro_personalize').style['display'] = 'none';
		document.getElementById('filtro_promocode').style['display'] = 'none';
    } else {
        //ipt_de_int.removeAttribute('name');
        ipt_de_int.value = '';
        ipt_de_int_hidden.value = '';
        ipt_de_int.setAttribute('require', '');
        ipt_de_int.style['border'] = '1px solid'
        //ipt_para_int.removeAttribute('name');
        ipt_para_int.value = '';
        ipt_para_int_hidden.value = '';
        ipt_para_int.setAttribute('require', '');
        ipt_para_int.style['border'] = '1px solid'
        ipt_tipo_pesquisa.value = 'nacional';
        ipt_ida.disabled = ""
        ipt_de.setAttribute('require', 'Campo origem obrigatório');
        ipt_para.setAttribute('require', 'Campo destino obrigatório');
        //ipt_de.setAttribute('name', 'origem_view');
        //ipt_para.setAttribute('name', 'destino_view');
		document.getElementById('filtro_personalize').style['display'] = 'block';
		document.getElementById('filtro_promocode').style['display'] = 'block';
    }
 }catch(e){
   //tratar erro
 }
}

/**function para manter conpatibilidade de voo nacional e internacional*/
function setupDateFields(){
    setupDateFields("busca_form");
}

/**
 * monta os campos de data de ida e dada de volta
 * @type void
 */
function setupDateFields(tipoframe)
{
	try{
    var nacional = document.getElementsByName('tipo_voo')[0].checked
	var internacional = document.getElementsByName('tipo_voo')[1].checked
	}
	catch(e){
	var internacional = false;
	}
    if (internacional)
    {
        nameform = 'busca_form'
        indicaPesquisa('internnacional','indica_pesquisa')
    }
    else
    {
        nameform = 'busca_form'
        indicaPesquisa('nacional','indica_pesquisa')
    }

    if (document.forms[nameform].idaevolta.checked == true)
    {
        if (nameform == "busca_form_internacional")
        {
            desabilitavoltainternacional(false);
        }
        else
        {
            desabilitavolta(false);
        }
    }

    if (document.forms[nameform].idaevolta.checked == false)
    {
        if (nameform == "busca_form_internacional")
        {
            desabilitavoltainternacional(true);
            var frm = document.forms[nameform];
            frm.ida.checked = true;            
        }
        else
        {
            desabilitavolta(false);
            var frm = document.forms[nameform];
            frm.ida.checked = true;            
        }
    }

    var frm = document.forms[nameform];
    var tYear = today.getFullYear();
    var tMonth = parseInt(today.getMonth());
    var tDay = today.getDate();
    var numfields = 10;

/*    // seta os meses e o ano
    for (i = 0; i < numfields; i++)
    {
        var nmonth = parseInt(tMonth) + i;
        var year = tYear;
        if (nmonth > months.length - 1)
        {
            nmonth = parseInt(nmonth) - parseInt(months.length);
            year++;
        }
        var month = months[nmonth];
        var iter = month + "/" + year;
        frm.mes_ida.appendChild(createOptionTag(iter, iter));
        try 
        {
            frm.mes_volta.appendChild(createOptionTag(iter, iter));
        }
        catch (e)
        {
            //Nao ha voos de volta.
        }
    }

    // seta os dias
    for (i = 1; i <= 31; i++)
    {
        frm.dia_ida.appendChild(createOptionTag(i, i));
        try 
        {
            frm.dia_volta.appendChild(createOptionTag(i, i));
        }
        catch (e)
        {
            //Nao ha voos de volta.
        }
    }
        frm.dia_ida.selectedIndex = tDay - 1;

        try
        {
            frm.dia_volta.selectedIndex = tDay - 1; 
        }
        catch (e)
        {
        }
*/
}



/**
 * altera a data dos combos com texto 'dez/2005' de acordo com
 * a data escolhida no calendario
 * @type void
 */
function on_date_hide_change(field, flag)
{
    var frm = document.forms["busca_form"];
    var reg = /^(\d{2})\/(\d{2})\/(\d{4})$/;
    var res = reg.exec(field.value);

    var dia = res[1];
    var mes = res[2];
    var ano = res[3];

    with (frm)
    {
        month = months[parseInt(parseFloat(mes)) - 1];
        if (flag == 'ida')
        {
            for (i = 0; i < mes_ida.options.length; i++)
            {
                if (mes_ida.options[i].value == month + "/" + ano)
                {
                    mes_ida.selectedIndex = i;
                    dia_ida.selectedIndex = dia - 1;

                    // lembrando que quando o camarada troca a data da ida
                    // essa parte altera tambem a data de volta pro mesmo dia da
                    // data da ida
                    mes_volta.selectedIndex = i;
                    dia_volta.selectedIndex = dia - 1;
                    break;
                }
            }
        }
        if (flag == 'volta')
        {
            for (i = 0; i < mes_volta.options.length; i++)
            {
                if (mes_volta.options[i].value == month + "/" + ano)
                {
                    mes_volta.selectedIndex = i;
                    dia_volta.selectedIndex = dia - 1;
                    break;
                }
            }
        }
    }
}

/**
 * valida o form de pesquisa por passagens
 * @type bool
 */
function validarPesquisa()
{
	setaEmpresas();
    if(document.getElementById("idaevolta").checked == true)
    {
        desabilitavolta(false);
    }

    if(document.getElementById("idaevolta").checked == false)
    {
       desabilitavolta(true);
       var frm = document.forms["busca_form"];
       frm.ida.checked = true;
    }

    var frm = document.forms["busca_form"];
    var error = 0;
    //rescebe true ou false, de acordo com tipo de voo
    var nacional = document.getElementsByName('tipo_voo')[0].checked;
    var internacional = document.getElementsByName('tipo_voo')[1].checked;
    with (frm)
    {

        // testa a origem e destino nacional
        if(nacional){
           if (isEmpty(origem[0].value))
           {
            window.alert("Por favor informe a origem da viagem.");
            origem_view[0].focus();
            error++;
            return;
           }
           if (isEmpty(destino[0].value))
           {
            window.alert("Por favor informe o destino da viagem.");
            destino_view[0].focus();
            error++;
            return;
           }
           // valida o trajeto da viagem
           if (destino[0].value == origem[0].value)
           {
            window.alert("A cidade de origem e a cidade de destino nao podem ser iguais.");
            destino_view[0].focus()
            return;
           }
           //passa os valores do vetor de origem destino para um unico imput
           frm.codOrigem.value = origem[0].value;
           frm.codDestino.value = destino[0].value;
           frm.codOrigemView.value = origem_view[0].value;
           frm.codDestinoView.value = destino_view[0].value;
        }

        // testa a origem e destino internacional
        if(internacional){
           if (isEmpty(origem[1].value))
           {
            window.alert("Por favor informe a origem da viagem.");
            origem_view[1].focus();
            error++;
            return;
           }
           if (isEmpty(destino[1].value))
           {
            window.alert("Por favor informe o destino da viagem.");
            destino_view[1].focus();
            error++;
            return;
           }
           // valida o trajeto da viagem
           if (destino[1].value == origem[1].value)
           {
            window.alert("A cidade de origem e a cidade de destino nao podem ser iguais.");
            destino_view[1].focus()
            return;
           }
           //passa os valores do vetor de origem destino para um unico imput
           frm.codOrigem.value = origem[1].value;
           frm.codDestino.value = destino[1].value;
           frm.codOrigemView.value = origem_view[1].value;
           frm.codDestinoView.value = destino_view[1].value;
        }

        // testa a quantidade de passageiros
        qtpax = parseInt(qtadultos.value) +
                parseInt(qtcriancas.value) +
                parseInt(qtbebes.value);
        if (qtpax > 7)
        {
            window.alert("A quantidade maxima e de 7 passageiros.");
            qtadultos.focus();
            error++;
            return;
        }
        if (parseInt(qtbebes) > parseInt(qtadultos))
        {
            window.alert("O numero de bebes deve ser menor ou igual ao numero de adultos.");
            qtadultos.focus();
            error++;
            return;
        }

	 if (qtpax == 0)
	 {
		window.alert("Selecione pelo menos um passageiro.");
		qtadultos.focus();
		error++;
		return;
	 }
/*
        // validando as datas
        var spMesIda = frm.mes_ida[frm.mes_ida.selectedIndex].value.split("/");
        var mesIda = spMesIda[0];
        var anoIda = spMesIda[1];
        var dataIda = anoIda + "/" +
                  getMonth(mesIda) + "/" +
                  dia_ida[dia_ida.selectedIndex].value;
        var dataIda = new Date(anoIda,getMonth(mesIda),dia_ida[dia_ida.selectedIndex].value,23,59,59);
        var dataIdaForm = dia_ida[dia_ida.selectedIndex].value + "/" +
                      zfill(getMonth(mesIda) + 1, 2) + "/" +
                      anoIda;

        var spMesVolta = mes_volta[mes_volta.selectedIndex].value.split("/");
        var mesVolta = spMesVolta[0];
        var anoVolta = spMesVolta[1];
        var dataVolta = anoVolta + "/" +
                    getMonth(mesVolta) + "/" +
                    dia_volta[dia_volta.selectedIndex].value;
        var dataVolta = new Date(anoVolta,getMonth(mesVolta),dia_volta[dia_volta.selectedIndex].value,23,59,59);
        var dataVoltaForm = dia_volta[dia_volta.selectedIndex].value + "/" +
                        zfill(getMonth(mesVolta) + 1, 2) + "/" +
                        anoVolta;


        //validando se data é valida
        if (parseInt(dia_ida[dia_ida.selectedIndex].value) <10) {
            var diaida = '0' + dia_ida[dia_ida.selectedIndex].value
        } else {
            var diaida = dia_ida[dia_ida.selectedIndex].value
        }
        var dida = diaida+"/"+(getMonthtratado(mesIda))+"/"+anoIda
        if (!isDate(dida,"dd/MM/yyyy")) {
           window.alert('Data informado no campo data ida inválida.')
           return
        }
        if (parseInt(dia_volta.options[dia_volta.selectedIndex].value) <10) {
            diavolta = '0' + dia_volta[dia_volta.selectedIndex].value
        } else {
            diavolta = dia_volta[dia_volta.selectedIndex].value
        }        
        var dvolta = diavolta+"/"+(getMonthtratado(mesVolta))+"/"+anoVolta
        if (!isDate(dvolta,"dd/MM/yyyy")) {
           window.alert('Data informado no campo volta inválida.')
           return
        }

        //verifica se data de ida é anterior a data atual
	var now = new Date();     
        if (dataIda < now)
        {
            window.alert("A data de ida deve ser igual ou maior a data atual");
            error++;
            dia_ida.focus();
            return;
        }

        //verifica se data de ida é anterior a data volta
        if (dataIda > dataVolta && tipo_viagem[0].checked)
        {
            window.alert("A data de ida deve ser anterior a data de volta");
            error++;
            dia_ida.focus();
            return;
        }
*/
        // final da validacao dos campos caso nao haja nenhum erro
        // monta as datas nos campos hidden e o form e enviado
        if (error < 1)
        {
            /*dataida_hidden.value = dataIdaForm;

            if (tipo_viagem[0].checked)
            {
                datavolta_hidden.value = dataVoltaForm;
            }*/
            submit();
        }
    }
}
function setaEmpresas()
{
	var emp = document.getElementById('empresas')
	l = emp.getElementsByTagName('img');
	var empresas = '['
	var db = '';
	for (i=0;i<=l.length;i++)
	{
		try
		{
			if (l[i].getAttribute('value') == 'True')
			{
				if (empresas.length > 1)
				{
					empresas = empresas + ','
					db = db + ','
				}
				db = db+String(l[i].name)
				empresas = empresas+'"'+String(l[i].name)+'"'
			}
		}
		catch(e){}
	}
	empresas = empresas+']'
	document.getElementById('psq_empresas').value = empresas
	document.getElementById('psq_db').value = db

}
function setaRegiao(imagem)
{
	var emp = document.getElementById('empresas')
	l = emp.getElementsByTagName('img');
	var verdade = imagem
	for (i=0;i<=l.length;i++)
	{
		try
		{	
			if (l[i].getAttribute('value') != 'Expirado'){
			var id = l[i].getAttribute('id')
			if(verdade == 'True')
			{
				if (id != 'Gol' && id != 'NovaTam' && id != 'Azul')
				{
					l[i].setAttribute('value','False')
					statusimagem = l[i].getAttribute('desativo')
					//l[i].setAttribute('src',statusimagem)
                                        try{
                                                l[i].previousSibling.checked = false;
                                            }catch(e){}
				}
				else if (id == 'Gol' || id == 'NovaTam' || id == 'Azul')
				{
					l[i].setAttribute('value','True')
					statusimagem = l[i].getAttribute('ativo')
					//l[i].setAttribute('src',statusimagem)
                                        try{
                                                l[i].previousSibling.checked = true;
                                            }catch(e){}
				}
			}
			else 
			{
				if (id == 'Gol' || id == 'NovaTam' || id == 'Azul')
				{
					l[i].setAttribute('value','False')
					statusimagem = l[i].getAttribute('desativo')
					//l[i].setAttribute('src',statusimagem)
                                        try{
                                                l[i].previousSibling.checked = false;
                                            }catch(e){}
				}
				else if (id != 'Gol' && id != 'NovaTam' && id != 'Azul')
				{
					l[i].setAttribute('value','True')
					statusimagem = l[i].getAttribute('ativo')
					//l[i].setAttribute('src',statusimagem)
                                        try{
                                                l[i].previousSibling.checked = true;
                                            }catch(e){}
				}
			}
			}
		}
		catch(e){}
	}
}

function mostraFiltroPsq()
{
       var valor = document.getElementById('filtro_selecao').value;
       if (valor == 'True')
       {
           document.getElementById('filtro_selecao').value = 'False'; 
           document.getElementById('filtro_opcoes').style['display'] = 'none';
           document.getElementById('filtro_cias').style['display'] = 'none';
       }
       else
       {
           document.getElementById('filtro_selecao').value = 'True'; 
           document.getElementById('filtro_opcoes').style['display'] = 'block';
           document.getElementById('filtro_cias').style['display'] = 'block';
       }
}
