/*globals $$: false, Element: false */
// Set the correct classes in the stocklists
(function () {
    var colorStocklist, scrollify, lazyLinks;

    window.addEvent('domready', function () {
        lazyLinks();
        colorStocklist();

        $$("table.products, table.products-wide").each(scrollify);
    });

    lazyLinks = function () {
        $$('#stocklistlinks a').each(function (item, index, array) {
            var href = item.get('href');

            item.set('href', '#');
            item.addEvent('click', function (event) {
                var stocklist;

                event.stop();

                stocklist = $('stocklist');
                stocklist.getElement('h1').set('text', item.get('text'));
                stocklist.getElement('div.bottomrightcorner')
                .set('html', '<p class="loading"> Loading <br /> Stocklist ... </p>')

                // Element.get returns a Request.HTML instance
                // So that I can use the Request method addEvent
                .get('load').get(href + '?altTemplate=ajaxBody')

                // When it's loaded you need to set the colors again
                .addEvent('complete', function(){
                    $$("table.products, table.products-wide").each(scrollify);
                    colorStocklist();
                });
            });
        });
    };

    scrollify = function (outer) {
        var inner, first_row, widths, total_width, rows, wrapper_body, columns, wrapper, _wrapper, mask;

        inner = new Element('table', {
            'cellspacing': 0,
            'cellpadding': 0
        });

        first_row = outer.getElements('thead tr:first-child td');

        widths = first_row.map(function (el) {
            return el.getSize().x;
        });

        total_width = widths.sum();

        rows = outer.getElements('tbody tr').dispose();

        wrapper_body = new Element('tbody')
            .adopt(rows) 
            .inject(inner);

        mask = new Element('div').grab(inner);

        mask.setStyles({
            'max-height': 500,
            'overflow-x': 'hidden',
            'overflow-y': 'auto'
        });

        columns = widths.map(function (value, index) {
            var el = new Element('col');
            el.setStyles({'width': (value - 10), 'overflow-x': "hidden"});
            return el;
        });
    
        columns = $$(columns);

        inner.adopt(columns);         
        outer.adopt(columns.clone(true));

        _wrapper = new Element('td');
        wrapper = new Element('tr').grab(_wrapper);
        outer.getElement('tbody').grab(wrapper);

        _wrapper
            .setStyles({padding: 0})
            .setProperty('colspan', widths.length)
            .grab(mask);

        // Now we need to set the widths of the tables
        // to compensate for our friend the scrollbar
        $$(inner, outer).setStyles({
            overflow: 'hidden',
            width: total_width,
            padding: 0
        });
    };

    colorStocklist = function () {
        var tables, colorify;
            
        colorify = function (table) {
            table.getElements('tr').each(function (item, n) {
                var cells = item.getChildren('td');

                if (n % 2 === 0) {
                    cells.addClass('even');
                } else {
                    cells.addClass('odd');
                }

                if (item.getElement('td').get('text').match(/^\s*$/)) {
                    // /^\s*$/ - contains only whitespace characters
                    cells.addClass('empty');
                } else {
                    cells.removeClass('empty');
                }
            });
        };

        tables = $$("#stocklist table");

        tables.each(colorify);
    };
}());

Array.implement({
    reduce: function (fn, seed, ctx) {
        var i, len;

        for (i = 0, len = this.length; i < len; i++) {
            seed = fn.call(ctx, this[i], seed);
        }

        return seed;
    },

    sum: function () {
        return this.reduce(function (a, b) {
            return a + b;
        }, 0);
    }
});

