bh.stocks = function() {
  var that = {},
      my = {},

  symbol = {
    name: function(sym) {
      var symbol_name = {
        BH: "BHI",
        BZ: "Brent",
        CL: "WTI",
        NG: "Natural Gas"
      }

      return symbol_name[sym.slice(0,2)];
    }
  },

  init = function(element_id) {

      that.container = $('#' + element_id);

      var url_string = '/investor_info.json';

      if(that.container.length > 0) {

        bh.loader.add(element_id);

        make_request(url_string, function(data) {
          bh.loader.remove(element_id);
          load_data({quotes: data});
          if(bh.stockCharts) bh.stockCharts.init();
        });
      }

  },

  make_request = function(url, callback) {
    $.getJSON(url, function(data) {
      if(data.length > 0 && callback) {
        callback(data);
      }   else if(data.error) {
        if(console) console.warn("Stock Request Failed... Trying Again");
        
        // make_request(url, callback);
      }
    });
  },

  load_data = function(data) {
    var quotes = data.quotes;

    // getDate(data.date).appendTo(that.container);
    drawTable([quotes.shift()],["Stock","Value","Change"]).appendTo(that.container).hide().fadeIn();
    drawTable(quotes, ["Commodity", "Value", "Change"]).appendTo(that.container).hide().fadeIn();
  },

  getDate = function(d) {
    var date_string   = d.match(/^.*?(?=T)/)[0].split('-');

    date_string.push(date_string.shift());

    date_string = date_string.join('.');

    var elem = $('<span></span>', { "class": "date", text: date_string});

    return elem;
  },

  drawTable = function(data, header) {
    var table_html = '<table class="stock">' +
                        '<col class="one">' +
                        '<col class="two">' +
                        '<col class="three">' +
                        '<thead>' +
                          '<tr>' +
                            '<th>' + header[0] + '</th>' +
                            '<th>' + header[1] + '</th>' +
                            '<th class="change">' + header[2] + '</th>' +
                          '</tr>'
                        '<tbody></tbody>' +
                      '</table>';

    var table = $(table_html);

    $(data).each(function(index, quote) {
      try {
        var color, change,
            symbol_name = (symbol.name(quote.symbol) || quote.symbol);

        if(quote.change.match(/^-/)) {
          color = 'red';
          change = '- $' + quote.change.slice(1);
        }
        else {
          color = 'green';
          change = '+ $' + quote.change.slice(1);
        }

        var row = $('<tr title="' + symbol_name + '">' +
                    '<td>' + symbol_name + '</td>' +
                    '<td>$' + quote.last_trade_price_only + '</td>' +
                    '<td class="' + color + '">' + change + '</td>' +
                  '</tr>');

        if(!that.quotes) that.quotes = {};

        that.quotes[symbol_name] = {};
        that.quotes[symbol_name].quote = quote;
        that.quotes[symbol_name].element = row;
        
        table.append(row);
      }
      catch(error) {
        if(console) console.warn(error.message);
      }
    });

    return table;
  };


  that.init = init;

  return that;
}();

bh.stockCharts = function() {

  var that = {},
      my = {},

  init = function() {
    var container = bh.stocks.container,
        quotes    = bh.stocks.quotes,
        name;

    my.popup = new Popup();

    //for(name in quotes) {
      //quotes[name].element.addClass('chartable');
      //quotes[name].element.bind('click', quotes[name].quote, my.popup.open);
    //}
    quotes["BHI"].element.addClass('chartable');
    quotes["BHI"].element.bind('click', quotes["BHI"].quote, my.popup.open);

  },

  Popup = function() {
    var that = {},
        my = {};

    my.container = $('<div></div>', {
      "class": "stockChart",
      css: {
        position: 'absolute',
        left: 0,
        top: 0,
        display: 'none'
      }
    }).appendTo('body');

    my.content = $('<div></div>', {
      "class": "stock_info",
      width: "100%",
      height: "100%"
    }).appendTo(my.container);

    $('<div></div>', {
      "class": "close",
      css: {
        position: 'absolute',
        top: 5,
        right: 7
      },
      click: function(event) {
        close(event);
      }
    }).appendTo(my.container);


    var open = function(event) {

      var target = $(event.target).closest('tr');
      var left = (target.offset().left) - (my.container.outerWidth()/2) + 10,
          top  = (target.offset().top) - my.container.outerHeight() + 10;

      target.parents('div').find('tr').removeClass('active');
      target.addClass('active');

      my.content.empty();

      my.container.css({left: left, top: top});
      my.container.fadeIn(function() {
        if(event.data) load(event.data);
      });
    },

    close = function(event) {
      $('#stocks').find('tr').removeClass('active');
      my.container.fadeOut();
    },

    load = function(object) {
      var graph_wrapper = $('<div></div>', {"class":"graph"});

      my.content.append(graph_wrapper);
      my.content.append(stats(object)).hide().fadeIn(function() {
        bh.loader.add(graph_wrapper);
        graph(object, graph_wrapper);
      });
    },

    graph = function(quote, wrapper) {

      var chart = $('<div></div>');

      var symbol = quote.symbol.slice(0,2);

      wrapper.append(chart);

      var width = wrapper.width(),
          height = wrapper.height();

      var paper = Raphael(chart[0], width, height);

      var nav_html = $("<ul>" +
                        "<li><a href='#' title='MONTH' class='active'>1 Month</a></li>" +
                        "<li><a href='#' title='QUARTER'>1 Quarter</a></li>" +
                        "<li><a href='#' title='YEAR'>1 Year</a></li>" +
                        "<li class='last'><a href= '#' title='5_YEARS'>5 Years</a></li>" +
                      "</ul>");

      wrapper.prepend(nav_html);

      nav_html.bind('click', function(event) {
        event.preventDefault();

        var target = $(event.target);

        if(target.attr('title') && !target.hasClass('active')) {
          target.closest('li').siblings().find('a').removeClass('active');
          target.addClass('active');
          makeRequest({period: target.attr('title')});
        }
      });

      // Local functions make AJAX request and draw graph
      var makeRequest = function(object) {
        var symbol = object && object.symbol || 'BHI',
            period = object && object.period || 'MONTH';

        paper.clear();
        bh.loader.add(wrapper);

        $.getJSON("/investors/stock/historical.json?symbol=" + symbol + "&period=" + period, function(data) {
          draw_graph(data.data);
        });

      },

      draw_graph = function(data) {
        var x = data[0],
            y = data[1];

        bh.loader.remove(wrapper);
        paper.g.linechart(30, 0, width - 30, 123, x, y, {colors: ["#ff5d00"], axis: "1 1 1 1", gutter: 10, width: 1.5});
      };

      makeRequest();


    },

    stats = function(quote) {
      var table, color, change;

      var wrapper = $('<div></div>', {"class":"stats"});

      if(quote.change.match(/^-/)) {
        color = 'red';
        change = '- $' + quote.change.slice(1);
      }
      else {
        color = 'green';
        change = '+ $' + quote.change.slice(1);
      }

      table = '<table>' +
               '<col class="one" />' +
               '<col class="two" />' +
               '<col class="three" />' +
               '<col class="four" />' +
               '<thead>' +
                  '<tr>' +
                    '<th>Last Trade (<em>' + quote.last_trade_time + '</em>)</th><th>Change</th><th>Days High</th><th>Days Low</th>' +
                  '</tr>' +
               '</thead>' +
               '<tbody>' +
                  '<tr>' +
                    '<td>$' + quote.last_trade_price_only + '</td><td class="' + color + '">' + change + '</td><td>$' + (quote.day_high || 'n/a') + '</td><td>$' + (quote.day_low || 'n/a') + '</td>' +
                  '</tr>' +
               '</tbody>' +
             '</table>';

      wrapper.append(table);

      return wrapper;
    };

    that.open = open;

    return that;

  };

  //var wrapper = $('<div></div>').appendTo('body');

  //var chart = Raphael(wrapper[0], 640, 480);

  //chart.g.linechart(10, 10, 620, 460, [1,2,3,4,5,6,7], [2,4,56,3,2,8,5], {axis:"0 0 1 1"});

  that.init = init;

  return that;
}();


