$(function(){
    if ($('#tmpFamily').val() != '') {
        setCarType($('#tmpFamily').val());
    }
    $('#searchFamily').change(function() {
        clearCarType();
        clearCarModel();
        setCarType($(this).val());
    });

    $('#searchType').change(function(){
        clearCarModel();
        setCarModel($(this).val());
    });
    if ($('#tmpFamilyLeft').val() != '') {
        setCarType($('#tmpFamilyLeft').val(), 'Left');
    }
    $('#searchFamilyLeft').change(function() {
        clearCarType('Left');
        clearCarModel('Left');
        setCarType($(this).val(), 'Left');
    });

    $('#searchTypeLeft').change(function(){
        clearCarModel('Left');
        setCarModel($(this).val(), 'Left');
    });
    
    $('#carDetailPrint').click(function(){
        window.open(LANGROOT + '/car-offer/car-print/id/' + $(this).attr('rel') + '/');
        return false;
    })
});

function clearCarType(suffix) {
    if (typeof(suffix) == 'undefined') {suffix = '';}
    $("#searchType" + suffix + "> option[value!='']").remove();
    $('#tmpType' + suffix).val('');
}

function clearCarModel(suffix) {
    if (typeof(suffix) == 'undefined') {suffix = '';}
    $("#searchModel" + suffix + " > option[value!='']").remove();
    $('#tmpModel' + suffix).val('');
}

function setCarType(brand, suffix) {
    if (typeof(suffix) == 'undefined') {suffix = '';}
    if (brand) { 
        $.ajax({
            url: WEBROOT + '/ajax/get-car-types/brand/' + brand,
            dataType: 'json',
            success: function(res) {
                for (i in res) {
                    var el = '<option value="' + res[i][0] + '" ' + ($('#tmpType' + suffix).val() == res[i][0] ? 'selected="selected"' : '') + '>' +  res[i][1] + '</option>';
                    $('#searchType' + suffix).append(el);
                }
                if ($('#tmpType' + suffix).val() != '') {
                    setCarModel($('#tmpType' + suffix).val(), suffix);
                }
            }
        });
    }
}

function setCarModel(type, suffix) {
    if (typeof(suffix) == 'undefined') {suffix = '';}
    $.ajax({
        url: WEBROOT + '/ajax/get-car-models/type/' + type,
        dataType: 'json',
        success: function(res) {
            for (i in res) {
                var el = '<option value="' + res[i][0] + '" ' + ($('#tmpModel' + suffix).val() == res[i][0] ? 'selected="selected"' : '') + '>' +  res[i][1] + '</option>';
                $('#searchModel' + suffix).append(el);
            }
        }
    });
}

