function iniciaAjax()
{
    Ajax = false;
    if ( window.XMLHttpRequest )
        Ajax = new XMLHttpRequest();
    else if ( window.ActiveXObject )
    {
        try {
            Ajax = new ActiveXObject("Msxm12.XMLHTTP");
        } catch (e) {
            try {
            Ajax = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    else
        alert("Não foi possivel iniciar o Ajax!")
}

function buscaModelos(form)
{
    var marca = form.f_marca.value;
    var tipo  = form.f_tipo.value;
	var categoria = form.f_categoria.value;
	
    iniciaAjax();
    if ( !Ajax )
    {
        alert("Não foi possivel iniciar o Ajax!");
        return;
    }
    Ajax.onreadystatechange = function(){mostraModelos(form)};

    if ( form.name.substring(4,7) != 'adm' )
        Ajax.open('GET','./xml/xml_modelos2.php?marca='+marca+'&tipo='+tipo,true);
    else if ( categoria == 'shopcar' )
    	Ajax.open('GET','../xml/xml_modelos2.php?marca='+marca+'&tipo='+tipo,true);
    else if ( categoria == 'pouptempo' )
        Ajax.open('GET','../xml/xml_modelos2.php?marca='+marca+'&tipo='+tipo,true);
    else
        Ajax.open('GET','../xml/xml_modelos.php?marca='+marca+'&tipo='+tipo,true);

    Ajax.send(null);
}

function mostraModelos(form)
{
    if ( Ajax.readyState == 4 )
    {
        if ( Ajax.status == 200 )
        {
            var xmlMarca 	= Ajax.responseXML;
			var sel2		= form.f_marca;
			var sel = form.f_modelo;

			if ( form.name.substring(4,7) == 'adm' )
				var vmodelo = form.f_vmodelo.value;
			else
				var vmodelo = 'Selecione';

            if ( xmlMarca.hasChildNodes() )
            {
                var codigo  = xmlMarca.getElementsByTagName('codigo');
                var modelo  = xmlMarca.getElementsByTagName('modelo');

                limpa(sel);
                sel.disabled = false;
                sel.options[sel.options.length] = new Option("Selecione","Selecione",true,false);

                for ( i=0; i<modelo.length; i++ )
                {
                    var cod = codigo[i].childNodes;
                    var mod = modelo[i].childNodes;
                    
                    if ( cod[0].nodeValue == vmodelo )
                    	sel.options[0] = new Option(mod[0].nodeValue,cod[0].nodeValue,false,true);
                    else
                    	sel.options[sel.options.length] = new Option(mod[0].nodeValue,cod[0].nodeValue);
                    
                }
            }
            
            if ( sel2.value == 'Selecione' )
            {
                sel.selectedIndex = 'Selecione';
                sel.disabled = true;
            }
        }
        else
            alert('Erro5: '+ Ajax.statusText);
    }
}

function limpa(ob)
{
    if ( ob.hasChildNodes())
    {
        var nos = ob.childNodes;

        while (nos.length > 0)
        {
            var no = nos[nos.length-1];
            ob.removeChild(no);
        }
    }
}