﻿// ~ pack at http://dean.edwards.name/packer/ 


// ~~~~ INICIALIZADOR ~~~~~~~~~~~~~~~~~~~
addEvent(window, 'load', init);


    	

// ********************************************************** //
// >>> FUNÇÕES AUXILIARES
// ********************************************************** //

// alias para getElementById
function $(id) { return document.getElementById(id); };

// retorna o valor selecionado em um select-input
function $sv(id){ return $(id).options[$(id).selectedIndex].value; };

function addEvent( obj, type, fn )
{
	if (obj.addEventListener){
		obj.addEventListener( type, fn, false );
	}else if (obj.attachEvent)
	{
		obj.attachEvent( "on"+type, fn );
	} 
};

function addHidden(parentNode, name, value) {
	var e = document.createElement('input');
	e.setAttribute('type', 'hidden');
	parentNode.appendChild(e);
	e.setAttribute('name', name);
	e.setAttribute('value', value);
};

// filtra os caracteres permitidos em um campo
// o segundo parâmetro define o que será removido
function setInputFilter (element, regexp)
{
	addEvent(element, 'keyup', function (e) {
		element.value = element.value.replace(regexp, '');
	});
}; // end setInputFilter 


// pula o cursor automaticamente caso tenha atingido a quantidade máxima de 
// caracteres
function setAutoTab(element, maxChar, nxtElement) {
	addEvent(element, 'keyup', function (e)	{
		var key;
        if (document.all) {
            var evnt = window.event;
            key = evnt.keyCode;
        }
        else {
            key = e.keyCode;
        }
        
        // ignorar comandos específicos
        switch (key) {
        	case 8:  // backspace
        	case 9:  // tab 
        	case 16: // shift
        	case 17: // ctrl
        	case 18: // alt
        		return;
        		
        	default: break;
        }
        
		// se exceder a quantidade de caracteres, corta (no caso de derem um 
		// Ctrl+v )
		if (element.value.length > maxChar) {
			element.value = element.value.substr(0,maxChar);
		}
		
		// se chegou ao limite, vai pro próximo elemento
		if (element.value.length == maxChar) {
			// caso a linha seguinte estiver lançando uma Excessão "Permission 
			// denied to get property XULElement.selectedIndex", coloque no 
			// input o seguinte atributo: autocomplete="off" (bug firefox)
			try
			{
	            nxtElement.focus();
			}
			catch(ex){}
		}
		
	});
}; // end setAutoTab



function padLeft(value, maxChar, padString) {
	value = value.toString();

	while (value.length < maxChar) {
		value = padString + value;
	}

	if (value.length > maxChar) {
		return value.substr(value.length - maxChar);
	}
	
	return value;
}

// ********************************************************** //
// >>> FUNÇÕES DE DATA
// ********************************************************** //


function setCampoData(element, description, maxChar){
	element.value = description;
	
	setInputFilter (element, new RegExp(/[^0-9]/gi));
	
	addEvent(element, 'focus', function () {
		if (element.value == description) {
			element.value = '';
		}
	});
	
	addEvent(element, 'blur', function () {
		if (element.value == '') {
			element.value = description;
		} else {
			element.value = padLeft(element.value, maxChar, '0');
		}
	});
	
}

// converte d/m/y para objeto data
function dmy2dto (d, m, y) {
    var dto = new Date();
	dto.setFullYear(y,parseInt(m, 10)-1,d);
	return dto;
};

function somaDias(objData, intDias) {
	var diaTs = 1000*60*60*24;
	var d = new Date();
	d.setTime(objData.getTime() + (intDias*diaTs));
	return d;
};

function putLeadingZero(input){
	var str = input.toString();
	return (str.length < 2) ? ('0'+str) : str;
};


// valida data (string dd/mm/yyyy)
function validaData (d, m, y) {
	if (d == DAY_INLINE_DESCRIPTION || m == MONTH_INLINE_DESCRIPTION
		|| y == YEAR_INLINE_DESCRIPTION ) {
		return false;
	}
	
	// valida ano
	var ano = parseInt(y, 10);
	if (ano < 0) {return false;}
	
	// valida mes
	var mes = parseInt(m, 10);
	if (mes < 1 || mes > 12 ) {return false;}
	
	// valida dia
	var dia = parseInt(d, 10);
	switch (mes) {
		case 2:
			var bsxt = ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) ? true : false;
			if (bsxt && dia > 29) { return false; }
			if (!bsxt && dia > 28) { return false; }	
			break;
			
		case 1: case 3: case 5: case 7: 
		case 8: case 10: case 12:
			if (dia > 31) { return false; }
			break;
			
		case 4: case 6: 
		case 9: case 11:
			if (dia > 30) { return false; }
			break;
			
		default:
			return false;
			
	} // end switch
	    		
	return true;
	
}; // validaData


// ********************************************************** //
// >>> ROTINAS DE EVENTOS
// ********************************************************** //
var DAY_INLINE_DESCRIPTION = 'dd';
var MONTH_INLINE_DESCRIPTION = 'mm';
var YEAR_INLINE_DESCRIPTION = 'aaaa';


// inicialização geral
function init () {
	
	// pega a configuração externa ao iframe
//	if (parent && parent.buscatrip_css && parent.buscatrip_css != '') {
//		var t = document.getElementById("linkTema");
//		t.setAttribute('href',parent.buscatrip_css);
//	}
		
	$('btnPesquisar').onclick = submitFormulario;
	
	hoje = new Date();
	hoje.setDate(hoje.getDate() + 3);
	mes = hoje.getMonth() + 1;
	
	// configuração dos campos de data	
//	setCampoData($('txiIdaDia'), DAY_INLINE_DESCRIPTION, 2);
	$('txiIdaDia').value = (hoje.getDate().toString().length == 1 ? '0' + hoje.getDate().toString() : hoje.getDate().toString());
	setAutoTab($('txiIdaDia'), 2, $('txiIdaMes'));
	
//	setCampoData($('txiIdaMes'), MONTH_INLINE_DESCRIPTION, 2);
	$('txiIdaMes').value = (mes.toString().length == 1 ? '0' + mes : mes);
	setAutoTab($('txiIdaMes'), 2, $('txiIdaAno'));
	
//	setCampoData($('txiIdaAno'), YEAR_INLINE_DESCRIPTION, 4);
	$('txiIdaAno').value = hoje.getFullYear();
	setAutoTab($('txiIdaAno'), 4, $('txiVoltaDia'));
	
	hoje.setDate(hoje.getDate() + 11);
	mes = hoje.getMonth() + 1;
	
//	setCampoData($('txiVoltaDia'), DAY_INLINE_DESCRIPTION, 2);
    $('txiVoltaDia').value = (hoje.getDate().toString().length == 1 ? '0' + hoje.getDate().toString() : hoje.getDate().toString());
	setAutoTab($('txiVoltaDia'), 2, $('txiVoltaMes'));
	
//	setCampoData($('txiVoltaMes'), MONTH_INLINE_DESCRIPTION, 2);
    $('txiVoltaMes').value = (mes.toString().length == 1 ? '0' + mes : mes);
	setAutoTab($('txiVoltaMes'), 2, $('txiVoltaAno'));
	
//	setCampoData($('txiVoltaAno'), YEAR_INLINE_DESCRIPTION, 4);
    $('txiVoltaAno').value = hoje.getFullYear();
	//setAutoTab($('txiIdaAno'), 4, $('txiVoltaDia'));
	
	preencheCampos();
	
}; // end init 

function preencheCampos()
{
    // Definir locais de origem e destino
    if(QueryString("origem") != null){ 
        selecionarItemCombo($('sbOrigem'), QueryString("origem"), "val");
    }
    
    if(QueryString("destino") != null){
        selecionarItemCombo($('sbDestino'), QueryString("destino"), "val");
    }
    
    // Definir se é ida e volta ou somente ida
    if(QueryString("IdaVolta") != null){
        if(QueryString("IdaVolta") == "0"){
            $('rdSoIda').checked = true;
            $('divDataVolta').style.visibility='hidden';
            $('txiVoltaDia').disabled = true;
        }else {
            $('rdIdaVolta').checked = true;
        }
    }
    
    // Definir datas de saida e chegada
    defineData($('txiIdaDia'), $('txiIdaMes'), $('txiIdaAno'), QueryString("dataIda"));
    defineData($('txiVoltaDia'), $('txiVoltaMes'), $('txiVoltaAno'), QueryString("dataVolta"));
}

function selecionarItemCombo(obj, str)
{
    if(str != null){
        //Varrer todas as opcoes do combo para encontrar o item à selecionar... 
        for (var i=1;i < obj.length;i++){ 
            if(obj[i].value.toLowerCase().indexOf(str.toLowerCase()) > -1){ 
                obj.selectedIndex=i; 
                break;
            } 
        }
    }
}

function defineData(objDia, objMes, objAno, data)
{
    if(data != null){
        // Instanciar obj e definir valores para a data 
        objDia.value = obterData(data, "day");
        objMes.value = obterData(data, "month");
        objAno.value = obterData(data, "year");
    }
}

function obterData(data, param)
{
    data = data.toString('dd/MM/yyyy');
    if(param == "day"){
        return data.substring(0, 2);
    }else if(param == "month"){
        return data.substring(3, 5);
    }else if(param == "year"){
        return data.substring(6, 10);
    }else{
        return null;
    }
}

// valida, popula o formulário oficial e envia os dados
function submitFormulario () {
  	
  	var lsErrors = validarFormulario();
 
  	if (lsErrors.length > 0) {
//  		alert("Atenção: \n"+lsErrors.join("\n"));
//  		return false;
        
        // caso encontre algum erro de preenchimento, apenas redireciona para a home 
        submitOficial("/Home.aspx");
  	}
  	else {
	    submitOficial(null);
	}
    return false;
    
}; // end submitFormulario



// valida o formulário, caso haja algum erro, retorna um array com a lista de erros, se estiver tudo correto, retorna um array vazio
function validarFormulario () {
	var lsErrors = [];
	
	var valorSbOrigem = $sv("sbOrigem");
	if (!valorSbOrigem) {
		lsErrors.push('Selecione o local de Origem.'); 
	}
	
	var valorSbDestino = $sv("sbDestino");
	if (!valorSbDestino)	{
		lsErrors.push('Selecione o local de Destino.'); 
	}
	
	if (valorSbOrigem == valorSbDestino && valorSbOrigem != '') {
		lsErrors.push('Selecione um Destino diferente da Origem.');
	}
	
	var DataIda = 0;
	if (!validaData($('txiIdaDia').value,$('txiIdaMes').value,$('txiIdaAno').value)) {
		lsErrors.push('Preencha a data de Ida corretamente.'); 
	} else {
	    var hoje = new Date();
	    if($('txiIdaAno').value < hoje.getFullYear())
	    {
	        $('txiIdaAno').value = hoje.getFullYear();
	    }
	
		DataIda = dmy2dto($('txiIdaDia').value,$('txiIdaMes').value,$('txiIdaAno').value).getTime();
		if (!DataIda) { 
			lsErrors.push('Preencha a data de Ida corretamente.'); 
		} else if (DataIda < somaDias(hoje,3)) {
			var d = somaDias(hoje,3);
			lsErrors.push('A data de Ida deve ser após '+d.getDate()+'/'+(d.getMonth()+1)+'.'); 
		} else if (parseInt($('txiIdaAno').value, 10) > (hoje.getFullYear()+2) ) {
			lsErrors.push('A data de Ida é muito distante'); 
		}
	}
	
	var DataVolta = 0;
    if (!$("rdSoIda").checked){
    	if (!validaData($('txiVoltaDia').value,$('txiVoltaMes').value,$('txiVoltaAno').value)) {
			lsErrors.push('Preencha a data de Volta corretamente.'); 
		} else {
		    var hoje = new Date();
	        if($('txiVoltaAno').value < hoje.getFullYear())
	        {
	            $('txiVoltaAno').value = hoje.getFullYear();
	        }
			DataVolta = dmy2dto($('txiVoltaDia').value,$('txiVoltaMes').value,$('txiVoltaAno').value).getTime();
			if (!DataVolta) {
	  			lsErrors.push('Preencha a Data de Volta corretamente.'); 
	  		} else if (parseInt($('txiVoltaAno').value, 10) > (hoje.getFullYear()+2) ) {
				lsErrors.push('A data de Volta é muito distante'); 
			}
		}
	} // end !$("rdSoIda").checked
  	
  	if (DataIda && DataVolta && DataIda > DataVolta) {
  		lsErrors.push('A data da Volta não pode ser anterior à data da Ida.');
  	}
	
	return lsErrors;
	
}; // end validarFormulario 



function submitOficial (url) {
	
	// configura o formulário
	var f = document.createElement('form');
	var pr = "";
	
	if(QueryString("pr") != null && QueryString("pr") != "")
	{   
	    if(url == null)
	    {
	        pr = "&pr=";
	        pr += QueryString("pr");
	    }
	    else
	    {
	        url += "&pr=";
	        url += QueryString("pr");
	    }
	}
	
	var queryString = "";
	
	// configura os parâmetros
	var idaVolta = ($("rdSoIda").checked ? "0": "1");

	var origem = $sv("sbOrigem");
	var destino = $sv("sbDestino");
	
	var ida = $("txiIdaDia").value+'/'+$("txiIdaMes").value+'/'+$("txiIdaAno").value;
	var volta = $("txiVoltaDia").value+'/'+$("txiVoltaMes").value+'/'+$("txiVoltaAno").value;
	
	var classe = $sv("sbClasse");

    if (url == null) {
	    f.setAttribute('action', '/Resultado.aspx?origem=' + origem + '&destino=' + destino + '&dataida=' + ida + '&idaVolta=' + idaVolta + '&validado=1&datavolta=' + volta + '&classe=' + classe + '&adt=1&chd=0&inf=0' + pr);
	}
	else {
	    f.setAttribute('action', url);
	}
	f.setAttribute('target','_blank');
	f.setAttribute('method','post');
	document.body.appendChild(f);
	
	// envia
	f.submit();
	
}; // end submitOficial

