$(function(){

    $('#formCadastro').formAjax(function(msg){
        showDialog(msg)
    });

    $('#formOrcamento').formAjax(function(msg){
        if(msg == 'ok'){
            showDialog('Orçamento enviado com sucesso.');
            $('#formOrcamento').find('input, select, textarea').val('');
        }else{
            showDialog(msg);
        }
    });
	
    $('#formTrabalhe').formAjax(function(msg){
        if(msg == 'ok'){
            showDialog('Curriculo cadastrado com sucesso.');
            $('#formOrcamento').find('input, select, textarea').val('');
        }else{
            showDialog(msg);
        }
    });

    $('#formLogin').formAjax(function(msg){
        if(msg == 'ok'){
            window.location = _rootPath + 'turismo-fretamento';
        }else{
            showDialog(msg);
        }
    });

    $('#formLembrar').formAjax(function(msg){
        if(msg == 'ok'){
            $('#formLogin').show();
            $('#formLembrar').hide()
            showDialog("Uma nova senha foi envia por e-mail.");
        }else{
            showDialog(msg);
        }
    });


    if($('#tp_rota').val() != ''){
        $('#tx_origem, #tx_destino').removeAttr('disabled')
        $('#tx_origem').autocompleteJson(_rootPath + 'ajax/autocomplete-origem.php?tp_rota=' + $('#tp_rota').val());
        $('#tx_destino').autocompleteJson(_rootPath + 'ajax/autocomplete-origem.php?tp_rota=' + $('#tp_rota').val());
    }
    
    $('#tp_rota').change(function(){
        if($(this).val() != ''){
            $('#tx_origem, #tx_destino').removeAttr('disabled')
            $('#tx_origem').autocompleteJson(_rootPath + 'ajax/autocomplete-origem.php?tp_rota=' + $(this).val());
            $('#tx_destino').autocompleteJson(_rootPath + 'ajax/autocomplete-origem.php?tp_rota=' + $(this).val());
        }
    });

    $('#id_estado_origem').change(function(){
        if($(this).val() != ''){
            $.getJSON(_rootPath + 'ajax/json-cidade.php?id_estado=' + $(this).val(), null, function(data) {
                $('#orcamento-id_cidade_origem').populateSelectJson(data);
            });
        }
    });

    $('#id_estado_destino').change(function(){
        if($(this).val() != ''){
            $.getJSON(_rootPath + 'ajax/json-cidade.php?id_estado=' + $(this).val(), null, function(data) {
                $('#orcamento-id_cidade_destino').populateSelectJson(data);
            });
        }
    });

    $('#btnFormHorario').click(function(){
        var tpRota = $('#tp_rota').val();
        var txOrigem = $('#tx_origem').val();
        var txDestino = $('#tx_destino').val();
        var hrInicial = $('#hr_inicial').val();
        var hrFinal = $('#hr_final').val();

        if(tpRota == ''){
            showDialog("Favor selecione o que você precisa.");
        } else if(txOrigem == ''){
            showDialog("Favor selecione de onde vai sair.");
        } else if(txDestino == ''){
            showDialog("Favor selecione onde vai chegar.");
        } else if(compareHour(hrInicial, hrFinal)){
            showDialog("A hora inicial n&atilde;o pode ser maior ou igual à hora final.");
        } else if(txOrigem == txDestino){
            showDialog("O Destino n&atilde;o pode ser o mesmo que a Origem.");
        } else {
            var url;
            switch (tpRota) {
                case 'O':
                    url = 'cco';
                    break;
                case 'A':
                    url = 'cca'
                    break;
                default:
                    url = 'avoa';
                    break;
            }
            $('#formHorario')
            .attr('action', _rootPath + url)
            .submit();
        }
        
        return false;
    });

});


/* gera um autocomplete com json */
$.fn.autocompleteJson = function(url){
    this.autocomplete({
        source: url,
        minLength: 2,
        select: false
    });
}

function compareHour(hour1, hour2){

    if(hour1 == '__:__' || hour1 == ''){
        return true;
    }
    if(hour2 == '__:__' || hour2 == ''){
        return true;
    }

    var ahour = hour2.split(':');
    var hi = parseInt(ahour[0],10);
    var mi = parseInt(ahour[1],10);

    ahour = hour1.split(':');
    var hf = parseInt(ahour[0],10);
    var mf = parseInt(ahour[1],10);

    if ( hf * 60 + mf * 1 < hi * 60 + mi * 1 ) {
        return false;
    }

    return true;
}

$.fn.populateSelectJson = function(data){
    var html = '';
    for (var i in data) {
        html += '<option value="' + i + '">'+ data[i] +'</option>';
    }
    this.html(html);
}

$.fn.formAjax = function(success){
    /*
    $(this).submit(function(){
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serializeArray(),
            success: success
        });
        return false;
    });
    return false;*/

    $(this).ajaxForm(success);
}



function showDialog(message)
{
    var html = '';
    html+= '<div id="dialog" title="Mensagem">'
    +       '<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>'
    +       '<p>' + message + '</p>'
    +   '</div>';

    var options = {
        buttons: {
            Ok: function() {
                $("#dialog").dialog('close');
                $("#dialog").remove();
            }
        },
        close: function() {
            $("#dialog").remove()
        },
        modal: true
    }

    $("body").append(html);
    $("#dialog").dialog(options)
}

