var ajaxRequest;  // The variable that makes Ajax possible!
var target;

function ajaxFunction( url, func ) {

	try {
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest(  );
	} catch ( e ) {
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject( "Msxml2.XMLHTTP" );
		} catch ( e ) {
			try{
				ajaxRequest = new ActiveXObject( "Microsoft.XMLHTTP" );
			} catch ( e ) {
				// Something went wrong
				alert( "Your browser broke!" );
				return false;
			}
		}
	}

	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = func;
	ajaxRequest.open( "GET", url, true );
	ajaxRequest.send( null );
}

function getModels( sourceId, targetId ) {
    var source = document.getElementById( sourceId );
    var modelsStr = '';

    var i = 1;

    target = document.getElementById( targetId );
    ajaxFunction( 'models.php?model=' + source.value, printModels );
}

function printModels(  ) {
    var i = 1;
    var modelsStr = ajaxRequest.responseText;
    var models = modelsStr.split( ',' );

    if ( ajaxRequest.readyState == 4 ) {
        target.options.length = 1;

        while( models[i - 1] ) {
            target.options[target.options.length] = new Option( models[i - 1], models[i] );
            i = i + 2;
        }

        getModelImage( 'SelectMake', 'orderPreview' );
    }
}

function getModelImage( sourceId, targetId ) {
    var source = document.getElementById( sourceId );

    target = document.getElementById( targetId );

    target.src = 'images/' + source[source.selectedIndex].value + '.jpg';
}


function resetForm(  ) {
    document.orderForm.Year.selectedIndex = 0;
    document.orderForm.Make.selectedIndex = 0;
}


function submitOrder(  ) {
    var form = document.orderForm;
    var pass = 1;

    // verify user submitted everything correctly
    if ( form.firstName.value.length == 0 ) {
        form.firstName.style.backgroundColor = "red";
        pass = 0;
    }
    if ( form.lastName.value.length == 0 ) {
        form.lastName.style.backgroundColor = "red";
        pass = 0;
    }
    if ( form.phone1.value.length == 0 ) {
        form.phone1.style.backgroundColor = "red";
        pass = 0;
    }
    if ( form.phone2.value.length == 0 ) {
        form.phone2.style.backgroundColor = "red";
        pass = 0;
    }
    if ( form.phone3.value.length == 0 ) {
        form.phone3.style.backgroundColor = "red";
        pass = 0;
    }
    if ( form.Email.value.length == 0 ) {
        form.Email.style.backgroundColor = "red";
        pass = 0;
    }

    if ( pass == 1 ) {
        // input Model
        form.Model.options[form.Model.selectedIndex].value = form.Model.options[form.Model.selectedIndex].innerHTML;

        // send e-mail
        document.orderForm.submit(  );
    }
}
