(function() {
// Set the stocks you'd like to receive
var stocks = "^DJI,^GSPC,^IXIC";
// Set to the URL to the stocks.php file
var php_url = "s/stocks.php";
// Set to the URL to the style.css file (the one included in the stocks package.)
var style_url = "s/style.css";

// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
        "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
    script_tag.onload = scriptLoadHandler;
    script_tag.onreadystatechange = function () { // Same thing but for IE
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
            scriptLoadHandler();
        }
    };
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}

/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    // Call our main function
    main(); 
}

/******** Our main function ********/
function main() { 
    jQuery(document).ready(function($) { 
        /******* Load CSS *******/
        var css_link = $("<link>", { 
            rel: "stylesheet", 
            type: "text/css", 
            href: style_url
        });
        css_link.appendTo('head');  
        
      var url= php_url + "?jsoncallback=?&stocks=" + stocks;
      $("#stocks").append('<table width="100%" border="0"></table>');
      $.getJSON(url,function(data){
        $.each(data.stocks,function(i,stock){
          $("#stocks table").append(
            '<tr class="stock">'+
              '<td class="name">'+stock.name+'</td>'+
              '<td align="right" class="current">'+stock.current_price+'</td>'+
              '<td align="right" class="'+stock.updown+' change">'+stock.change_amt+' <div class="'+stock.updown+'"></div></td>'+
            '</tr>'
          );
        });
      });
    });
}
})();
