// initialization
window.onload = init;

var xml, xsl;

// initialize by loading xml/xsl and applying transform
function init()
{
    document.getElementById("showaddress").onsubmit = showaddress;
    xml = loadDoc("bikelist/xml","address=fifth+and+vine");
    xsl = loadDoc("xml/bikelist.xsl",null);
    doTransform();
    return false;
}

// load an xml/xsl document in FF or IE
function loadDoc(filename,args)
{
    var xhr = (window.XMLHttpRequest && new XMLHttpRequest()) ||
    (window.ActiveXObject && new ActiveXObject("Microsoft.XMLHTTP"));
    if (xhr)
    {
        xhr.open("POST",filename, false);
        //this must go after the open for a POST
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(args);
    }
    else
    {
        alert("Sorry, but I couldn't create an XMLDOM");
    }
    return xhr.responseXML;
}

// apply the xsl to xml
function doTransform()
{
    var bikelist = document.getElementById("sortoutput");
    // code for IE
    if (window.ActiveXObject)
    {
        var ex=xml.transformNode(xsl);
        bikelist.innerHTML=ex;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation
        && document.implementation.createDocument)
        {
        xsltProcessor=new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);
        var resultDocument = xsltProcessor.transformToFragment(xml,document);
        if (bikelist.firstChild)
            bikelist.replaceChild(resultDocument, bikelist.firstChild);
        else
            bikelist.appendChild(resultDocument);
    }
    // event handlers for sorting buttons
    var buttons = document.getElementById("sortoutput").getElementsByTagName("input");
    for (var i = 0; i < buttons.length; i++)
        buttons[i].onclick = sortbikelist;
    // alternating background colors for table rows
    var rows = document.getElementById("sortoutput").getElementsByTagName("tr");
    for (var i = 1; i < rows.length; i++)
        rows[i].className = i%2 ? "odd" : "even";
}

// change the xsl:sort attributes to sort by "select" parameter
function orderBy(select)
{
    // xsl = loadDoc("xml/bikelist.xsl");
    var sortItem = xsl.getElementsByTagName("xsl:sort")[0];
    sortItem.setAttribute("select", select);
    doTransform();
}

// sort using the html's input tag's id field
// this.id MUST match the name of the element in the bikelist.xml
function sortbikelist()
{
    //alert(this.className);
    orderBy(this.id + "/text()");
    return false;
}

function showaddress(){
    var addr = this.address.value;
    var city = this.city.value;
    var state = this.state.value;

    if (addr == "Enter address or intersection") {
        alert("Please enter a Cincinnati address or intersection");
    }
    else {
        xml = loadDoc("bikelist/xml","address="+addr+"&city="+city+"&state="+state);
        xsl = loadDoc("xml/bikelist.xsl");
        doTransform();
    }
    return false;
}

