/**
 * stock.js
 *
 * Fetches stock information from the server.
 *
 * @author Richard J. Turner <rjt@zygous.co.uk>
 * @copyright 2008 Richard J. Turner. All rights reserved.
 */

// Set-up name-space
var Solent   = Solent       || {};
Solent.Stock = Solent.Stock || {};

Solent.Stock.dataSourceUrl = '/vehicle/stock/';

/**
 * An event that's fired when stock data has been fetched from the server and
 * saved into Solent.stock. Scripts can subscribe to this event to be
 * notified when stock data is available for them to use.
 */
Solent.Stock.stockDataAvailableEvent = new YAHOO.util.CustomEvent(
    'stockDataAvailable'
);

Solent.Stock.fetchStock = function () {
    YAHOO.util.Connect.asyncRequest(
        'GET',
        Solent.Stock.dataSourceUrl,
        {
            success : function (oHttpResponse) {
                var oJson = YAHOO.lang.JSON.parse(oHttpResponse.responseText);
                
                if (oJson.bError) {
                    // Handle the error
                }
                else {
                    // Save the stock information into Solent.Stock.stock and
                    // fire an event to let observers know that it's there
                    // ready for use.
                    Solent.Stock.stock = oJson;
                    Solent.Stock.stockDataAvailableEvent.fire();
                }
            },
            failure : function (oHttpResponse) {
                // HTTP error. Try again in a few seconds....
                setTimeout('Solent.Stock.fetchStock();', 5000);
            }
        }
    );
};

YAHOO.util.Event.onDOMReady(function () {
    // Fetch stock data from the server. This starts-off a cascade of events
    // which results in the ticker being rendered and animated.
    Solent.Stock.fetchStock();
});