var httpRequest;

/*
 * Create XMLHttpRequest object to communicate with the 
 * servlet.
 */
function getPrice()
{
    var url = 'http://binbot.com/servlet/GetLocalPrice';

    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function() { processRequest(); };
    httpRequest.send(null);
}

/*
 * Process request.
 */
function processRequest()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
            // Get the XML sent by the servlet
            var priceXml = httpRequest.responseXML.getElementsByTagName("LocalPrice")[0];

            // Update the HTML
            updateHtml(priceXml);
        }
    }
}

/*
 * Update the HTML DOM.
 */
function updateHtml(priceXml)
{
    var localPrice = priceXml.firstChild.nodeValue;
    var usdPrice = document.getElementById("usdPrice").firstChild.nodeValue;

    if ((localPrice.length > 0) && (localPrice != usdPrice)) {
        // Create the Text Node with the data received
        var priceNode = document.createTextNode(' / ' + localPrice);
                    
        // Get the reference of the element in the HTML DOM by passing the ID
        var priceElement = document.getElementById("localPrice");
        
        // Check if the TextNode already exist
        if(priceElement.hasChildNodes())
        {
            // Replace the existing node with the new one
            priceElement.replaceChild(priceNode, priceElement.firstChild);
        }
        else
        {
            // Append the new Text node
            priceElement.appendChild(priceNode);
        }       
    }
}

