var N_DROPDOWNS = 4; // Number of dropdown menus in the page

var URL_MAKELIST  = '/carmakexml.php';
var URL_MODELLIST = '/carmodelxml.php?carmakeID=';

// Custom tag names for our xml database
var TAG_MAKE  = 'carmakename';
var TAG_MODEL = 'carmodelname';
var TAG_ID    = 'id';

var MESSAGE_MAKE  = 'Select a Car Make';
var MESSAGE_MODEL = 'Select a model';

// Ajax callbacks for model dropdowns
var model_callbacks = new Array;

// Ajax XMLHTTPRequest object for loading carlist
// requests[0] is for car makes
// requests[1..4] is for the models.
var requests = new Array(5);  



//---------------
// This is the main function that is called once the document
// has been loaded successfully.
//---------------
function loadcars() {
    init_model_callbacks();

    background_load(URL_MAKELIST, carlist_callback, 0);
}

//------------------
// This function is called when the car-list xml is loaded successfully.
//------------------
function carlist_loaded(xml) {
    var carlist = xml.getElementsByTagName('carmake');
    if (!carlist.length) {
        alert('There was an error in the carlist XML file');
        return;
    }

    for (var i=0; i<N_DROPDOWNS; i++) {
        var id = i+1;

        var sel = get_make(id);
        sel.onchange = new Function('make_changed("'+id+'")');
        load_select(sel, carlist, TAG_MAKE, MESSAGE_MAKE);
        load_make_from_cookie(id);

        var model = get_model(id);
        model.onchange = new Function('model_changed("'+id+'")');
    }
}

//---------------
// Generic Ajx loader for any XML file.
// Pass the URL and the callback function to be called.
//
// This also takes care of cross-browser compatibility
//
// id = 0 for loading car makes
// id = 1,2,3,4 for loading car models for the corresponding
//              model dropdowns.
//---------------

function background_load(url, callback, id) {
    var req;

    try {
        req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            req = false;
        }
    }
    if (!req && typeof XMLHttpRequest!='undefined') {
        req = new XMLHttpRequest();
    }    

    if(req) {
        requests[id] = req;
		req.onreadystatechange = callback;
		req.open("GET", url, true);
		req.send("");
	} else {
        alert('Your browser does not support Ajax');
        return;
    }


    return req;
}

//------------------
// This is the Ajax callback to handle car-list load.
//------------------

function carlist_callback() {
    var req = requests[0];

    if (req.readyState == 4) {
        if (req.status == 0 || 
            req.status == 200) {

            //Process the xml file
            carlist_loaded(req.responseXML);
            
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }

}

function load_select(sel, xmllist, attrname, message) {
    var i;
    sel.options.length = 0;

    sel.options[0] = new Option(message, -1);
    for (i=0; i<xmllist.length; i++) {
        sel.options[i+1] = new Option(xmllist[i].getAttribute(attrname),
                                    xmllist[i].getAttribute(TAG_ID));
    }
}

function make_changed(id) {
    // Since make changed, save it.
    save_make_to_cookie(id);

    resetModel(id);
    load_models(id);
}

//---------------------------
// Call this function to update the models for 
// model dropdown 'id' based on the selection on 
// make dropdown 'id'
// id = 1,2,3,4
//---------------------------

function load_models(id) {
    var sel = get_make(id);

    if (!sel) { // Should never happen
        alert('Dropdown '+id+' not found!');
        return;
    }

    var makeid = sel.options[sel.selectedIndex].value;

    if (makeid == -1) {
        var model = get_model(id);
        model.options.length = 0;
    } else {
        background_load(URL_MODELLIST + makeid, model_callbacks[id], id);
    }
}

function modellist_loaded(id, xml) {
    var modellist = xml.getElementsByTagName('carmodel');
    var sel = get_model(id);

    load_select(sel, modellist, TAG_MODEL, MESSAGE_MODEL);
    
    load_model_from_cookie(id);
}

function model_changed(id) {
    save_model_to_cookie(id);
}


function modellist_callback(id) {
    var req = requests[id];

    if (req.readyState == 4) {
        if (req.status == 0 || 
            req.status == 200) {

            //Process the xml file
            modellist_loaded(id, req.responseXML);
            
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }

}

function init_model_callbacks() {
    model_callbacks[1] = function() {
        return modellist_callback(1);
    }

    model_callbacks[2] = function() {
        return modellist_callback(2);
    }

    model_callbacks[3] = function() {
        return modellist_callback(3);
    }


    model_callbacks[4] = function() {
        return modellist_callback(4);
    }
}

//------------------
// Miscellaneous Functions
//------------------
function resetMake(id) {
    var make = get_make(id);
    make.options.selectedIndex = 0;
    save_make_to_cookie(id); // Save it.
}

function resetModel(id) {
    var model = get_model(id);
    model.options.length = 0;
    save_model_to_cookie(id);
}

function resetListGroup(name) {
    var id = name;
    if (name.match(/vehicles(.*)/) != null) {
        id = RegExp.$1
    }
    
    resetMake(id);
    resetModel(id);
}

function get_make(id) {
    return document.forms[0]['make'+id];
}

function get_model(id) {
    return document.forms[0]['model'+id];
}

//---------------------
// Cookies
//---------------------
function _setCookie(name, value) {
  document.cookie=name+"="+value;
}
function cs_setCookie(name, value) {
  setTimeout("_setCookie('"+name+"','"+value+"')",0);
}

function cs_getCookie(name) {
  var cookieRE=new RegExp(name+"=([^;]+)");
  if (document.cookie.search(cookieRE)!=-1) {
    return RegExp.$1;
  }
  else {
    return "";
  }
}

function load_make_from_cookie(id) {
    var makeidx = cs_getCookie('c'+id+'_0');

    if (makeidx != "") {
        var make = get_make(id);
        make.options.selectedIndex = makeidx;

        load_models(id);
    }
}

function save_make_to_cookie(id) {
    var make = get_make(id);

    cs_setCookie('c'+id+'_0', make.options.selectedIndex);
}

function load_model_from_cookie(id) {
    var modelidx = cs_getCookie('c'+id+'_1');
    var model = get_model(id);

    model.options.selectedIndex = 0;
    if (modelidx != "" && modelidx != -1) {
        model.options.selectedIndex = modelidx;
    }
}

function save_model_to_cookie(id) {
    var model = get_model(id);

    cs_setCookie('c'+id+'_1', model.options.selectedIndex);
}

