$(document).ready(function(){
    // INITIALIZE FORM ELEMENTS

    InitializeFormElements();
    
    $('.car-make').change(function(){
        SetModelOptions(
            '.car-model',
            $(this).val(),
            '-- Select Model --'
        );
    });
    $('.car-model, .car-make').change(function(){
        SetYearOptions(
            '.car-year',
            $('.car-make').val(),
            $('.car-model').val(),
            '-- Year --'
        );
    });
    
    SetModelOptions(
            '.car-model',
            $('.car-make').val(),
            '-- Select Model --'
    );
    SetYearOptions(
            '.car-year',
            $('.car-make').val(),
            $('.car-model').val(),
            '-- Year --'
    );
});

function InitializeFormElements() {
    $("input.labelinside, textarea.labelinside").each(function(i){
        if ( $(this).val().length == 0 ) {                    
            $(this).val($(this).attr('title'));
            $(this).addClass("default");
        }
    });    
    $("input.labelinside, textarea.labelinside").focus(function(e){
        if ( $(this).val() == $(this).attr('title') ) {
            $(this).val('');
            $(this).removeClass("default");
        }
    });
    $("input.labelinside, textarea.labelinside").blur(function(e){
        if ( $(this).val() == '' ) {
            $(this).val($(this).attr('title'));
            $(this).addClass("default");
        }
    });
    $("input.numeric").keypress(function(e){
        if ( ( e.which >= 48 && e.which <= 57 ) || ( e.which == 8 ) ) {
                       
        } else {
            return false;
        }
    });
}

function SetModelOptions(make_selector, for_make, first_option) {
    if ( $(make_selector).size() > 0 ) {
        $.post("/ajax/makemodelyear.php", { action: "GetCommonUsedCarModelOptions", make: for_make, first: first_option},
            function(data){
                $(make_selector).html(data);
            });
    }
}

function SetYearOptions(year_selector, for_make, for_model, first_option) {
    if ( $(year_selector).size() > 0 ) {
        $.post("/ajax/makemodelyear.php", { action: "GetUsedCarYearOptions", make: for_make, model: for_model, first: first_option},
            function(data){
                $(year_selector).html(data);
            });    
    }
}

function BrowseMakes() {
    var make = $('#browse_makes_select').val();
    if ( make != '' ) {
        document.location = make + '.html';
    }
    return false;
}