/*
    Market Summary, req mootools 1.2, cnet clientside
*/

var MarketSummary = new Class({
    options: {
        dataUrlPrefix: '/auctions/json'
    },
    
    elContainer: null,
    elCountContainerSpan: null,
    priceAvg:0.0,
    stddev:0.0,
    priceHigh:0.0,
    priceLow:0.0,    
    salesCount:0,

    initialize: function(e, ec, o) {
        this.setOptions(o);
        this.elContainer = $(e);
        this.elCountContainerSpan = $(ec);
    },

    updateWithState: function(stateUrl) {
        var url = this.options.dataUrlPrefix + stateUrl + 'market_summary/';
        var req = new Request.JSON({
            url: url,   
            onComplete: this.processData.bind(this)
        }).send();
    },

    processData: function(data) {
        if (data.average_price == null) {
            data.average_price = 0;
        }
        if (data.high_price == null) {
            data.high_price = 0;
        }
        if (data.low_price == null) {
            data.low_price = 0;
        }
        if (data.sales_count==null) {
            data.sales_count = 0;    
        }
        this.priceAvg = this.addCommas(data.average_price.toInt());
        this.stddev = data.std_dev;
        this.priceHigh = this.addCommas(data.high_price.toInt());
        this.priceLow = this.addCommas(data.low_price.toInt());
        this.salesCount = this.addCommas(data.sales_count);
        this.updateView();
    },

    updateView: function() {
        var html = [];
        html.push('');
        html.push('  <h3>Market Summary</h3>');
        var divs = '<div><span class="marketSummaryLabel">Sales:</span><span class="marketSummaryValue">' + this.salesCount + '</span></div>';
        divs += '<div><span class="marketSummaryLabel">Average:</span><span class="marketSummaryValue">' + this.priceAvg + '</span></div>';
        divs += '<div><span class="marketSummaryLabel">Low:</span><span class="marketSummaryValue">' + this.priceLow + '</span></div>';
        divs += '<div><span class="marketSummaryLabel">High:</span><span class="marketSummaryValue">' + this.priceHigh + '</span></div>';
        html.push(divs);
        html = html.join('');
        this.elContainer.set('html', html);
        this.elCountContainerSpan.innerHTML = this.salesCount;
    },

    addCommas: function(nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    } 
});
MarketSummary.implement(new Options);
