ListManager = function() {
    bindMethods(this);
};

ListManager.prototype.initialize = function() {
    this.product_id = product_id;
    this.type_arr = [];
    appendChildNodes('main', DIV({'id':'placeholder', 'style':'padding: 1em; text-align: center;'}, 
        P({}, 'Looking up the products for this category...'), P({}, IMG({'border':'0', 'src':'/media/img/loading.gif'}))));
    this.servicesproxy = new JsonRpcProxy('http://' + location.host + '/services/products/', ['get_table_data']);
    var def = this.servicesproxy.get_table_data(this.product_id);
    def.addCallback(this.BuildTable, -1, 'u');
    def.addErrback(function(e) { log(e); });
};

ListManager.prototype.BuildTable = function(sort_index, sort_direction, data) {
    for(var i = 0; i < 10; i++) {
        if($('col_' + i)) {
            disconnectAll('col_' + i);
        } else {
            break;
        }
    }
    data['sort_index'] = sort_index;
    data['sort_direction'] = sort_direction;
    var res = TrimPath.processDOMTemplate('product_table', data);
    if($('placeholder')) {
        removeElement('placeholder');
    } else if($('prodlist')) {
        removeElement('prodlist');
    }
    $('main').innerHTML += res;
    for(var i = 0; i < 10; i++) {
        if($('col_' + i)) {
            connect('col_' + i, 'onclick', this, 'Resort');
        } else {
            break;
        }
    }
    if(this.type_arr.length == 0) {
        this.header_arr = data['header'];
        this.type2url = {};
        this.type_arr = {};
        for(var i = 0; i < data['rows'].length; i++) {
            var row = data['rows'][i];
            this.type_arr[row[0]['type']] = row.slice(1);
            this.type2url[row[0]['type']] = row[0]['url'];
        }
    }
};

ListManager.prototype.Resort = function(e) {
    sort_index = e.src().id.replace(/col_(\d+)/, "$1");
    sort_direction = scrapeText(e.src());
    switch(sort_direction) {
        case '\u2191': sort_direction = 'd'; break;
        default: sort_direction = 'u'; break;
    }
    var sort_arr = [];
    var k = 0;
    for(var type in this.type_arr) {
        var val = this.type_arr[type][sort_index];
        if(val.match(/([\d.]+)\/[\d.]+/)) {
            val = val.replace(/([\d.]+)\/[\d.]+/, "$1"); 
        }
        if(val.match(/^[\d.]+$/)) {
            val = parseFloat(val)
        }
        sort_arr[k] = { 'type':type, 'val':val };
        k = k + 1;
    }
    sort_arr.sort(keyComparator('val'));
    var sorted_types = map(itemgetter('type'), sort_arr);
    if(sort_direction == 'u') {
        sorted_types.reverse();
    }
    rows = [];
    for(var i = 0; i < sorted_types.length; i++) {
        var type = sorted_types[i]; 
        rows[i] = concat([ { 'url':this.type2url[type], 'type':type } ], this.type_arr[type]);
    }
    this.BuildTable(sort_index, sort_direction, { 'header':this.header_arr, 'rows':rows });
};

listManager = new ListManager();
addLoadEvent(listManager.initialize);
