function updateDropdown(id, data) {
    /* removing existing options */
    id.childElements().each(function(e) {e.remove();});

    /* add new options */
    data.each(function(row) {
            id.insert(new Element('option', {value: row.id}).update(row.name));
        });
}

function resetDropdown(id, name) {
    /* removing existing options */
    id.childElements().each(function(e) {e.remove();});
    /* add Select .. option */
            id.insert(new Element('option', {value: '-'}).update(name));
}

function AJAXUpdateModels() {
        new Ajax.Request('/ajax/dropdown.php', {
                method:'get',
		    parameters: {action: 'year_model', make: $F('dd_make'),  year: $F('dd_year'), type: $F('dd_type')},
                    onSuccess: DOMupdateModels
                    });
}

function DOMupdateModels(transport) {
    updateDropdown($('dd_model'), transport.responseText.evalJSON());
}

function AJAXUpdateYears() {
        new Ajax.Request('/ajax/dropdown.php', {
                method:'get',
		    parameters: {action: 'years', make: $F('dd_make'), type: $F('dd_type')},
                    onSuccess: DOMupdateYears
                    });
}

function DOMupdateYears(transport) {
    updateDropdown($('dd_year'), transport.responseText.evalJSON());
    resetDropdown($('dd_model'), 'Select Model');
    /* If there's only one option in dd_years automaticly fetch the models */
    if($('dd_make').childElements().size() == 1){
	AJAXUpdateModels();
    }


}

function DOMupdateMake(transport) {
    updateDropdown($('dd_make'), transport.responseText.evalJSON());
    resetDropdown($('dd_year'), 'Select Year');
    resetDropdown($('dd_model'), 'Select Model');

    /* If there's only one option in dd_make automaticly fetch the years */
    if($('dd_make').childElements().size() == 1){
	AJAXUpdateYears();
    }
}

/* attach the observers */
$('dd_type').observe('change', function(e) {
        new Ajax.Request('/ajax/dropdown.php', {
                method:'get',
		    parameters: {action: 'make', type: $F('dd_type')},
                    onSuccess: DOMupdateMake
                    });

        Event.stop(e);
    });


$('dd_make').observe('change', function(e) {
	/* if "Select Make" chosen do nothing */
	if($F('dd_make') == '-'){
	    return;
	}
	AJAXUpdateYears();
        Event.stop(e);
    });

$('dd_year').observe('change', function(e) {
	/* if "Select Model" chosen do nothing */
	if($F('dd_year') == '-'){
	    return;
	}

	AJAXUpdateModels();
        Event.stop(e);
    });


$('dd_button').observe('click', function(e) {
	if(($F('dd_make') == '-') || ($F('dd_model') == '-') || ($F('dd_year') == '-')) {
            Event.stop(e);
	}
    });


