var Interval;
var count = 0;
var DATA_DISPLAY_MODE = 0;
var sAjaxErrorString = 'По данному запросу ничего не найдено! \nПопробуйте изменить запрос.';
var bInAjaxProcess = false;

function make_targets (obj) {
    var obj;
    var html_2 = '<option value=""></option>';
    var html_3 = '<option value=""></option>';
    for (var i in obj) {
        if (obj[i]['dest']) html_3 += '<option value="' + obj[i]['dest'] + '">' + obj[i]['dest'] + '</option>';
        if (obj[i]['line']) html_2 += '<option value="' + obj[i]['line'] + '">' + obj[i]['line'] + '</option>';
    }
    $('#fld_2').empty().append(html_2);
    $('#fld_3').empty().append(html_3);
}

function make_lines (obj) {
    var obj, id, line, dest, time, days, miles, cost, carrier;
    if (obj.length < 1) {
        $('#alert').text(sAjaxErrorString).show();
        alert_show();
        return;
    }
    var html = '<tr id="res_tit">';
    if ((DATA_DISPLAY_MODE & 1) == 1) html += '<th>Номер маршрута</th>';
    if ((DATA_DISPLAY_MODE & 2) == 2) html += '<th>Пункт назначения</th>';
    if ((DATA_DISPLAY_MODE & 4) == 4) html += '<th>Время отправления</th>';
    if ((DATA_DISPLAY_MODE & 8) == 8) html += '<th>Дни следования</th>';
    if ((DATA_DISPLAY_MODE & 16) == 16) html += '<th>Расстояние, км</th>';
    if ((DATA_DISPLAY_MODE & 32) == 32) html += '<th>Стоимость</th>';
    if ((DATA_DISPLAY_MODE & 64) == 64) html += '<th>Автопредприятие</th>';
    html += '</tr>';
    for (var row in obj) {
        id = (obj[row]['id']) ? obj[row]['id'] : '';
        line = (obj[row]['line']) ? obj[row]['line'] : '';
        dest = (obj[row]['destination']) ? obj[row]['destination'] : '';
        time = (obj[row]['time']) ? obj[row]['time'] : '';
        days = (obj[row]['days']) ? obj[row]['days'] : '';
        miles = (obj[row]['miles']) ? obj[row]['miles'] : '';
        cost = (obj[row]['cash']) ? obj[row]['cash'] : '';
        carrier = (obj[row]['carrier']) ? obj[row]['carrier'] : '';
        if (id != '') {
            html += '<tr>';
            if ((DATA_DISPLAY_MODE & 1) == 1) html += '<td>' + line + '</td>';
            if ((DATA_DISPLAY_MODE & 2) == 2) html += '<td>' + dest + '</td>';
            if ((DATA_DISPLAY_MODE & 4) == 4) html += '<td class="center">' + time + '</td>';
            if ((DATA_DISPLAY_MODE & 8) == 8) html += '<td>' + days + '</td>';
            if ((DATA_DISPLAY_MODE & 16) == 16) html += '<td class="center">' + miles + '</td>';
            if ((DATA_DISPLAY_MODE & 32) == 32) html += '<td class="center">' + cost + '</td>';
            if ((DATA_DISPLAY_MODE & 64) == 64) html += '<td>' + carrier + '</td>';
            html += '</tr>';
        }
    }
    $('#result table').append(html);
    $('#result table tr:nth-child(odd)').addClass('t_1');
    $('#result table tr:nth-child(even)').addClass('t_2');
    $('#result table tr:nth-child(1)').removeAttr('class');
    $('#result').show();

	$('.t_1, .t_2').hover(
    function () {
        changed = $(this).css('background-color');
        $(this).css('background-color', '#eeeeee');
    },
    function () {
        $(this).css('background-color', changed);
    });

    $('#fld_4').blur();
}

function make_mode (str) {
    var str;
    DATA_DISPLAY_MODE = parseInt(str);
}

function add_dot () {
	var text = $('#loading').html();
	$('#loading').html($('#loading').html() + ' .');
	count++;
	if (count > 5) {
		$('#loading').html(text);
		count = 0;
	}
}

function load_destinations () {
    $.getJSON('/inc/ajax.php', { q:'target_list', id:$('#fld_1').val() }, make_targets);
    $.get('/inc/ajax.php', {q:'mode_list', id:$('#fld_1').val()}, make_mode);
}

function reset_fields () {
    $("#fld_2").val('');
    $("#fld_3").val('');
    $("#fld_4").val('');
    $('#chk_1').attr('checked', false);
    $('#chk_2').click();
}

$(document).ready( function () {

    load_destinations();

    $('#fld_4').suggest(
        "/inc/ajax.php",
        { onSelect: function () { $("#fld_4").focus(); }, idObjName: '#fld_1' }
    );

    $("#fld_1").change( function () {
        reset_fields();
        load_destinations();
    });

    $("#chk_2").click( function () {
        $('#fld_3').val('').show();
        $('#fld_4').hide();
    });

    $("#chk_3").click( function () {
        $('#fld_4').val('').show();
        $('#fld_3').hide();
    });

    $('#select').submit( function () {
        if (bInAjaxProcess) return false;
        var line = $.trim($("#fld_2").val());
        var dest = $.trim($("#fld_3").val());
        if (dest == '') dest = $.trim($("#fld_4").val());
        $('#result table').empty();
        $('#result').hide();
        if (line == '' && dest == '') {
            $('#alert').text('Введите пункт назначения и/или номер рейса!').show();
            alert_show();
        }
        else {
            $.getJSON(
                '/inc/ajax.php',
                {q:'lines_list', l:line, d:dest, id:$('#fld_1').val(), e:($('#chk_1').attr('checked') ? '1' : '0')},
                make_lines
            );
        }
        return false;
    });

    $('#reset_btn').click( function () {
        reset_fields();
    });

}).ajaxStart( function () {
    $('#loading').show();
    Interval = setInterval('add_dot()', 500);
    bInAjaxProcess = true;
}).ajaxStop( function () {
    $('#loading').hide();
    clearInterval(Interval);
    bInAjaxProcess = false;
}).ajaxError( function (request, settings) {
    $('#alert').text(sAjaxErrorString).show();
    alert_show();
    bInAjaxProcess = false;
});