﻿//addEvent(window, 'load', init);
$(document).ready(function(){
	init();
});

    	

// ********************************************************** //
// >>> FUNÇÕES AUXILIARES
// ********************************************************** //

// alias para getElementById
function getE(id) { return document.getElementById(id); };

// retorna o valor selecionado em um select-input
function getEsv(id){ return getE(id).options[getE(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 () {
	
	if(getE('searchForm')){
		// 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);
	//	}
		
		getE('btnPesquisar').onclick = submitFormulario;
		
		hoje = new Date();
		hoje.setDate(hoje.getDate() + 3);
		mes = hoje.getMonth() + 1;
		
		// configuração dos campos de data	
	//	setCampoData(getE('txiIdaDia'), DAY_INLINE_DESCRIPTION, 2);
		getE('txiIdaDia').value = (hoje.getDate().toString().length == 1 ? '0' + hoje.getDate().toString() : hoje.getDate().toString());
		setAutoTab(getE('txiIdaDia'), 2, getE('txiIdaMes'));
		
	//	setCampoData(getE('txiIdaMes'), MONTH_INLINE_DESCRIPTION, 2);
		getE('txiIdaMes').value = (mes.toString().length == 1 ? '0' + mes : mes);
		setAutoTab(getE('txiIdaMes'), 2, getE('txiIdaAno'));
		
	//	setCampoData(getE('txiIdaAno'), YEAR_INLINE_DESCRIPTION, 4);
		getE('txiIdaAno').value = hoje.getFullYear();
		setAutoTab(getE('txiIdaAno'), 4, getE('txiVoltaDia'));
		
		hoje.setDate(hoje.getDate() + 11);
		mes = hoje.getMonth() + 1;
		
	//	setCampoData(getE('txiVoltaDia'), DAY_INLINE_DESCRIPTION, 2);
		getE('txiVoltaDia').value = (hoje.getDate().toString().length == 1 ? '0' + hoje.getDate().toString() : hoje.getDate().toString());
		setAutoTab(getE('txiVoltaDia'), 2, getE('txiVoltaMes'));
		
	//	setCampoData(getE('txiVoltaMes'), MONTH_INLINE_DESCRIPTION, 2);
		getE('txiVoltaMes').value = (mes.toString().length == 1 ? '0' + mes : mes);
		setAutoTab(getE('txiVoltaMes'), 2, getE('txiVoltaAno'));
		
	//	setCampoData(getE('txiVoltaAno'), YEAR_INLINE_DESCRIPTION, 4);
		getE('txiVoltaAno').value = hoje.getFullYear();
		//setAutoTab(getE('txiIdaAno'), 4, getE('txiVoltaDia'));
		
		preencheCampos();
	}
	
}; // end init 

function preencheCampos()
{
    // Definir locais de origem e destino
    if(QueryString("origem") != null){ 
        selecionarItemCombo(getE('sbOrigem'), QueryString("origem"), "val");
    }
    
    if(QueryString("destino") != null){
        selecionarItemCombo(getE('sbDestino'), QueryString("destino"), "val");
    }
    
    // Definir se é ida e volta ou somente ida
    if(QueryString("IdaVolta") != null){
        if(QueryString("IdaVolta") == "0"){
            getE('rdSoIda').checked = true;
            getE('divDataVolta').style.visibility='hidden';
            getE('txiVoltaDia').disabled = true;
        }else {
            getE('rdIdaVolta').checked = true;
        }
    }
    
    // Definir datas de saida e chegada
    defineData(getE('txiIdaDia'), getE('txiIdaMes'), getE('txiIdaAno'), QueryString("dataIda"));
    defineData(getE('txiVoltaDia'), getE('txiVoltaMes'), getE('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("http://www.shoppinguolviagens.com.br/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 = getEsv("sbOrigem");
	if (!valorSbOrigem) {
		lsErrors.push('Selecione o local de Origem.'); 
	}
	
	var valorSbDestino = getEsv("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(getE('txiIdaDia').value,getE('txiIdaMes').value,getE('txiIdaAno').value)) {
		lsErrors.push('Preencha a data de Ida corretamente.'); 
	} else {
	    var hoje = new Date();
	    if(getE('txiIdaAno').value < hoje.getFullYear())
	    {
	        getE('txiIdaAno').value = hoje.getFullYear();
	    }
	
		DataIda = dmy2dto(getE('txiIdaDia').value,getE('txiIdaMes').value,getE('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(getE('txiIdaAno').value, 10) > (hoje.getFullYear()+2) ) {
			lsErrors.push('A data de Ida é muito distante'); 
		}
	}
	
	var DataVolta = 0;
    if (!getE("rdSoIda").checked){
    	if (!validaData(getE('txiVoltaDia').value,getE('txiVoltaMes').value,getE('txiVoltaAno').value)) {
			lsErrors.push('Preencha a data de Volta corretamente.'); 
		} else {
		    var hoje = new Date();
	        if(getE('txiVoltaAno').value < hoje.getFullYear())
	        {
	            getE('txiVoltaAno').value = hoje.getFullYear();
	        }
			DataVolta = dmy2dto(getE('txiVoltaDia').value,getE('txiVoltaMes').value,getE('txiVoltaAno').value).getTime();
			if (!DataVolta) {
	  			lsErrors.push('Preencha a Data de Volta corretamente.'); 
	  		} else if (parseInt(getE('txiVoltaAno').value, 10) > (hoje.getFullYear()+2) ) {
				lsErrors.push('A data de Volta é muito distante'); 
			}
		}
	} // end !getE("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 = (getE("rdSoIda").checked ? "0": "1");

	var origem = getEsv("sbOrigem");
	var destino = getEsv("sbDestino");
	
	var ida = getE("txiIdaDia").value+'/'+getE("txiIdaMes").value+'/'+getE("txiIdaAno").value;
	var volta = getE("txiVoltaDia").value+'/'+getE("txiVoltaMes").value+'/'+getE("txiVoltaAno").value;
	
	var classe = getEsv("sbClasse");

    if (url == null) {
	    f.setAttribute('action', 'http://www.shoppinguolviagens.com.br/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

function MM_swapImgRestore() 
{ 
    //v3.0
    var i,x,a=document.MM_sr; 
    for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
    {
        x.src=x.oSrc;
    }
}

function MM_swapImage() 
{ 
    //v3.0
    var i,j=0,x,a=MM_swapImage.arguments; 
    document.MM_sr=new Array; 
    for(i=0;i<(a.length-2);i+=3)
    {
        if ((x=MM_findObj(a[i]))!=null)
        {
            document.MM_sr[j++]=x; 
            if(!x.oSrc) 
            {
                x.oSrc=x.src; 
            }
            x.src=a[i+2];
        }
    }
}

function MM_findObj(n, d)
{ 
    //v4.01
    var p,i,x;  
    if(!d) 
    {
        d=document; 
    }
    if((p=n.indexOf("?"))>0&&parent.frames.length) 
    {
        d=parent.frames[n.substring(p+1)].document; 
        n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all) 
    {
        x=d.all[n]; 
    }
    for (i=0;!x&&i<d.forms.length;i++) 
    {
        x=d.forms[i][n];
    }
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
    {
        x=MM_findObj(n,d.layers[i].document);
    }
    if(!x && d.getElementById) 
    {
        x=d.getElementById(n); 
    }
    return x;
}

